Файловый менеджер - Редактировать - /home/clickysoft/public_html/travel-guru.clickysoft.net/public/js/app.js
Назад
/******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ /***/ "./resources/js/app.js": /*!*****************************!*\ !*** ./resources/js/app.js ***! \*****************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _components_HelloReact__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./components/HelloReact */ "./resources/js/components/HelloReact.js"); /* harmony import */ var _components_WebBuilder__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./components/WebBuilder */ "./resources/js/components/WebBuilder.js"); /** * Next, we will create a fresh React component instance and attach it to * the page. Then, you may begin adding components to this application * or customize the JavaScript scaffolding to fit your unique needs. */ /***/ }), /***/ "./resources/js/components/HelloReact.js": /*!***********************************************!*\ !*** ./resources/js/components/HelloReact.js ***! \***********************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (/* binding */ HelloReact) /* harmony export */ }); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js"); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react-dom */ "./node_modules/react-dom/index.js"); /* harmony import */ var react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react/jsx-runtime */ "./node_modules/react/jsx-runtime.js"); function HelloReact() { return /*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)("h1", { children: "Hello React!ss" }); } if (document.getElementById('hello-react')) { react_dom__WEBPACK_IMPORTED_MODULE_1__.render( /*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_2__.jsx)(HelloReact, {}), document.getElementById('hello-react')); } /***/ }), /***/ "./resources/js/components/WebBuilder.js": /*!***********************************************!*\ !*** ./resources/js/components/WebBuilder.js ***! \***********************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js"); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react-dom */ "./node_modules/react-dom/index.js"); /* harmony import */ var grapesjs__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! grapesjs */ "./node_modules/grapesjs/dist/grapes.mjs"); /* harmony import */ var grapesjs_preset_webpage__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! grapesjs-preset-webpage */ "./node_modules/grapesjs-preset-webpage/dist/index.js"); /* harmony import */ var grapesjs_preset_webpage__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(grapesjs_preset_webpage__WEBPACK_IMPORTED_MODULE_2__); /* harmony import */ var grapesjs_blocks_basic__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! grapesjs-blocks-basic */ "./node_modules/grapesjs-blocks-basic/dist/index.js"); /* harmony import */ var grapesjs_blocks_basic__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(grapesjs_blocks_basic__WEBPACK_IMPORTED_MODULE_3__); /* harmony import */ var grapesjs_dist_css_grapes_min_css__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! grapesjs/dist/css/grapes.min.css */ "./node_modules/grapesjs/dist/css/grapes.min.css"); /* harmony import */ var react_jsx_runtime__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! react/jsx-runtime */ "./node_modules/react/jsx-runtime.js"); function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } var WebBuilder = function WebBuilder(props) { var primaryId = props.primaryId, appUrl = props.appUrl; var editorRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null); var projectEndpoint = "".concat(appUrl, "/get-template/").concat(primaryId); (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(function () { var editor = grapesjs__WEBPACK_IMPORTED_MODULE_6__["default"].init({ container: '#gjs', height: '700px', width: '100%', plugins: [(grapesjs_preset_webpage__WEBPACK_IMPORTED_MODULE_2___default()), (grapesjs_blocks_basic__WEBPACK_IMPORTED_MODULE_3___default())], storageManager: { id: 'gjs-', type: 'remote', contentTypeJson: true, autosave: false, // Disable autosave autoload: true, storeComponents: true, storeStyles: true, storeHtml: true, storeCss: true, options: { remote: { urlStore: "".concat(appUrl, "/save-template"), urlLoad: projectEndpoint, onStore: function onStore(data) { return { id: primaryId, data: data }; }, onLoad: function onLoad(result) { return result; } } }, headers: { 'Content-Type': 'application/json' } }, deviceManager: { devices: [{ id: 'desktop', name: 'Desktop', width: '' }, { id: 'tablet', name: 'Tablet', width: '768px', widthMedia: '992px' }, { id: 'mobilePortrait', name: 'Mobile portrait', width: '320px', widthMedia: '575px' }] }, pluginsOpts: {} }); editorRef.current = editor; }, [primaryId]); // Event handler for the "Save" button var handleSave = function handleSave() { var editor = editorRef.current; editor.store(); Swal.fire({ icon: 'success', title: 'Saved!', text: 'Your changes have been saved successfully.' }); }; return /*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_5__.jsxs)("div", { children: [/*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_5__.jsx)("div", { id: "gjs" }), /*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_5__.jsx)("div", { "class": "row mt-3", children: /*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_5__.jsx)("div", { "class": "col-md-12", children: /*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_5__.jsx)("button", { onClick: handleSave, "class": "btn btn-primary", children: "Update page builder" }) }) }), /*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_5__.jsx)("div", { "class": "row mt-3" })] }); }; /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (WebBuilder); var el = document.getElementById('web-builder'); console.log(el.length); if (el !== undefined) { react_dom__WEBPACK_IMPORTED_MODULE_1__.render( /*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_5__.jsx)(WebBuilder, _objectSpread({}, el.dataset)), document.getElementById('web-builder')); } /***/ }), /***/ "./node_modules/base64-js/index.js": /*!*****************************************!*\ !*** ./node_modules/base64-js/index.js ***! \*****************************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; exports.byteLength = byteLength exports.toByteArray = toByteArray exports.fromByteArray = fromByteArray var lookup = [] var revLookup = [] var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' for (var i = 0, len = code.length; i < len; ++i) { lookup[i] = code[i] revLookup[code.charCodeAt(i)] = i } // Support decoding URL-safe base64 strings, as Node.js does. // See: https://en.wikipedia.org/wiki/Base64#URL_applications revLookup['-'.charCodeAt(0)] = 62 revLookup['_'.charCodeAt(0)] = 63 function getLens (b64) { var len = b64.length if (len % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4') } // Trim off extra bytes after placeholder bytes are found // See: https://github.com/beatgammit/base64-js/issues/42 var validLen = b64.indexOf('=') if (validLen === -1) validLen = len var placeHoldersLen = validLen === len ? 0 : 4 - (validLen % 4) return [validLen, placeHoldersLen] } // base64 is 4/3 + up to two characters of the original data function byteLength (b64) { var lens = getLens(b64) var validLen = lens[0] var placeHoldersLen = lens[1] return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen } function _byteLength (b64, validLen, placeHoldersLen) { return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen } function toByteArray (b64) { var tmp var lens = getLens(b64) var validLen = lens[0] var placeHoldersLen = lens[1] var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) var curByte = 0 // if there are placeholders, only get up to the last complete 4 chars var len = placeHoldersLen > 0 ? validLen - 4 : validLen var i for (i = 0; i < len; i += 4) { tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] arr[curByte++] = (tmp >> 16) & 0xFF arr[curByte++] = (tmp >> 8) & 0xFF arr[curByte++] = tmp & 0xFF } if (placeHoldersLen === 2) { tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) arr[curByte++] = tmp & 0xFF } if (placeHoldersLen === 1) { tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) arr[curByte++] = (tmp >> 8) & 0xFF arr[curByte++] = tmp & 0xFF } return arr } function tripletToBase64 (num) { return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] } function encodeChunk (uint8, start, end) { var tmp var output = [] for (var i = start; i < end; i += 3) { tmp = ((uint8[i] << 16) & 0xFF0000) + ((uint8[i + 1] << 8) & 0xFF00) + (uint8[i + 2] & 0xFF) output.push(tripletToBase64(tmp)) } return output.join('') } function fromByteArray (uint8) { var tmp var len = uint8.length var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes var parts = [] var maxChunkLength = 16383 // must be multiple of 3 // go through the array every three bytes, we'll deal with trailing stuff later for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) } // pad the end with zeros, but make sure to not forget the extra bytes if (extraBytes === 1) { tmp = uint8[len - 1] parts.push( lookup[tmp >> 2] + lookup[(tmp << 4) & 0x3F] + '==' ) } else if (extraBytes === 2) { tmp = (uint8[len - 2] << 8) + uint8[len - 1] parts.push( lookup[tmp >> 10] + lookup[(tmp >> 4) & 0x3F] + lookup[(tmp << 2) & 0x3F] + '=' ) } return parts.join('') } /***/ }), /***/ "./node_modules/buffer/index.js": /*!**************************************!*\ !*** ./node_modules/buffer/index.js ***! \**************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh <http://feross.org> * @license MIT */ /* eslint-disable no-proto */ var base64 = __webpack_require__(/*! base64-js */ "./node_modules/base64-js/index.js") var ieee754 = __webpack_require__(/*! ieee754 */ "./node_modules/ieee754/index.js") var isArray = __webpack_require__(/*! isarray */ "./node_modules/isarray/index.js") exports.Buffer = Buffer exports.SlowBuffer = SlowBuffer exports.INSPECT_MAX_BYTES = 50 /** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) * === false Use Object implementation (most compatible, even IE6) * * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, * Opera 11.6+, iOS 4.2+. * * Due to various browser bugs, sometimes the Object implementation will be used even * when the browser supports typed arrays. * * Note: * * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. * * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. * * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of * incorrect length in some situations. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they * get the Object implementation, which is slower but behaves correctly. */ Buffer.TYPED_ARRAY_SUPPORT = __webpack_require__.g.TYPED_ARRAY_SUPPORT !== undefined ? __webpack_require__.g.TYPED_ARRAY_SUPPORT : typedArraySupport() /* * Export kMaxLength after typed array support is determined. */ exports.kMaxLength = kMaxLength() function typedArraySupport () { try { var arr = new Uint8Array(1) arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} return arr.foo() === 42 && // typed array instances can be augmented typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` } catch (e) { return false } } function kMaxLength () { return Buffer.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff } function createBuffer (that, length) { if (kMaxLength() < length) { throw new RangeError('Invalid typed array length') } if (Buffer.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = new Uint8Array(length) that.__proto__ = Buffer.prototype } else { // Fallback: Return an object instance of the Buffer class if (that === null) { that = new Buffer(length) } that.length = length } return that } /** * The Buffer constructor returns instances of `Uint8Array` that have their * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of * `Uint8Array`, so the returned instances will have all the node `Buffer` methods * and the `Uint8Array` methods. Square bracket notation works as expected -- it * returns a single octet. * * The `Uint8Array` prototype remains unmodified. */ function Buffer (arg, encodingOrOffset, length) { if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { return new Buffer(arg, encodingOrOffset, length) } // Common case. if (typeof arg === 'number') { if (typeof encodingOrOffset === 'string') { throw new Error( 'If encoding is specified then the first argument must be a string' ) } return allocUnsafe(this, arg) } return from(this, arg, encodingOrOffset, length) } Buffer.poolSize = 8192 // not used by this implementation // TODO: Legacy, not needed anymore. Remove in next major version. Buffer._augment = function (arr) { arr.__proto__ = Buffer.prototype return arr } function from (that, value, encodingOrOffset, length) { if (typeof value === 'number') { throw new TypeError('"value" argument must not be a number') } if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { return fromArrayBuffer(that, value, encodingOrOffset, length) } if (typeof value === 'string') { return fromString(that, value, encodingOrOffset) } return fromObject(that, value) } /** * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError * if value is a number. * Buffer.from(str[, encoding]) * Buffer.from(array) * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ Buffer.from = function (value, encodingOrOffset, length) { return from(null, value, encodingOrOffset, length) } if (Buffer.TYPED_ARRAY_SUPPORT) { Buffer.prototype.__proto__ = Uint8Array.prototype Buffer.__proto__ = Uint8Array if (typeof Symbol !== 'undefined' && Symbol.species && Buffer[Symbol.species] === Buffer) { // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 Object.defineProperty(Buffer, Symbol.species, { value: null, configurable: true }) } } function assertSize (size) { if (typeof size !== 'number') { throw new TypeError('"size" argument must be a number') } else if (size < 0) { throw new RangeError('"size" argument must not be negative') } } function alloc (that, size, fill, encoding) { assertSize(size) if (size <= 0) { return createBuffer(that, size) } if (fill !== undefined) { // Only pay attention to encoding if it's a string. This // prevents accidentally sending in a number that would // be interpretted as a start offset. return typeof encoding === 'string' ? createBuffer(that, size).fill(fill, encoding) : createBuffer(that, size).fill(fill) } return createBuffer(that, size) } /** * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ Buffer.alloc = function (size, fill, encoding) { return alloc(null, size, fill, encoding) } function allocUnsafe (that, size) { assertSize(size) that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) if (!Buffer.TYPED_ARRAY_SUPPORT) { for (var i = 0; i < size; ++i) { that[i] = 0 } } return that } /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ Buffer.allocUnsafe = function (size) { return allocUnsafe(null, size) } /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ Buffer.allocUnsafeSlow = function (size) { return allocUnsafe(null, size) } function fromString (that, string, encoding) { if (typeof encoding !== 'string' || encoding === '') { encoding = 'utf8' } if (!Buffer.isEncoding(encoding)) { throw new TypeError('"encoding" must be a valid string encoding') } var length = byteLength(string, encoding) | 0 that = createBuffer(that, length) var actual = that.write(string, encoding) if (actual !== length) { // Writing a hex string, for example, that contains invalid characters will // cause everything after the first invalid character to be ignored. (e.g. // 'abxxcd' will be treated as 'ab') that = that.slice(0, actual) } return that } function fromArrayLike (that, array) { var length = array.length < 0 ? 0 : checked(array.length) | 0 that = createBuffer(that, length) for (var i = 0; i < length; i += 1) { that[i] = array[i] & 255 } return that } function fromArrayBuffer (that, array, byteOffset, length) { array.byteLength // this throws if `array` is not a valid ArrayBuffer if (byteOffset < 0 || array.byteLength < byteOffset) { throw new RangeError('\'offset\' is out of bounds') } if (array.byteLength < byteOffset + (length || 0)) { throw new RangeError('\'length\' is out of bounds') } if (byteOffset === undefined && length === undefined) { array = new Uint8Array(array) } else if (length === undefined) { array = new Uint8Array(array, byteOffset) } else { array = new Uint8Array(array, byteOffset, length) } if (Buffer.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = array that.__proto__ = Buffer.prototype } else { // Fallback: Return an object instance of the Buffer class that = fromArrayLike(that, array) } return that } function fromObject (that, obj) { if (Buffer.isBuffer(obj)) { var len = checked(obj.length) | 0 that = createBuffer(that, len) if (that.length === 0) { return that } obj.copy(that, 0, 0, len) return that } if (obj) { if ((typeof ArrayBuffer !== 'undefined' && obj.buffer instanceof ArrayBuffer) || 'length' in obj) { if (typeof obj.length !== 'number' || isnan(obj.length)) { return createBuffer(that, 0) } return fromArrayLike(that, obj) } if (obj.type === 'Buffer' && isArray(obj.data)) { return fromArrayLike(that, obj.data) } } throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') } function checked (length) { // Note: cannot use `length < kMaxLength()` here because that fails when // length is NaN (which is otherwise coerced to zero.) if (length >= kMaxLength()) { throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + kMaxLength().toString(16) + ' bytes') } return length | 0 } function SlowBuffer (length) { if (+length != length) { // eslint-disable-line eqeqeq length = 0 } return Buffer.alloc(+length) } Buffer.isBuffer = function isBuffer (b) { return !!(b != null && b._isBuffer) } Buffer.compare = function compare (a, b) { if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { throw new TypeError('Arguments must be Buffers') } if (a === b) return 0 var x = a.length var y = b.length for (var i = 0, len = Math.min(x, y); i < len; ++i) { if (a[i] !== b[i]) { x = a[i] y = b[i] break } } if (x < y) return -1 if (y < x) return 1 return 0 } Buffer.isEncoding = function isEncoding (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'latin1': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return true default: return false } } Buffer.concat = function concat (list, length) { if (!isArray(list)) { throw new TypeError('"list" argument must be an Array of Buffers') } if (list.length === 0) { return Buffer.alloc(0) } var i if (length === undefined) { length = 0 for (i = 0; i < list.length; ++i) { length += list[i].length } } var buffer = Buffer.allocUnsafe(length) var pos = 0 for (i = 0; i < list.length; ++i) { var buf = list[i] if (!Buffer.isBuffer(buf)) { throw new TypeError('"list" argument must be an Array of Buffers') } buf.copy(buffer, pos) pos += buf.length } return buffer } function byteLength (string, encoding) { if (Buffer.isBuffer(string)) { return string.length } if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { return string.byteLength } if (typeof string !== 'string') { string = '' + string } var len = string.length if (len === 0) return 0 // Use a for loop to avoid recursion var loweredCase = false for (;;) { switch (encoding) { case 'ascii': case 'latin1': case 'binary': return len case 'utf8': case 'utf-8': case undefined: return utf8ToBytes(string).length case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return len * 2 case 'hex': return len >>> 1 case 'base64': return base64ToBytes(string).length default: if (loweredCase) return utf8ToBytes(string).length // assume utf8 encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.byteLength = byteLength function slowToString (encoding, start, end) { var loweredCase = false // No need to verify that "this.length <= MAX_UINT32" since it's a read-only // property of a typed array. // This behaves neither like String nor Uint8Array in that we set start/end // to their upper/lower bounds if the value passed is out of range. // undefined is handled specially as per ECMA-262 6th Edition, // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. if (start === undefined || start < 0) { start = 0 } // Return early if start > this.length. Done here to prevent potential uint32 // coercion fail below. if (start > this.length) { return '' } if (end === undefined || end > this.length) { end = this.length } if (end <= 0) { return '' } // Force coersion to uint32. This will also coerce falsey/NaN values to 0. end >>>= 0 start >>>= 0 if (end <= start) { return '' } if (!encoding) encoding = 'utf8' while (true) { switch (encoding) { case 'hex': return hexSlice(this, start, end) case 'utf8': case 'utf-8': return utf8Slice(this, start, end) case 'ascii': return asciiSlice(this, start, end) case 'latin1': case 'binary': return latin1Slice(this, start, end) case 'base64': return base64Slice(this, start, end) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return utf16leSlice(this, start, end) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = (encoding + '').toLowerCase() loweredCase = true } } } // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect // Buffer instances. Buffer.prototype._isBuffer = true function swap (b, n, m) { var i = b[n] b[n] = b[m] b[m] = i } Buffer.prototype.swap16 = function swap16 () { var len = this.length if (len % 2 !== 0) { throw new RangeError('Buffer size must be a multiple of 16-bits') } for (var i = 0; i < len; i += 2) { swap(this, i, i + 1) } return this } Buffer.prototype.swap32 = function swap32 () { var len = this.length if (len % 4 !== 0) { throw new RangeError('Buffer size must be a multiple of 32-bits') } for (var i = 0; i < len; i += 4) { swap(this, i, i + 3) swap(this, i + 1, i + 2) } return this } Buffer.prototype.swap64 = function swap64 () { var len = this.length if (len % 8 !== 0) { throw new RangeError('Buffer size must be a multiple of 64-bits') } for (var i = 0; i < len; i += 8) { swap(this, i, i + 7) swap(this, i + 1, i + 6) swap(this, i + 2, i + 5) swap(this, i + 3, i + 4) } return this } Buffer.prototype.toString = function toString () { var length = this.length | 0 if (length === 0) return '' if (arguments.length === 0) return utf8Slice(this, 0, length) return slowToString.apply(this, arguments) } Buffer.prototype.equals = function equals (b) { if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return true return Buffer.compare(this, b) === 0 } Buffer.prototype.inspect = function inspect () { var str = '' var max = exports.INSPECT_MAX_BYTES if (this.length > 0) { str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') if (this.length > max) str += ' ... ' } return '<Buffer ' + str + '>' } Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { if (!Buffer.isBuffer(target)) { throw new TypeError('Argument must be a Buffer') } if (start === undefined) { start = 0 } if (end === undefined) { end = target ? target.length : 0 } if (thisStart === undefined) { thisStart = 0 } if (thisEnd === undefined) { thisEnd = this.length } if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { throw new RangeError('out of range index') } if (thisStart >= thisEnd && start >= end) { return 0 } if (thisStart >= thisEnd) { return -1 } if (start >= end) { return 1 } start >>>= 0 end >>>= 0 thisStart >>>= 0 thisEnd >>>= 0 if (this === target) return 0 var x = thisEnd - thisStart var y = end - start var len = Math.min(x, y) var thisCopy = this.slice(thisStart, thisEnd) var targetCopy = target.slice(start, end) for (var i = 0; i < len; ++i) { if (thisCopy[i] !== targetCopy[i]) { x = thisCopy[i] y = targetCopy[i] break } } if (x < y) return -1 if (y < x) return 1 return 0 } // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, // OR the last index of `val` in `buffer` at offset <= `byteOffset`. // // Arguments: // - buffer - a Buffer to search // - val - a string, Buffer, or number // - byteOffset - an index into `buffer`; will be clamped to an int32 // - encoding - an optional encoding, relevant is val is a string // - dir - true for indexOf, false for lastIndexOf function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { // Empty buffer means no match if (buffer.length === 0) return -1 // Normalize byteOffset if (typeof byteOffset === 'string') { encoding = byteOffset byteOffset = 0 } else if (byteOffset > 0x7fffffff) { byteOffset = 0x7fffffff } else if (byteOffset < -0x80000000) { byteOffset = -0x80000000 } byteOffset = +byteOffset // Coerce to Number. if (isNaN(byteOffset)) { // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer byteOffset = dir ? 0 : (buffer.length - 1) } // Normalize byteOffset: negative offsets start from the end of the buffer if (byteOffset < 0) byteOffset = buffer.length + byteOffset if (byteOffset >= buffer.length) { if (dir) return -1 else byteOffset = buffer.length - 1 } else if (byteOffset < 0) { if (dir) byteOffset = 0 else return -1 } // Normalize val if (typeof val === 'string') { val = Buffer.from(val, encoding) } // Finally, search either indexOf (if dir is true) or lastIndexOf if (Buffer.isBuffer(val)) { // Special case: looking for empty string/buffer always fails if (val.length === 0) { return -1 } return arrayIndexOf(buffer, val, byteOffset, encoding, dir) } else if (typeof val === 'number') { val = val & 0xFF // Search for a byte value [0-255] if (Buffer.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === 'function') { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) } else { return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) } } return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) } throw new TypeError('val must be string, number or Buffer') } function arrayIndexOf (arr, val, byteOffset, encoding, dir) { var indexSize = 1 var arrLength = arr.length var valLength = val.length if (encoding !== undefined) { encoding = String(encoding).toLowerCase() if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') { if (arr.length < 2 || val.length < 2) { return -1 } indexSize = 2 arrLength /= 2 valLength /= 2 byteOffset /= 2 } } function read (buf, i) { if (indexSize === 1) { return buf[i] } else { return buf.readUInt16BE(i * indexSize) } } var i if (dir) { var foundIndex = -1 for (i = byteOffset; i < arrLength; i++) { if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { if (foundIndex === -1) foundIndex = i if (i - foundIndex + 1 === valLength) return foundIndex * indexSize } else { if (foundIndex !== -1) i -= i - foundIndex foundIndex = -1 } } } else { if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength for (i = byteOffset; i >= 0; i--) { var found = true for (var j = 0; j < valLength; j++) { if (read(arr, i + j) !== read(val, j)) { found = false break } } if (found) return i } } return -1 } Buffer.prototype.includes = function includes (val, byteOffset, encoding) { return this.indexOf(val, byteOffset, encoding) !== -1 } Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, true) } Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, false) } function hexWrite (buf, string, offset, length) { offset = Number(offset) || 0 var remaining = buf.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } // must be an even number of digits var strLen = string.length if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') if (length > strLen / 2) { length = strLen / 2 } for (var i = 0; i < length; ++i) { var parsed = parseInt(string.substr(i * 2, 2), 16) if (isNaN(parsed)) return i buf[offset + i] = parsed } return i } function utf8Write (buf, string, offset, length) { return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) } function asciiWrite (buf, string, offset, length) { return blitBuffer(asciiToBytes(string), buf, offset, length) } function latin1Write (buf, string, offset, length) { return asciiWrite(buf, string, offset, length) } function base64Write (buf, string, offset, length) { return blitBuffer(base64ToBytes(string), buf, offset, length) } function ucs2Write (buf, string, offset, length) { return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } Buffer.prototype.write = function write (string, offset, length, encoding) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8' length = this.length offset = 0 // Buffer#write(string, encoding) } else if (length === undefined && typeof offset === 'string') { encoding = offset length = this.length offset = 0 // Buffer#write(string, offset[, length][, encoding]) } else if (isFinite(offset)) { offset = offset | 0 if (isFinite(length)) { length = length | 0 if (encoding === undefined) encoding = 'utf8' } else { encoding = length length = undefined } // legacy write(string, encoding, offset, length) - remove in v0.13 } else { throw new Error( 'Buffer.write(string, encoding, offset[, length]) is no longer supported' ) } var remaining = this.length - offset if (length === undefined || length > remaining) length = remaining if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { throw new RangeError('Attempt to write outside buffer bounds') } if (!encoding) encoding = 'utf8' var loweredCase = false for (;;) { switch (encoding) { case 'hex': return hexWrite(this, string, offset, length) case 'utf8': case 'utf-8': return utf8Write(this, string, offset, length) case 'ascii': return asciiWrite(this, string, offset, length) case 'latin1': case 'binary': return latin1Write(this, string, offset, length) case 'base64': // Warning: maxLength not taken into account in base64Write return base64Write(this, string, offset, length) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return ucs2Write(this, string, offset, length) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.prototype.toJSON = function toJSON () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) } } function base64Slice (buf, start, end) { if (start === 0 && end === buf.length) { return base64.fromByteArray(buf) } else { return base64.fromByteArray(buf.slice(start, end)) } } function utf8Slice (buf, start, end) { end = Math.min(buf.length, end) var res = [] var i = start while (i < end) { var firstByte = buf[i] var codePoint = null var bytesPerSequence = (firstByte > 0xEF) ? 4 : (firstByte > 0xDF) ? 3 : (firstByte > 0xBF) ? 2 : 1 if (i + bytesPerSequence <= end) { var secondByte, thirdByte, fourthByte, tempCodePoint switch (bytesPerSequence) { case 1: if (firstByte < 0x80) { codePoint = firstByte } break case 2: secondByte = buf[i + 1] if ((secondByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) if (tempCodePoint > 0x7F) { codePoint = tempCodePoint } } break case 3: secondByte = buf[i + 1] thirdByte = buf[i + 2] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { codePoint = tempCodePoint } } break case 4: secondByte = buf[i + 1] thirdByte = buf[i + 2] fourthByte = buf[i + 3] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { codePoint = tempCodePoint } } } } if (codePoint === null) { // we did not generate a valid codePoint so insert a // replacement char (U+FFFD) and advance only 1 byte codePoint = 0xFFFD bytesPerSequence = 1 } else if (codePoint > 0xFFFF) { // encode to utf16 (surrogate pair dance) codePoint -= 0x10000 res.push(codePoint >>> 10 & 0x3FF | 0xD800) codePoint = 0xDC00 | codePoint & 0x3FF } res.push(codePoint) i += bytesPerSequence } return decodeCodePointsArray(res) } // Based on http://stackoverflow.com/a/22747272/680742, the browser with // the lowest limit is Chrome, with 0x10000 args. // We go 1 magnitude less, for safety var MAX_ARGUMENTS_LENGTH = 0x1000 function decodeCodePointsArray (codePoints) { var len = codePoints.length if (len <= MAX_ARGUMENTS_LENGTH) { return String.fromCharCode.apply(String, codePoints) // avoid extra slice() } // Decode in chunks to avoid "call stack size exceeded". var res = '' var i = 0 while (i < len) { res += String.fromCharCode.apply( String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) ) } return res } function asciiSlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i] & 0x7F) } return ret } function latin1Slice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i]) } return ret } function hexSlice (buf, start, end) { var len = buf.length if (!start || start < 0) start = 0 if (!end || end < 0 || end > len) end = len var out = '' for (var i = start; i < end; ++i) { out += toHex(buf[i]) } return out } function utf16leSlice (buf, start, end) { var bytes = buf.slice(start, end) var res = '' for (var i = 0; i < bytes.length; i += 2) { res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) } return res } Buffer.prototype.slice = function slice (start, end) { var len = this.length start = ~~start end = end === undefined ? len : ~~end if (start < 0) { start += len if (start < 0) start = 0 } else if (start > len) { start = len } if (end < 0) { end += len if (end < 0) end = 0 } else if (end > len) { end = len } if (end < start) end = start var newBuf if (Buffer.TYPED_ARRAY_SUPPORT) { newBuf = this.subarray(start, end) newBuf.__proto__ = Buffer.prototype } else { var sliceLen = end - start newBuf = new Buffer(sliceLen, undefined) for (var i = 0; i < sliceLen; ++i) { newBuf[i] = this[i + start] } } return newBuf } /* * Need to make sure that buffer isn't trying to write out of bounds. */ function checkOffset (offset, ext, length) { if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } return val } Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) { checkOffset(offset, byteLength, this.length) } var val = this[offset + --byteLength] var mul = 1 while (byteLength > 0 && (mul *= 0x100)) { val += this[offset + --byteLength] * mul } return val } Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length) return this[offset] } Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) return this[offset] | (this[offset + 1] << 8) } Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) return (this[offset] << 8) | this[offset + 1] } Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ((this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16)) + (this[offset + 3] * 0x1000000) } Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] * 0x1000000) + ((this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3]) } Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var i = byteLength var mul = 1 var val = this[offset + --i] while (i > 0 && (mul *= 0x100)) { val += this[offset + --i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length) if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) } Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset] | (this[offset + 1] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset + 1] | (this[offset] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16) | (this[offset + 3] << 24) } Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] << 24) | (this[offset + 1] << 16) | (this[offset + 2] << 8) | (this[offset + 3]) } Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, true, 23, 4) } Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, false, 23, 4) } Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, true, 52, 8) } Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, false, 52, 8) } function checkInt (buf, value, offset, ext, max, min) { if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') if (offset + ext > buf.length) throw new RangeError('Index out of range') } Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1 checkInt(this, value, offset, byteLength, maxBytes, 0) } var mul = 1 var i = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1 checkInt(this, value, offset, byteLength, maxBytes, 0) } var i = byteLength - 1 var mul = 1 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) this[offset] = (value & 0xff) return offset + 1 } function objectWriteUInt16 (buf, value, offset, littleEndian) { if (value < 0) value = 0xffff + value + 1 for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> (littleEndian ? i : 1 - i) * 8 } } Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) } else { objectWriteUInt16(this, value, offset, true) } return offset + 2 } Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) } else { objectWriteUInt16(this, value, offset, false) } return offset + 2 } function objectWriteUInt32 (buf, value, offset, littleEndian) { if (value < 0) value = 0xffffffff + value + 1 for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff } } Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset + 3] = (value >>> 24) this[offset + 2] = (value >>> 16) this[offset + 1] = (value >>> 8) this[offset] = (value & 0xff) } else { objectWriteUInt32(this, value, offset, true) } return offset + 4 } Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) } else { objectWriteUInt32(this, value, offset, false) } return offset + 4 } Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = 0 var mul = 1 var sub = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { sub = 1 } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = byteLength - 1 var mul = 1 var sub = 0 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { sub = 1 } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) if (value < 0) value = 0xff + value + 1 this[offset] = (value & 0xff) return offset + 1 } Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) } else { objectWriteUInt16(this, value, offset, true) } return offset + 2 } Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) } else { objectWriteUInt16(this, value, offset, false) } return offset + 2 } Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) this[offset + 2] = (value >>> 16) this[offset + 3] = (value >>> 24) } else { objectWriteUInt32(this, value, offset, true) } return offset + 4 } Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (value < 0) value = 0xffffffff + value + 1 if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) } else { objectWriteUInt32(this, value, offset, false) } return offset + 4 } function checkIEEE754 (buf, value, offset, ext, max, min) { if (offset + ext > buf.length) throw new RangeError('Index out of range') if (offset < 0) throw new RangeError('Index out of range') } function writeFloat (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) } ieee754.write(buf, value, offset, littleEndian, 23, 4) return offset + 4 } Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert) } Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert) } function writeDouble (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) } ieee754.write(buf, value, offset, littleEndian, 52, 8) return offset + 8 } Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) } Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) } // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy = function copy (target, targetStart, start, end) { if (!start) start = 0 if (!end && end !== 0) end = this.length if (targetStart >= target.length) targetStart = target.length if (!targetStart) targetStart = 0 if (end > 0 && end < start) end = start // Copy 0 bytes; we're done if (end === start) return 0 if (target.length === 0 || this.length === 0) return 0 // Fatal error conditions if (targetStart < 0) { throw new RangeError('targetStart out of bounds') } if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') if (end < 0) throw new RangeError('sourceEnd out of bounds') // Are we oob? if (end > this.length) end = this.length if (target.length - targetStart < end - start) { end = target.length - targetStart + start } var len = end - start var i if (this === target && start < targetStart && targetStart < end) { // descending copy from end for (i = len - 1; i >= 0; --i) { target[i + targetStart] = this[i + start] } } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { // ascending copy from start for (i = 0; i < len; ++i) { target[i + targetStart] = this[i + start] } } else { Uint8Array.prototype.set.call( target, this.subarray(start, start + len), targetStart ) } return len } // Usage: // buffer.fill(number[, offset[, end]]) // buffer.fill(buffer[, offset[, end]]) // buffer.fill(string[, offset[, end]][, encoding]) Buffer.prototype.fill = function fill (val, start, end, encoding) { // Handle string cases: if (typeof val === 'string') { if (typeof start === 'string') { encoding = start start = 0 end = this.length } else if (typeof end === 'string') { encoding = end end = this.length } if (val.length === 1) { var code = val.charCodeAt(0) if (code < 256) { val = code } } if (encoding !== undefined && typeof encoding !== 'string') { throw new TypeError('encoding must be a string') } if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding) } } else if (typeof val === 'number') { val = val & 255 } // Invalid ranges are not set to a default, so can range check early. if (start < 0 || this.length < start || this.length < end) { throw new RangeError('Out of range index') } if (end <= start) { return this } start = start >>> 0 end = end === undefined ? this.length : end >>> 0 if (!val) val = 0 var i if (typeof val === 'number') { for (i = start; i < end; ++i) { this[i] = val } } else { var bytes = Buffer.isBuffer(val) ? val : utf8ToBytes(new Buffer(val, encoding).toString()) var len = bytes.length for (i = 0; i < end - start; ++i) { this[i + start] = bytes[i % len] } } return this } // HELPER FUNCTIONS // ================ var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g function base64clean (str) { // Node strips out invalid characters like \n and \t from the string, base64-js does not str = stringtrim(str).replace(INVALID_BASE64_RE, '') // Node converts strings with length < 2 to '' if (str.length < 2) return '' // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not while (str.length % 4 !== 0) { str = str + '=' } return str } function stringtrim (str) { if (str.trim) return str.trim() return str.replace(/^\s+|\s+$/g, '') } function toHex (n) { if (n < 16) return '0' + n.toString(16) return n.toString(16) } function utf8ToBytes (string, units) { units = units || Infinity var codePoint var length = string.length var leadSurrogate = null var bytes = [] for (var i = 0; i < length; ++i) { codePoint = string.charCodeAt(i) // is surrogate component if (codePoint > 0xD7FF && codePoint < 0xE000) { // last char was a lead if (!leadSurrogate) { // no lead yet if (codePoint > 0xDBFF) { // unexpected trail if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } else if (i + 1 === length) { // unpaired lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } // valid lead leadSurrogate = codePoint continue } // 2 leads in a row if (codePoint < 0xDC00) { if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) leadSurrogate = codePoint continue } // valid surrogate pair codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 } else if (leadSurrogate) { // valid bmp char, but last char was a lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) } leadSurrogate = null // encode utf8 if (codePoint < 0x80) { if ((units -= 1) < 0) break bytes.push(codePoint) } else if (codePoint < 0x800) { if ((units -= 2) < 0) break bytes.push( codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x10000) { if ((units -= 3) < 0) break bytes.push( codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x110000) { if ((units -= 4) < 0) break bytes.push( codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else { throw new Error('Invalid code point') } } return bytes } function asciiToBytes (str) { var byteArray = [] for (var i = 0; i < str.length; ++i) { // Node's code seems to be doing this and not & 0x7F.. byteArray.push(str.charCodeAt(i) & 0xFF) } return byteArray } function utf16leToBytes (str, units) { var c, hi, lo var byteArray = [] for (var i = 0; i < str.length; ++i) { if ((units -= 2) < 0) break c = str.charCodeAt(i) hi = c >> 8 lo = c % 256 byteArray.push(lo) byteArray.push(hi) } return byteArray } function base64ToBytes (str) { return base64.toByteArray(base64clean(str)) } function blitBuffer (src, dst, offset, length) { for (var i = 0; i < length; ++i) { if ((i + offset >= dst.length) || (i >= src.length)) break dst[i + offset] = src[i] } return i } function isnan (val) { return val !== val // eslint-disable-line no-self-compare } /***/ }), /***/ "./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[6].oneOf[1].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[6].oneOf[1].use[2]!./node_modules/grapesjs/dist/css/grapes.min.css": /*!*****************************************************************************************************************************************************************************************************************!*\ !*** ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[6].oneOf[1].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[6].oneOf[1].use[2]!./node_modules/grapesjs/dist/css/grapes.min.css ***! \*****************************************************************************************************************************************************************************************************************/ /***/ ((module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../../css-loader/dist/runtime/api.js */ "./node_modules/css-loader/dist/runtime/api.js"); /* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_0__); // Imports var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_0___default()(function(i){return i[1]}); // Module ___CSS_LOADER_EXPORT___.push([module.id, ".CodeMirror{font-family:monospace;height:300px;color:black;direction:ltr}.CodeMirror-lines{padding:4px 0}.CodeMirror pre.CodeMirror-line,.CodeMirror pre.CodeMirror-line-like{padding:0 4px}.CodeMirror-scrollbar-filler,.CodeMirror-gutter-filler{background-color:white}.CodeMirror-gutters{border-right:1px solid #ddd;background-color:#f7f7f7;white-space:nowrap}.CodeMirror-linenumber{padding:0 3px 0 5px;min-width:20px;text-align:right;color:#999;white-space:nowrap}.CodeMirror-guttermarker{color:black}.CodeMirror-guttermarker-subtle{color:#999}.CodeMirror-cursor{border-left:1px solid black;border-right:none;width:0}.CodeMirror div.CodeMirror-secondarycursor{border-left:1px solid silver}.cm-fat-cursor .CodeMirror-cursor{width:auto;border:0 !important;background:#7e7}.cm-fat-cursor div.CodeMirror-cursors{z-index:1}.cm-fat-cursor .CodeMirror-line::-moz-selection, .cm-fat-cursor .CodeMirror-line>span::-moz-selection, .cm-fat-cursor .CodeMirror-line>span>span::-moz-selection{background:transparent}.cm-fat-cursor .CodeMirror-line::selection,.cm-fat-cursor .CodeMirror-line>span::selection,.cm-fat-cursor .CodeMirror-line>span>span::selection{background:transparent}.cm-fat-cursor .CodeMirror-line::-moz-selection,.cm-fat-cursor .CodeMirror-line>span::-moz-selection,.cm-fat-cursor .CodeMirror-line>span>span::-moz-selection{background:transparent}.cm-fat-cursor{caret-color:transparent}@keyframes blink{50%{background-color:transparent}}.cm-tab{display:inline-block;text-decoration:inherit}.CodeMirror-rulers{position:absolute;left:0;right:0;top:-50px;bottom:0;overflow:hidden}.CodeMirror-ruler{border-left:1px solid #ccc;top:0;bottom:0;position:absolute}.cm-s-default .cm-header{color:blue}.cm-s-default .cm-quote{color:#090}.cm-negative{color:#d44}.cm-positive{color:#292}.cm-header,.cm-strong{font-weight:bold}.cm-em{font-style:italic}.cm-link{text-decoration:underline}.cm-strikethrough{text-decoration:line-through}.cm-s-default .cm-keyword{color:#708}.cm-s-default .cm-atom{color:#219}.cm-s-default .cm-number{color:#164}.cm-s-default .cm-def{color:blue}.cm-s-default .cm-variable-2{color:#05a}.cm-s-default .cm-variable-3,.cm-s-default .cm-type{color:#085}.cm-s-default .cm-comment{color:#a50}.cm-s-default .cm-string{color:#a11}.cm-s-default .cm-string-2{color:#f50}.cm-s-default .cm-meta{color:#555}.cm-s-default .cm-qualifier{color:#555}.cm-s-default .cm-builtin{color:#30a}.cm-s-default .cm-bracket{color:#997}.cm-s-default .cm-tag{color:#170}.cm-s-default .cm-attribute{color:#00c}.cm-s-default .cm-hr{color:#999}.cm-s-default .cm-link{color:#00c}.cm-s-default .cm-error{color:red}.cm-invalidchar{color:red}.CodeMirror-composing{border-bottom:2px solid}div.CodeMirror span.CodeMirror-matchingbracket{color:#0b0}div.CodeMirror span.CodeMirror-nonmatchingbracket{color:#a22}.CodeMirror-matchingtag{background:rgba(255, 150, 0, 0.3)}.CodeMirror-activeline-background{background:#e8f2ff}.CodeMirror{position:relative;overflow:hidden;background:white}.CodeMirror-scroll{overflow:scroll !important;margin-bottom:-50px;margin-right:-50px;padding-bottom:50px;height:100%;outline:none;position:relative;z-index:0}.CodeMirror-sizer{position:relative;border-right:50px solid transparent}.CodeMirror-vscrollbar,.CodeMirror-hscrollbar,.CodeMirror-scrollbar-filler,.CodeMirror-gutter-filler{position:absolute;z-index:6;display:none;outline:none}.CodeMirror-vscrollbar{right:0;top:0;overflow-x:hidden;overflow-y:scroll}.CodeMirror-hscrollbar{bottom:0;left:0;overflow-y:hidden;overflow-x:scroll}.CodeMirror-scrollbar-filler{right:0;bottom:0}.CodeMirror-gutter-filler{left:0;bottom:0}.CodeMirror-gutters{position:absolute;left:0;top:0;min-height:100%;z-index:3}.CodeMirror-gutter{white-space:normal;height:100%;display:inline-block;vertical-align:top;margin-bottom:-50px}.CodeMirror-gutter-wrapper{position:absolute;z-index:4;background:none !important;border:none !important}.CodeMirror-gutter-background{position:absolute;top:0;bottom:0;z-index:4}.CodeMirror-gutter-elt{position:absolute;cursor:default;z-index:4}.CodeMirror-gutter-wrapper ::-moz-selection{background-color:transparent}.CodeMirror-gutter-wrapper ::selection{background-color:transparent}.CodeMirror-gutter-wrapper ::-moz-selection{background-color:transparent}.CodeMirror-lines{cursor:text;min-height:1px}.CodeMirror pre.CodeMirror-line,.CodeMirror pre.CodeMirror-line-like{border-radius:0;border-width:0;background:transparent;font-family:inherit;font-size:inherit;margin:0;white-space:pre;word-wrap:normal;line-height:inherit;color:inherit;z-index:2;position:relative;overflow:visible;-webkit-tap-highlight-color:transparent;font-variant-ligatures:contextual}.CodeMirror-wrap pre.CodeMirror-line,.CodeMirror-wrap pre.CodeMirror-line-like{word-wrap:break-word;white-space:pre-wrap;word-break:normal}.CodeMirror-linebackground{position:absolute;left:0;right:0;top:0;bottom:0;z-index:0}.CodeMirror-linewidget{position:relative;z-index:2;padding:.1px}.CodeMirror-rtl pre{direction:rtl}.CodeMirror-code{outline:none}.CodeMirror-scroll,.CodeMirror-sizer,.CodeMirror-gutter,.CodeMirror-gutters,.CodeMirror-linenumber{box-sizing:content-box}.CodeMirror-measure{position:absolute;width:100%;height:0;overflow:hidden;visibility:hidden}.CodeMirror-cursor{position:absolute;pointer-events:none}.CodeMirror-measure pre{position:static}div.CodeMirror-cursors{visibility:hidden;position:relative;z-index:3}div.CodeMirror-dragcursors{visibility:visible}.CodeMirror-focused div.CodeMirror-cursors{visibility:visible}.CodeMirror-selected{background:#d9d9d9}.CodeMirror-focused .CodeMirror-selected{background:#d7d4f0}.CodeMirror-crosshair{cursor:crosshair}.CodeMirror-line::-moz-selection, .CodeMirror-line>span::-moz-selection, .CodeMirror-line>span>span::-moz-selection{background:#d7d4f0}.CodeMirror-line::selection,.CodeMirror-line>span::selection,.CodeMirror-line>span>span::selection{background:#d7d4f0}.CodeMirror-line::-moz-selection,.CodeMirror-line>span::-moz-selection,.CodeMirror-line>span>span::-moz-selection{background:#d7d4f0}.cm-searching{background-color:#ffa;background-color:rgba(255, 255, 0, 0.4)}.cm-force-border{padding-right:.1px}@media print{.CodeMirror div.CodeMirror-cursors{visibility:hidden}}.cm-tab-wrap-hack:after{content:\"\"}span.CodeMirror-selectedtext{background:none}.cm-s-hopscotch.CodeMirror{background:#322931;color:#d5d3d5}.cm-s-hopscotch div.CodeMirror-selected{background:#433b42 !important}.cm-s-hopscotch .CodeMirror-gutters{background:#322931;border-right:0px}.cm-s-hopscotch .CodeMirror-linenumber{color:#797379}.cm-s-hopscotch .CodeMirror-cursor{border-left:1px solid #989498 !important}.cm-s-hopscotch span.cm-comment{color:#b33508}.cm-s-hopscotch span.cm-atom{color:#c85e7c}.cm-s-hopscotch span.cm-number{color:#c85e7c}.cm-s-hopscotch span.cm-property,.cm-s-hopscotch span.cm-attribute{color:#8fc13e}.cm-s-hopscotch span.cm-keyword{color:#dd464c}.cm-s-hopscotch span.cm-string{color:#fdcc59}.cm-s-hopscotch span.cm-variable{color:#8fc13e}.cm-s-hopscotch span.cm-variable-2{color:#1290bf}.cm-s-hopscotch span.cm-def{color:#fd8b19}.cm-s-hopscotch span.cm-error{background:#dd464c;color:#989498}.cm-s-hopscotch span.cm-bracket{color:#d5d3d5}.cm-s-hopscotch span.cm-tag{color:#dd464c}.cm-s-hopscotch span.cm-link{color:#c85e7c}.cm-s-hopscotch .CodeMirror-matchingbracket{text-decoration:underline;color:white !important}.cm-s-hopscotch .CodeMirror-activeline-background{background:#302020}.sp-container{position:absolute;top:0;left:0;display:inline-block;z-index:9999994;overflow:hidden}.sp-container.sp-flat{position:relative}.sp-container,.sp-container *{box-sizing:content-box}.sp-top{position:relative;width:100%;display:inline-block}.sp-top-inner{position:absolute;top:0;left:0;bottom:0;right:0}.sp-color{position:absolute;top:0;left:0;bottom:0;right:20%}.sp-hue{position:absolute;top:0;right:0;bottom:0;left:84%;height:100%}.sp-clear-enabled .sp-hue{top:33px;height:77.5%}.sp-fill{padding-top:80%}.sp-sat,.sp-val{position:absolute;top:0;left:0;right:0;bottom:0}.sp-alpha-enabled .sp-top{margin-bottom:18px}.sp-alpha-enabled .sp-alpha{display:block}.sp-alpha-handle{position:absolute;top:-4px;bottom:-4px;width:6px;left:50%;cursor:pointer;border:1px solid #000;background:#fff;opacity:.8}.sp-alpha{display:none;position:absolute;bottom:-14px;right:0;left:0;height:8px}.sp-alpha-inner{border:solid 1px #333}.sp-clear{display:none}.sp-clear.sp-clear-display{background-position:center}.sp-clear-enabled .sp-clear{display:block;position:absolute;top:0px;right:0;bottom:0;left:84%;height:28px}.sp-container,.sp-replacer,.sp-preview,.sp-dragger,.sp-slider,.sp-alpha,.sp-clear,.sp-alpha-handle,.sp-container.sp-dragging .sp-input,.sp-container button{-webkit-user-select:none;-moz-user-select:-moz-none;-o-user-select:none;user-select:none}.sp-container.sp-input-disabled .sp-input-container{display:none}.sp-container.sp-buttons-disabled .sp-button-container{display:none}.sp-container.sp-palette-buttons-disabled .sp-palette-button-container{display:none}.sp-palette-only .sp-picker-container{display:none}.sp-palette-disabled .sp-palette-container{display:none}.sp-initial-disabled .sp-initial{display:none}.sp-sat{background-image:linear-gradient(to right, #fff, rgba(204, 154, 129, 0));-ms-filter:\"progid:DXImageTransform.Microsoft.gradient(GradientType = 1, startColorstr=#FFFFFFFF, endColorstr=#00CC9A81)\";filter:progid:DXImageTransform.Microsoft.gradient(GradientType = 1, startColorstr=\"#FFFFFFFF\", endColorstr=\"#00CC9A81\")}.sp-val{background-image:linear-gradient(to top, #000, rgba(204, 154, 129, 0));-ms-filter:\"progid:DXImageTransform.Microsoft.gradient(startColorstr=#00CC9A81, endColorstr=#FF000000)\";filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=\"#00CC9A81\", endColorstr=\"#FF000000\")}.sp-hue{background:linear-gradient(to bottom, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%)}.sp-1{height:17%;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=\"#ff0000\", endColorstr=\"#ffff00\")}.sp-2{height:16%;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=\"#ffff00\", endColorstr=\"#00ff00\")}.sp-3{height:17%;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=\"#00ff00\", endColorstr=\"#00ffff\")}.sp-4{height:17%;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=\"#00ffff\", endColorstr=\"#0000ff\")}.sp-5{height:16%;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=\"#0000ff\", endColorstr=\"#ff00ff\")}.sp-6{height:17%;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=\"#ff00ff\", endColorstr=\"#ff0000\")}.sp-hidden{display:none !important}.sp-cf:before,.sp-cf:after{content:\"\";display:table}.sp-cf:after{clear:both}@media(max-device-width: 480px){.sp-color{right:40%}.sp-hue{left:63%}.sp-fill{padding-top:60%}}.sp-dragger{border-radius:5px;height:5px;width:5px;border:1px solid #fff;background:#000;cursor:pointer;position:absolute;top:0;left:0}.sp-slider{position:absolute;top:0;cursor:pointer;height:3px;left:-1px;right:-1px;border:1px solid #000;background:#fff;opacity:.8}.sp-container{border-radius:0;background-color:#ececec;border:solid 1px #f0c49b;padding:0}.sp-container,.sp-container button,.sp-container input,.sp-color,.sp-hue,.sp-clear{font:normal 12px \"Lucida Grande\",\"Lucida Sans Unicode\",\"Lucida Sans\",Geneva,Verdana,sans-serif;-ms-box-sizing:border-box;box-sizing:border-box}.sp-top{margin-bottom:3px}.sp-color,.sp-hue,.sp-clear{border:solid 1px #666}.sp-input-container{float:right;width:100px;margin-bottom:4px}.sp-initial-disabled .sp-input-container{width:100%}.sp-input{font-size:12px !important;border:1px inset;padding:4px 5px;margin:0;width:100%;background:rgba(0,0,0,0);border-radius:3px;color:#222}.sp-input:focus{border:1px solid orange}.sp-input.sp-validation-error{border:1px solid red;background:#fdd}.sp-picker-container,.sp-palette-container{float:left;position:relative;padding:10px;padding-bottom:300px;margin-bottom:-290px}.sp-picker-container{width:172px;border-left:solid 1px #fff}.sp-palette-container{border-right:solid 1px #ccc}.sp-palette-only .sp-palette-container{border:0}.sp-palette .sp-thumb-el{display:block;position:relative;float:left;width:24px;height:15px;margin:3px;cursor:pointer;border:solid 2px rgba(0,0,0,0)}.sp-palette .sp-thumb-el:hover,.sp-palette .sp-thumb-el.sp-thumb-active{border-color:orange}.sp-thumb-el{position:relative}.sp-initial{float:left;border:solid 1px #333}.sp-initial span{width:30px;height:25px;border:none;display:block;float:left;margin:0}.sp-initial .sp-clear-display{background-position:center}.sp-palette-button-container,.sp-button-container{float:right}.sp-replacer{margin:0;overflow:hidden;cursor:pointer;padding:4px;display:inline-block;border:solid 1px #91765d;background:#eee;color:#333;vertical-align:middle}.sp-replacer:hover,.sp-replacer.sp-active{border-color:#f0c49b;color:#111}.sp-replacer.sp-disabled{cursor:default;border-color:silver;color:silver}.sp-dd{padding:2px 0;height:16px;line-height:16px;float:left;font-size:10px}.sp-preview{position:relative;width:25px;height:20px;border:solid 1px #222;margin-right:5px;float:left;z-index:0}.sp-palette{max-width:220px}.sp-palette .sp-thumb-el{width:16px;height:16px;margin:2px 1px;border:solid 1px #d0d0d0}.sp-container{padding-bottom:0}.sp-container button{background-color:#eee;background-image:linear-gradient(to bottom, #eeeeee, #cccccc);border:1px solid #ccc;border-bottom:1px solid #bbb;border-radius:3px;color:#333;font-size:14px;line-height:1;padding:5px 4px;text-align:center;text-shadow:0 1px 0 #eee;vertical-align:middle}.sp-container button:hover{background-color:#ddd;background-image:linear-gradient(to bottom, #dddddd, #bbbbbb);border:1px solid #bbb;border-bottom:1px solid #999;cursor:pointer;text-shadow:0 1px 0 #ddd}.sp-container button:active{border:1px solid #aaa;border-bottom:1px solid #888;-ms-box-shadow:inset 0 0 5px 2px #aaa,0 1px 0 0 #eee;-o-box-shadow:inset 0 0 5px 2px #aaa,0 1px 0 0 #eee;box-shadow:inset 0 0 5px 2px #aaa,0 1px 0 0 #eee}.sp-cancel{font-size:11px;color:#d93f3f !important;margin:0;padding:2px;margin-right:5px;vertical-align:middle;text-decoration:none}.sp-cancel:hover{color:#d93f3f !important;text-decoration:underline}.sp-palette span:hover,.sp-palette span.sp-thumb-active{border-color:#000}.sp-preview,.sp-alpha,.sp-thumb-el{position:relative;background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAIAAADZF8uwAAAAGUlEQVQYV2M4gwH+YwCGIasIUwhT25BVBADtzYNYrHvv4gAAAABJRU5ErkJggg==)}.sp-preview-inner,.sp-alpha-inner,.sp-thumb-inner{display:block;position:absolute;top:0;left:0;bottom:0;right:0}.sp-palette .sp-thumb-inner{background-position:50% 50%;background-repeat:no-repeat}.sp-palette .sp-thumb-light.sp-thumb-active .sp-thumb-inner{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAASCAYAAABWzo5XAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAIVJREFUeNpiYBhsgJFMffxAXABlN5JruT4Q3wfi/0DsT64h8UD8HmpIPCWG/KemIfOJCUB+Aoacx6EGBZyHBqI+WsDCwuQ9mhxeg2A210Ntfo8klk9sOMijaURm7yc1UP2RNCMbKE9ODK1HM6iegYLkfx8pligC9lCD7KmRof0ZhjQACDAAceovrtpVBRkAAAAASUVORK5CYII=)}.sp-palette .sp-thumb-dark.sp-thumb-active .sp-thumb-inner{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAASCAYAAABWzo5XAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAadEVYdFNvZnR3YXJlAFBhaW50Lk5FVCB2My41LjEwMPRyoQAAAMdJREFUOE+tkgsNwzAMRMugEAahEAahEAZhEAqlEAZhEAohEAYh81X2dIm8fKpEspLGvudPOsUYpxE2BIJCroJmEW9qJ+MKaBFhEMNabSy9oIcIPwrB+afvAUFoK4H0tMaQ3XtlrggDhOVVMuT4E5MMG0FBbCEYzjYT7OxLEvIHQLY2zWwQ3D+9luyOQTfKDiFD3iUIfPk8VqrKjgAiSfGFPecrg6HN6m/iBcwiDAo7WiBeawa+Kwh7tZoSCGLMqwlSAzVDhoK+6vH4G0P5wdkAAAAASUVORK5CYII=)}.sp-clear-display{background-repeat:no-repeat;background-position:center;background-image:url(data:image/gif;base64,R0lGODlhFAAUAPcAAAAAAJmZmZ2dnZ6enqKioqOjo6SkpKWlpaampqenp6ioqKmpqaqqqqurq/Hx8fLy8vT09PX19ff39/j4+Pn5+fr6+vv7+wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAP8ALAAAAAAUABQAAAihAP9FoPCvoMGDBy08+EdhQAIJCCMybCDAAYUEARBAlFiQQoMABQhKUJBxY0SPICEYHBnggEmDKAuoPMjS5cGYMxHW3IiT478JJA8M/CjTZ0GgLRekNGpwAsYABHIypcAgQMsITDtWJYBR6NSqMico9cqR6tKfY7GeBCuVwlipDNmefAtTrkSzB1RaIAoXodsABiZAEFB06gIBWC1mLVgBa0AAOw==)}.gjs-is__grab,.gjs-is__grab *{cursor:grab !important}.gjs-is__grabbing,.gjs-is__grabbing *{-moz-user-select:none;-webkit-user-select:none;-o-user-select:none;user-select:none;cursor:grabbing !important}.gjs-one-bg{background-color:#444}.gjs-one-color{color:#444}.gjs-one-color-h:hover{color:#444}.gjs-two-bg{background-color:#ddd}.gjs-two-color{color:#ddd}.gjs-two-color-h:hover{color:#ddd}.gjs-three-bg{background-color:#804f7b}.gjs-three-color{color:#804f7b}.gjs-three-color-h:hover{color:#804f7b}.gjs-four-bg{background-color:#d278c9}.gjs-four-color{color:#d278c9}.gjs-four-color-h:hover{color:#d278c9}.gjs-danger-bg{background-color:#dd3636}.gjs-danger-color{color:#dd3636}.gjs-danger-color-h:hover{color:#dd3636}.gjs-bg-main,.gjs-sm-colorp-c,.gjs-off-prv{background-color:#444}.gjs-color-main,.gjs-sm-stack #gjs-sm-add,.gjs-off-prv{color:#ddd;fill:#ddd}.gjs-color-active{color:#f8f8f8;fill:#f8f8f8}.gjs-color-warn{color:#ffca6f;fill:#ffca6f}.gjs-color-hl{color:#71b7f1;fill:#71b7f1}.gjs-invis-invis,.gjs-clm-tags #gjs-clm-new,.gjs-no-app{background-color:rgba(0,0,0,0);border:none;color:inherit}.gjs-no-app{height:10px}.gjs-test::btn{color:\"#fff\"}.opac50{opacity:.5;filter:alpha(opacity=50)}.gjs-checker-bg,.gjs-field-colorp-c,.checker-bg,.gjs-sm-layer-preview{background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAIAAADZF8uwAAAAGUlEQVQYV2M4gwH+YwCGIasIUwhT25BVBADtzYNYrHvv4gAAAABJRU5ErkJggg==\")}.gjs-no-user-select,.gjs-rte-toolbar,.gjs-layer-name,.gjs-grabbing,.gjs-grabbing *{-moz-user-select:none;-webkit-user-select:none;-o-user-select:none;user-select:none}.gjs-no-pointer-events,.gjs-margin-v-el,.gjs-padding-v-el,.gjs-fixedmargin-v-el,.gjs-fixedpadding-v-el,.gjs-resizer-c{pointer-events:none}.gjs-bdrag{pointer-events:none !important;position:absolute !important;z-index:10 !important;width:auto}.gjs-drag-helper{background-color:#3b97e3 !important;pointer-events:none !important;position:absolute !important;z-index:10 !important;transform:scale(0.3) !important;transform-origin:top left !important;-webkit-transform-origin:top left !important;margin:15px !important;transition:none !important;outline:none !important}.gjs-grabbing,.gjs-grabbing *{cursor:grabbing !important;cursor:-webkit-grabbing !important}.gjs-grabbing{overflow:hidden}.gjs-off-prv{position:relative;z-index:10;padding:5px;cursor:pointer}.gjs-editor-cont ::-webkit-scrollbar-track{background:rgba(0,0,0,.1)}.gjs-editor-cont ::-webkit-scrollbar-thumb{background-color:rgba(255,255,255,.2)}.gjs-editor-cont ::-webkit-scrollbar{width:8px}.clear{clear:both}.no-select,.gjs-clm-tags #gjs-clm-close,.gjs-category-title,.gjs-layer-title,.gjs-block-category .gjs-title,.gjs-sm-sector-title,.gjs-com-no-select,.gjs-com-no-select img{-moz-user-select:none;-webkit-user-select:none;-o-user-select:none;user-select:none}.gjs-no-touch-actions{touch-action:none}.gjs-disabled{-moz-user-select:none;-webkit-user-select:none;-o-user-select:none;user-select:none;opacity:.5;filter:alpha(opacity=50)}.gjs-editor{font-family:Helvetica,sans-serif;font-size:.75rem;position:relative;box-sizing:border-box;height:100%}.gjs-freezed,.gjs-freezed{opacity:.5;filter:alpha(opacity=50);pointer-events:none}.gjs-traits-label{border-bottom:1px solid rgba(0,0,0,.2);font-weight:lighter;margin-bottom:5px;padding:10px;text-align:left}.gjs-label-wrp{width:30%;min-width:30%}.gjs-field-wrp{flex-grow:1}.gjs-trt-header{font-weight:lighter;padding:10px}.gjs-trt-trait{display:flex;justify-content:flex-start;padding:5px 10px;font-weight:lighter;align-items:center;text-align:left}.gjs-trt-traits{font-size:.75rem}.gjs-trt-trait .gjs-label{text-align:left;text-overflow:ellipsis;overflow:hidden}.gjs-guide-info{position:absolute}.gjs-guide-info__content{position:absolute;height:100%;display:flex;width:100%;padding:5px}.gjs-guide-info__line{position:relative;margin:auto}.gjs-guide-info__line::before,.gjs-guide-info__line::after{content:\"\";display:block;position:absolute;background-color:inherit}.gjs-guide-info__y{padding:0 5px}.gjs-guide-info__y .gjs-guide-info__content{justify-content:center}.gjs-guide-info__y .gjs-guide-info__line{width:100%;height:1px}.gjs-guide-info__y .gjs-guide-info__line::before,.gjs-guide-info__y .gjs-guide-info__line::after{width:1px;height:10px;top:0;bottom:0;left:0;margin:auto}.gjs-guide-info__y .gjs-guide-info__line::after{left:auto;right:0}.gjs-guide-info__x{padding:5px 0}.gjs-guide-info__x .gjs-guide-info__content{align-items:center}.gjs-guide-info__x .gjs-guide-info__line{height:100%;width:1px}.gjs-guide-info__x .gjs-guide-info__line::before,.gjs-guide-info__x .gjs-guide-info__line::after{width:10px;height:1px;left:0;right:0;top:0;margin:auto;transform:translateX(-50%)}.gjs-guide-info__x .gjs-guide-info__line::after{top:auto;bottom:0}.gjs-badge{white-space:nowrap}.gjs-badge__icon{vertical-align:middle;display:inline-block;width:15px;height:15px}.gjs-badge__icon svg{fill:currentColor}.gjs-badge__name{display:inline-block;vertical-align:middle}.gjs-frame-wrapper{position:absolute;width:100%;height:100%;left:0;right:0;margin:auto}.gjs-frame-wrapper--anim{transition:width .35s ease,height .35s ease}.gjs-frame-wrapper__top{transform:translateY(-100%) translateX(-50%);display:flex;padding:5px 0;position:absolute;width:100%;left:50%;top:0}.gjs-frame-wrapper__top-r{margin-left:auto}.gjs-frame-wrapper__left{position:absolute;left:0;transform:translateX(-100%) translateY(-50%);height:100%;top:50%}.gjs-frame-wrapper__bottom{position:absolute;bottom:0;transform:translateY(100%) translateX(-50%);width:100%;left:50%}.gjs-frame-wrapper__right{position:absolute;right:0;transform:translateX(100%) translateY(-50%);height:100%;top:50%}.gjs-frame-wrapper__icon{width:24px;cursor:pointer}.gjs-frame-wrapper__icon>svg{fill:currentColor}.gjs-padding-v-top,.gjs-fixedpadding-v-top{width:100%;top:0;left:0}.gjs-padding-v-right,.gjs-fixedpadding-v-right{right:0}.gjs-padding-v-bottom,.gjs-fixedpadding-v-bottom{width:100%;left:0;bottom:0}.gjs-padding-v-left,.gjs-fixedpadding-v-left{left:0}.gjs-cv-canvas{box-sizing:border-box;width:85%;height:calc(100% - 40px);bottom:0;overflow:hidden;z-index:1;position:absolute;left:0;top:40px}.gjs-cv-canvas-bg{background-color:rgba(0,0,0,.15)}.gjs-cv-canvas.gjs-cui{width:100%;height:100%;top:0}.gjs-cv-canvas.gjs-is__grab .gjs-cv-canvas__frames,.gjs-cv-canvas.gjs-is__grabbing .gjs-cv-canvas__frames{pointer-events:none}.gjs-cv-canvas__frames{position:absolute;top:0;left:0;width:100%;height:100%}.gjs-cv-canvas__spots{position:absolute;pointer-events:none;z-index:1}.gjs-cv-canvas .gjs-ghost{display:none;pointer-events:none;background-color:#5b5b5b;border:2px dashed #ccc;position:absolute;z-index:10;opacity:.55;filter:alpha(opacity=55)}.gjs-cv-canvas .gjs-highlighter,.gjs-cv-canvas .gjs-highlighter-sel{position:absolute;outline:1px solid #3b97e3;outline-offset:-1px;pointer-events:none;width:100%;height:100%}.gjs-cv-canvas .gjs-highlighter-warning{outline:3px solid #ffca6f}.gjs-cv-canvas .gjs-highlighter-sel{outline:2px solid #3b97e3;outline-offset:-2px}.gjs-cv-canvas #gjs-tools,.gjs-cv-canvas .gjs-tools{width:100%;height:100%;position:absolute;top:0;left:0;outline:none;z-index:1}.gjs-cv-canvas *{box-sizing:border-box}.gjs-frame{outline:medium none;height:100%;width:100%;border:none;margin:auto;display:block;transition:width .35s ease,height .35s ease;position:absolute;top:0;bottom:0;left:0;right:0}.gjs-toolbar{position:absolute;background-color:#3b97e3;white-space:nowrap;color:#fff;z-index:10;top:0;left:0}.gjs-toolbar-item{width:26px;padding:5px;cursor:pointer;display:inline-block}.gjs-toolbar-item svg{fill:currentColor;vertical-align:middle}.gjs-resizer-c{position:absolute;left:0;top:0;width:100%;height:100%;z-index:9}.gjs-margin-v-el,.gjs-padding-v-el,.gjs-fixedmargin-v-el,.gjs-fixedpadding-v-el{opacity:.1;filter:alpha(opacity=10);position:absolute;background-color:#ff0}.gjs-fixedmargin-v-el,.gjs-fixedpadding-v-el{opacity:.2;filter:alpha(opacity=20)}.gjs-padding-v-el,.gjs-fixedpadding-v-el{background-color:navy}.gjs-resizer-h{pointer-events:all;position:absolute;border:3px solid #3b97e3;width:10px;height:10px;background-color:#fff;margin:-5px}.gjs-resizer-h-tl{top:0;left:0;cursor:nwse-resize}.gjs-resizer-h-tr{top:0;right:0;cursor:nesw-resize}.gjs-resizer-h-tc{top:0;margin:-5px auto;left:0;right:0;cursor:ns-resize}.gjs-resizer-h-cl{left:0;margin:auto -5px;top:0;bottom:0;cursor:ew-resize}.gjs-resizer-h-cr{margin:auto -5px;top:0;bottom:0;right:0;cursor:ew-resize}.gjs-resizer-h-bl{bottom:0;left:0;cursor:nesw-resize}.gjs-resizer-h-bc{bottom:0;margin:-5px auto;left:0;right:0;cursor:ns-resize}.gjs-resizer-h-br{bottom:0;right:0;cursor:nwse-resize}.gjs-pn-panel .gjs-resizer-h{background-color:rgba(0,0,0,.2);border:none;opacity:0;transition:opacity .25s}.gjs-pn-panel .gjs-resizer-h:hover{opacity:1}.gjs-pn-panel .gjs-resizer-h-tc,.gjs-pn-panel .gjs-resizer-h-bc{margin:0 auto;width:100%}.gjs-pn-panel .gjs-resizer-h-cr,.gjs-pn-panel .gjs-resizer-h-cl{margin:auto 0;height:100%}.gjs-resizing .gjs-highlighter,.gjs-resizing .gjs-badge{display:none !important}.gjs-resizing-tl *{cursor:nwse-resize !important}.gjs-resizing-tr *{cursor:nesw-resize !important}.gjs-resizing-tc *{cursor:ns-resize !important}.gjs-resizing-cl *{cursor:ew-resize !important}.gjs-resizing-cr *{cursor:ew-resize !important}.gjs-resizing-bl *{cursor:nesw-resize !important}.gjs-resizing-bc *{cursor:ns-resize !important}.gjs-resizing-br *{cursor:nwse-resize !important}.btn-cl,.gjs-am-close,.gjs-mdl-btn-close{opacity:.3;filter:alpha(opacity=30);font-size:25px;cursor:pointer}.btn-cl:hover,.gjs-am-close:hover,.gjs-mdl-btn-close:hover{opacity:.7;filter:alpha(opacity=70)}.no-dots,.ui-resizable-handle{border:none !important;margin:0 !important;outline:none !important}.gjs-com-dashed *{outline:1px dashed #888;outline-offset:-2px;box-sizing:border-box}.gjs-com-badge,.gjs-badge{pointer-events:none;background-color:#3b97e3;color:#fff;padding:2px 5px;position:absolute;z-index:1;font-size:12px;outline:none;display:none}.gjs-badge-warning{background-color:#ffca6f}.gjs-placeholder,.gjs-com-placeholder,.gjs-placeholder{position:absolute;z-index:10;pointer-events:none;display:none}.gjs-placeholder,.gjs-placeholder{border-style:solid !important;outline:none;box-sizing:border-box;transition:top .2s,left .2s,width .2s,height .2s}.gjs-placeholder.horizontal,.gjs-com-placeholder.horizontal,.gjs-placeholder.horizontal{border-color:rgba(0,0,0,0) #62c462;border-width:3px 5px;margin:-3px 0 0}.gjs-placeholder.vertical,.gjs-com-placeholder.vertical,.gjs-placeholder.vertical{border-color:#62c462 rgba(0,0,0,0);border-width:5px 3px;margin:0 0 0 -3px}.gjs-placeholder-int,.gjs-com-placeholder-int,.gjs-placeholder-int{background-color:#62c462;box-shadow:0 0 3px rgba(0,0,0,.2);height:100%;width:100%;pointer-events:none;padding:1.5px;outline:none}.gjs-pn-panel{display:inline-block;position:absolute;box-sizing:border-box;text-align:center;padding:5px;z-index:3}.gjs-pn-panel .icon-undo,.gjs-pn-panel .icon-redo{font-size:20px;height:30px;width:25px}.gjs-pn-commands{width:85%;left:0;top:0;box-shadow:0 0 5px rgba(0,0,0,.2)}.gjs-pn-options{right:15%;top:0}.gjs-pn-views{border-bottom:2px solid rgba(0,0,0,.2);right:0;width:15%;z-index:4}.gjs-pn-views-container{height:100%;padding:42px 0 0;right:0;width:15%;overflow:auto;box-shadow:0 0 5px rgba(0,0,0,.2)}.gjs-pn-buttons{align-items:center;display:flex;justify-content:space-between}.gjs-pn-btn{box-sizing:border-box;min-height:30px;min-width:30px;line-height:21px;background-color:rgba(0,0,0,0);border:none;font-size:18px;margin-right:5px;border-radius:2px;padding:4px;position:relative;cursor:pointer}.gjs-pn-btn.gjs-pn-active{background-color:rgba(0,0,0,.15);box-shadow:0 0 3px rgba(0,0,0,.25) inset}.gjs-pn-btn svg{fill:currentColor}.gjs-label{line-height:18px}.gjs-fields{display:flex}.gjs-select{padding:0;width:100%}.gjs-select select{padding-right:10px}.gjs-select:-moz-focusring,.gjs-select select:-moz-focusring{color:rgba(0,0,0,0);text-shadow:0 0 0 rgba(255,255,255,.7)}.gjs-input:focus,.gjs-button:focus,.gjs-btn-prim:focus,.gjs-select:focus,.gjs-select select:focus{outline:none}.gjs-field input,.gjs-field select,.gjs-field textarea{-webkit-appearance:none;-moz-appearance:none;appearance:none;color:inherit;border:none;background-color:rgba(0,0,0,0);box-sizing:border-box;width:100%;position:relative;padding:5px;z-index:1}.gjs-field input:focus,.gjs-field select:focus,.gjs-field textarea:focus{outline:none}.gjs-field input[type=number]{-moz-appearance:textfield}.gjs-field input[type=number]::-webkit-outer-spin-button,.gjs-field input[type=number]::-webkit-inner-spin-button{-webkit-appearance:none;margin:0}.gjs-field-range{flex:9 1 auto}.gjs-field-integer input{padding-right:30px}.gjs-select option,.gjs-field-select option,.gjs-clm-select option,.gjs-sm-select option,.gjs-fields option,.gjs-sm-unit option{background-color:#444;color:#ddd}.gjs-field{background-color:rgba(0,0,0,.2);border:none;box-shadow:none;border-radius:2px;box-sizing:border-box;padding:0;position:relative}.gjs-field textarea{resize:vertical}.gjs-field .gjs-sel-arrow{height:100%;width:9px;position:absolute;right:0;top:0;z-index:0}.gjs-field .gjs-d-s-arrow{bottom:0;top:0;margin:auto;right:5px;border-top:4px solid rgba(255,255,255,.7);position:absolute;height:0;width:0;border-left:3px solid rgba(0,0,0,0);border-right:4px solid rgba(0,0,0,0);cursor:pointer}.gjs-field-arrows{position:absolute;cursor:ns-resize;margin:auto;height:20px;width:9px;z-index:10;bottom:0;right:3px;top:0}.gjs-field-color,.gjs-field-radio{width:100%}.gjs-field-color input{padding-right:22px;box-sizing:border-box}.gjs-field-colorp{border-left:1px solid rgba(0,0,0,.2);box-sizing:border-box;height:100%;padding:2px;position:absolute;right:0;top:0;width:22px;z-index:10}.gjs-field-colorp .gjs-checker-bg,.gjs-field-colorp .gjs-field-colorp-c{height:100%;width:100%;border-radius:1px}.gjs-field-colorp-c{height:100%;position:relative;width:100%}.gjs-field-color-picker{background-color:#ddd;cursor:pointer;height:100%;width:100%;box-shadow:0 0 1px rgba(0,0,0,.2);border-radius:1px;position:absolute;top:0}.gjs-field-checkbox{padding:0;width:17px;height:17px;display:block;cursor:pointer}.gjs-field-checkbox input{display:none}.gjs-field-checkbox input:checked+.gjs-chk-icon{border-color:rgba(255,255,255,.5);border-width:0 2px 2px 0;border-style:solid}.gjs-radio-item{flex:1 1 auto;text-align:center;border-left:1px solid rgba(0,0,0,.2)}.gjs-radio-item:first-child{border:none}.gjs-radio-item:hover{background:rgba(0,0,0,.2)}.gjs-radio-item input{display:none}.gjs-radio-item input:checked+.gjs-radio-item-label{background-color:rgba(255,255,255,.2)}.gjs-radio-items{display:flex}.gjs-radio-item-label{cursor:pointer;display:block;padding:5px}.gjs-field-units{position:absolute;margin:auto;right:10px;bottom:0;top:0}.gjs-field-unit{position:absolute;right:10px;top:3px;font-size:10px;color:rgba(255,255,255,.7);cursor:pointer}.gjs-input-unit{text-align:center}.gjs-field-arrow-u,.gjs-field-arrow-d{position:absolute;height:0;width:0;border-left:3px solid rgba(0,0,0,0);border-right:4px solid rgba(0,0,0,0);border-top:4px solid rgba(255,255,255,.7);bottom:4px;cursor:pointer}.gjs-field-arrow-u{border-bottom:4px solid rgba(255,255,255,.7);border-top:none;top:4px}.gjs-field-select{padding:0}.gjs-field-range{background-color:rgba(0,0,0,0);border:none;box-shadow:none;padding:0}.gjs-field-range input{margin:0;height:100%}.gjs-field-range input:focus{outline:none}.gjs-field-range input::-webkit-slider-thumb{-webkit-appearance:none;margin-top:-4px;height:10px;width:10px;border:1px solid rgba(0,0,0,.2);border-radius:100%;background-color:#ddd;cursor:pointer}.gjs-field-range input::-moz-range-thumb{height:10px;width:10px;border:1px solid rgba(0,0,0,.2);border-radius:100%;background-color:#ddd;cursor:pointer}.gjs-field-range input::-ms-thumb{height:10px;width:10px;border:1px solid rgba(0,0,0,.2);border-radius:100%;background-color:#ddd;cursor:pointer}.gjs-field-range input::-moz-range-track{background-color:rgba(0,0,0,.2);border-radius:1px;margin-top:3px;height:3px}.gjs-field-range input::-webkit-slider-runnable-track{background-color:rgba(0,0,0,.2);border-radius:1px;margin-top:3px;height:3px}.gjs-field-range input::-ms-track{background-color:rgba(0,0,0,.2);border-radius:1px;margin-top:3px;height:3px}.gjs-btn-prim{color:inherit;background-color:rgba(255,255,255,.1);border-radius:2px;padding:3px 6px;padding:5px;cursor:pointer;border:none}.gjs-btn-prim:active{background-color:rgba(255,255,255,.1)}.gjs-btn--full{width:100%}.gjs-chk-icon{transform:rotate(45deg);box-sizing:border-box;display:block;height:14px;margin:0 5px;width:6px}.gjs-add-trasp{background:none;border:none;color:#ddd;cursor:pointer;font-size:1em;border-radius:2px;opacity:.75;filter:alpha(opacity=75)}.gjs-add-trasp:hover{opacity:1;filter:alpha(opacity=100)}.gjs-add-trasp:active{background-color:rgba(0,0,0,.2)}.gjs-devices-c{display:flex;align-items:center;padding:2px 3px 3px 3px}.gjs-devices-c .gjs-device-label{flex-grow:2;text-align:left;margin-right:10px}.gjs-devices-c .gjs-select{flex-grow:20}.gjs-devices-c .gjs-add-trasp{flex-grow:1;margin-left:5px}.gjs-category-open,.gjs-block-category.gjs-open,.gjs-sm-sector.gjs-sm-open{border-bottom:1px solid rgba(0,0,0,.25)}.gjs-category-title,.gjs-layer-title,.gjs-block-category .gjs-title,.gjs-sm-sector-title{font-weight:lighter;background-color:rgba(0,0,0,.1);letter-spacing:1px;padding:9px 10px 9px 20px;border-bottom:1px solid rgba(0,0,0,.25);text-align:left;position:relative;cursor:pointer}.gjs-sm-clear{cursor:pointer;width:14px;min-width:14px;height:14px;margin-left:3px}.gjs-sm-header{font-weight:lighter;padding:10px}.gjs-sm-sector{clear:both;font-weight:lighter;text-align:left}.gjs-sm-sector-title{display:flex;align-items:center}.gjs-sm-sector-caret{width:17px;height:17px;min-width:17px;transform:rotate(-90deg)}.gjs-sm-sector-label{margin-left:5px}.gjs-sm-sector.gjs-sm-open .gjs-sm-sector-caret{transform:none}.gjs-sm-properties{font-size:.75rem;padding:10px 5px;display:flex;flex-wrap:wrap;align-items:flex-end;box-sizing:border-box;width:100%}.gjs-sm-label{margin:5px 5px 3px 0;display:flex;align-items:center}.gjs-sm-close-btn,.gjs-sm-preview-file-close{display:block;font-size:23px;position:absolute;cursor:pointer;right:5px;top:0;opacity:.7;filter:alpha(opacity=70)}.gjs-sm-close-btn:hover,.gjs-sm-preview-file-close:hover{opacity:.9;filter:alpha(opacity=90)}.gjs-sm-field,.gjs-clm-select,.gjs-clm-field{width:100%;position:relative}.gjs-sm-field input,.gjs-clm-select input,.gjs-clm-field input,.gjs-sm-field select,.gjs-clm-select select,.gjs-clm-field select{background-color:rgba(0,0,0,0);color:rgba(255,255,255,.7);border:none;width:100%}.gjs-sm-field input,.gjs-clm-select input,.gjs-clm-field input{box-sizing:border-box}.gjs-sm-field select,.gjs-clm-select select,.gjs-clm-field select{position:relative;z-index:1;-webkit-appearance:none;-moz-appearance:none;appearance:none}.gjs-sm-field select::-ms-expand,.gjs-clm-select select::-ms-expand,.gjs-clm-field select::-ms-expand{display:none}.gjs-sm-field select:-moz-focusring,.gjs-clm-select select:-moz-focusring,.gjs-clm-field select:-moz-focusring{color:rgba(0,0,0,0);text-shadow:0 0 0 rgba(255,255,255,.7)}.gjs-sm-field input:focus,.gjs-clm-select input:focus,.gjs-clm-field input:focus,.gjs-sm-field select:focus,.gjs-clm-select select:focus,.gjs-clm-field select:focus{outline:none}.gjs-sm-field .gjs-sm-unit,.gjs-clm-select .gjs-sm-unit,.gjs-clm-field .gjs-sm-unit{position:absolute;right:10px;top:3px;font-size:10px;color:rgba(255,255,255,.7);cursor:pointer}.gjs-sm-field .gjs-clm-sel-arrow,.gjs-clm-select .gjs-clm-sel-arrow,.gjs-clm-field .gjs-clm-sel-arrow,.gjs-sm-field .gjs-sm-int-arrows,.gjs-clm-select .gjs-sm-int-arrows,.gjs-clm-field .gjs-sm-int-arrows,.gjs-sm-field .gjs-sm-sel-arrow,.gjs-clm-select .gjs-sm-sel-arrow,.gjs-clm-field .gjs-sm-sel-arrow{height:100%;width:9px;position:absolute;right:0;top:0;cursor:ns-resize}.gjs-sm-field .gjs-sm-sel-arrow,.gjs-clm-select .gjs-sm-sel-arrow,.gjs-clm-field .gjs-sm-sel-arrow{cursor:pointer}.gjs-sm-field .gjs-clm-d-s-arrow,.gjs-clm-select .gjs-clm-d-s-arrow,.gjs-clm-field .gjs-clm-d-s-arrow,.gjs-sm-field .gjs-sm-d-arrow,.gjs-clm-select .gjs-sm-d-arrow,.gjs-clm-field .gjs-sm-d-arrow,.gjs-sm-field .gjs-sm-d-s-arrow,.gjs-clm-select .gjs-sm-d-s-arrow,.gjs-clm-field .gjs-sm-d-s-arrow,.gjs-sm-field .gjs-sm-u-arrow,.gjs-clm-select .gjs-sm-u-arrow,.gjs-clm-field .gjs-sm-u-arrow{position:absolute;height:0;width:0;border-left:3px solid rgba(0,0,0,0);border-right:4px solid rgba(0,0,0,0);cursor:pointer}.gjs-sm-field .gjs-sm-u-arrow,.gjs-clm-select .gjs-sm-u-arrow,.gjs-clm-field .gjs-sm-u-arrow{border-bottom:4px solid rgba(255,255,255,.7);top:4px}.gjs-sm-field .gjs-clm-d-s-arrow,.gjs-clm-select .gjs-clm-d-s-arrow,.gjs-clm-field .gjs-clm-d-s-arrow,.gjs-sm-field .gjs-sm-d-arrow,.gjs-clm-select .gjs-sm-d-arrow,.gjs-clm-field .gjs-sm-d-arrow,.gjs-sm-field .gjs-sm-d-s-arrow,.gjs-clm-select .gjs-sm-d-s-arrow,.gjs-clm-field .gjs-sm-d-s-arrow{border-top:4px solid rgba(255,255,255,.7);bottom:4px}.gjs-sm-field .gjs-clm-d-s-arrow,.gjs-clm-select .gjs-clm-d-s-arrow,.gjs-clm-field .gjs-clm-d-s-arrow,.gjs-sm-field .gjs-sm-d-s-arrow,.gjs-clm-select .gjs-sm-d-s-arrow,.gjs-clm-field .gjs-sm-d-s-arrow{bottom:7px}.gjs-sm-field.gjs-sm-color,.gjs-sm-color.gjs-clm-field,.gjs-sm-field.gjs-sm-input,.gjs-sm-input.gjs-clm-field,.gjs-sm-field.gjs-sm-integer,.gjs-sm-integer.gjs-clm-field,.gjs-sm-field.gjs-sm-list,.gjs-sm-list.gjs-clm-field,.gjs-sm-field.gjs-sm-select,.gjs-clm-select,.gjs-sm-select.gjs-clm-field{background-color:rgba(0,0,0,.2);border:1px solid rgba(0,0,0,.1);box-shadow:1px 1px 0 rgba(255,255,255,.1);color:rgba(255,255,255,.7);border-radius:2px;box-sizing:border-box;padding:0 5px}.gjs-sm-field.gjs-sm-composite,.gjs-sm-composite.gjs-clm-select,.gjs-sm-composite.gjs-clm-field{border-radius:2px}.gjs-sm-field.gjs-sm-select,.gjs-clm-select,.gjs-sm-select.gjs-clm-field{padding:0}.gjs-sm-field.gjs-sm-select select,.gjs-clm-select select,.gjs-sm-select.gjs-clm-field select{height:20px}.gjs-sm-field.gjs-sm-select option,.gjs-clm-select option,.gjs-sm-select.gjs-clm-field option{padding:3px 0}.gjs-sm-field.gjs-sm-composite,.gjs-sm-composite.gjs-clm-select,.gjs-sm-composite.gjs-clm-field{background-color:rgba(0,0,0,.1);border:1px solid rgba(0,0,0,.25)}.gjs-sm-field.gjs-sm-list,.gjs-sm-list.gjs-clm-select,.gjs-sm-list.gjs-clm-field{width:auto;padding:0;overflow:hidden;float:left}.gjs-sm-field.gjs-sm-list input,.gjs-sm-list.gjs-clm-select input,.gjs-sm-list.gjs-clm-field input{display:none}.gjs-sm-field.gjs-sm-list label,.gjs-sm-list.gjs-clm-select label,.gjs-sm-list.gjs-clm-field label{cursor:pointer;padding:5px;display:block}.gjs-sm-field.gjs-sm-list .gjs-sm-radio:checked+label,.gjs-sm-list.gjs-clm-select .gjs-sm-radio:checked+label,.gjs-sm-list.gjs-clm-field .gjs-sm-radio:checked+label{background-color:rgba(255,255,255,.2)}.gjs-sm-field.gjs-sm-list .gjs-sm-icon,.gjs-sm-list.gjs-clm-select .gjs-sm-icon,.gjs-sm-list.gjs-clm-field .gjs-sm-icon{background-repeat:no-repeat;background-position:center;text-shadow:none;line-height:normal}.gjs-sm-field.gjs-sm-integer select,.gjs-sm-integer.gjs-clm-select select,.gjs-sm-integer.gjs-clm-field select{width:auto;padding:0}.gjs-sm-list .gjs-sm-el{float:left;border-left:1px solid rgba(0,0,0,.2)}.gjs-sm-list .gjs-sm-el:first-child{border:none}.gjs-sm-list .gjs-sm-el:hover{background:rgba(0,0,0,.2)}.gjs-sm-slider .gjs-field-integer{flex:1 1 65px}.gjs-sm-property{box-sizing:border-box;float:left;width:50%;margin-bottom:5px;padding:0 5px}.gjs-sm-property--full,.gjs-sm-property.gjs-sm-composite,.gjs-sm-property.gjs-sm-file,.gjs-sm-property.gjs-sm-list,.gjs-sm-property.gjs-sm-stack,.gjs-sm-property.gjs-sm-slider,.gjs-sm-property.gjs-sm-color{width:100%}.gjs-sm-property .gjs-sm-btn{background-color:rgba(33,33,33,.2);border-radius:2px;box-shadow:1px 1px 0 rgba(5,5,5,.2),1px 1px 0 rgba(43,43,43,.2) inset;padding:5px;position:relative;text-align:center;height:auto;width:100%;cursor:pointer;color:#ddd;box-sizing:border-box;text-shadow:-1px -1px 0 rgba(0,0,0,.2);border:none;opacity:.85;filter:alpha(opacity=85)}.gjs-sm-property .gjs-sm-btn-c{box-sizing:border-box;float:left;width:100%}.gjs-sm-property__text-shadow .gjs-sm-layer-preview-cnt::after{color:#000;content:\"T\";font-weight:900;line-height:17px;padding:0 4px}.gjs-sm-preview-file{background-color:rgba(255,255,255,.05);border-radius:2px;margin-top:5px;position:relative;overflow:hidden;border:1px solid rgba(252,252,252,.05);padding:3px 20px}.gjs-sm-preview-file-cnt{background-size:auto 100%;background-repeat:no-repeat;background-position:center center;height:50px}.gjs-sm-preview-file-close{top:-5px;width:14px;height:14px}.gjs-sm-layers{margin-top:5px;padding:1px 3px;min-height:30px}.gjs-sm-layer{background-color:rgba(255,255,255,.055);border-radius:2px;margin:2px 0;padding:7px;position:relative}.gjs-sm-layer.gjs-sm-active{background-color:rgba(255,255,255,.12)}.gjs-sm-layer .gjs-sm-label-wrp{display:flex;align-items:center}.gjs-sm-layer #gjs-sm-move{height:14px;width:14px;min-width:14px;cursor:grab}.gjs-sm-layer #gjs-sm-label{flex-grow:1;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;margin:0 5px}.gjs-sm-layer-preview{height:15px;width:15px;min-width:15px;margin-right:5px;border-radius:2px}.gjs-sm-layer-preview-cnt{border-radius:2px;background-color:#fff;height:100%;width:100%;background-size:cover !important}.gjs-sm-layer #gjs-sm-close-layer{display:block;cursor:pointer;height:14px;width:14px;min-width:14px;opacity:.5;filter:alpha(opacity=50)}.gjs-sm-layer #gjs-sm-close-layer:hover{opacity:.8;filter:alpha(opacity=80)}.gjs-sm-stack .gjs-sm-properties{padding:5px 0 0}.gjs-sm-stack #gjs-sm-add{background:none;border:none;cursor:pointer;outline:none;position:absolute;right:0;top:-17px;opacity:.75;padding:0;width:18px;height:18px}.gjs-sm-stack #gjs-sm-add:hover{opacity:1;filter:alpha(opacity=100)}.gjs-sm-colorp-c{height:100%;width:20px;position:absolute;right:0;top:0;box-sizing:border-box;border-radius:2px;padding:2px}.gjs-sm-colorp-c .gjs-checker-bg,.gjs-sm-colorp-c .gjs-field-colorp-c{height:100%;width:100%;border-radius:1px}.gjs-sm-color-picker{background-color:#ddd;cursor:pointer;height:16px;width:100%;margin-top:-16px;box-shadow:0 0 1px rgba(0,0,0,.2);border-radius:1px}.gjs-sm-btn-upload #gjs-sm-upload{left:0;top:0;position:absolute;width:100%;opacity:0;cursor:pointer}.gjs-sm-btn-upload #gjs-sm-label{padding:2px 0}.gjs-sm-layer>#gjs-sm-move{opacity:.7;filter:alpha(opacity=70);cursor:move;font-size:12px;float:left;margin:0 5px 0 0}.gjs-sm-layer>#gjs-sm-move:hover{opacity:.9;filter:alpha(opacity=90)}.gjs-blocks-c{display:flex;flex-wrap:wrap;justify-content:flex-start}.gjs-block-categories{display:flex;flex-direction:column}.gjs-block-category{width:100%}.gjs-block-category .gjs-caret-icon{margin-right:5px}.gjs-block{-moz-user-select:none;-webkit-user-select:none;-o-user-select:none;user-select:none;width:45%;min-width:45px;padding:1em;box-sizing:border-box;min-height:90px;cursor:all-scroll;font-size:11px;font-weight:lighter;text-align:center;display:flex;flex-direction:column;justify-content:space-between;border:1px solid rgba(0,0,0,.2);border-radius:3px;margin:10px 2.5% 5px;box-shadow:0 1px 0 0 rgba(0,0,0,.15);transition:all .2s ease 0s;transition-property:box-shadow,color}.gjs-block:hover{box-shadow:0 3px 4px 0 rgba(0,0,0,.15)}.gjs-block svg{fill:currentColor}.gjs-block__media{margin-bottom:10px;pointer-events:none}.gjs-block-svg{width:54px;fill:currentColor}.gjs-block-svg-path{fill:currentColor}.gjs-block.fa{font-size:2em;line-height:2em;padding:11px}.gjs-block-label{line-height:normal;font-size:.65rem;font-weight:normal;font-family:Helvetica,sans-serif;overflow:hidden;text-overflow:ellipsis;pointer-events:none}.gjs-block.gjs-bdrag{width:auto;padding:0}.gjs-selected-parent{border:1px solid #ffca6f}.gjs-opac50{opacity:.5;filter:alpha(opacity=50)}.gjs-layer{font-weight:lighter;text-align:left;position:relative;background-color:rgba(0,0,0,.1);font-size:.75rem;display:grid}.gjs-layer-hidden{opacity:.55;filter:alpha(opacity=55)}.gjs-layer-count{position:absolute;right:27px;top:9px}.gjs-layer-vis{left:0;top:0;padding:7px 5px 7px 10px;position:absolute;box-sizing:content-box;cursor:pointer;width:13px;z-index:1}.gjs-layer-vis-off{display:none}.gjs-layer-vis.gjs-layer-off .gjs-layer-vis-on{display:none}.gjs-layer-vis.gjs-layer-off .gjs-layer-vis-off{display:block}.gjs-layer-caret{width:15px;padding:2px;cursor:pointer;position:absolute;box-sizing:content-box;left:-15px;top:0;transform:rotate(90deg);opacity:.7;filter:alpha(opacity=70)}.gjs-layer-caret:hover{opacity:1;filter:alpha(opacity=100)}.gjs-layer-caret.gjs-layer-open{transform:rotate(180deg)}.gjs-layer-title{padding:3px 10px 5px 30px;display:flex;align-items:center}.gjs-layer-title-inn{align-items:center;position:relative;display:flex;width:100%}.gjs-layer__icon{display:block;width:100%;max-width:15px;max-height:15px;padding-left:5px}.gjs-layer__icon svg{fill:currentColor}.gjs-layer-name{padding:5px 0;display:inline-block;box-sizing:content-box;overflow:hidden;white-space:nowrap;margin:0 30px 0 5px;max-width:170px}.gjs-layer-name--no-edit{text-overflow:ellipsis}.gjs-layer>.gjs-layer-children{display:none}.gjs-layer.open>.gjs-layer-children{display:block}.gjs-layer-no-chld>.gjs-layer-title-inn>.gjs-layer-caret{display:none}.gjs-layer-move{padding:9px 7px;position:absolute;width:13px;box-sizing:content-box;cursor:move;right:0;top:0}.gjs-layer.gjs-hovered .gjs-layer-title{background-color:rgba(255,255,255,.015)}.gjs-layer.gjs-selected .gjs-layer-title{background-color:rgba(255,255,255,.1)}.gjs-layers{position:relative;height:100%}.gjs-layers #gjs-placeholder{width:100%;position:absolute}.gjs-layers #gjs-placeholder #gjs-plh-int{height:100%;padding:1px}.gjs-layers #gjs-placeholder #gjs-plh-int.gjs-insert{background-color:#62c462}#gjs-clm-add-tag,.gjs-clm-tags-btn{background-color:rgba(255,255,255,.15);border-radius:2px;padding:3px;margin-right:3px;border:1px solid rgba(0,0,0,.15);width:24px;height:24px;box-sizing:border-box;cursor:pointer}.gjs-clm-tags-btn svg{fill:currentColor;display:block}.gjs-clm-header{display:flex;align-items:center;margin:7px 0}.gjs-clm-header-status{flex-shrink:1;margin-left:auto}.gjs-clm-tag{display:flex;overflow:hidden;align-items:center;border-radius:3px;margin:0 3px 3px 0;padding:5px;cursor:default}.gjs-clm-tag-status,.gjs-clm-tag-close{width:12px;height:12px;flex-shrink:1}.gjs-clm-tag-status svg,.gjs-clm-tag-close svg{vertical-align:middle;fill:currentColor}.gjs-clm-sels-info{margin:7px 0;text-align:left}.gjs-clm-sel-id{font-size:.9em;opacity:.5;filter:alpha(opacity=50)}.gjs-clm-label-sel{float:left;padding-right:5px}.gjs-clm-tags{font-size:.75rem;padding:10px 5px}.gjs-clm-tags #gjs-clm-sel{padding:7px 0;float:left}.gjs-clm-tags #gjs-clm-sel{font-style:italic;margin-left:5px}.gjs-clm-tags #gjs-clm-tags-field{clear:both;padding:5px;margin-bottom:5px;display:flex;flex-wrap:wrap}.gjs-clm-tags #gjs-clm-tags-c{display:flex;flex-wrap:wrap;vertical-align:top;overflow:hidden}.gjs-clm-tags #gjs-clm-new{color:#ddd;padding:5px 6px;display:none}.gjs-clm-tags #gjs-clm-close{opacity:.85;filter:alpha(opacity=85);font-size:20px;line-height:0;cursor:pointer;color:rgba(255,255,255,.9)}.gjs-clm-tags #gjs-clm-close:hover{opacity:1;filter:alpha(opacity=100)}.gjs-clm-tags #gjs-clm-checkbox{color:rgba(255,255,255,.9);vertical-align:middle;cursor:pointer;font-size:9px}.gjs-clm-tags #gjs-clm-tag-label{flex-grow:1;text-overflow:ellipsis;overflow:hidden;padding:0 3px;cursor:text}.gjs-mdl-container{font-family:Helvetica,sans-serif;overflow-y:auto;position:fixed;background-color:rgba(0,0,0,.5);display:flex;top:0;left:0;right:0;bottom:0;z-index:100}.gjs-mdl-dialog{text-shadow:-1px -1px 0 rgba(0,0,0,.05);animation:gjs-slide-down .215s;margin:auto;max-width:850px;width:90%;border-radius:3px;font-weight:lighter;position:relative;z-index:2}.gjs-mdl-title{font-size:1rem}.gjs-mdl-btn-close{position:absolute;right:15px;top:5px}.gjs-mdl-active .gjs-mdl-dialog{animation:gjs-mdl-slide-down .216s}.gjs-mdl-header,.gjs-mdl-content{padding:10px 15px;clear:both}.gjs-mdl-header{position:relative;border-bottom:1px solid rgba(0,0,0,.2);padding:15px 15px 7px}.gjs-export-dl::after{content:\"\";clear:both;display:block;margin-bottom:10px}.gjs-dropzone{display:none;opacity:0;position:absolute;top:0;left:0;z-index:11;width:100%;height:100%;transition:opacity .25s;pointer-events:none}.gjs-dropzone-active .gjs-dropzone{display:block;opacity:1}.gjs-am-assets{height:290px;overflow:auto;clear:both;display:flex;flex-wrap:wrap;align-items:flex-start;align-content:flex-start}.gjs-am-assets-header{padding:5px}.gjs-am-add-asset .gjs-am-add-field{width:70%;float:left}.gjs-am-add-asset button{width:25%;float:right}.gjs-am-preview-cont{position:relative;height:70px;width:30%;background-color:#444;border-radius:2px;float:left;overflow:hidden}.gjs-am-preview{position:absolute;background-position:center center;background-size:cover;background-repeat:no-repeat;height:100%;width:100%;z-index:1}.gjs-am-preview-bg{opacity:.5;filter:alpha(opacity=50);position:absolute;height:100%;width:100%;z-index:0}.gjs-am-dimensions{opacity:.5;filter:alpha(opacity=50);font-size:10px}.gjs-am-meta{width:70%;float:left;font-size:12px;padding:5px 0 0 5px;box-sizing:border-box}.gjs-am-meta>div{margin-bottom:5px}.gjs-am-close{cursor:pointer;position:absolute;right:5px;top:0;display:none}.gjs-am-asset{border-bottom:1px solid rgba(0,0,0,.2);padding:5px;cursor:pointer;position:relative;box-sizing:border-box;width:100%}.gjs-am-asset:hover .gjs-am-close{display:block}.gjs-am-highlight{background-color:rgba(255,255,255,.1)}.gjs-am-assets-cont{background-color:rgba(0,0,0,.1);border-radius:3px;box-sizing:border-box;padding:10px;width:45%;float:right;height:325px;overflow:hidden}.gjs-am-file-uploader{width:55%;float:left}.gjs-am-file-uploader>form{background-color:rgba(0,0,0,.1);border:2px dashed;border-radius:3px;position:relative;text-align:center;margin-bottom:15px}.gjs-am-file-uploader>form.gjs-am-hover{border:2px solid #62c462;color:#75cb75}.gjs-am-file-uploader>form.gjs-am-disabled{border-color:red}.gjs-am-file-uploader>form #gjs-am-uploadFile{opacity:0;filter:alpha(opacity=0);padding:150px 10px;width:100%;box-sizing:border-box}.gjs-am-file-uploader #gjs-am-title{position:absolute;padding:150px 10px;width:100%}.gjs-cm-editor-c{float:left;box-sizing:border-box;width:50%}.gjs-cm-editor-c .CodeMirror{height:450px}.gjs-cm-editor{font-size:12px}.gjs-cm-editor#gjs-cm-htmlmixed{padding-right:10px;border-right:1px solid rgba(0,0,0,.2)}.gjs-cm-editor#gjs-cm-htmlmixed #gjs-cm-title{color:#a97d44}.gjs-cm-editor#gjs-cm-css{padding-left:10px}.gjs-cm-editor#gjs-cm-css #gjs-cm-title{color:#ddca7e}.gjs-cm-editor #gjs-cm-title{background-color:rgba(0,0,0,.2);font-size:12px;padding:5px 10px 3px;text-align:right}.gjs-rte-toolbar{position:absolute;z-index:10}.gjs-rte-toolbar-ui{border:1px solid rgba(0,0,0,.2);border-radius:3px}.gjs-rte-actionbar{display:flex}.gjs-rte-action{display:flex;align-items:center;justify-content:center;padding:5px;width:25px;border-right:1px solid rgba(0,0,0,.2);text-align:center;cursor:pointer;outline:none}.gjs-rte-action:last-child{border-right:none}.gjs-rte-action:hover{background-color:rgba(255,255,255,.1)}.gjs-rte-active{background-color:rgba(255,255,255,.1)}.gjs-rte-disabled{color:rgba(255,255,255,.1);cursor:not-allowed}.gjs-rte-disabled:hover{background-color:unset}.gjs-editor-cont .sp-hue,.gjs-editor-cont .sp-slider{cursor:row-resize}.gjs-editor-cont .sp-color,.gjs-editor-cont .sp-dragger{cursor:crosshair}.gjs-editor-cont .sp-alpha-inner,.gjs-editor-cont .sp-alpha-handle{cursor:col-resize}.gjs-editor-cont .sp-hue{left:90%}.gjs-editor-cont .sp-color{right:15%}.gjs-editor-cont .sp-container{border:1px solid rgba(0,0,0,.2);box-shadow:0 0 7px rgba(0,0,0,.2);border-radius:3px}.gjs-editor-cont .sp-picker-container{border:none}.gjs-editor-cont .colpick_dark .colpick_color{outline:1px solid rgba(0,0,0,.2)}.gjs-editor-cont .sp-cancel,.gjs-editor-cont .sp-cancel:hover{bottom:-8px;color:#777 !important;font-size:25px;left:0;position:absolute;text-decoration:none}.gjs-editor-cont .sp-alpha-handle{background-color:#ccc;border:1px solid #555;width:4px}.gjs-editor-cont .sp-color,.gjs-editor-cont .sp-hue{border:1px solid #333}.gjs-editor-cont .sp-slider{background-color:#ccc;border:1px solid #555;height:3px;left:-4px;width:22px}.gjs-editor-cont .sp-dragger{background:rgba(0,0,0,0);box-shadow:0 0 0 1px #111}.gjs-editor-cont .sp-button-container{float:none;width:100%;position:relative;text-align:right}.gjs-editor-cont .sp-container button,.gjs-editor-cont .sp-container button:hover,.gjs-editor-cont .sp-container button:active{background:rgba(0,0,0,.2);border-color:rgba(0,0,0,.2);color:#ddd;text-shadow:none;box-shadow:none;padding:3px 5px}.gjs-editor-cont .sp-palette-container{border:none;float:none;margin:0;padding:5px 10px 0}.gjs-editor-cont .sp-palette .sp-thumb-el,.gjs-editor-cont .sp-palette .sp-thumb-el:hover{border:1px solid rgba(0,0,0,.9)}.gjs-editor-cont .sp-palette .sp-thumb-el:hover,.gjs-editor-cont .sp-palette .sp-thumb-el.sp-thumb-active{border-color:rgba(0,0,0,.9)}.gjs-hidden{display:none}@keyframes gjs-slide-down{0%{transform:translate(0, -3rem);opacity:0}100%{transform:translate(0, 0);opacity:1}}@keyframes gjs-slide-up{0%{transform:translate(0, 0);opacity:1}100%{transform:translate(0, -3rem);opacity:0}}.cm-s-hopscotch span.cm-error{color:#fff}\n", ""]); // Exports /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___); /***/ }), /***/ "./node_modules/css-loader/dist/runtime/api.js": /*!*****************************************************!*\ !*** ./node_modules/css-loader/dist/runtime/api.js ***! \*****************************************************/ /***/ ((module) => { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ // css base code, injected by the css-loader // eslint-disable-next-line func-names module.exports = function (cssWithMappingToString) { var list = []; // return the list of modules as css string list.toString = function toString() { return this.map(function (item) { var content = cssWithMappingToString(item); if (item[2]) { return "@media ".concat(item[2], " {").concat(content, "}"); } return content; }).join(""); }; // import a list of modules into the list // eslint-disable-next-line func-names list.i = function (modules, mediaQuery, dedupe) { if (typeof modules === "string") { // eslint-disable-next-line no-param-reassign modules = [[null, modules, ""]]; } var alreadyImportedModules = {}; if (dedupe) { for (var i = 0; i < this.length; i++) { // eslint-disable-next-line prefer-destructuring var id = this[i][0]; if (id != null) { alreadyImportedModules[id] = true; } } } for (var _i = 0; _i < modules.length; _i++) { var item = [].concat(modules[_i]); if (dedupe && alreadyImportedModules[item[0]]) { // eslint-disable-next-line no-continue continue; } if (mediaQuery) { if (!item[2]) { item[2] = mediaQuery; } else { item[2] = "".concat(mediaQuery, " and ").concat(item[2]); } } list.push(item); } }; return list; }; /***/ }), /***/ "./node_modules/grapesjs-blocks-basic/dist/index.js": /*!**********************************************************!*\ !*** ./node_modules/grapesjs-blocks-basic/dist/index.js ***! \**********************************************************/ /***/ (function(module) { /*! grapesjs-blocks-basic - 1.0.2 */ !function(n,a){ true?module.exports=a():0}('undefined'!=typeof globalThis?globalThis:'undefined'!=typeof window?window:this,(()=>(()=>{"use strict";var n={d:(a,e)=>{for(var t in e)n.o(e,t)&&!n.o(a,t)&&Object.defineProperty(a,t,{enumerable:!0,get:e[t]})},o:(n,a)=>Object.prototype.hasOwnProperty.call(n,a),r:n=>{'undefined'!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(n,Symbol.toStringTag,{value:'Module'}),Object.defineProperty(n,'__esModule',{value:!0})}},a={};n.r(a),n.d(a,{default:()=>l});var e=void 0&&(void 0).__assign||function(){return e=Object.assign||function(n){for(var a,e=1,t=arguments.length;e<t;e++)for(var l in a=arguments[e])Object.prototype.hasOwnProperty.call(a,l)&&(n[l]=a[l]);return n},e.apply(this,arguments)};var t=void 0&&(void 0).__assign||function(){return t=Object.assign||function(n){for(var a,e=1,t=arguments.length;e<t;e++)for(var l in a=arguments[e])Object.prototype.hasOwnProperty.call(a,l)&&(n[l]=a[l]);return n},t.apply(this,arguments)};const l=function(n,a){void 0===a&&(a={}),function(n,a){var t=n.BlockManager,l=a.category,o=a.blocks,c=a.stylePrefix,i=a.flexGrid,d=a.rowHeight,r=a.addBasicStyle,s="".concat(c,"row"),v="".concat(c,"cell"),m=i?"\n .".concat(s," {\n display: flex;\n justify-content: flex-start;\n align-items: stretch;\n flex-wrap: nowrap;\n padding: 10px;\n }\n @media (max-width: 768px) {\n .").concat(s," {\n flex-wrap: wrap;\n }\n }"):"\n .".concat(s," {\n display: table;\n padding: 10px;\n width: 100%;\n }\n @media (max-width: 768px) {\n .").concat(c,"cell, .").concat(c,"cell30, .").concat(c,"cell70 {\n width: 100%;\n display: block;\n }\n }"),p=i?"\n .".concat(v," {\n min-height: ").concat(d,"px;\n flex-grow: 1;\n flex-basis: 100%;\n }"):"\n .".concat(v," {\n width: 8%;\n display: table-cell;\n height: ").concat(d,"px;\n }"),u="\n .".concat(c,"cell30 {\n width: 30%;\n }"),b="\n .".concat(c,"cell70 {\n width: 70%;\n }"),g=1,h={tl:0,tc:0,tr:0,cl:0,cr:0,bl:0,br:0,minDim:g},f=e(e({},h),{cr:1,bc:0,currentUnit:1,minDim:g,step:.2});i&&(f.keyWidth='flex-basis');var y={class:s,'data-gjs-droppable':".".concat(v),'data-gjs-resizable':h,'data-gjs-name':'Row'},C={class:v,'data-gjs-draggable':".".concat(s),'data-gjs-resizable':f,'data-gjs-name':'Cell'};i&&(C['data-gjs-unstylable']=['width'],C['data-gjs-stylable-require']=['flex-basis']);var x=[".".concat(s),".".concat(v)];n.on('selector:add',(function(n){return x.indexOf(n.getFullName())>=0&&n.set('private',1)}));var V=function(n){var a=[];for(var e in n){var t=n[e];t=t instanceof Array||t instanceof Object?JSON.stringify(t):t,a.push("".concat(e,"=").concat("'".concat(t,"'")))}return a.length?" ".concat(a.join(' ')):''},w=function(n){return o.indexOf(n)>=0},L=V(y),H=V(C),M={category:l,select:!0};w('column1')&&t.add('column1',e(e({},M),{label:a.labelColumn1,media:"<svg viewBox=\"0 0 24 24\">\n <path fill=\"currentColor\" d=\"M2 20h20V4H2v16Zm-1 0V4a1 1 0 0 1 1-1h20a1 1 0 0 1 1 1v16a1 1 0 0 1-1 1H2a1 1 0 0 1-1-1Z\"/>\n </svg>",content:"<div ".concat(L,">\n <div ").concat(H,"></div>\n </div>\n ").concat(r?"<style>\n ".concat(m,"\n ").concat(p,"\n </style>"):'')})),w('column2')&&t.add('column2',e(e({},M),{label:a.labelColumn2,media:"<svg viewBox=\"0 0 23 24\">\n <path fill=\"currentColor\" d=\"M2 20h8V4H2v16Zm-1 0V4a1 1 0 0 1 1-1h8a1 1 0 0 1 1 1v16a1 1 0 0 1-1 1H2a1 1 0 0 1-1-1ZM13 20h8V4h-8v16Zm-1 0V4a1 1 0 0 1 1-1h8a1 1 0 0 1 1 1v16a1 1 0 0 1-1 1h-8a1 1 0 0 1-1-1Z\"/>\n </svg>",content:"<div ".concat(L,">\n <div ").concat(H,"></div>\n <div ").concat(H,"></div>\n </div>\n ").concat(r?"<style>\n ".concat(m,"\n ").concat(p,"\n </style>"):'')})),w('column3')&&t.add('column3',e(e({},M),{label:a.labelColumn3,media:"<svg viewBox=\"0 0 23 24\">\n <path fill=\"currentColor\" d=\"M2 20h4V4H2v16Zm-1 0V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v16a1 1 0 0 1-1 1H2a1 1 0 0 1-1-1ZM17 20h4V4h-4v16Zm-1 0V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v16a1 1 0 0 1-1 1h-4a1 1 0 0 1-1-1ZM9.5 20h4V4h-4v16Zm-1 0V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v16a1 1 0 0 1-1 1h-4a1 1 0 0 1-1-1Z\"/>\n </svg>",content:"<div ".concat(L,">\n <div ").concat(H,"></div>\n <div ").concat(H,"></div>\n <div ").concat(H,"></div>\n </div>\n ").concat(r?"<style>\n ".concat(m,"\n ").concat(p,"\n </style>"):'')})),w('column3-7')&&t.add('column3-7',e(e({},M),{label:a.labelColumn37,media:"<svg viewBox=\"0 0 24 24\">\n <path fill=\"currentColor\" d=\"M2 20h5V4H2v16Zm-1 0V4a1 1 0 0 1 1-1h5a1 1 0 0 1 1 1v16a1 1 0 0 1-1 1H2a1 1 0 0 1-1-1ZM10 20h12V4H10v16Zm-1 0V4a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v16a1 1 0 0 1-1 1H10a1 1 0 0 1-1-1Z\"/>\n </svg>",content:"<div ".concat(L,">\n <div ").concat(H," style='").concat(i?'flex-basis':'width',": 30%;'></div>\n <div ").concat(H," style='").concat(i?'flex-basis':'width',": 70%;'></div>\n </div>\n ").concat(r?"<style>\n ".concat(m,"\n ").concat(p,"\n ").concat(u,"\n ").concat(b,"\n </style>"):'')})),w('text')&&t.add('text',e(e({},M),{activate:!0,label:a.labelText,media:"<svg viewBox=\"0 0 24 24\">\n <path fill=\"currentColor\" d=\"M18.5,4L19.66,8.35L18.7,8.61C18.25,7.74 17.79,6.87 17.26,6.43C16.73,6 16.11,6 15.5,6H13V16.5C13,17 13,17.5 13.33,17.75C13.67,18 14.33,18 15,18V19H9V18C9.67,18 10.33,18 10.67,17.75C11,17.5 11,17 11,16.5V6H8.5C7.89,6 7.27,6 6.74,6.43C6.21,6.87 5.75,7.74 5.3,8.61L4.34,8.35L5.5,4H18.5Z\" />\n </svg>",content:{type:'text',content:'Insert your text here',style:{padding:'10px'}}})),w('link')&&t.add('link',e(e({},M),{label:a.labelLink,media:"<svg viewBox=\"0 0 24 24\">\n <path fill=\"currentColor\" d=\"M3.9,12C3.9,10.29 5.29,8.9 7,8.9H11V7H7A5,5 0 0,0 2,12A5,5 0 0,0 7,17H11V15.1H7C5.29,15.1 3.9,13.71 3.9,12M8,13H16V11H8V13M17,7H13V8.9H17C18.71,8.9 20.1,10.29 20.1,12C20.1,13.71 18.71,15.1 17,15.1H13V17H17A5,5 0 0,0 22,12A5,5 0 0,0 17,7Z\" />\n </svg>",content:{type:'link',content:'Link',style:{color:'#d983a6'}}})),w('image')&&t.add('image',e(e({},M),{activate:!0,label:a.labelImage,media:"<svg viewBox=\"0 0 24 24\">\n <path fill=\"currentColor\" d=\"M21,3H3C2,3 1,4 1,5V19A2,2 0 0,0 3,21H21C22,21 23,20 23,19V5C23,4 22,3 21,3M5,17L8.5,12.5L11,15.5L14.5,11L19,17H5Z\" />\n </svg>",content:{style:{color:'black'},type:'image'}})),w('video')&&t.add('video',e(e({},M),{label:a.labelVideo,media:"<svg viewBox=\"0 0 24 24\">\n <path fill=\"currentColor\" d=\"M10,15L15.19,12L10,9V15M21.56,7.17C21.69,7.64 21.78,8.27 21.84,9.07C21.91,9.87 21.94,10.56 21.94,11.16L22,12C22,14.19 21.84,15.8 21.56,16.83C21.31,17.73 20.73,18.31 19.83,18.56C19.36,18.69 18.5,18.78 17.18,18.84C15.88,18.91 14.69,18.94 13.59,18.94L12,19C7.81,19 5.2,18.84 4.17,18.56C3.27,18.31 2.69,17.73 2.44,16.83C2.31,16.36 2.22,15.73 2.16,14.93C2.09,14.13 2.06,13.44 2.06,12.84L2,12C2,9.81 2.16,8.2 2.44,7.17C2.69,6.27 3.27,5.69 4.17,5.44C4.64,5.31 5.5,5.22 6.82,5.16C8.12,5.09 9.31,5.06 10.41,5.06L12,5C16.19,5 18.8,5.16 19.83,5.44C20.73,5.69 21.31,6.27 21.56,7.17Z\" />\n </svg>",content:{type:'video',src:'img/video2.webm',style:{height:'350px',width:'615px'}}})),w('map')&&t.add('map',e(e({},M),{label:a.labelMap,media:"<svg viewBox=\"0 0 24 24\">\n <path fill=\"currentColor\" d=\"M20.5,3L20.34,3.03L15,5.1L9,3L3.36,4.9C3.15,4.97 3,5.15 3,5.38V20.5A0.5,0.5 0 0,0 3.5,21L3.66,20.97L9,18.9L15,21L20.64,19.1C20.85,19.03 21,18.85 21,18.62V3.5A0.5,0.5 0 0,0 20.5,3M10,5.47L14,6.87V18.53L10,17.13V5.47M5,6.46L8,5.45V17.15L5,18.31V6.46M19,17.54L16,18.55V6.86L19,5.7V17.54Z\" />\n </svg>",content:{type:'map',style:{height:'350px'}}}))}(n,t({blocks:['column1','column2','column3','column3-7','text','link','image','video','map'],flexGrid:!1,stylePrefix:'gjs-',addBasicStyle:!0,category:'Basic',labelColumn1:'1 Column',labelColumn2:'2 Columns',labelColumn3:'3 Columns',labelColumn37:'2 Columns 3/7',labelText:'Text',labelLink:'Link',labelImage:'Image',labelVideo:'Video',labelMap:'Map',rowHeight:75},a))};return a})())); //# sourceMappingURL=index.js.map /***/ }), /***/ "./node_modules/grapesjs-preset-webpage/dist/index.js": /*!************************************************************!*\ !*** ./node_modules/grapesjs-preset-webpage/dist/index.js ***! \************************************************************/ /***/ (function(module) { /*! grapesjs-preset-webpage - 1.0.3 */ !function(e,n){ true?module.exports=n():0}('undefined'!=typeof globalThis?globalThis:'undefined'!=typeof window?window:this,(()=>(()=>{"use strict";var e={d:(n,t)=>{for(var o in t)e.o(t,o)&&!e.o(n,o)&&Object.defineProperty(n,o,{enumerable:!0,get:t[o]})},o:(e,n)=>Object.prototype.hasOwnProperty.call(e,n),r:e=>{'undefined'!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:'Module'}),Object.defineProperty(e,'__esModule',{value:!0})}},n={};e.r(n),e.d(n,{default:()=>u});var t=void 0&&(void 0).__assign||function(){return t=Object.assign||function(e){for(var n,t=1,o=arguments.length;t<o;t++)for(var r in n=arguments[t])Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r]);return e},t.apply(this,arguments)};var o='gjs-open-import-webpage',r='set-device-desktop',i='set-device-tablet',a='set-device-mobile',c='canvas-clear',l=void 0&&(void 0).__assign||function(){return l=Object.assign||function(e){for(var n,t=1,o=arguments.length;t<o;t++)for(var r in n=arguments[t])Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r]);return e},l.apply(this,arguments)};const s=function(e,n){var t=e.Commands,s=n.textCleanCanvas;!function(e,n){var t=e.getConfig('stylePrefix'),r=n.modalImportLabel,i=n.modalImportContent;e.Commands.add(o,{codeViewer:null,container:null,run:function(e){var t='function'==typeof i?i(e):i,r=this.getCodeViewer();e.Modal.open({title:n.modalImportTitle,content:this.getContainer()}).onceClose((function(){return e.stopCommand(o)})),r.setContent(null!=t?t:''),r.refresh(),setTimeout((function(){return r.focus()}),0)},stop:function(){e.Modal.close()},getContainer:function(){if(!this.container){var o=this.getCodeViewer(),i=document.createElement('div');if(i.className="".concat(t,"import-container"),r){var a=document.createElement('div');a.className="".concat(t,"import-label"),a.innerHTML=r,i.appendChild(a)}i.appendChild(o.getElement());var c=document.createElement('button');c.type='button',c.innerHTML=n.modalImportButton,c.className="".concat(t,"btn-prim ").concat(t,"btn-import"),c.onclick=function(){e.Css.clear(),e.setComponents(o.getContent().trim()),e.Modal.close()},i.appendChild(c),this.container=i}return this.container},getCodeViewer:function(){return this.codeViewer||(this.codeViewer=e.CodeManager.createViewer(l({codeName:'htmlmixed',theme:'hopscotch',readOnly:!1},n.importViewerOptions))),this.codeViewer}})}(e,n),t.add(r,{run:function(e){return e.setDevice('Desktop')},stop:function(){}}),t.add(i,{run:function(e){return e.setDevice('Tablet')},stop:function(){}}),t.add(a,{run:function(e){return e.setDevice('Mobile portrait')},stop:function(){}}),t.add(c,(function(e){return confirm(s)&&e.runCommand('core:canvas-clear')}))};var d=void 0&&(void 0).__assign||function(){return d=Object.assign||function(e){for(var n,t=1,o=arguments.length;t<o;t++)for(var r in n=arguments[t])Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r]);return e},d.apply(this,arguments)};const u=function(e,n){void 0===n&&(n={});var l=d({blocks:['link-block','quote','text-basic'],block:function(){return{}},modalImportTitle:'Import',modalImportButton:'Import',modalImportLabel:'',modalImportContent:'',importViewerOptions:{},textCleanCanvas:'Are you sure you want to clear the canvas?',showStylesOnChange:!0,useCustomTheme:!0},n);if(l.useCustomTheme&&'undefined'!=typeof window){var u='gjs-',m='';[['one','#463a3c'],['two','#b9a5a6'],['three','#804f7b'],['four','#d97aa6']].forEach((function(e){var n=e[0],t=e[1];m+="\n .".concat(u).concat(n,"-bg {\n background-color: ").concat(t,";\n }\n\n .").concat(u).concat(n,"-color {\n color: ").concat(t,";\n }\n\n .").concat(u).concat(n,"-color-h:hover {\n color: ").concat(t,";\n }\n ")}));var p=document.createElement('style');p.innerText=m,document.head.appendChild(p)}!function(e,n){var o=function(o,r){n.blocks.indexOf(o)>=0&&e.Blocks.add(o,t(t({select:!0,category:'Basic'},r),n.block(o)))};o('link-block',{label:'Link Block',media:"<svg viewBox=\"0 0 24 24\">\n <path fill=\"currentColor\" d=\"M3.9,12C3.9,10.29 5.29,8.9 7,8.9H11V7H7A5,5 0 0,0 2,12A5,5 0 0,0 7,17H11V15.1H7C5.29,15.1 3.9,13.71 3.9,12M8,13H16V11H8V13M17,7H13V8.9H17C18.71,8.9 20.1,10.29 20.1,12C20.1,13.71 18.71,15.1 17,15.1H13V17H17A5,5 0 0,0 22,12A5,5 0 0,0 17,7Z\"></path>\n </svg>",content:{type:'link',editable:!1,droppable:!0,style:{display:'inline-block',padding:'5px','min-height':'50px','min-width':'50px'}}}),o('quote',{label:'Quote',media:"<svg viewBox=\"0 0 24 24\">\n <path fill=\"currentColor\" d=\"M14,17H17L19,13V7H13V13H16M6,17H9L11,13V7H5V13H8L6,17Z\" />\n </svg>",content:"<blockquote class=\"quote\">\n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore ipsum dolor sit\n </blockquote>"}),o('text-basic',{label:'Text section',media:"<svg viewBox=\"0 0 24 24\">\n <path fill=\"currentColor\" d=\"M21,6V8H3V6H21M3,18H12V16H3V18M3,13H21V11H3V13Z\" />\n </svg>",content:"<section class=\"bdg-sect\">\n <h1 class=\"heading\">Insert title here</h1>\n <p class=\"paragraph\">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua</p>\n </section>"})}(e,l),s(e,l),function(e,n){var t=e.Panels,l=e.getConfig(),s='sw-visibility',d='export-template',u='open-sm',m='open-tm',p='open-layers',v='open-blocks',H='fullscreen',C='preview',f='style="display: block; max-width:22px"';l.showDevices=!1,t.getPanels().reset([{id:'commands',buttons:[{}]},{id:'devices-c',buttons:[{id:r,command:r,active:!0,label:"<svg ".concat(f," viewBox=\"0 0 24 24\">\n <path fill=\"currentColor\" d=\"M21,16H3V4H21M21,2H3C1.89,2 1,2.89 1,4V16A2,2 0 0,0 3,18H10V20H8V22H16V20H14V18H21A2,2 0 0,0 23,16V4C23,2.89 22.1,2 21,2Z\" />\n </svg>")},{id:i,command:i,label:"<svg ".concat(f," viewBox=\"0 0 24 24\">\n <path fill=\"currentColor\" d=\"M19,18H5V6H19M21,4H3C1.89,4 1,4.89 1,6V18A2,2 0 0,0 3,20H21A2,2 0 0,0 23,18V6C23,4.89 22.1,4 21,4Z\" />\n </svg>")},{id:a,command:a,label:"<svg ".concat(f," viewBox=\"0 0 24 24\">\n <path fill=\"currentColor\" d=\"M17,19H7V5H17M17,1H7C5.89,1 5,1.89 5,3V21A2,2 0 0,0 7,23H17A2,2 0 0,0 19,21V3C19,1.89 18.1,1 17,1Z\" />\n </svg>")}]},{id:'options',buttons:[{id:s,command:s,context:s,label:"<svg ".concat(f," viewBox=\"0 0 24 24\">\n <path fill=\"currentColor\" d=\"M15,5H17V3H15M15,21H17V19H15M11,5H13V3H11M19,5H21V3H19M19,9H21V7H19M19,21H21V19H19M19,13H21V11H19M19,17H21V15H19M3,5H5V3H3M3,9H5V7H3M3,13H5V11H3M3,17H5V15H3M3,21H5V19H3M11,21H13V19H11M7,21H9V19H7M7,5H9V3H7V5Z\" />\n </svg>")},{id:C,context:C,command:function(){return e.runCommand(C)},label:"<svg ".concat(f," viewBox=\"0 0 24 24\"><path fill=\"currentColor\" d=\"M12,9A3,3 0 0,0 9,12A3,3 0 0,0 12,15A3,3 0 0,0 15,12A3,3 0 0,0 12,9M12,17A5,5 0 0,1 7,12A5,5 0 0,1 12,7A5,5 0 0,1 17,12A5,5 0 0,1 12,17M12,4.5C7,4.5 2.73,7.61 1,12C2.73,16.39 7,19.5 12,19.5C17,19.5 21.27,16.39 23,12C21.27,7.61 17,4.5 12,4.5Z\"></path></svg>")},{id:H,command:H,context:H,label:"<svg ".concat(f," viewBox=\"0 0 24 24\">\n <path fill=\"currentColor\" d=\"M5,5H10V7H7V10H5V5M14,5H19V10H17V7H14V5M17,14H19V19H14V17H17V14M10,17V19H5V14H7V17H10Z\" />\n </svg>")},{id:d,command:function(){return e.runCommand(d)},label:"<svg ".concat(f," viewBox=\"0 0 24 24\">\n <path fill=\"currentColor\" d=\"M12.89,3L14.85,3.4L11.11,21L9.15,20.6L12.89,3M19.59,12L16,8.41V5.58L22.42,12L16,18.41V15.58L19.59,12M1.58,12L8,5.58V8.41L4.41,12L8,15.58V18.41L1.58,12Z\" />\n </svg>")},{id:'undo',command:function(){return e.runCommand('core:undo')},label:"<svg ".concat(f," viewBox=\"0 0 24 24\">\n <path fill=\"currentColor\" d=\"M20 13.5C20 17.09 17.09 20 13.5 20H6V18H13.5C16 18 18 16 18 13.5S16 9 13.5 9H7.83L10.91 12.09L9.5 13.5L4 8L9.5 2.5L10.92 3.91L7.83 7H13.5C17.09 7 20 9.91 20 13.5Z\" />\n </svg>")},{id:'redo',command:function(){return e.runCommand('core:redo')},label:"<svg ".concat(f," viewBox=\"0 0 24 24\">\n <path fill=\"currentColor\" d=\"M10.5 18H18V20H10.5C6.91 20 4 17.09 4 13.5S6.91 7 10.5 7H16.17L13.08 3.91L14.5 2.5L20 8L14.5 13.5L13.09 12.09L16.17 9H10.5C8 9 6 11 6 13.5S8 18 10.5 18Z\" />\n </svg>")},{id:o,command:function(){return e.runCommand(o)},label:"<svg ".concat(f," viewBox=\"0 0 24 24\">\n <path fill=\"currentColor\" d=\"M5,20H19V18H5M19,9H15V3H9V9H5L12,16L19,9Z\" />\n </svg>")},{id:c,command:function(){return e.runCommand(c)},label:"<svg ".concat(f," viewBox=\"0 0 24 24\">\n <path fill=\"currentColor\" d=\"M19,4H15.5L14.5,3H9.5L8.5,4H5V6H19M6,19A2,2 0 0,0 8,21H16A2,2 0 0,0 18,19V7H6V19Z\" />\n </svg>")}]},{id:'views',buttons:[{id:u,command:u,active:!0,label:"<svg ".concat(f," viewBox=\"0 0 24 24\">\n <path fill=\"currentColor\" d=\"M20.71,4.63L19.37,3.29C19,2.9 18.35,2.9 17.96,3.29L9,12.25L11.75,15L20.71,6.04C21.1,5.65 21.1,5 20.71,4.63M7,14A3,3 0 0,0 4,17C4,18.31 2.84,19 2,19C2.92,20.22 4.5,21 6,21A4,4 0 0,0 10,17A3,3 0 0,0 7,14Z\" />\n </svg>")},{id:m,command:m,label:"<svg ".concat(f," viewBox=\"0 0 24 24\">\n <path fill=\"currentColor\" d=\"M12,15.5A3.5,3.5 0 0,1 8.5,12A3.5,3.5 0 0,1 12,8.5A3.5,3.5 0 0,1 15.5,12A3.5,3.5 0 0,1 12,15.5M19.43,12.97C19.47,12.65 19.5,12.33 19.5,12C19.5,11.67 19.47,11.34 19.43,11L21.54,9.37C21.73,9.22 21.78,8.95 21.66,8.73L19.66,5.27C19.54,5.05 19.27,4.96 19.05,5.05L16.56,6.05C16.04,5.66 15.5,5.32 14.87,5.07L14.5,2.42C14.46,2.18 14.25,2 14,2H10C9.75,2 9.54,2.18 9.5,2.42L9.13,5.07C8.5,5.32 7.96,5.66 7.44,6.05L4.95,5.05C4.73,4.96 4.46,5.05 4.34,5.27L2.34,8.73C2.21,8.95 2.27,9.22 2.46,9.37L4.57,11C4.53,11.34 4.5,11.67 4.5,12C4.5,12.33 4.53,12.65 4.57,12.97L2.46,14.63C2.27,14.78 2.21,15.05 2.34,15.27L4.34,18.73C4.46,18.95 4.73,19.03 4.95,18.95L7.44,17.94C7.96,18.34 8.5,18.68 9.13,18.93L9.5,21.58C9.54,21.82 9.75,22 10,22H14C14.25,22 14.46,21.82 14.5,21.58L14.87,18.93C15.5,18.67 16.04,18.34 16.56,17.94L19.05,18.95C19.27,19.03 19.54,18.95 19.66,18.73L21.66,15.27C21.78,15.05 21.73,14.78 21.54,14.63L19.43,12.97Z\" />\n </svg>")},{id:p,command:p,label:"<svg ".concat(f," viewBox=\"0 0 24 24\">\n <path fill=\"currentColor\" d=\"M12,16L19.36,10.27L21,9L12,2L3,9L4.63,10.27M12,18.54L4.62,12.81L3,14.07L12,21.07L21,14.07L19.37,12.8L12,18.54Z\" />\n </svg>")},{id:v,command:v,label:"<svg ".concat(f," viewBox=\"0 0 24 24\">\n <path fill=\"currentColor\" d=\"M17,13H13V17H11V13H7V11H11V7H13V11H17M19,3H5C3.89,3 3,3.89 3,5V19A2,2 0 0,0 5,21H19A2,2 0 0,0 21,19V5C21,3.89 20.1,3 19,3Z\" />\n </svg>")}]}]);var g=t.getButton('views',v);e.on('load',(function(){return null==g?void 0:g.set('active',!0)})),n.showStylesOnChange&&e.on('component:selected',(function(){var n=t.getButton('views',u),o=t.getButton('views',p);o&&o.get('active')||!e.getSelected()||null==n||n.set('active',!0)}))}(e,l)};return n})())); //# sourceMappingURL=index.js.map /***/ }), /***/ "./node_modules/ieee754/index.js": /*!***************************************!*\ !*** ./node_modules/ieee754/index.js ***! \***************************************/ /***/ ((__unused_webpack_module, exports) => { /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */ exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m var eLen = (nBytes * 8) - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var nBits = -7 var i = isLE ? (nBytes - 1) : 0 var d = isLE ? -1 : 1 var s = buffer[offset + i] i += d e = s & ((1 << (-nBits)) - 1) s >>= (-nBits) nBits += eLen for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} m = e & ((1 << (-nBits)) - 1) e >>= (-nBits) nBits += mLen for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} if (e === 0) { e = 1 - eBias } else if (e === eMax) { return m ? NaN : ((s ? -1 : 1) * Infinity) } else { m = m + Math.pow(2, mLen) e = e - eBias } return (s ? -1 : 1) * m * Math.pow(2, e - mLen) } exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { var e, m, c var eLen = (nBytes * 8) - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) var i = isLE ? 0 : (nBytes - 1) var d = isLE ? 1 : -1 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 value = Math.abs(value) if (isNaN(value) || value === Infinity) { m = isNaN(value) ? 1 : 0 e = eMax } else { e = Math.floor(Math.log(value) / Math.LN2) if (value * (c = Math.pow(2, -e)) < 1) { e-- c *= 2 } if (e + eBias >= 1) { value += rt / c } else { value += rt * Math.pow(2, 1 - eBias) } if (value * c >= 2) { e++ c /= 2 } if (e + eBias >= eMax) { m = 0 e = eMax } else if (e + eBias >= 1) { m = ((value * c) - 1) * Math.pow(2, mLen) e = e + eBias } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) e = 0 } } for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} e = (e << mLen) | m eLen += mLen for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} buffer[offset + i - d] |= s * 128 } /***/ }), /***/ "./node_modules/isarray/index.js": /*!***************************************!*\ !*** ./node_modules/isarray/index.js ***! \***************************************/ /***/ ((module) => { var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; /***/ }), /***/ "./resources/css/app.css": /*!*******************************!*\ !*** ./resources/css/app.css ***! \*******************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); // extracted by mini-css-extract-plugin /***/ }), /***/ "./node_modules/react-dom/cjs/react-dom.development.js": /*!*************************************************************!*\ !*** ./node_modules/react-dom/cjs/react-dom.development.js ***! \*************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /** * @license React * react-dom.development.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ if (true) { (function() { 'use strict'; /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */ if ( typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === 'function' ) { __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error()); } var React = __webpack_require__(/*! react */ "./node_modules/react/index.js"); var Scheduler = __webpack_require__(/*! scheduler */ "./node_modules/scheduler/index.js"); var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; var suppressWarning = false; function setSuppressWarning(newSuppressWarning) { { suppressWarning = newSuppressWarning; } } // In DEV, calls to console.warn and console.error get replaced // by calls to these methods by a Babel plugin. // // In PROD (or in packages without access to React internals), // they are left as they are instead. function warn(format) { { if (!suppressWarning) { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } printWarning('warn', format, args); } } } function error(format) { { if (!suppressWarning) { for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } printWarning('error', format, args); } } } function printWarning(level, format, args) { // When changing this logic, you might want to also // update consoleWithStackDev.www.js as well. { var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; var stack = ReactDebugCurrentFrame.getStackAddendum(); if (stack !== '') { format += '%s'; args = args.concat([stack]); } // eslint-disable-next-line react-internal/safe-string-coercion var argsWithFormat = args.map(function (item) { return String(item); }); // Careful: RN currently depends on this prefix argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it // breaks IE9: https://github.com/facebook/react/issues/13610 // eslint-disable-next-line react-internal/no-production-logging Function.prototype.apply.call(console[level], console, argsWithFormat); } } var FunctionComponent = 0; var ClassComponent = 1; var IndeterminateComponent = 2; // Before we know whether it is function or class var HostRoot = 3; // Root of a host tree. Could be nested inside another node. var HostPortal = 4; // A subtree. Could be an entry point to a different renderer. var HostComponent = 5; var HostText = 6; var Fragment = 7; var Mode = 8; var ContextConsumer = 9; var ContextProvider = 10; var ForwardRef = 11; var Profiler = 12; var SuspenseComponent = 13; var MemoComponent = 14; var SimpleMemoComponent = 15; var LazyComponent = 16; var IncompleteClassComponent = 17; var DehydratedFragment = 18; var SuspenseListComponent = 19; var ScopeComponent = 21; var OffscreenComponent = 22; var LegacyHiddenComponent = 23; var CacheComponent = 24; var TracingMarkerComponent = 25; // ----------------------------------------------------------------------------- var enableClientRenderFallbackOnTextMismatch = true; // TODO: Need to review this code one more time before landing // the react-reconciler package. var enableNewReconciler = false; // Support legacy Primer support on internal FB www var enableLazyContextPropagation = false; // FB-only usage. The new API has different semantics. var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber var enableSuspenseAvoidThisFallback = false; // Enables unstable_avoidThisFallback feature in Fizz // React DOM Chopping Block // // Similar to main Chopping Block but only flags related to React DOM. These are // grouped because we will likely batch all of them into a single major release. // ----------------------------------------------------------------------------- // Disable support for comment nodes as React DOM containers. Already disabled // in open source, but www codebase still relies on it. Need to remove. var disableCommentsAsDOMContainers = true; // Disable javascript: URL strings in href for XSS protection. // and client rendering, mostly to allow JSX attributes to apply to the custom // element's object properties instead of only HTML attributes. // https://github.com/facebook/react/issues/11347 var enableCustomElementPropertySupport = false; // Disables children for <textarea> elements var warnAboutStringRefs = false; // ----------------------------------------------------------------------------- // Debugging and DevTools // ----------------------------------------------------------------------------- // Adds user timing marks for e.g. state updates, suspense, and work loop stuff, // for an experimental timeline tool. var enableSchedulingProfiler = true; // Helps identify side effects in render-phase lifecycle hooks and setState var enableProfilerTimer = true; // Record durations for commit and passive effects phases. var enableProfilerCommitHooks = true; // Phase param passed to onRender callback differentiates between an "update" and a "cascading-update". var allNativeEvents = new Set(); /** * Mapping from registration name to event name */ var registrationNameDependencies = {}; /** * Mapping from lowercase registration names to the properly cased version, * used to warn in the case of missing event handlers. Available * only in true. * @type {Object} */ var possibleRegistrationNames = {} ; // Trust the developer to only use possibleRegistrationNames in true function registerTwoPhaseEvent(registrationName, dependencies) { registerDirectEvent(registrationName, dependencies); registerDirectEvent(registrationName + 'Capture', dependencies); } function registerDirectEvent(registrationName, dependencies) { { if (registrationNameDependencies[registrationName]) { error('EventRegistry: More than one plugin attempted to publish the same ' + 'registration name, `%s`.', registrationName); } } registrationNameDependencies[registrationName] = dependencies; { var lowerCasedName = registrationName.toLowerCase(); possibleRegistrationNames[lowerCasedName] = registrationName; if (registrationName === 'onDoubleClick') { possibleRegistrationNames.ondblclick = registrationName; } } for (var i = 0; i < dependencies.length; i++) { allNativeEvents.add(dependencies[i]); } } var canUseDOM = !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined'); var hasOwnProperty = Object.prototype.hasOwnProperty; /* * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol * and Temporal.* types. See https://github.com/facebook/react/pull/22064. * * The functions in this module will throw an easier-to-understand, * easier-to-debug exception with a clear errors message message explaining the * problem. (Instead of a confusing exception thrown inside the implementation * of the `value` object). */ // $FlowFixMe only called in DEV, so void return is not possible. function typeName(value) { { // toStringTag is needed for namespaced types like Temporal.Instant var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag; var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object'; return type; } } // $FlowFixMe only called in DEV, so void return is not possible. function willCoercionThrow(value) { { try { testStringCoercion(value); return false; } catch (e) { return true; } } } function testStringCoercion(value) { // If you ended up here by following an exception call stack, here's what's // happened: you supplied an object or symbol value to React (as a prop, key, // DOM attribute, CSS property, string ref, etc.) and when React tried to // coerce it to a string using `'' + value`, an exception was thrown. // // The most common types that will cause this exception are `Symbol` instances // and Temporal objects like `Temporal.Instant`. But any object that has a // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this // exception. (Library authors do this to prevent users from using built-in // numeric operators like `+` or comparison operators like `>=` because custom // methods are needed to perform accurate arithmetic or comparison.) // // To fix the problem, coerce this object or symbol value to a string before // passing it to React. The most reliable way is usually `String(value)`. // // To find which value is throwing, check the browser or debugger console. // Before this exception was thrown, there should be `console.error` output // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the // problem and how that type was used: key, atrribute, input value prop, etc. // In most cases, this console output also shows the component and its // ancestor components where the exception happened. // // eslint-disable-next-line react-internal/safe-string-coercion return '' + value; } function checkAttributeStringCoercion(value, attributeName) { { if (willCoercionThrow(value)) { error('The provided `%s` attribute is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', attributeName, typeName(value)); return testStringCoercion(value); // throw (to help callers find troubleshooting comments) } } } function checkKeyStringCoercion(value) { { if (willCoercionThrow(value)) { error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value)); return testStringCoercion(value); // throw (to help callers find troubleshooting comments) } } } function checkPropStringCoercion(value, propName) { { if (willCoercionThrow(value)) { error('The provided `%s` prop is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', propName, typeName(value)); return testStringCoercion(value); // throw (to help callers find troubleshooting comments) } } } function checkCSSPropertyStringCoercion(value, propName) { { if (willCoercionThrow(value)) { error('The provided `%s` CSS property is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', propName, typeName(value)); return testStringCoercion(value); // throw (to help callers find troubleshooting comments) } } } function checkHtmlStringCoercion(value) { { if (willCoercionThrow(value)) { error('The provided HTML markup uses a value of unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value)); return testStringCoercion(value); // throw (to help callers find troubleshooting comments) } } } function checkFormFieldValueStringCoercion(value) { { if (willCoercionThrow(value)) { error('Form field values (value, checked, defaultValue, or defaultChecked props)' + ' must be strings, not %s.' + ' This value must be coerced to a string before before using it here.', typeName(value)); return testStringCoercion(value); // throw (to help callers find troubleshooting comments) } } } // A reserved attribute. // It is handled by React separately and shouldn't be written to the DOM. var RESERVED = 0; // A simple string attribute. // Attributes that aren't in the filter are presumed to have this type. var STRING = 1; // A string attribute that accepts booleans in React. In HTML, these are called // "enumerated" attributes with "true" and "false" as possible values. // When true, it should be set to a "true" string. // When false, it should be set to a "false" string. var BOOLEANISH_STRING = 2; // A real boolean attribute. // When true, it should be present (set either to an empty string or its name). // When false, it should be omitted. var BOOLEAN = 3; // An attribute that can be used as a flag as well as with a value. // When true, it should be present (set either to an empty string or its name). // When false, it should be omitted. // For any other value, should be present with that value. var OVERLOADED_BOOLEAN = 4; // An attribute that must be numeric or parse as a numeric. // When falsy, it should be removed. var NUMERIC = 5; // An attribute that must be positive numeric or parse as a positive numeric. // When falsy, it should be removed. var POSITIVE_NUMERIC = 6; /* eslint-disable max-len */ var ATTRIBUTE_NAME_START_CHAR = ":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD"; /* eslint-enable max-len */ var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + "\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040"; var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + ATTRIBUTE_NAME_START_CHAR + '][' + ATTRIBUTE_NAME_CHAR + ']*$'); var illegalAttributeNameCache = {}; var validatedAttributeNameCache = {}; function isAttributeNameSafe(attributeName) { if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) { return true; } if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) { return false; } if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) { validatedAttributeNameCache[attributeName] = true; return true; } illegalAttributeNameCache[attributeName] = true; { error('Invalid attribute name: `%s`', attributeName); } return false; } function shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag) { if (propertyInfo !== null) { return propertyInfo.type === RESERVED; } if (isCustomComponentTag) { return false; } if (name.length > 2 && (name[0] === 'o' || name[0] === 'O') && (name[1] === 'n' || name[1] === 'N')) { return true; } return false; } function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) { if (propertyInfo !== null && propertyInfo.type === RESERVED) { return false; } switch (typeof value) { case 'function': // $FlowIssue symbol is perfectly valid here case 'symbol': // eslint-disable-line return true; case 'boolean': { if (isCustomComponentTag) { return false; } if (propertyInfo !== null) { return !propertyInfo.acceptsBooleans; } else { var prefix = name.toLowerCase().slice(0, 5); return prefix !== 'data-' && prefix !== 'aria-'; } } default: return false; } } function shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag) { if (value === null || typeof value === 'undefined') { return true; } if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag)) { return true; } if (isCustomComponentTag) { return false; } if (propertyInfo !== null) { switch (propertyInfo.type) { case BOOLEAN: return !value; case OVERLOADED_BOOLEAN: return value === false; case NUMERIC: return isNaN(value); case POSITIVE_NUMERIC: return isNaN(value) || value < 1; } } return false; } function getPropertyInfo(name) { return properties.hasOwnProperty(name) ? properties[name] : null; } function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace, sanitizeURL, removeEmptyString) { this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN; this.attributeName = attributeName; this.attributeNamespace = attributeNamespace; this.mustUseProperty = mustUseProperty; this.propertyName = name; this.type = type; this.sanitizeURL = sanitizeURL; this.removeEmptyString = removeEmptyString; } // When adding attributes to this list, be sure to also add them to // the `possibleStandardNames` module to ensure casing and incorrect // name warnings. var properties = {}; // These props are reserved by React. They shouldn't be written to the DOM. var reservedProps = ['children', 'dangerouslySetInnerHTML', // TODO: This prevents the assignment of defaultValue to regular // elements (not just inputs). Now that ReactDOMInput assigns to the // defaultValue property -- do we need this? 'defaultValue', 'defaultChecked', 'innerHTML', 'suppressContentEditableWarning', 'suppressHydrationWarning', 'style']; reservedProps.forEach(function (name) { properties[name] = new PropertyInfoRecord(name, RESERVED, false, // mustUseProperty name, // attributeName null, // attributeNamespace false, // sanitizeURL false); }); // A few React string attributes have a different name. // This is a mapping from React prop names to the attribute names. [['acceptCharset', 'accept-charset'], ['className', 'class'], ['htmlFor', 'for'], ['httpEquiv', 'http-equiv']].forEach(function (_ref) { var name = _ref[0], attributeName = _ref[1]; properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty attributeName, // attributeName null, // attributeNamespace false, // sanitizeURL false); }); // These are "enumerated" HTML attributes that accept "true" and "false". // In React, we let users pass `true` and `false` even though technically // these aren't boolean attributes (they are coerced to strings). ['contentEditable', 'draggable', 'spellCheck', 'value'].forEach(function (name) { properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty name.toLowerCase(), // attributeName null, // attributeNamespace false, // sanitizeURL false); }); // These are "enumerated" SVG attributes that accept "true" and "false". // In React, we let users pass `true` and `false` even though technically // these aren't boolean attributes (they are coerced to strings). // Since these are SVG attributes, their attribute names are case-sensitive. ['autoReverse', 'externalResourcesRequired', 'focusable', 'preserveAlpha'].forEach(function (name) { properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty name, // attributeName null, // attributeNamespace false, // sanitizeURL false); }); // These are HTML boolean attributes. ['allowFullScreen', 'async', // Note: there is a special case that prevents it from being written to the DOM // on the client side because the browsers are inconsistent. Instead we call focus(). 'autoFocus', 'autoPlay', 'controls', 'default', 'defer', 'disabled', 'disablePictureInPicture', 'disableRemotePlayback', 'formNoValidate', 'hidden', 'loop', 'noModule', 'noValidate', 'open', 'playsInline', 'readOnly', 'required', 'reversed', 'scoped', 'seamless', // Microdata 'itemScope'].forEach(function (name) { properties[name] = new PropertyInfoRecord(name, BOOLEAN, false, // mustUseProperty name.toLowerCase(), // attributeName null, // attributeNamespace false, // sanitizeURL false); }); // These are the few React props that we set as DOM properties // rather than attributes. These are all booleans. ['checked', // Note: `option.selected` is not updated if `select.multiple` is // disabled with `removeAttribute`. We have special logic for handling this. 'multiple', 'muted', 'selected' // NOTE: if you add a camelCased prop to this list, // you'll need to set attributeName to name.toLowerCase() // instead in the assignment below. ].forEach(function (name) { properties[name] = new PropertyInfoRecord(name, BOOLEAN, true, // mustUseProperty name, // attributeName null, // attributeNamespace false, // sanitizeURL false); }); // These are HTML attributes that are "overloaded booleans": they behave like // booleans, but can also accept a string value. ['capture', 'download' // NOTE: if you add a camelCased prop to this list, // you'll need to set attributeName to name.toLowerCase() // instead in the assignment below. ].forEach(function (name) { properties[name] = new PropertyInfoRecord(name, OVERLOADED_BOOLEAN, false, // mustUseProperty name, // attributeName null, // attributeNamespace false, // sanitizeURL false); }); // These are HTML attributes that must be positive numbers. ['cols', 'rows', 'size', 'span' // NOTE: if you add a camelCased prop to this list, // you'll need to set attributeName to name.toLowerCase() // instead in the assignment below. ].forEach(function (name) { properties[name] = new PropertyInfoRecord(name, POSITIVE_NUMERIC, false, // mustUseProperty name, // attributeName null, // attributeNamespace false, // sanitizeURL false); }); // These are HTML attributes that must be numbers. ['rowSpan', 'start'].forEach(function (name) { properties[name] = new PropertyInfoRecord(name, NUMERIC, false, // mustUseProperty name.toLowerCase(), // attributeName null, // attributeNamespace false, // sanitizeURL false); }); var CAMELIZE = /[\-\:]([a-z])/g; var capitalize = function (token) { return token[1].toUpperCase(); }; // This is a list of all SVG attributes that need special casing, namespacing, // or boolean value assignment. Regular attributes that just accept strings // and have the same names are omitted, just like in the HTML attribute filter. // Some of these attributes can be hard to find. This list was created by // scraping the MDN documentation. ['accent-height', 'alignment-baseline', 'arabic-form', 'baseline-shift', 'cap-height', 'clip-path', 'clip-rule', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'dominant-baseline', 'enable-background', 'fill-opacity', 'fill-rule', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'glyph-name', 'glyph-orientation-horizontal', 'glyph-orientation-vertical', 'horiz-adv-x', 'horiz-origin-x', 'image-rendering', 'letter-spacing', 'lighting-color', 'marker-end', 'marker-mid', 'marker-start', 'overline-position', 'overline-thickness', 'paint-order', 'panose-1', 'pointer-events', 'rendering-intent', 'shape-rendering', 'stop-color', 'stop-opacity', 'strikethrough-position', 'strikethrough-thickness', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-decoration', 'text-rendering', 'underline-position', 'underline-thickness', 'unicode-bidi', 'unicode-range', 'units-per-em', 'v-alphabetic', 'v-hanging', 'v-ideographic', 'v-mathematical', 'vector-effect', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'word-spacing', 'writing-mode', 'xmlns:xlink', 'x-height' // NOTE: if you add a camelCased prop to this list, // you'll need to set attributeName to name.toLowerCase() // instead in the assignment below. ].forEach(function (attributeName) { var name = attributeName.replace(CAMELIZE, capitalize); properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty attributeName, null, // attributeNamespace false, // sanitizeURL false); }); // String SVG attributes with the xlink namespace. ['xlink:actuate', 'xlink:arcrole', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type' // NOTE: if you add a camelCased prop to this list, // you'll need to set attributeName to name.toLowerCase() // instead in the assignment below. ].forEach(function (attributeName) { var name = attributeName.replace(CAMELIZE, capitalize); properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty attributeName, 'http://www.w3.org/1999/xlink', false, // sanitizeURL false); }); // String SVG attributes with the xml namespace. ['xml:base', 'xml:lang', 'xml:space' // NOTE: if you add a camelCased prop to this list, // you'll need to set attributeName to name.toLowerCase() // instead in the assignment below. ].forEach(function (attributeName) { var name = attributeName.replace(CAMELIZE, capitalize); properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty attributeName, 'http://www.w3.org/XML/1998/namespace', false, // sanitizeURL false); }); // These attribute exists both in HTML and SVG. // The attribute name is case-sensitive in SVG so we can't just use // the React name like we do for attributes that exist only in HTML. ['tabIndex', 'crossOrigin'].forEach(function (attributeName) { properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty attributeName.toLowerCase(), // attributeName null, // attributeNamespace false, // sanitizeURL false); }); // These attributes accept URLs. These must not allow javascript: URLS. // These will also need to accept Trusted Types object in the future. var xlinkHref = 'xlinkHref'; properties[xlinkHref] = new PropertyInfoRecord('xlinkHref', STRING, false, // mustUseProperty 'xlink:href', 'http://www.w3.org/1999/xlink', true, // sanitizeURL false); ['src', 'href', 'action', 'formAction'].forEach(function (attributeName) { properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty attributeName.toLowerCase(), // attributeName null, // attributeNamespace true, // sanitizeURL true); }); // and any newline or tab are filtered out as if they're not part of the URL. // https://url.spec.whatwg.org/#url-parsing // Tab or newline are defined as \r\n\t: // https://infra.spec.whatwg.org/#ascii-tab-or-newline // A C0 control is a code point in the range \u0000 NULL to \u001F // INFORMATION SEPARATOR ONE, inclusive: // https://infra.spec.whatwg.org/#c0-control-or-space /* eslint-disable max-len */ var isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i; var didWarn = false; function sanitizeURL(url) { { if (!didWarn && isJavaScriptProtocol.test(url)) { didWarn = true; error('A future version of React will block javascript: URLs as a security precaution. ' + 'Use event handlers instead if you can. If you need to generate unsafe HTML try ' + 'using dangerouslySetInnerHTML instead. React was passed %s.', JSON.stringify(url)); } } } /** * Get the value for a property on a node. Only used in DEV for SSR validation. * The "expected" argument is used as a hint of what the expected value is. * Some properties have multiple equivalent values. */ function getValueForProperty(node, name, expected, propertyInfo) { { if (propertyInfo.mustUseProperty) { var propertyName = propertyInfo.propertyName; return node[propertyName]; } else { // This check protects multiple uses of `expected`, which is why the // react-internal/safe-string-coercion rule is disabled in several spots // below. { checkAttributeStringCoercion(expected, name); } if ( propertyInfo.sanitizeURL) { // If we haven't fully disabled javascript: URLs, and if // the hydration is successful of a javascript: URL, we // still want to warn on the client. // eslint-disable-next-line react-internal/safe-string-coercion sanitizeURL('' + expected); } var attributeName = propertyInfo.attributeName; var stringValue = null; if (propertyInfo.type === OVERLOADED_BOOLEAN) { if (node.hasAttribute(attributeName)) { var value = node.getAttribute(attributeName); if (value === '') { return true; } if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { return value; } // eslint-disable-next-line react-internal/safe-string-coercion if (value === '' + expected) { return expected; } return value; } } else if (node.hasAttribute(attributeName)) { if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { // We had an attribute but shouldn't have had one, so read it // for the error message. return node.getAttribute(attributeName); } if (propertyInfo.type === BOOLEAN) { // If this was a boolean, it doesn't matter what the value is // the fact that we have it is the same as the expected. return expected; } // Even if this property uses a namespace we use getAttribute // because we assume its namespaced name is the same as our config. // To use getAttributeNS we need the local name which we don't have // in our config atm. stringValue = node.getAttribute(attributeName); } if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { return stringValue === null ? expected : stringValue; // eslint-disable-next-line react-internal/safe-string-coercion } else if (stringValue === '' + expected) { return expected; } else { return stringValue; } } } } /** * Get the value for a attribute on a node. Only used in DEV for SSR validation. * The third argument is used as a hint of what the expected value is. Some * attributes have multiple equivalent values. */ function getValueForAttribute(node, name, expected, isCustomComponentTag) { { if (!isAttributeNameSafe(name)) { return; } if (!node.hasAttribute(name)) { return expected === undefined ? undefined : null; } var value = node.getAttribute(name); { checkAttributeStringCoercion(expected, name); } if (value === '' + expected) { return expected; } return value; } } /** * Sets the value for a property on a node. * * @param {DOMElement} node * @param {string} name * @param {*} value */ function setValueForProperty(node, name, value, isCustomComponentTag) { var propertyInfo = getPropertyInfo(name); if (shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag)) { return; } if (shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag)) { value = null; } if (isCustomComponentTag || propertyInfo === null) { if (isAttributeNameSafe(name)) { var _attributeName = name; if (value === null) { node.removeAttribute(_attributeName); } else { { checkAttributeStringCoercion(value, name); } node.setAttribute(_attributeName, '' + value); } } return; } var mustUseProperty = propertyInfo.mustUseProperty; if (mustUseProperty) { var propertyName = propertyInfo.propertyName; if (value === null) { var type = propertyInfo.type; node[propertyName] = type === BOOLEAN ? false : ''; } else { // Contrary to `setAttribute`, object properties are properly // `toString`ed by IE8/9. node[propertyName] = value; } return; } // The rest are treated as attributes with special cases. var attributeName = propertyInfo.attributeName, attributeNamespace = propertyInfo.attributeNamespace; if (value === null) { node.removeAttribute(attributeName); } else { var _type = propertyInfo.type; var attributeValue; if (_type === BOOLEAN || _type === OVERLOADED_BOOLEAN && value === true) { // If attribute type is boolean, we know for sure it won't be an execution sink // and we won't require Trusted Type here. attributeValue = ''; } else { // `setAttribute` with objects becomes only `[object]` in IE8/9, // ('' + value) makes it output the correct toString()-value. { { checkAttributeStringCoercion(value, attributeName); } attributeValue = '' + value; } if (propertyInfo.sanitizeURL) { sanitizeURL(attributeValue.toString()); } } if (attributeNamespace) { node.setAttributeNS(attributeNamespace, attributeName, attributeValue); } else { node.setAttribute(attributeName, attributeValue); } } } // ATTENTION // When adding new symbols to this file, // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' // The Symbol used to tag the ReactElement-like types. var REACT_ELEMENT_TYPE = Symbol.for('react.element'); var REACT_PORTAL_TYPE = Symbol.for('react.portal'); var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment'); var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode'); var REACT_PROFILER_TYPE = Symbol.for('react.profiler'); var REACT_PROVIDER_TYPE = Symbol.for('react.provider'); var REACT_CONTEXT_TYPE = Symbol.for('react.context'); var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref'); var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense'); var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list'); var REACT_MEMO_TYPE = Symbol.for('react.memo'); var REACT_LAZY_TYPE = Symbol.for('react.lazy'); var REACT_SCOPE_TYPE = Symbol.for('react.scope'); var REACT_DEBUG_TRACING_MODE_TYPE = Symbol.for('react.debug_trace_mode'); var REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen'); var REACT_LEGACY_HIDDEN_TYPE = Symbol.for('react.legacy_hidden'); var REACT_CACHE_TYPE = Symbol.for('react.cache'); var REACT_TRACING_MARKER_TYPE = Symbol.for('react.tracing_marker'); var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; function getIteratorFn(maybeIterable) { if (maybeIterable === null || typeof maybeIterable !== 'object') { return null; } var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; if (typeof maybeIterator === 'function') { return maybeIterator; } return null; } var assign = Object.assign; // Helpers to patch console.logs to avoid logging during side-effect free // replaying on render function. This currently only patches the object // lazily which won't cover if the log function was extracted eagerly. // We could also eagerly patch the method. var disabledDepth = 0; var prevLog; var prevInfo; var prevWarn; var prevError; var prevGroup; var prevGroupCollapsed; var prevGroupEnd; function disabledLog() {} disabledLog.__reactDisabledLog = true; function disableLogs() { { if (disabledDepth === 0) { /* eslint-disable react-internal/no-production-logging */ prevLog = console.log; prevInfo = console.info; prevWarn = console.warn; prevError = console.error; prevGroup = console.group; prevGroupCollapsed = console.groupCollapsed; prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099 var props = { configurable: true, enumerable: true, value: disabledLog, writable: true }; // $FlowFixMe Flow thinks console is immutable. Object.defineProperties(console, { info: props, log: props, warn: props, error: props, group: props, groupCollapsed: props, groupEnd: props }); /* eslint-enable react-internal/no-production-logging */ } disabledDepth++; } } function reenableLogs() { { disabledDepth--; if (disabledDepth === 0) { /* eslint-disable react-internal/no-production-logging */ var props = { configurable: true, enumerable: true, writable: true }; // $FlowFixMe Flow thinks console is immutable. Object.defineProperties(console, { log: assign({}, props, { value: prevLog }), info: assign({}, props, { value: prevInfo }), warn: assign({}, props, { value: prevWarn }), error: assign({}, props, { value: prevError }), group: assign({}, props, { value: prevGroup }), groupCollapsed: assign({}, props, { value: prevGroupCollapsed }), groupEnd: assign({}, props, { value: prevGroupEnd }) }); /* eslint-enable react-internal/no-production-logging */ } if (disabledDepth < 0) { error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.'); } } } var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; var prefix; function describeBuiltInComponentFrame(name, source, ownerFn) { { if (prefix === undefined) { // Extract the VM specific prefix used by each line. try { throw Error(); } catch (x) { var match = x.stack.trim().match(/\n( *(at )?)/); prefix = match && match[1] || ''; } } // We use the prefix to ensure our stacks line up with native stack frames. return '\n' + prefix + name; } } var reentry = false; var componentFrameCache; { var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map; componentFrameCache = new PossiblyWeakMap(); } function describeNativeComponentFrame(fn, construct) { // If something asked for a stack inside a fake render, it should get ignored. if ( !fn || reentry) { return ''; } { var frame = componentFrameCache.get(fn); if (frame !== undefined) { return frame; } } var control; reentry = true; var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined. Error.prepareStackTrace = undefined; var previousDispatcher; { previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function // for warnings. ReactCurrentDispatcher.current = null; disableLogs(); } try { // This should throw. if (construct) { // Something should be setting the props in the constructor. var Fake = function () { throw Error(); }; // $FlowFixMe Object.defineProperty(Fake.prototype, 'props', { set: function () { // We use a throwing setter instead of frozen or non-writable props // because that won't throw in a non-strict mode function. throw Error(); } }); if (typeof Reflect === 'object' && Reflect.construct) { // We construct a different control for this case to include any extra // frames added by the construct call. try { Reflect.construct(Fake, []); } catch (x) { control = x; } Reflect.construct(fn, [], Fake); } else { try { Fake.call(); } catch (x) { control = x; } fn.call(Fake.prototype); } } else { try { throw Error(); } catch (x) { control = x; } fn(); } } catch (sample) { // This is inlined manually because closure doesn't do it for us. if (sample && control && typeof sample.stack === 'string') { // This extracts the first frame from the sample that isn't also in the control. // Skipping one frame that we assume is the frame that calls the two. var sampleLines = sample.stack.split('\n'); var controlLines = control.stack.split('\n'); var s = sampleLines.length - 1; var c = controlLines.length - 1; while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { // We expect at least one stack frame to be shared. // Typically this will be the root most one. However, stack frames may be // cut off due to maximum stack limits. In this case, one maybe cut off // earlier than the other. We assume that the sample is longer or the same // and there for cut off earlier. So we should find the root most frame in // the sample somewhere in the control. c--; } for (; s >= 1 && c >= 0; s--, c--) { // Next we find the first one that isn't the same which should be the // frame that called our sample function and the control. if (sampleLines[s] !== controlLines[c]) { // In V8, the first line is describing the message but other VMs don't. // If we're about to return the first line, and the control is also on the same // line, that's a pretty good indicator that our sample threw at same line as // the control. I.e. before we entered the sample frame. So we ignore this result. // This can happen if you passed a class to function component, or non-function. if (s !== 1 || c !== 1) { do { s--; c--; // We may still have similar intermediate frames from the construct call. // The next one that isn't the same should be our match though. if (c < 0 || sampleLines[s] !== controlLines[c]) { // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier. var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "<anonymous>" // but we have a user-provided "displayName" // splice it in to make the stack more readable. if (fn.displayName && _frame.includes('<anonymous>')) { _frame = _frame.replace('<anonymous>', fn.displayName); } { if (typeof fn === 'function') { componentFrameCache.set(fn, _frame); } } // Return the line we found. return _frame; } } while (s >= 1 && c >= 0); } break; } } } } finally { reentry = false; { ReactCurrentDispatcher.current = previousDispatcher; reenableLogs(); } Error.prepareStackTrace = previousPrepareStackTrace; } // Fallback to just using the name if we couldn't make it throw. var name = fn ? fn.displayName || fn.name : ''; var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ''; { if (typeof fn === 'function') { componentFrameCache.set(fn, syntheticFrame); } } return syntheticFrame; } function describeClassComponentFrame(ctor, source, ownerFn) { { return describeNativeComponentFrame(ctor, true); } } function describeFunctionComponentFrame(fn, source, ownerFn) { { return describeNativeComponentFrame(fn, false); } } function shouldConstruct(Component) { var prototype = Component.prototype; return !!(prototype && prototype.isReactComponent); } function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { if (type == null) { return ''; } if (typeof type === 'function') { { return describeNativeComponentFrame(type, shouldConstruct(type)); } } if (typeof type === 'string') { return describeBuiltInComponentFrame(type); } switch (type) { case REACT_SUSPENSE_TYPE: return describeBuiltInComponentFrame('Suspense'); case REACT_SUSPENSE_LIST_TYPE: return describeBuiltInComponentFrame('SuspenseList'); } if (typeof type === 'object') { switch (type.$$typeof) { case REACT_FORWARD_REF_TYPE: return describeFunctionComponentFrame(type.render); case REACT_MEMO_TYPE: // Memo may contain any component type so we recursively resolve it. return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); case REACT_LAZY_TYPE: { var lazyComponent = type; var payload = lazyComponent._payload; var init = lazyComponent._init; try { // Lazy may contain any component type so we recursively resolve it. return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); } catch (x) {} } } } return ''; } function describeFiber(fiber) { var owner = fiber._debugOwner ? fiber._debugOwner.type : null ; var source = fiber._debugSource ; switch (fiber.tag) { case HostComponent: return describeBuiltInComponentFrame(fiber.type); case LazyComponent: return describeBuiltInComponentFrame('Lazy'); case SuspenseComponent: return describeBuiltInComponentFrame('Suspense'); case SuspenseListComponent: return describeBuiltInComponentFrame('SuspenseList'); case FunctionComponent: case IndeterminateComponent: case SimpleMemoComponent: return describeFunctionComponentFrame(fiber.type); case ForwardRef: return describeFunctionComponentFrame(fiber.type.render); case ClassComponent: return describeClassComponentFrame(fiber.type); default: return ''; } } function getStackByFiberInDevAndProd(workInProgress) { try { var info = ''; var node = workInProgress; do { info += describeFiber(node); node = node.return; } while (node); return info; } catch (x) { return '\nError generating stack: ' + x.message + '\n' + x.stack; } } function getWrappedName(outerType, innerType, wrapperName) { var displayName = outerType.displayName; if (displayName) { return displayName; } var functionName = innerType.displayName || innerType.name || ''; return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName; } // Keep in sync with react-reconciler/getComponentNameFromFiber function getContextName(type) { return type.displayName || 'Context'; } // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead. function getComponentNameFromType(type) { if (type == null) { // Host root, text node or just invalid type. return null; } { if (typeof type.tag === 'number') { error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.'); } } if (typeof type === 'function') { return type.displayName || type.name || null; } if (typeof type === 'string') { return type; } switch (type) { case REACT_FRAGMENT_TYPE: return 'Fragment'; case REACT_PORTAL_TYPE: return 'Portal'; case REACT_PROFILER_TYPE: return 'Profiler'; case REACT_STRICT_MODE_TYPE: return 'StrictMode'; case REACT_SUSPENSE_TYPE: return 'Suspense'; case REACT_SUSPENSE_LIST_TYPE: return 'SuspenseList'; } if (typeof type === 'object') { switch (type.$$typeof) { case REACT_CONTEXT_TYPE: var context = type; return getContextName(context) + '.Consumer'; case REACT_PROVIDER_TYPE: var provider = type; return getContextName(provider._context) + '.Provider'; case REACT_FORWARD_REF_TYPE: return getWrappedName(type, type.render, 'ForwardRef'); case REACT_MEMO_TYPE: var outerName = type.displayName || null; if (outerName !== null) { return outerName; } return getComponentNameFromType(type.type) || 'Memo'; case REACT_LAZY_TYPE: { var lazyComponent = type; var payload = lazyComponent._payload; var init = lazyComponent._init; try { return getComponentNameFromType(init(payload)); } catch (x) { return null; } } // eslint-disable-next-line no-fallthrough } } return null; } function getWrappedName$1(outerType, innerType, wrapperName) { var functionName = innerType.displayName || innerType.name || ''; return outerType.displayName || (functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName); } // Keep in sync with shared/getComponentNameFromType function getContextName$1(type) { return type.displayName || 'Context'; } function getComponentNameFromFiber(fiber) { var tag = fiber.tag, type = fiber.type; switch (tag) { case CacheComponent: return 'Cache'; case ContextConsumer: var context = type; return getContextName$1(context) + '.Consumer'; case ContextProvider: var provider = type; return getContextName$1(provider._context) + '.Provider'; case DehydratedFragment: return 'DehydratedFragment'; case ForwardRef: return getWrappedName$1(type, type.render, 'ForwardRef'); case Fragment: return 'Fragment'; case HostComponent: // Host component type is the display name (e.g. "div", "View") return type; case HostPortal: return 'Portal'; case HostRoot: return 'Root'; case HostText: return 'Text'; case LazyComponent: // Name comes from the type in this case; we don't have a tag. return getComponentNameFromType(type); case Mode: if (type === REACT_STRICT_MODE_TYPE) { // Don't be less specific than shared/getComponentNameFromType return 'StrictMode'; } return 'Mode'; case OffscreenComponent: return 'Offscreen'; case Profiler: return 'Profiler'; case ScopeComponent: return 'Scope'; case SuspenseComponent: return 'Suspense'; case SuspenseListComponent: return 'SuspenseList'; case TracingMarkerComponent: return 'TracingMarker'; // The display name for this tags come from the user-provided type: case ClassComponent: case FunctionComponent: case IncompleteClassComponent: case IndeterminateComponent: case MemoComponent: case SimpleMemoComponent: if (typeof type === 'function') { return type.displayName || type.name || null; } if (typeof type === 'string') { return type; } break; } return null; } var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; var current = null; var isRendering = false; function getCurrentFiberOwnerNameInDevOrNull() { { if (current === null) { return null; } var owner = current._debugOwner; if (owner !== null && typeof owner !== 'undefined') { return getComponentNameFromFiber(owner); } } return null; } function getCurrentFiberStackInDev() { { if (current === null) { return ''; } // Safe because if current fiber exists, we are reconciling, // and it is guaranteed to be the work-in-progress version. return getStackByFiberInDevAndProd(current); } } function resetCurrentFiber() { { ReactDebugCurrentFrame.getCurrentStack = null; current = null; isRendering = false; } } function setCurrentFiber(fiber) { { ReactDebugCurrentFrame.getCurrentStack = fiber === null ? null : getCurrentFiberStackInDev; current = fiber; isRendering = false; } } function getCurrentFiber() { { return current; } } function setIsRendering(rendering) { { isRendering = rendering; } } // Flow does not allow string concatenation of most non-string types. To work // around this limitation, we use an opaque type that can only be obtained by // passing the value through getToStringValue first. function toString(value) { // The coercion safety check is performed in getToStringValue(). // eslint-disable-next-line react-internal/safe-string-coercion return '' + value; } function getToStringValue(value) { switch (typeof value) { case 'boolean': case 'number': case 'string': case 'undefined': return value; case 'object': { checkFormFieldValueStringCoercion(value); } return value; default: // function, symbol are assigned as empty strings return ''; } } var hasReadOnlyValue = { button: true, checkbox: true, image: true, hidden: true, radio: true, reset: true, submit: true }; function checkControlledValueProps(tagName, props) { { if (!(hasReadOnlyValue[props.type] || props.onChange || props.onInput || props.readOnly || props.disabled || props.value == null)) { error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); } if (!(props.onChange || props.readOnly || props.disabled || props.checked == null)) { error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); } } } function isCheckable(elem) { var type = elem.type; var nodeName = elem.nodeName; return nodeName && nodeName.toLowerCase() === 'input' && (type === 'checkbox' || type === 'radio'); } function getTracker(node) { return node._valueTracker; } function detachTracker(node) { node._valueTracker = null; } function getValueFromNode(node) { var value = ''; if (!node) { return value; } if (isCheckable(node)) { value = node.checked ? 'true' : 'false'; } else { value = node.value; } return value; } function trackValueOnNode(node) { var valueField = isCheckable(node) ? 'checked' : 'value'; var descriptor = Object.getOwnPropertyDescriptor(node.constructor.prototype, valueField); { checkFormFieldValueStringCoercion(node[valueField]); } var currentValue = '' + node[valueField]; // if someone has already defined a value or Safari, then bail // and don't track value will cause over reporting of changes, // but it's better then a hard failure // (needed for certain tests that spyOn input values and Safari) if (node.hasOwnProperty(valueField) || typeof descriptor === 'undefined' || typeof descriptor.get !== 'function' || typeof descriptor.set !== 'function') { return; } var get = descriptor.get, set = descriptor.set; Object.defineProperty(node, valueField, { configurable: true, get: function () { return get.call(this); }, set: function (value) { { checkFormFieldValueStringCoercion(value); } currentValue = '' + value; set.call(this, value); } }); // We could've passed this the first time // but it triggers a bug in IE11 and Edge 14/15. // Calling defineProperty() again should be equivalent. // https://github.com/facebook/react/issues/11768 Object.defineProperty(node, valueField, { enumerable: descriptor.enumerable }); var tracker = { getValue: function () { return currentValue; }, setValue: function (value) { { checkFormFieldValueStringCoercion(value); } currentValue = '' + value; }, stopTracking: function () { detachTracker(node); delete node[valueField]; } }; return tracker; } function track(node) { if (getTracker(node)) { return; } // TODO: Once it's just Fiber we can move this to node._wrapperState node._valueTracker = trackValueOnNode(node); } function updateValueIfChanged(node) { if (!node) { return false; } var tracker = getTracker(node); // if there is no tracker at this point it's unlikely // that trying again will succeed if (!tracker) { return true; } var lastValue = tracker.getValue(); var nextValue = getValueFromNode(node); if (nextValue !== lastValue) { tracker.setValue(nextValue); return true; } return false; } function getActiveElement(doc) { doc = doc || (typeof document !== 'undefined' ? document : undefined); if (typeof doc === 'undefined') { return null; } try { return doc.activeElement || doc.body; } catch (e) { return doc.body; } } var didWarnValueDefaultValue = false; var didWarnCheckedDefaultChecked = false; var didWarnControlledToUncontrolled = false; var didWarnUncontrolledToControlled = false; function isControlled(props) { var usesChecked = props.type === 'checkbox' || props.type === 'radio'; return usesChecked ? props.checked != null : props.value != null; } /** * Implements an <input> host component that allows setting these optional * props: `checked`, `value`, `defaultChecked`, and `defaultValue`. * * If `checked` or `value` are not supplied (or null/undefined), user actions * that affect the checked state or value will trigger updates to the element. * * If they are supplied (and not null/undefined), the rendered element will not * trigger updates to the element. Instead, the props must change in order for * the rendered element to be updated. * * The rendered element will be initialized as unchecked (or `defaultChecked`) * with an empty value (or `defaultValue`). * * See http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html */ function getHostProps(element, props) { var node = element; var checked = props.checked; var hostProps = assign({}, props, { defaultChecked: undefined, defaultValue: undefined, value: undefined, checked: checked != null ? checked : node._wrapperState.initialChecked }); return hostProps; } function initWrapperState(element, props) { { checkControlledValueProps('input', props); if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnCheckedDefaultChecked) { error('%s contains an input of type %s with both checked and defaultChecked props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the checked prop, or the defaultChecked prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component', props.type); didWarnCheckedDefaultChecked = true; } if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) { error('%s contains an input of type %s with both value and defaultValue props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component', props.type); didWarnValueDefaultValue = true; } } var node = element; var defaultValue = props.defaultValue == null ? '' : props.defaultValue; node._wrapperState = { initialChecked: props.checked != null ? props.checked : props.defaultChecked, initialValue: getToStringValue(props.value != null ? props.value : defaultValue), controlled: isControlled(props) }; } function updateChecked(element, props) { var node = element; var checked = props.checked; if (checked != null) { setValueForProperty(node, 'checked', checked, false); } } function updateWrapper(element, props) { var node = element; { var controlled = isControlled(props); if (!node._wrapperState.controlled && controlled && !didWarnUncontrolledToControlled) { error('A component is changing an uncontrolled input to be controlled. ' + 'This is likely caused by the value changing from undefined to ' + 'a defined value, which should not happen. ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components'); didWarnUncontrolledToControlled = true; } if (node._wrapperState.controlled && !controlled && !didWarnControlledToUncontrolled) { error('A component is changing a controlled input to be uncontrolled. ' + 'This is likely caused by the value changing from a defined to ' + 'undefined, which should not happen. ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components'); didWarnControlledToUncontrolled = true; } } updateChecked(element, props); var value = getToStringValue(props.value); var type = props.type; if (value != null) { if (type === 'number') { if (value === 0 && node.value === '' || // We explicitly want to coerce to number here if possible. // eslint-disable-next-line node.value != value) { node.value = toString(value); } } else if (node.value !== toString(value)) { node.value = toString(value); } } else if (type === 'submit' || type === 'reset') { // Submit/reset inputs need the attribute removed completely to avoid // blank-text buttons. node.removeAttribute('value'); return; } { // When syncing the value attribute, the value comes from a cascade of // properties: // 1. The value React property // 2. The defaultValue React property // 3. Otherwise there should be no change if (props.hasOwnProperty('value')) { setDefaultValue(node, props.type, value); } else if (props.hasOwnProperty('defaultValue')) { setDefaultValue(node, props.type, getToStringValue(props.defaultValue)); } } { // When syncing the checked attribute, it only changes when it needs // to be removed, such as transitioning from a checkbox into a text input if (props.checked == null && props.defaultChecked != null) { node.defaultChecked = !!props.defaultChecked; } } } function postMountWrapper(element, props, isHydrating) { var node = element; // Do not assign value if it is already set. This prevents user text input // from being lost during SSR hydration. if (props.hasOwnProperty('value') || props.hasOwnProperty('defaultValue')) { var type = props.type; var isButton = type === 'submit' || type === 'reset'; // Avoid setting value attribute on submit/reset inputs as it overrides the // default value provided by the browser. See: #12872 if (isButton && (props.value === undefined || props.value === null)) { return; } var initialValue = toString(node._wrapperState.initialValue); // Do not assign value if it is already set. This prevents user text input // from being lost during SSR hydration. if (!isHydrating) { { // When syncing the value attribute, the value property should use // the wrapperState._initialValue property. This uses: // // 1. The value React property when present // 2. The defaultValue React property when present // 3. An empty string if (initialValue !== node.value) { node.value = initialValue; } } } { // Otherwise, the value attribute is synchronized to the property, // so we assign defaultValue to the same thing as the value property // assignment step above. node.defaultValue = initialValue; } } // Normally, we'd just do `node.checked = node.checked` upon initial mount, less this bug // this is needed to work around a chrome bug where setting defaultChecked // will sometimes influence the value of checked (even after detachment). // Reference: https://bugs.chromium.org/p/chromium/issues/detail?id=608416 // We need to temporarily unset name to avoid disrupting radio button groups. var name = node.name; if (name !== '') { node.name = ''; } { // When syncing the checked attribute, both the checked property and // attribute are assigned at the same time using defaultChecked. This uses: // // 1. The checked React property when present // 2. The defaultChecked React property when present // 3. Otherwise, false node.defaultChecked = !node.defaultChecked; node.defaultChecked = !!node._wrapperState.initialChecked; } if (name !== '') { node.name = name; } } function restoreControlledState(element, props) { var node = element; updateWrapper(node, props); updateNamedCousins(node, props); } function updateNamedCousins(rootNode, props) { var name = props.name; if (props.type === 'radio' && name != null) { var queryRoot = rootNode; while (queryRoot.parentNode) { queryRoot = queryRoot.parentNode; } // If `rootNode.form` was non-null, then we could try `form.elements`, // but that sometimes behaves strangely in IE8. We could also try using // `form.getElementsByName`, but that will only return direct children // and won't include inputs that use the HTML5 `form=` attribute. Since // the input might not even be in a form. It might not even be in the // document. Let's just use the local `querySelectorAll` to ensure we don't // miss anything. { checkAttributeStringCoercion(name, 'name'); } var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type="radio"]'); for (var i = 0; i < group.length; i++) { var otherNode = group[i]; if (otherNode === rootNode || otherNode.form !== rootNode.form) { continue; } // This will throw if radio buttons rendered by different copies of React // and the same name are rendered into the same form (same as #1939). // That's probably okay; we don't support it just as we don't support // mixing React radio buttons with non-React ones. var otherProps = getFiberCurrentPropsFromNode(otherNode); if (!otherProps) { throw new Error('ReactDOMInput: Mixing React and non-React radio inputs with the ' + 'same `name` is not supported.'); } // We need update the tracked value on the named cousin since the value // was changed but the input saw no event or value set updateValueIfChanged(otherNode); // If this is a controlled radio button group, forcing the input that // was previously checked to update will cause it to be come re-checked // as appropriate. updateWrapper(otherNode, otherProps); } } } // In Chrome, assigning defaultValue to certain input types triggers input validation. // For number inputs, the display value loses trailing decimal points. For email inputs, // Chrome raises "The specified value <x> is not a valid email address". // // Here we check to see if the defaultValue has actually changed, avoiding these problems // when the user is inputting text // // https://github.com/facebook/react/issues/7253 function setDefaultValue(node, type, value) { if ( // Focused number inputs synchronize on blur. See ChangeEventPlugin.js type !== 'number' || getActiveElement(node.ownerDocument) !== node) { if (value == null) { node.defaultValue = toString(node._wrapperState.initialValue); } else if (node.defaultValue !== toString(value)) { node.defaultValue = toString(value); } } } var didWarnSelectedSetOnOption = false; var didWarnInvalidChild = false; var didWarnInvalidInnerHTML = false; /** * Implements an <option> host component that warns when `selected` is set. */ function validateProps(element, props) { { // If a value is not provided, then the children must be simple. if (props.value == null) { if (typeof props.children === 'object' && props.children !== null) { React.Children.forEach(props.children, function (child) { if (child == null) { return; } if (typeof child === 'string' || typeof child === 'number') { return; } if (!didWarnInvalidChild) { didWarnInvalidChild = true; error('Cannot infer the option value of complex children. ' + 'Pass a `value` prop or use a plain string as children to <option>.'); } }); } else if (props.dangerouslySetInnerHTML != null) { if (!didWarnInvalidInnerHTML) { didWarnInvalidInnerHTML = true; error('Pass a `value` prop if you set dangerouslyInnerHTML so React knows ' + 'which value should be selected.'); } } } // TODO: Remove support for `selected` in <option>. if (props.selected != null && !didWarnSelectedSetOnOption) { error('Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.'); didWarnSelectedSetOnOption = true; } } } function postMountWrapper$1(element, props) { // value="" should make a value attribute (#6219) if (props.value != null) { element.setAttribute('value', toString(getToStringValue(props.value))); } } var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare function isArray(a) { return isArrayImpl(a); } var didWarnValueDefaultValue$1; { didWarnValueDefaultValue$1 = false; } function getDeclarationErrorAddendum() { var ownerName = getCurrentFiberOwnerNameInDevOrNull(); if (ownerName) { return '\n\nCheck the render method of `' + ownerName + '`.'; } return ''; } var valuePropNames = ['value', 'defaultValue']; /** * Validation function for `value` and `defaultValue`. */ function checkSelectPropTypes(props) { { checkControlledValueProps('select', props); for (var i = 0; i < valuePropNames.length; i++) { var propName = valuePropNames[i]; if (props[propName] == null) { continue; } var propNameIsArray = isArray(props[propName]); if (props.multiple && !propNameIsArray) { error('The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, getDeclarationErrorAddendum()); } else if (!props.multiple && propNameIsArray) { error('The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, getDeclarationErrorAddendum()); } } } } function updateOptions(node, multiple, propValue, setDefaultSelected) { var options = node.options; if (multiple) { var selectedValues = propValue; var selectedValue = {}; for (var i = 0; i < selectedValues.length; i++) { // Prefix to avoid chaos with special keys. selectedValue['$' + selectedValues[i]] = true; } for (var _i = 0; _i < options.length; _i++) { var selected = selectedValue.hasOwnProperty('$' + options[_i].value); if (options[_i].selected !== selected) { options[_i].selected = selected; } if (selected && setDefaultSelected) { options[_i].defaultSelected = true; } } } else { // Do not set `select.value` as exact behavior isn't consistent across all // browsers for all cases. var _selectedValue = toString(getToStringValue(propValue)); var defaultSelected = null; for (var _i2 = 0; _i2 < options.length; _i2++) { if (options[_i2].value === _selectedValue) { options[_i2].selected = true; if (setDefaultSelected) { options[_i2].defaultSelected = true; } return; } if (defaultSelected === null && !options[_i2].disabled) { defaultSelected = options[_i2]; } } if (defaultSelected !== null) { defaultSelected.selected = true; } } } /** * Implements a <select> host component that allows optionally setting the * props `value` and `defaultValue`. If `multiple` is false, the prop must be a * stringable. If `multiple` is true, the prop must be an array of stringables. * * If `value` is not supplied (or null/undefined), user actions that change the * selected option will trigger updates to the rendered options. * * If it is supplied (and not null/undefined), the rendered options will not * update in response to user actions. Instead, the `value` prop must change in * order for the rendered options to update. * * If `defaultValue` is provided, any options with the supplied values will be * selected. */ function getHostProps$1(element, props) { return assign({}, props, { value: undefined }); } function initWrapperState$1(element, props) { var node = element; { checkSelectPropTypes(props); } node._wrapperState = { wasMultiple: !!props.multiple }; { if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue$1) { error('Select elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled select ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components'); didWarnValueDefaultValue$1 = true; } } } function postMountWrapper$2(element, props) { var node = element; node.multiple = !!props.multiple; var value = props.value; if (value != null) { updateOptions(node, !!props.multiple, value, false); } else if (props.defaultValue != null) { updateOptions(node, !!props.multiple, props.defaultValue, true); } } function postUpdateWrapper(element, props) { var node = element; var wasMultiple = node._wrapperState.wasMultiple; node._wrapperState.wasMultiple = !!props.multiple; var value = props.value; if (value != null) { updateOptions(node, !!props.multiple, value, false); } else if (wasMultiple !== !!props.multiple) { // For simplicity, reapply `defaultValue` if `multiple` is toggled. if (props.defaultValue != null) { updateOptions(node, !!props.multiple, props.defaultValue, true); } else { // Revert the select back to its default unselected state. updateOptions(node, !!props.multiple, props.multiple ? [] : '', false); } } } function restoreControlledState$1(element, props) { var node = element; var value = props.value; if (value != null) { updateOptions(node, !!props.multiple, value, false); } } var didWarnValDefaultVal = false; /** * Implements a <textarea> host component that allows setting `value`, and * `defaultValue`. This differs from the traditional DOM API because value is * usually set as PCDATA children. * * If `value` is not supplied (or null/undefined), user actions that affect the * value will trigger updates to the element. * * If `value` is supplied (and not null/undefined), the rendered element will * not trigger updates to the element. Instead, the `value` prop must change in * order for the rendered element to be updated. * * The rendered element will be initialized with an empty value, the prop * `defaultValue` if specified, or the children content (deprecated). */ function getHostProps$2(element, props) { var node = element; if (props.dangerouslySetInnerHTML != null) { throw new Error('`dangerouslySetInnerHTML` does not make sense on <textarea>.'); } // Always set children to the same thing. In IE9, the selection range will // get reset if `textContent` is mutated. We could add a check in setTextContent // to only set the value if/when the value differs from the node value (which would // completely solve this IE9 bug), but Sebastian+Sophie seemed to like this // solution. The value can be a boolean or object so that's why it's forced // to be a string. var hostProps = assign({}, props, { value: undefined, defaultValue: undefined, children: toString(node._wrapperState.initialValue) }); return hostProps; } function initWrapperState$2(element, props) { var node = element; { checkControlledValueProps('textarea', props); if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValDefaultVal) { error('%s contains a textarea with both value and defaultValue props. ' + 'Textarea elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled textarea ' + 'and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component'); didWarnValDefaultVal = true; } } var initialValue = props.value; // Only bother fetching default value if we're going to use it if (initialValue == null) { var children = props.children, defaultValue = props.defaultValue; if (children != null) { { error('Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.'); } { if (defaultValue != null) { throw new Error('If you supply `defaultValue` on a <textarea>, do not pass children.'); } if (isArray(children)) { if (children.length > 1) { throw new Error('<textarea> can only have at most one child.'); } children = children[0]; } defaultValue = children; } } if (defaultValue == null) { defaultValue = ''; } initialValue = defaultValue; } node._wrapperState = { initialValue: getToStringValue(initialValue) }; } function updateWrapper$1(element, props) { var node = element; var value = getToStringValue(props.value); var defaultValue = getToStringValue(props.defaultValue); if (value != null) { // Cast `value` to a string to ensure the value is set correctly. While // browsers typically do this as necessary, jsdom doesn't. var newValue = toString(value); // To avoid side effects (such as losing text selection), only set value if changed if (newValue !== node.value) { node.value = newValue; } if (props.defaultValue == null && node.defaultValue !== newValue) { node.defaultValue = newValue; } } if (defaultValue != null) { node.defaultValue = toString(defaultValue); } } function postMountWrapper$3(element, props) { var node = element; // This is in postMount because we need access to the DOM node, which is not // available until after the component has mounted. var textContent = node.textContent; // Only set node.value if textContent is equal to the expected // initial value. In IE10/IE11 there is a bug where the placeholder attribute // will populate textContent as well. // https://developer.microsoft.com/microsoft-edge/platform/issues/101525/ if (textContent === node._wrapperState.initialValue) { if (textContent !== '' && textContent !== null) { node.value = textContent; } } } function restoreControlledState$2(element, props) { // DOM component is still mounted; update updateWrapper$1(element, props); } var HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml'; var MATH_NAMESPACE = 'http://www.w3.org/1998/Math/MathML'; var SVG_NAMESPACE = 'http://www.w3.org/2000/svg'; // Assumes there is no parent namespace. function getIntrinsicNamespace(type) { switch (type) { case 'svg': return SVG_NAMESPACE; case 'math': return MATH_NAMESPACE; default: return HTML_NAMESPACE; } } function getChildNamespace(parentNamespace, type) { if (parentNamespace == null || parentNamespace === HTML_NAMESPACE) { // No (or default) parent namespace: potential entry point. return getIntrinsicNamespace(type); } if (parentNamespace === SVG_NAMESPACE && type === 'foreignObject') { // We're leaving SVG. return HTML_NAMESPACE; } // By default, pass namespace below. return parentNamespace; } /* globals MSApp */ /** * Create a function which has 'unsafe' privileges (required by windows8 apps) */ var createMicrosoftUnsafeLocalFunction = function (func) { if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) { return function (arg0, arg1, arg2, arg3) { MSApp.execUnsafeLocalFunction(function () { return func(arg0, arg1, arg2, arg3); }); }; } else { return func; } }; var reusableSVGContainer; /** * Set the innerHTML property of a node * * @param {DOMElement} node * @param {string} html * @internal */ var setInnerHTML = createMicrosoftUnsafeLocalFunction(function (node, html) { if (node.namespaceURI === SVG_NAMESPACE) { if (!('innerHTML' in node)) { // IE does not have innerHTML for SVG nodes, so instead we inject the // new markup in a temp node and then move the child nodes across into // the target node reusableSVGContainer = reusableSVGContainer || document.createElement('div'); reusableSVGContainer.innerHTML = '<svg>' + html.valueOf().toString() + '</svg>'; var svgNode = reusableSVGContainer.firstChild; while (node.firstChild) { node.removeChild(node.firstChild); } while (svgNode.firstChild) { node.appendChild(svgNode.firstChild); } return; } } node.innerHTML = html; }); /** * HTML nodeType values that represent the type of the node */ var ELEMENT_NODE = 1; var TEXT_NODE = 3; var COMMENT_NODE = 8; var DOCUMENT_NODE = 9; var DOCUMENT_FRAGMENT_NODE = 11; /** * Set the textContent property of a node. For text updates, it's faster * to set the `nodeValue` of the Text node directly instead of using * `.textContent` which will remove the existing node and create a new one. * * @param {DOMElement} node * @param {string} text * @internal */ var setTextContent = function (node, text) { if (text) { var firstChild = node.firstChild; if (firstChild && firstChild === node.lastChild && firstChild.nodeType === TEXT_NODE) { firstChild.nodeValue = text; return; } } node.textContent = text; }; // List derived from Gecko source code: // https://github.com/mozilla/gecko-dev/blob/4e638efc71/layout/style/test/property_database.js var shorthandToLonghand = { animation: ['animationDelay', 'animationDirection', 'animationDuration', 'animationFillMode', 'animationIterationCount', 'animationName', 'animationPlayState', 'animationTimingFunction'], background: ['backgroundAttachment', 'backgroundClip', 'backgroundColor', 'backgroundImage', 'backgroundOrigin', 'backgroundPositionX', 'backgroundPositionY', 'backgroundRepeat', 'backgroundSize'], backgroundPosition: ['backgroundPositionX', 'backgroundPositionY'], border: ['borderBottomColor', 'borderBottomStyle', 'borderBottomWidth', 'borderImageOutset', 'borderImageRepeat', 'borderImageSlice', 'borderImageSource', 'borderImageWidth', 'borderLeftColor', 'borderLeftStyle', 'borderLeftWidth', 'borderRightColor', 'borderRightStyle', 'borderRightWidth', 'borderTopColor', 'borderTopStyle', 'borderTopWidth'], borderBlockEnd: ['borderBlockEndColor', 'borderBlockEndStyle', 'borderBlockEndWidth'], borderBlockStart: ['borderBlockStartColor', 'borderBlockStartStyle', 'borderBlockStartWidth'], borderBottom: ['borderBottomColor', 'borderBottomStyle', 'borderBottomWidth'], borderColor: ['borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor'], borderImage: ['borderImageOutset', 'borderImageRepeat', 'borderImageSlice', 'borderImageSource', 'borderImageWidth'], borderInlineEnd: ['borderInlineEndColor', 'borderInlineEndStyle', 'borderInlineEndWidth'], borderInlineStart: ['borderInlineStartColor', 'borderInlineStartStyle', 'borderInlineStartWidth'], borderLeft: ['borderLeftColor', 'borderLeftStyle', 'borderLeftWidth'], borderRadius: ['borderBottomLeftRadius', 'borderBottomRightRadius', 'borderTopLeftRadius', 'borderTopRightRadius'], borderRight: ['borderRightColor', 'borderRightStyle', 'borderRightWidth'], borderStyle: ['borderBottomStyle', 'borderLeftStyle', 'borderRightStyle', 'borderTopStyle'], borderTop: ['borderTopColor', 'borderTopStyle', 'borderTopWidth'], borderWidth: ['borderBottomWidth', 'borderLeftWidth', 'borderRightWidth', 'borderTopWidth'], columnRule: ['columnRuleColor', 'columnRuleStyle', 'columnRuleWidth'], columns: ['columnCount', 'columnWidth'], flex: ['flexBasis', 'flexGrow', 'flexShrink'], flexFlow: ['flexDirection', 'flexWrap'], font: ['fontFamily', 'fontFeatureSettings', 'fontKerning', 'fontLanguageOverride', 'fontSize', 'fontSizeAdjust', 'fontStretch', 'fontStyle', 'fontVariant', 'fontVariantAlternates', 'fontVariantCaps', 'fontVariantEastAsian', 'fontVariantLigatures', 'fontVariantNumeric', 'fontVariantPosition', 'fontWeight', 'lineHeight'], fontVariant: ['fontVariantAlternates', 'fontVariantCaps', 'fontVariantEastAsian', 'fontVariantLigatures', 'fontVariantNumeric', 'fontVariantPosition'], gap: ['columnGap', 'rowGap'], grid: ['gridAutoColumns', 'gridAutoFlow', 'gridAutoRows', 'gridTemplateAreas', 'gridTemplateColumns', 'gridTemplateRows'], gridArea: ['gridColumnEnd', 'gridColumnStart', 'gridRowEnd', 'gridRowStart'], gridColumn: ['gridColumnEnd', 'gridColumnStart'], gridColumnGap: ['columnGap'], gridGap: ['columnGap', 'rowGap'], gridRow: ['gridRowEnd', 'gridRowStart'], gridRowGap: ['rowGap'], gridTemplate: ['gridTemplateAreas', 'gridTemplateColumns', 'gridTemplateRows'], listStyle: ['listStyleImage', 'listStylePosition', 'listStyleType'], margin: ['marginBottom', 'marginLeft', 'marginRight', 'marginTop'], marker: ['markerEnd', 'markerMid', 'markerStart'], mask: ['maskClip', 'maskComposite', 'maskImage', 'maskMode', 'maskOrigin', 'maskPositionX', 'maskPositionY', 'maskRepeat', 'maskSize'], maskPosition: ['maskPositionX', 'maskPositionY'], outline: ['outlineColor', 'outlineStyle', 'outlineWidth'], overflow: ['overflowX', 'overflowY'], padding: ['paddingBottom', 'paddingLeft', 'paddingRight', 'paddingTop'], placeContent: ['alignContent', 'justifyContent'], placeItems: ['alignItems', 'justifyItems'], placeSelf: ['alignSelf', 'justifySelf'], textDecoration: ['textDecorationColor', 'textDecorationLine', 'textDecorationStyle'], textEmphasis: ['textEmphasisColor', 'textEmphasisStyle'], transition: ['transitionDelay', 'transitionDuration', 'transitionProperty', 'transitionTimingFunction'], wordWrap: ['overflowWrap'] }; /** * CSS properties which accept numbers but are not in units of "px". */ var isUnitlessNumber = { animationIterationCount: true, aspectRatio: true, borderImageOutset: true, borderImageSlice: true, borderImageWidth: true, boxFlex: true, boxFlexGroup: true, boxOrdinalGroup: true, columnCount: true, columns: true, flex: true, flexGrow: true, flexPositive: true, flexShrink: true, flexNegative: true, flexOrder: true, gridArea: true, gridRow: true, gridRowEnd: true, gridRowSpan: true, gridRowStart: true, gridColumn: true, gridColumnEnd: true, gridColumnSpan: true, gridColumnStart: true, fontWeight: true, lineClamp: true, lineHeight: true, opacity: true, order: true, orphans: true, tabSize: true, widows: true, zIndex: true, zoom: true, // SVG-related properties fillOpacity: true, floodOpacity: true, stopOpacity: true, strokeDasharray: true, strokeDashoffset: true, strokeMiterlimit: true, strokeOpacity: true, strokeWidth: true }; /** * @param {string} prefix vendor-specific prefix, eg: Webkit * @param {string} key style name, eg: transitionDuration * @return {string} style name prefixed with `prefix`, properly camelCased, eg: * WebkitTransitionDuration */ function prefixKey(prefix, key) { return prefix + key.charAt(0).toUpperCase() + key.substring(1); } /** * Support style names that may come passed in prefixed by adding permutations * of vendor prefixes. */ var prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an // infinite loop, because it iterates over the newly added props too. Object.keys(isUnitlessNumber).forEach(function (prop) { prefixes.forEach(function (prefix) { isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop]; }); }); /** * Convert a value into the proper css writable value. The style name `name` * should be logical (no hyphens), as specified * in `CSSProperty.isUnitlessNumber`. * * @param {string} name CSS property name such as `topMargin`. * @param {*} value CSS property value such as `10px`. * @return {string} Normalized style value with dimensions applied. */ function dangerousStyleValue(name, value, isCustomProperty) { // Note that we've removed escapeTextForBrowser() calls here since the // whole string will be escaped when the attribute is injected into // the markup. If you provide unsafe user data here they can inject // arbitrary CSS which may be problematic (I couldn't repro this): // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/ // This is not an XSS hole but instead a potential CSS injection issue // which has lead to a greater discussion about how we're going to // trust URLs moving forward. See #2115901 var isEmpty = value == null || typeof value === 'boolean' || value === ''; if (isEmpty) { return ''; } if (!isCustomProperty && typeof value === 'number' && value !== 0 && !(isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name])) { return value + 'px'; // Presumes implicit 'px' suffix for unitless numbers } { checkCSSPropertyStringCoercion(value, name); } return ('' + value).trim(); } var uppercasePattern = /([A-Z])/g; var msPattern = /^ms-/; /** * Hyphenates a camelcased CSS property name, for example: * * > hyphenateStyleName('backgroundColor') * < "background-color" * > hyphenateStyleName('MozTransition') * < "-moz-transition" * > hyphenateStyleName('msTransition') * < "-ms-transition" * * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix * is converted to `-ms-`. */ function hyphenateStyleName(name) { return name.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern, '-ms-'); } var warnValidStyle = function () {}; { // 'msTransform' is correct, but the other prefixes should be capitalized var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/; var msPattern$1 = /^-ms-/; var hyphenPattern = /-(.)/g; // style values shouldn't contain a semicolon var badStyleValueWithSemicolonPattern = /;\s*$/; var warnedStyleNames = {}; var warnedStyleValues = {}; var warnedForNaNValue = false; var warnedForInfinityValue = false; var camelize = function (string) { return string.replace(hyphenPattern, function (_, character) { return character.toUpperCase(); }); }; var warnHyphenatedStyleName = function (name) { if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { return; } warnedStyleNames[name] = true; error('Unsupported style property %s. Did you mean %s?', name, // As Andi Smith suggests // (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix // is converted to lowercase `ms`. camelize(name.replace(msPattern$1, 'ms-'))); }; var warnBadVendoredStyleName = function (name) { if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { return; } warnedStyleNames[name] = true; error('Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1)); }; var warnStyleValueWithSemicolon = function (name, value) { if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) { return; } warnedStyleValues[value] = true; error("Style property values shouldn't contain a semicolon. " + 'Try "%s: %s" instead.', name, value.replace(badStyleValueWithSemicolonPattern, '')); }; var warnStyleValueIsNaN = function (name, value) { if (warnedForNaNValue) { return; } warnedForNaNValue = true; error('`NaN` is an invalid value for the `%s` css style property.', name); }; var warnStyleValueIsInfinity = function (name, value) { if (warnedForInfinityValue) { return; } warnedForInfinityValue = true; error('`Infinity` is an invalid value for the `%s` css style property.', name); }; warnValidStyle = function (name, value) { if (name.indexOf('-') > -1) { warnHyphenatedStyleName(name); } else if (badVendoredStyleNamePattern.test(name)) { warnBadVendoredStyleName(name); } else if (badStyleValueWithSemicolonPattern.test(value)) { warnStyleValueWithSemicolon(name, value); } if (typeof value === 'number') { if (isNaN(value)) { warnStyleValueIsNaN(name, value); } else if (!isFinite(value)) { warnStyleValueIsInfinity(name, value); } } }; } var warnValidStyle$1 = warnValidStyle; /** * Operations for dealing with CSS properties. */ /** * This creates a string that is expected to be equivalent to the style * attribute generated by server-side rendering. It by-passes warnings and * security checks so it's not safe to use this value for anything other than * comparison. It is only used in DEV for SSR validation. */ function createDangerousStringForStyles(styles) { { var serialized = ''; var delimiter = ''; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } var styleValue = styles[styleName]; if (styleValue != null) { var isCustomProperty = styleName.indexOf('--') === 0; serialized += delimiter + (isCustomProperty ? styleName : hyphenateStyleName(styleName)) + ':'; serialized += dangerousStyleValue(styleName, styleValue, isCustomProperty); delimiter = ';'; } } return serialized || null; } } /** * Sets the value for multiple styles on a node. If a value is specified as * '' (empty string), the corresponding style property will be unset. * * @param {DOMElement} node * @param {object} styles */ function setValueForStyles(node, styles) { var style = node.style; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } var isCustomProperty = styleName.indexOf('--') === 0; { if (!isCustomProperty) { warnValidStyle$1(styleName, styles[styleName]); } } var styleValue = dangerousStyleValue(styleName, styles[styleName], isCustomProperty); if (styleName === 'float') { styleName = 'cssFloat'; } if (isCustomProperty) { style.setProperty(styleName, styleValue); } else { style[styleName] = styleValue; } } } function isValueEmpty(value) { return value == null || typeof value === 'boolean' || value === ''; } /** * Given {color: 'red', overflow: 'hidden'} returns { * color: 'color', * overflowX: 'overflow', * overflowY: 'overflow', * }. This can be read as "the overflowY property was set by the overflow * shorthand". That is, the values are the property that each was derived from. */ function expandShorthandMap(styles) { var expanded = {}; for (var key in styles) { var longhands = shorthandToLonghand[key] || [key]; for (var i = 0; i < longhands.length; i++) { expanded[longhands[i]] = key; } } return expanded; } /** * When mixing shorthand and longhand property names, we warn during updates if * we expect an incorrect result to occur. In particular, we warn for: * * Updating a shorthand property (longhand gets overwritten): * {font: 'foo', fontVariant: 'bar'} -> {font: 'baz', fontVariant: 'bar'} * becomes .style.font = 'baz' * Removing a shorthand property (longhand gets lost too): * {font: 'foo', fontVariant: 'bar'} -> {fontVariant: 'bar'} * becomes .style.font = '' * Removing a longhand property (should revert to shorthand; doesn't): * {font: 'foo', fontVariant: 'bar'} -> {font: 'foo'} * becomes .style.fontVariant = '' */ function validateShorthandPropertyCollisionInDev(styleUpdates, nextStyles) { { if (!nextStyles) { return; } var expandedUpdates = expandShorthandMap(styleUpdates); var expandedStyles = expandShorthandMap(nextStyles); var warnedAbout = {}; for (var key in expandedUpdates) { var originalKey = expandedUpdates[key]; var correctOriginalKey = expandedStyles[key]; if (correctOriginalKey && originalKey !== correctOriginalKey) { var warningKey = originalKey + ',' + correctOriginalKey; if (warnedAbout[warningKey]) { continue; } warnedAbout[warningKey] = true; error('%s a style property during rerender (%s) when a ' + 'conflicting property is set (%s) can lead to styling bugs. To ' + "avoid this, don't mix shorthand and non-shorthand properties " + 'for the same value; instead, replace the shorthand with ' + 'separate values.', isValueEmpty(styleUpdates[originalKey]) ? 'Removing' : 'Updating', originalKey, correctOriginalKey); } } } } // For HTML, certain tags should omit their close tag. We keep a list for // those special-case tags. var omittedCloseTags = { area: true, base: true, br: true, col: true, embed: true, hr: true, img: true, input: true, keygen: true, link: true, meta: true, param: true, source: true, track: true, wbr: true // NOTE: menuitem's close tag should be omitted, but that causes problems. }; // `omittedCloseTags` except that `menuitem` should still have its closing tag. var voidElementTags = assign({ menuitem: true }, omittedCloseTags); var HTML = '__html'; function assertValidProps(tag, props) { if (!props) { return; } // Note the use of `==` which checks for null or undefined. if (voidElementTags[tag]) { if (props.children != null || props.dangerouslySetInnerHTML != null) { throw new Error(tag + " is a void element tag and must neither have `children` nor " + 'use `dangerouslySetInnerHTML`.'); } } if (props.dangerouslySetInnerHTML != null) { if (props.children != null) { throw new Error('Can only set one of `children` or `props.dangerouslySetInnerHTML`.'); } if (typeof props.dangerouslySetInnerHTML !== 'object' || !(HTML in props.dangerouslySetInnerHTML)) { throw new Error('`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' + 'Please visit https://reactjs.org/link/dangerously-set-inner-html ' + 'for more information.'); } } { if (!props.suppressContentEditableWarning && props.contentEditable && props.children != null) { error('A component is `contentEditable` and contains `children` managed by ' + 'React. It is now your responsibility to guarantee that none of ' + 'those nodes are unexpectedly modified or duplicated. This is ' + 'probably not intentional.'); } } if (props.style != null && typeof props.style !== 'object') { throw new Error('The `style` prop expects a mapping from style properties to values, ' + "not a string. For example, style={{marginRight: spacing + 'em'}} when " + 'using JSX.'); } } function isCustomComponent(tagName, props) { if (tagName.indexOf('-') === -1) { return typeof props.is === 'string'; } switch (tagName) { // These are reserved SVG and MathML elements. // We don't mind this list too much because we expect it to never grow. // The alternative is to track the namespace in a few places which is convoluted. // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts case 'annotation-xml': case 'color-profile': case 'font-face': case 'font-face-src': case 'font-face-uri': case 'font-face-format': case 'font-face-name': case 'missing-glyph': return false; default: return true; } } // When adding attributes to the HTML or SVG allowed attribute list, be sure to // also add them to this module to ensure casing and incorrect name // warnings. var possibleStandardNames = { // HTML accept: 'accept', acceptcharset: 'acceptCharset', 'accept-charset': 'acceptCharset', accesskey: 'accessKey', action: 'action', allowfullscreen: 'allowFullScreen', alt: 'alt', as: 'as', async: 'async', autocapitalize: 'autoCapitalize', autocomplete: 'autoComplete', autocorrect: 'autoCorrect', autofocus: 'autoFocus', autoplay: 'autoPlay', autosave: 'autoSave', capture: 'capture', cellpadding: 'cellPadding', cellspacing: 'cellSpacing', challenge: 'challenge', charset: 'charSet', checked: 'checked', children: 'children', cite: 'cite', class: 'className', classid: 'classID', classname: 'className', cols: 'cols', colspan: 'colSpan', content: 'content', contenteditable: 'contentEditable', contextmenu: 'contextMenu', controls: 'controls', controlslist: 'controlsList', coords: 'coords', crossorigin: 'crossOrigin', dangerouslysetinnerhtml: 'dangerouslySetInnerHTML', data: 'data', datetime: 'dateTime', default: 'default', defaultchecked: 'defaultChecked', defaultvalue: 'defaultValue', defer: 'defer', dir: 'dir', disabled: 'disabled', disablepictureinpicture: 'disablePictureInPicture', disableremoteplayback: 'disableRemotePlayback', download: 'download', draggable: 'draggable', enctype: 'encType', enterkeyhint: 'enterKeyHint', for: 'htmlFor', form: 'form', formmethod: 'formMethod', formaction: 'formAction', formenctype: 'formEncType', formnovalidate: 'formNoValidate', formtarget: 'formTarget', frameborder: 'frameBorder', headers: 'headers', height: 'height', hidden: 'hidden', high: 'high', href: 'href', hreflang: 'hrefLang', htmlfor: 'htmlFor', httpequiv: 'httpEquiv', 'http-equiv': 'httpEquiv', icon: 'icon', id: 'id', imagesizes: 'imageSizes', imagesrcset: 'imageSrcSet', innerhtml: 'innerHTML', inputmode: 'inputMode', integrity: 'integrity', is: 'is', itemid: 'itemID', itemprop: 'itemProp', itemref: 'itemRef', itemscope: 'itemScope', itemtype: 'itemType', keyparams: 'keyParams', keytype: 'keyType', kind: 'kind', label: 'label', lang: 'lang', list: 'list', loop: 'loop', low: 'low', manifest: 'manifest', marginwidth: 'marginWidth', marginheight: 'marginHeight', max: 'max', maxlength: 'maxLength', media: 'media', mediagroup: 'mediaGroup', method: 'method', min: 'min', minlength: 'minLength', multiple: 'multiple', muted: 'muted', name: 'name', nomodule: 'noModule', nonce: 'nonce', novalidate: 'noValidate', open: 'open', optimum: 'optimum', pattern: 'pattern', placeholder: 'placeholder', playsinline: 'playsInline', poster: 'poster', preload: 'preload', profile: 'profile', radiogroup: 'radioGroup', readonly: 'readOnly', referrerpolicy: 'referrerPolicy', rel: 'rel', required: 'required', reversed: 'reversed', role: 'role', rows: 'rows', rowspan: 'rowSpan', sandbox: 'sandbox', scope: 'scope', scoped: 'scoped', scrolling: 'scrolling', seamless: 'seamless', selected: 'selected', shape: 'shape', size: 'size', sizes: 'sizes', span: 'span', spellcheck: 'spellCheck', src: 'src', srcdoc: 'srcDoc', srclang: 'srcLang', srcset: 'srcSet', start: 'start', step: 'step', style: 'style', summary: 'summary', tabindex: 'tabIndex', target: 'target', title: 'title', type: 'type', usemap: 'useMap', value: 'value', width: 'width', wmode: 'wmode', wrap: 'wrap', // SVG about: 'about', accentheight: 'accentHeight', 'accent-height': 'accentHeight', accumulate: 'accumulate', additive: 'additive', alignmentbaseline: 'alignmentBaseline', 'alignment-baseline': 'alignmentBaseline', allowreorder: 'allowReorder', alphabetic: 'alphabetic', amplitude: 'amplitude', arabicform: 'arabicForm', 'arabic-form': 'arabicForm', ascent: 'ascent', attributename: 'attributeName', attributetype: 'attributeType', autoreverse: 'autoReverse', azimuth: 'azimuth', basefrequency: 'baseFrequency', baselineshift: 'baselineShift', 'baseline-shift': 'baselineShift', baseprofile: 'baseProfile', bbox: 'bbox', begin: 'begin', bias: 'bias', by: 'by', calcmode: 'calcMode', capheight: 'capHeight', 'cap-height': 'capHeight', clip: 'clip', clippath: 'clipPath', 'clip-path': 'clipPath', clippathunits: 'clipPathUnits', cliprule: 'clipRule', 'clip-rule': 'clipRule', color: 'color', colorinterpolation: 'colorInterpolation', 'color-interpolation': 'colorInterpolation', colorinterpolationfilters: 'colorInterpolationFilters', 'color-interpolation-filters': 'colorInterpolationFilters', colorprofile: 'colorProfile', 'color-profile': 'colorProfile', colorrendering: 'colorRendering', 'color-rendering': 'colorRendering', contentscripttype: 'contentScriptType', contentstyletype: 'contentStyleType', cursor: 'cursor', cx: 'cx', cy: 'cy', d: 'd', datatype: 'datatype', decelerate: 'decelerate', descent: 'descent', diffuseconstant: 'diffuseConstant', direction: 'direction', display: 'display', divisor: 'divisor', dominantbaseline: 'dominantBaseline', 'dominant-baseline': 'dominantBaseline', dur: 'dur', dx: 'dx', dy: 'dy', edgemode: 'edgeMode', elevation: 'elevation', enablebackground: 'enableBackground', 'enable-background': 'enableBackground', end: 'end', exponent: 'exponent', externalresourcesrequired: 'externalResourcesRequired', fill: 'fill', fillopacity: 'fillOpacity', 'fill-opacity': 'fillOpacity', fillrule: 'fillRule', 'fill-rule': 'fillRule', filter: 'filter', filterres: 'filterRes', filterunits: 'filterUnits', floodopacity: 'floodOpacity', 'flood-opacity': 'floodOpacity', floodcolor: 'floodColor', 'flood-color': 'floodColor', focusable: 'focusable', fontfamily: 'fontFamily', 'font-family': 'fontFamily', fontsize: 'fontSize', 'font-size': 'fontSize', fontsizeadjust: 'fontSizeAdjust', 'font-size-adjust': 'fontSizeAdjust', fontstretch: 'fontStretch', 'font-stretch': 'fontStretch', fontstyle: 'fontStyle', 'font-style': 'fontStyle', fontvariant: 'fontVariant', 'font-variant': 'fontVariant', fontweight: 'fontWeight', 'font-weight': 'fontWeight', format: 'format', from: 'from', fx: 'fx', fy: 'fy', g1: 'g1', g2: 'g2', glyphname: 'glyphName', 'glyph-name': 'glyphName', glyphorientationhorizontal: 'glyphOrientationHorizontal', 'glyph-orientation-horizontal': 'glyphOrientationHorizontal', glyphorientationvertical: 'glyphOrientationVertical', 'glyph-orientation-vertical': 'glyphOrientationVertical', glyphref: 'glyphRef', gradienttransform: 'gradientTransform', gradientunits: 'gradientUnits', hanging: 'hanging', horizadvx: 'horizAdvX', 'horiz-adv-x': 'horizAdvX', horizoriginx: 'horizOriginX', 'horiz-origin-x': 'horizOriginX', ideographic: 'ideographic', imagerendering: 'imageRendering', 'image-rendering': 'imageRendering', in2: 'in2', in: 'in', inlist: 'inlist', intercept: 'intercept', k1: 'k1', k2: 'k2', k3: 'k3', k4: 'k4', k: 'k', kernelmatrix: 'kernelMatrix', kernelunitlength: 'kernelUnitLength', kerning: 'kerning', keypoints: 'keyPoints', keysplines: 'keySplines', keytimes: 'keyTimes', lengthadjust: 'lengthAdjust', letterspacing: 'letterSpacing', 'letter-spacing': 'letterSpacing', lightingcolor: 'lightingColor', 'lighting-color': 'lightingColor', limitingconeangle: 'limitingConeAngle', local: 'local', markerend: 'markerEnd', 'marker-end': 'markerEnd', markerheight: 'markerHeight', markermid: 'markerMid', 'marker-mid': 'markerMid', markerstart: 'markerStart', 'marker-start': 'markerStart', markerunits: 'markerUnits', markerwidth: 'markerWidth', mask: 'mask', maskcontentunits: 'maskContentUnits', maskunits: 'maskUnits', mathematical: 'mathematical', mode: 'mode', numoctaves: 'numOctaves', offset: 'offset', opacity: 'opacity', operator: 'operator', order: 'order', orient: 'orient', orientation: 'orientation', origin: 'origin', overflow: 'overflow', overlineposition: 'overlinePosition', 'overline-position': 'overlinePosition', overlinethickness: 'overlineThickness', 'overline-thickness': 'overlineThickness', paintorder: 'paintOrder', 'paint-order': 'paintOrder', panose1: 'panose1', 'panose-1': 'panose1', pathlength: 'pathLength', patterncontentunits: 'patternContentUnits', patterntransform: 'patternTransform', patternunits: 'patternUnits', pointerevents: 'pointerEvents', 'pointer-events': 'pointerEvents', points: 'points', pointsatx: 'pointsAtX', pointsaty: 'pointsAtY', pointsatz: 'pointsAtZ', prefix: 'prefix', preservealpha: 'preserveAlpha', preserveaspectratio: 'preserveAspectRatio', primitiveunits: 'primitiveUnits', property: 'property', r: 'r', radius: 'radius', refx: 'refX', refy: 'refY', renderingintent: 'renderingIntent', 'rendering-intent': 'renderingIntent', repeatcount: 'repeatCount', repeatdur: 'repeatDur', requiredextensions: 'requiredExtensions', requiredfeatures: 'requiredFeatures', resource: 'resource', restart: 'restart', result: 'result', results: 'results', rotate: 'rotate', rx: 'rx', ry: 'ry', scale: 'scale', security: 'security', seed: 'seed', shaperendering: 'shapeRendering', 'shape-rendering': 'shapeRendering', slope: 'slope', spacing: 'spacing', specularconstant: 'specularConstant', specularexponent: 'specularExponent', speed: 'speed', spreadmethod: 'spreadMethod', startoffset: 'startOffset', stddeviation: 'stdDeviation', stemh: 'stemh', stemv: 'stemv', stitchtiles: 'stitchTiles', stopcolor: 'stopColor', 'stop-color': 'stopColor', stopopacity: 'stopOpacity', 'stop-opacity': 'stopOpacity', strikethroughposition: 'strikethroughPosition', 'strikethrough-position': 'strikethroughPosition', strikethroughthickness: 'strikethroughThickness', 'strikethrough-thickness': 'strikethroughThickness', string: 'string', stroke: 'stroke', strokedasharray: 'strokeDasharray', 'stroke-dasharray': 'strokeDasharray', strokedashoffset: 'strokeDashoffset', 'stroke-dashoffset': 'strokeDashoffset', strokelinecap: 'strokeLinecap', 'stroke-linecap': 'strokeLinecap', strokelinejoin: 'strokeLinejoin', 'stroke-linejoin': 'strokeLinejoin', strokemiterlimit: 'strokeMiterlimit', 'stroke-miterlimit': 'strokeMiterlimit', strokewidth: 'strokeWidth', 'stroke-width': 'strokeWidth', strokeopacity: 'strokeOpacity', 'stroke-opacity': 'strokeOpacity', suppresscontenteditablewarning: 'suppressContentEditableWarning', suppresshydrationwarning: 'suppressHydrationWarning', surfacescale: 'surfaceScale', systemlanguage: 'systemLanguage', tablevalues: 'tableValues', targetx: 'targetX', targety: 'targetY', textanchor: 'textAnchor', 'text-anchor': 'textAnchor', textdecoration: 'textDecoration', 'text-decoration': 'textDecoration', textlength: 'textLength', textrendering: 'textRendering', 'text-rendering': 'textRendering', to: 'to', transform: 'transform', typeof: 'typeof', u1: 'u1', u2: 'u2', underlineposition: 'underlinePosition', 'underline-position': 'underlinePosition', underlinethickness: 'underlineThickness', 'underline-thickness': 'underlineThickness', unicode: 'unicode', unicodebidi: 'unicodeBidi', 'unicode-bidi': 'unicodeBidi', unicoderange: 'unicodeRange', 'unicode-range': 'unicodeRange', unitsperem: 'unitsPerEm', 'units-per-em': 'unitsPerEm', unselectable: 'unselectable', valphabetic: 'vAlphabetic', 'v-alphabetic': 'vAlphabetic', values: 'values', vectoreffect: 'vectorEffect', 'vector-effect': 'vectorEffect', version: 'version', vertadvy: 'vertAdvY', 'vert-adv-y': 'vertAdvY', vertoriginx: 'vertOriginX', 'vert-origin-x': 'vertOriginX', vertoriginy: 'vertOriginY', 'vert-origin-y': 'vertOriginY', vhanging: 'vHanging', 'v-hanging': 'vHanging', videographic: 'vIdeographic', 'v-ideographic': 'vIdeographic', viewbox: 'viewBox', viewtarget: 'viewTarget', visibility: 'visibility', vmathematical: 'vMathematical', 'v-mathematical': 'vMathematical', vocab: 'vocab', widths: 'widths', wordspacing: 'wordSpacing', 'word-spacing': 'wordSpacing', writingmode: 'writingMode', 'writing-mode': 'writingMode', x1: 'x1', x2: 'x2', x: 'x', xchannelselector: 'xChannelSelector', xheight: 'xHeight', 'x-height': 'xHeight', xlinkactuate: 'xlinkActuate', 'xlink:actuate': 'xlinkActuate', xlinkarcrole: 'xlinkArcrole', 'xlink:arcrole': 'xlinkArcrole', xlinkhref: 'xlinkHref', 'xlink:href': 'xlinkHref', xlinkrole: 'xlinkRole', 'xlink:role': 'xlinkRole', xlinkshow: 'xlinkShow', 'xlink:show': 'xlinkShow', xlinktitle: 'xlinkTitle', 'xlink:title': 'xlinkTitle', xlinktype: 'xlinkType', 'xlink:type': 'xlinkType', xmlbase: 'xmlBase', 'xml:base': 'xmlBase', xmllang: 'xmlLang', 'xml:lang': 'xmlLang', xmlns: 'xmlns', 'xml:space': 'xmlSpace', xmlnsxlink: 'xmlnsXlink', 'xmlns:xlink': 'xmlnsXlink', xmlspace: 'xmlSpace', y1: 'y1', y2: 'y2', y: 'y', ychannelselector: 'yChannelSelector', z: 'z', zoomandpan: 'zoomAndPan' }; var ariaProperties = { 'aria-current': 0, // state 'aria-description': 0, 'aria-details': 0, 'aria-disabled': 0, // state 'aria-hidden': 0, // state 'aria-invalid': 0, // state 'aria-keyshortcuts': 0, 'aria-label': 0, 'aria-roledescription': 0, // Widget Attributes 'aria-autocomplete': 0, 'aria-checked': 0, 'aria-expanded': 0, 'aria-haspopup': 0, 'aria-level': 0, 'aria-modal': 0, 'aria-multiline': 0, 'aria-multiselectable': 0, 'aria-orientation': 0, 'aria-placeholder': 0, 'aria-pressed': 0, 'aria-readonly': 0, 'aria-required': 0, 'aria-selected': 0, 'aria-sort': 0, 'aria-valuemax': 0, 'aria-valuemin': 0, 'aria-valuenow': 0, 'aria-valuetext': 0, // Live Region Attributes 'aria-atomic': 0, 'aria-busy': 0, 'aria-live': 0, 'aria-relevant': 0, // Drag-and-Drop Attributes 'aria-dropeffect': 0, 'aria-grabbed': 0, // Relationship Attributes 'aria-activedescendant': 0, 'aria-colcount': 0, 'aria-colindex': 0, 'aria-colspan': 0, 'aria-controls': 0, 'aria-describedby': 0, 'aria-errormessage': 0, 'aria-flowto': 0, 'aria-labelledby': 0, 'aria-owns': 0, 'aria-posinset': 0, 'aria-rowcount': 0, 'aria-rowindex': 0, 'aria-rowspan': 0, 'aria-setsize': 0 }; var warnedProperties = {}; var rARIA = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$'); var rARIACamel = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$'); function validateProperty(tagName, name) { { if (hasOwnProperty.call(warnedProperties, name) && warnedProperties[name]) { return true; } if (rARIACamel.test(name)) { var ariaName = 'aria-' + name.slice(4).toLowerCase(); var correctName = ariaProperties.hasOwnProperty(ariaName) ? ariaName : null; // If this is an aria-* attribute, but is not listed in the known DOM // DOM properties, then it is an invalid aria-* attribute. if (correctName == null) { error('Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.', name); warnedProperties[name] = true; return true; } // aria-* attributes should be lowercase; suggest the lowercase version. if (name !== correctName) { error('Invalid ARIA attribute `%s`. Did you mean `%s`?', name, correctName); warnedProperties[name] = true; return true; } } if (rARIA.test(name)) { var lowerCasedName = name.toLowerCase(); var standardName = ariaProperties.hasOwnProperty(lowerCasedName) ? lowerCasedName : null; // If this is an aria-* attribute, but is not listed in the known DOM // DOM properties, then it is an invalid aria-* attribute. if (standardName == null) { warnedProperties[name] = true; return false; } // aria-* attributes should be lowercase; suggest the lowercase version. if (name !== standardName) { error('Unknown ARIA attribute `%s`. Did you mean `%s`?', name, standardName); warnedProperties[name] = true; return true; } } } return true; } function warnInvalidARIAProps(type, props) { { var invalidProps = []; for (var key in props) { var isValid = validateProperty(type, key); if (!isValid) { invalidProps.push(key); } } var unknownPropString = invalidProps.map(function (prop) { return '`' + prop + '`'; }).join(', '); if (invalidProps.length === 1) { error('Invalid aria prop %s on <%s> tag. ' + 'For details, see https://reactjs.org/link/invalid-aria-props', unknownPropString, type); } else if (invalidProps.length > 1) { error('Invalid aria props %s on <%s> tag. ' + 'For details, see https://reactjs.org/link/invalid-aria-props', unknownPropString, type); } } } function validateProperties(type, props) { if (isCustomComponent(type, props)) { return; } warnInvalidARIAProps(type, props); } var didWarnValueNull = false; function validateProperties$1(type, props) { { if (type !== 'input' && type !== 'textarea' && type !== 'select') { return; } if (props != null && props.value === null && !didWarnValueNull) { didWarnValueNull = true; if (type === 'select' && props.multiple) { error('`value` prop on `%s` should not be null. ' + 'Consider using an empty array when `multiple` is set to `true` ' + 'to clear the component or `undefined` for uncontrolled components.', type); } else { error('`value` prop on `%s` should not be null. ' + 'Consider using an empty string to clear the component or `undefined` ' + 'for uncontrolled components.', type); } } } } var validateProperty$1 = function () {}; { var warnedProperties$1 = {}; var EVENT_NAME_REGEX = /^on./; var INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/; var rARIA$1 = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$'); var rARIACamel$1 = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$'); validateProperty$1 = function (tagName, name, value, eventRegistry) { if (hasOwnProperty.call(warnedProperties$1, name) && warnedProperties$1[name]) { return true; } var lowerCasedName = name.toLowerCase(); if (lowerCasedName === 'onfocusin' || lowerCasedName === 'onfocusout') { error('React uses onFocus and onBlur instead of onFocusIn and onFocusOut. ' + 'All React events are normalized to bubble, so onFocusIn and onFocusOut ' + 'are not needed/supported by React.'); warnedProperties$1[name] = true; return true; } // We can't rely on the event system being injected on the server. if (eventRegistry != null) { var registrationNameDependencies = eventRegistry.registrationNameDependencies, possibleRegistrationNames = eventRegistry.possibleRegistrationNames; if (registrationNameDependencies.hasOwnProperty(name)) { return true; } var registrationName = possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? possibleRegistrationNames[lowerCasedName] : null; if (registrationName != null) { error('Invalid event handler property `%s`. Did you mean `%s`?', name, registrationName); warnedProperties$1[name] = true; return true; } if (EVENT_NAME_REGEX.test(name)) { error('Unknown event handler property `%s`. It will be ignored.', name); warnedProperties$1[name] = true; return true; } } else if (EVENT_NAME_REGEX.test(name)) { // If no event plugins have been injected, we are in a server environment. // So we can't tell if the event name is correct for sure, but we can filter // out known bad ones like `onclick`. We can't suggest a specific replacement though. if (INVALID_EVENT_NAME_REGEX.test(name)) { error('Invalid event handler property `%s`. ' + 'React events use the camelCase naming convention, for example `onClick`.', name); } warnedProperties$1[name] = true; return true; } // Let the ARIA attribute hook validate ARIA attributes if (rARIA$1.test(name) || rARIACamel$1.test(name)) { return true; } if (lowerCasedName === 'innerhtml') { error('Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.'); warnedProperties$1[name] = true; return true; } if (lowerCasedName === 'aria') { error('The `aria` attribute is reserved for future use in React. ' + 'Pass individual `aria-` attributes instead.'); warnedProperties$1[name] = true; return true; } if (lowerCasedName === 'is' && value !== null && value !== undefined && typeof value !== 'string') { error('Received a `%s` for a string attribute `is`. If this is expected, cast ' + 'the value to a string.', typeof value); warnedProperties$1[name] = true; return true; } if (typeof value === 'number' && isNaN(value)) { error('Received NaN for the `%s` attribute. If this is expected, cast ' + 'the value to a string.', name); warnedProperties$1[name] = true; return true; } var propertyInfo = getPropertyInfo(name); var isReserved = propertyInfo !== null && propertyInfo.type === RESERVED; // Known attributes should match the casing specified in the property config. if (possibleStandardNames.hasOwnProperty(lowerCasedName)) { var standardName = possibleStandardNames[lowerCasedName]; if (standardName !== name) { error('Invalid DOM property `%s`. Did you mean `%s`?', name, standardName); warnedProperties$1[name] = true; return true; } } else if (!isReserved && name !== lowerCasedName) { // Unknown attributes should have lowercase casing since that's how they // will be cased anyway with server rendering. error('React does not recognize the `%s` prop on a DOM element. If you ' + 'intentionally want it to appear in the DOM as a custom ' + 'attribute, spell it as lowercase `%s` instead. ' + 'If you accidentally passed it from a parent component, remove ' + 'it from the DOM element.', name, lowerCasedName); warnedProperties$1[name] = true; return true; } if (typeof value === 'boolean' && shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) { if (value) { error('Received `%s` for a non-boolean attribute `%s`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s="%s" or %s={value.toString()}.', value, name, name, value, name); } else { error('Received `%s` for a non-boolean attribute `%s`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s="%s" or %s={value.toString()}.\n\n' + 'If you used to conditionally omit it with %s={condition && value}, ' + 'pass %s={condition ? value : undefined} instead.', value, name, name, value, name, name, name); } warnedProperties$1[name] = true; return true; } // Now that we've validated casing, do not validate // data types for reserved props if (isReserved) { return true; } // Warn when a known attribute is a bad type if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) { warnedProperties$1[name] = true; return false; } // Warn when passing the strings 'false' or 'true' into a boolean prop if ((value === 'false' || value === 'true') && propertyInfo !== null && propertyInfo.type === BOOLEAN) { error('Received the string `%s` for the boolean attribute `%s`. ' + '%s ' + 'Did you mean %s={%s}?', value, name, value === 'false' ? 'The browser will interpret it as a truthy value.' : 'Although this works, it will not work as expected if you pass the string "false".', name, value); warnedProperties$1[name] = true; return true; } return true; }; } var warnUnknownProperties = function (type, props, eventRegistry) { { var unknownProps = []; for (var key in props) { var isValid = validateProperty$1(type, key, props[key], eventRegistry); if (!isValid) { unknownProps.push(key); } } var unknownPropString = unknownProps.map(function (prop) { return '`' + prop + '`'; }).join(', '); if (unknownProps.length === 1) { error('Invalid value for prop %s on <%s> tag. Either remove it from the element, ' + 'or pass a string or number value to keep it in the DOM. ' + 'For details, see https://reactjs.org/link/attribute-behavior ', unknownPropString, type); } else if (unknownProps.length > 1) { error('Invalid values for props %s on <%s> tag. Either remove them from the element, ' + 'or pass a string or number value to keep them in the DOM. ' + 'For details, see https://reactjs.org/link/attribute-behavior ', unknownPropString, type); } } }; function validateProperties$2(type, props, eventRegistry) { if (isCustomComponent(type, props)) { return; } warnUnknownProperties(type, props, eventRegistry); } var IS_EVENT_HANDLE_NON_MANAGED_NODE = 1; var IS_NON_DELEGATED = 1 << 1; var IS_CAPTURE_PHASE = 1 << 2; // set to LEGACY_FB_SUPPORT. LEGACY_FB_SUPPORT only gets set when // we call willDeferLaterForLegacyFBSupport, thus not bailing out // will result in endless cycles like an infinite loop. // We also don't want to defer during event replaying. var SHOULD_NOT_PROCESS_POLYFILL_EVENT_PLUGINS = IS_EVENT_HANDLE_NON_MANAGED_NODE | IS_NON_DELEGATED | IS_CAPTURE_PHASE; // This exists to avoid circular dependency between ReactDOMEventReplaying // and DOMPluginEventSystem. var currentReplayingEvent = null; function setReplayingEvent(event) { { if (currentReplayingEvent !== null) { error('Expected currently replaying event to be null. This error ' + 'is likely caused by a bug in React. Please file an issue.'); } } currentReplayingEvent = event; } function resetReplayingEvent() { { if (currentReplayingEvent === null) { error('Expected currently replaying event to not be null. This error ' + 'is likely caused by a bug in React. Please file an issue.'); } } currentReplayingEvent = null; } function isReplayingEvent(event) { return event === currentReplayingEvent; } /** * Gets the target node from a native browser event by accounting for * inconsistencies in browser DOM APIs. * * @param {object} nativeEvent Native browser event. * @return {DOMEventTarget} Target node. */ function getEventTarget(nativeEvent) { // Fallback to nativeEvent.srcElement for IE9 // https://github.com/facebook/react/issues/12506 var target = nativeEvent.target || nativeEvent.srcElement || window; // Normalize SVG <use> element events #4963 if (target.correspondingUseElement) { target = target.correspondingUseElement; } // Safari may fire events on text nodes (Node.TEXT_NODE is 3). // @see http://www.quirksmode.org/js/events_properties.html return target.nodeType === TEXT_NODE ? target.parentNode : target; } var restoreImpl = null; var restoreTarget = null; var restoreQueue = null; function restoreStateOfTarget(target) { // We perform this translation at the end of the event loop so that we // always receive the correct fiber here var internalInstance = getInstanceFromNode(target); if (!internalInstance) { // Unmounted return; } if (typeof restoreImpl !== 'function') { throw new Error('setRestoreImplementation() needs to be called to handle a target for controlled ' + 'events. This error is likely caused by a bug in React. Please file an issue.'); } var stateNode = internalInstance.stateNode; // Guard against Fiber being unmounted. if (stateNode) { var _props = getFiberCurrentPropsFromNode(stateNode); restoreImpl(internalInstance.stateNode, internalInstance.type, _props); } } function setRestoreImplementation(impl) { restoreImpl = impl; } function enqueueStateRestore(target) { if (restoreTarget) { if (restoreQueue) { restoreQueue.push(target); } else { restoreQueue = [target]; } } else { restoreTarget = target; } } function needsStateRestore() { return restoreTarget !== null || restoreQueue !== null; } function restoreStateIfNeeded() { if (!restoreTarget) { return; } var target = restoreTarget; var queuedTargets = restoreQueue; restoreTarget = null; restoreQueue = null; restoreStateOfTarget(target); if (queuedTargets) { for (var i = 0; i < queuedTargets.length; i++) { restoreStateOfTarget(queuedTargets[i]); } } } // the renderer. Such as when we're dispatching events or if third party // libraries need to call batchedUpdates. Eventually, this API will go away when // everything is batched by default. We'll then have a similar API to opt-out of // scheduled work and instead do synchronous work. // Defaults var batchedUpdatesImpl = function (fn, bookkeeping) { return fn(bookkeeping); }; var flushSyncImpl = function () {}; var isInsideEventHandler = false; function finishEventHandler() { // Here we wait until all updates have propagated, which is important // when using controlled components within layers: // https://github.com/facebook/react/issues/1698 // Then we restore state of any controlled component. var controlledComponentsHavePendingUpdates = needsStateRestore(); if (controlledComponentsHavePendingUpdates) { // If a controlled event was fired, we may need to restore the state of // the DOM node back to the controlled value. This is necessary when React // bails out of the update without touching the DOM. // TODO: Restore state in the microtask, after the discrete updates flush, // instead of early flushing them here. flushSyncImpl(); restoreStateIfNeeded(); } } function batchedUpdates(fn, a, b) { if (isInsideEventHandler) { // If we are currently inside another batch, we need to wait until it // fully completes before restoring state. return fn(a, b); } isInsideEventHandler = true; try { return batchedUpdatesImpl(fn, a, b); } finally { isInsideEventHandler = false; finishEventHandler(); } } // TODO: Replace with flushSync function setBatchingImplementation(_batchedUpdatesImpl, _discreteUpdatesImpl, _flushSyncImpl) { batchedUpdatesImpl = _batchedUpdatesImpl; flushSyncImpl = _flushSyncImpl; } function isInteractive(tag) { return tag === 'button' || tag === 'input' || tag === 'select' || tag === 'textarea'; } function shouldPreventMouseEvent(name, type, props) { switch (name) { case 'onClick': case 'onClickCapture': case 'onDoubleClick': case 'onDoubleClickCapture': case 'onMouseDown': case 'onMouseDownCapture': case 'onMouseMove': case 'onMouseMoveCapture': case 'onMouseUp': case 'onMouseUpCapture': case 'onMouseEnter': return !!(props.disabled && isInteractive(type)); default: return false; } } /** * @param {object} inst The instance, which is the source of events. * @param {string} registrationName Name of listener (e.g. `onClick`). * @return {?function} The stored callback. */ function getListener(inst, registrationName) { var stateNode = inst.stateNode; if (stateNode === null) { // Work in progress (ex: onload events in incremental mode). return null; } var props = getFiberCurrentPropsFromNode(stateNode); if (props === null) { // Work in progress. return null; } var listener = props[registrationName]; if (shouldPreventMouseEvent(registrationName, inst.type, props)) { return null; } if (listener && typeof listener !== 'function') { throw new Error("Expected `" + registrationName + "` listener to be a function, instead got a value of `" + typeof listener + "` type."); } return listener; } var passiveBrowserEventsSupported = false; // Check if browser support events with passive listeners // https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support if (canUseDOM) { try { var options = {}; // $FlowFixMe: Ignore Flow complaining about needing a value Object.defineProperty(options, 'passive', { get: function () { passiveBrowserEventsSupported = true; } }); window.addEventListener('test', options, options); window.removeEventListener('test', options, options); } catch (e) { passiveBrowserEventsSupported = false; } } function invokeGuardedCallbackProd(name, func, context, a, b, c, d, e, f) { var funcArgs = Array.prototype.slice.call(arguments, 3); try { func.apply(context, funcArgs); } catch (error) { this.onError(error); } } var invokeGuardedCallbackImpl = invokeGuardedCallbackProd; { // In DEV mode, we swap out invokeGuardedCallback for a special version // that plays more nicely with the browser's DevTools. The idea is to preserve // "Pause on exceptions" behavior. Because React wraps all user-provided // functions in invokeGuardedCallback, and the production version of // invokeGuardedCallback uses a try-catch, all user exceptions are treated // like caught exceptions, and the DevTools won't pause unless the developer // takes the extra step of enabling pause on caught exceptions. This is // unintuitive, though, because even though React has caught the error, from // the developer's perspective, the error is uncaught. // // To preserve the expected "Pause on exceptions" behavior, we don't use a // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake // DOM node, and call the user-provided callback from inside an event handler // for that fake event. If the callback throws, the error is "captured" using // a global event handler. But because the error happens in a different // event loop context, it does not interrupt the normal program flow. // Effectively, this gives us try-catch behavior without actually using // try-catch. Neat! // Check that the browser supports the APIs we need to implement our special // DEV version of invokeGuardedCallback if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') { var fakeNode = document.createElement('react'); invokeGuardedCallbackImpl = function invokeGuardedCallbackDev(name, func, context, a, b, c, d, e, f) { // If document doesn't exist we know for sure we will crash in this method // when we call document.createEvent(). However this can cause confusing // errors: https://github.com/facebook/create-react-app/issues/3482 // So we preemptively throw with a better message instead. if (typeof document === 'undefined' || document === null) { throw new Error('The `document` global was defined when React was initialized, but is not ' + 'defined anymore. This can happen in a test environment if a component ' + 'schedules an update from an asynchronous callback, but the test has already ' + 'finished running. To solve this, you can either unmount the component at ' + 'the end of your test (and ensure that any asynchronous operations get ' + 'canceled in `componentWillUnmount`), or you can change the test itself ' + 'to be asynchronous.'); } var evt = document.createEvent('Event'); var didCall = false; // Keeps track of whether the user-provided callback threw an error. We // set this to true at the beginning, then set it to false right after // calling the function. If the function errors, `didError` will never be // set to false. This strategy works even if the browser is flaky and // fails to call our global error handler, because it doesn't rely on // the error event at all. var didError = true; // Keeps track of the value of window.event so that we can reset it // during the callback to let user code access window.event in the // browsers that support it. var windowEvent = window.event; // Keeps track of the descriptor of window.event to restore it after event // dispatching: https://github.com/facebook/react/issues/13688 var windowEventDescriptor = Object.getOwnPropertyDescriptor(window, 'event'); function restoreAfterDispatch() { // We immediately remove the callback from event listeners so that // nested `invokeGuardedCallback` calls do not clash. Otherwise, a // nested call would trigger the fake event handlers of any call higher // in the stack. fakeNode.removeEventListener(evtType, callCallback, false); // We check for window.hasOwnProperty('event') to prevent the // window.event assignment in both IE <= 10 as they throw an error // "Member not found" in strict mode, and in Firefox which does not // support window.event. if (typeof window.event !== 'undefined' && window.hasOwnProperty('event')) { window.event = windowEvent; } } // Create an event handler for our fake event. We will synchronously // dispatch our fake event using `dispatchEvent`. Inside the handler, we // call the user-provided callback. var funcArgs = Array.prototype.slice.call(arguments, 3); function callCallback() { didCall = true; restoreAfterDispatch(); func.apply(context, funcArgs); didError = false; } // Create a global error event handler. We use this to capture the value // that was thrown. It's possible that this error handler will fire more // than once; for example, if non-React code also calls `dispatchEvent` // and a handler for that event throws. We should be resilient to most of // those cases. Even if our error event handler fires more than once, the // last error event is always used. If the callback actually does error, // we know that the last error event is the correct one, because it's not // possible for anything else to have happened in between our callback // erroring and the code that follows the `dispatchEvent` call below. If // the callback doesn't error, but the error event was fired, we know to // ignore it because `didError` will be false, as described above. var error; // Use this to track whether the error event is ever called. var didSetError = false; var isCrossOriginError = false; function handleWindowError(event) { error = event.error; didSetError = true; if (error === null && event.colno === 0 && event.lineno === 0) { isCrossOriginError = true; } if (event.defaultPrevented) { // Some other error handler has prevented default. // Browsers silence the error report if this happens. // We'll remember this to later decide whether to log it or not. if (error != null && typeof error === 'object') { try { error._suppressLogging = true; } catch (inner) {// Ignore. } } } } // Create a fake event type. var evtType = "react-" + (name ? name : 'invokeguardedcallback'); // Attach our event handlers window.addEventListener('error', handleWindowError); fakeNode.addEventListener(evtType, callCallback, false); // Synchronously dispatch our fake event. If the user-provided function // errors, it will trigger our global error handler. evt.initEvent(evtType, false, false); fakeNode.dispatchEvent(evt); if (windowEventDescriptor) { Object.defineProperty(window, 'event', windowEventDescriptor); } if (didCall && didError) { if (!didSetError) { // The callback errored, but the error event never fired. // eslint-disable-next-line react-internal/prod-error-codes error = new Error('An error was thrown inside one of your components, but React ' + "doesn't know what it was. This is likely due to browser " + 'flakiness. React does its best to preserve the "Pause on ' + 'exceptions" behavior of the DevTools, which requires some ' + "DEV-mode only tricks. It's possible that these don't work in " + 'your browser. Try triggering the error in production mode, ' + 'or switching to a modern browser. If you suspect that this is ' + 'actually an issue with React, please file an issue.'); } else if (isCrossOriginError) { // eslint-disable-next-line react-internal/prod-error-codes error = new Error("A cross-origin error was thrown. React doesn't have access to " + 'the actual error object in development. ' + 'See https://reactjs.org/link/crossorigin-error for more information.'); } this.onError(error); } // Remove our event listeners window.removeEventListener('error', handleWindowError); if (!didCall) { // Something went really wrong, and our event was not dispatched. // https://github.com/facebook/react/issues/16734 // https://github.com/facebook/react/issues/16585 // Fall back to the production implementation. restoreAfterDispatch(); return invokeGuardedCallbackProd.apply(this, arguments); } }; } } var invokeGuardedCallbackImpl$1 = invokeGuardedCallbackImpl; var hasError = false; var caughtError = null; // Used by event system to capture/rethrow the first error. var hasRethrowError = false; var rethrowError = null; var reporter = { onError: function (error) { hasError = true; caughtError = error; } }; /** * Call a function while guarding against errors that happens within it. * Returns an error if it throws, otherwise null. * * In production, this is implemented using a try-catch. The reason we don't * use a try-catch directly is so that we can swap out a different * implementation in DEV mode. * * @param {String} name of the guard to use for logging or debugging * @param {Function} func The function to invoke * @param {*} context The context to use when calling the function * @param {...*} args Arguments for function */ function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) { hasError = false; caughtError = null; invokeGuardedCallbackImpl$1.apply(reporter, arguments); } /** * Same as invokeGuardedCallback, but instead of returning an error, it stores * it in a global so it can be rethrown by `rethrowCaughtError` later. * TODO: See if caughtError and rethrowError can be unified. * * @param {String} name of the guard to use for logging or debugging * @param {Function} func The function to invoke * @param {*} context The context to use when calling the function * @param {...*} args Arguments for function */ function invokeGuardedCallbackAndCatchFirstError(name, func, context, a, b, c, d, e, f) { invokeGuardedCallback.apply(this, arguments); if (hasError) { var error = clearCaughtError(); if (!hasRethrowError) { hasRethrowError = true; rethrowError = error; } } } /** * During execution of guarded functions we will capture the first error which * we will rethrow to be handled by the top level error handler. */ function rethrowCaughtError() { if (hasRethrowError) { var error = rethrowError; hasRethrowError = false; rethrowError = null; throw error; } } function hasCaughtError() { return hasError; } function clearCaughtError() { if (hasError) { var error = caughtError; hasError = false; caughtError = null; return error; } else { throw new Error('clearCaughtError was called but no error was captured. This error ' + 'is likely caused by a bug in React. Please file an issue.'); } } /** * `ReactInstanceMap` maintains a mapping from a public facing stateful * instance (key) and the internal representation (value). This allows public * methods to accept the user facing instance as an argument and map them back * to internal methods. * * Note that this module is currently shared and assumed to be stateless. * If this becomes an actual Map, that will break. */ function get(key) { return key._reactInternals; } function has(key) { return key._reactInternals !== undefined; } function set(key, value) { key._reactInternals = value; } // Don't change these two values. They're used by React Dev Tools. var NoFlags = /* */ 0; var PerformedWork = /* */ 1; // You can change the rest (and add more). var Placement = /* */ 2; var Update = /* */ 4; var ChildDeletion = /* */ 16; var ContentReset = /* */ 32; var Callback = /* */ 64; var DidCapture = /* */ 128; var ForceClientRender = /* */ 256; var Ref = /* */ 512; var Snapshot = /* */ 1024; var Passive = /* */ 2048; var Hydrating = /* */ 4096; var Visibility = /* */ 8192; var StoreConsistency = /* */ 16384; var LifecycleEffectMask = Passive | Update | Callback | Ref | Snapshot | StoreConsistency; // Union of all commit flags (flags with the lifetime of a particular commit) var HostEffectMask = /* */ 32767; // These are not really side effects, but we still reuse this field. var Incomplete = /* */ 32768; var ShouldCapture = /* */ 65536; var ForceUpdateForLegacySuspense = /* */ 131072; var Forked = /* */ 1048576; // Static tags describe aspects of a fiber that are not specific to a render, // e.g. a fiber uses a passive effect (even if there are no updates on this particular render). // This enables us to defer more work in the unmount case, // since we can defer traversing the tree during layout to look for Passive effects, // and instead rely on the static flag as a signal that there may be cleanup work. var RefStatic = /* */ 2097152; var LayoutStatic = /* */ 4194304; var PassiveStatic = /* */ 8388608; // These flags allow us to traverse to fibers that have effects on mount // without traversing the entire tree after every commit for // double invoking var MountLayoutDev = /* */ 16777216; var MountPassiveDev = /* */ 33554432; // Groups of flags that are used in the commit phase to skip over trees that // don't contain effects, by checking subtreeFlags. var BeforeMutationMask = // TODO: Remove Update flag from before mutation phase by re-landing Visibility // flag logic (see #20043) Update | Snapshot | ( 0); var MutationMask = Placement | Update | ChildDeletion | ContentReset | Ref | Hydrating | Visibility; var LayoutMask = Update | Callback | Ref | Visibility; // TODO: Split into PassiveMountMask and PassiveUnmountMask var PassiveMask = Passive | ChildDeletion; // Union of tags that don't get reset on clones. // This allows certain concepts to persist without recalculating them, // e.g. whether a subtree contains passive effects or portals. var StaticMask = LayoutStatic | PassiveStatic | RefStatic; var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner; function getNearestMountedFiber(fiber) { var node = fiber; var nearestMounted = fiber; if (!fiber.alternate) { // If there is no alternate, this might be a new tree that isn't inserted // yet. If it is, then it will have a pending insertion effect on it. var nextNode = node; do { node = nextNode; if ((node.flags & (Placement | Hydrating)) !== NoFlags) { // This is an insertion or in-progress hydration. The nearest possible // mounted fiber is the parent but we need to continue to figure out // if that one is still mounted. nearestMounted = node.return; } nextNode = node.return; } while (nextNode); } else { while (node.return) { node = node.return; } } if (node.tag === HostRoot) { // TODO: Check if this was a nested HostRoot when used with // renderContainerIntoSubtree. return nearestMounted; } // If we didn't hit the root, that means that we're in an disconnected tree // that has been unmounted. return null; } function getSuspenseInstanceFromFiber(fiber) { if (fiber.tag === SuspenseComponent) { var suspenseState = fiber.memoizedState; if (suspenseState === null) { var current = fiber.alternate; if (current !== null) { suspenseState = current.memoizedState; } } if (suspenseState !== null) { return suspenseState.dehydrated; } } return null; } function getContainerFromFiber(fiber) { return fiber.tag === HostRoot ? fiber.stateNode.containerInfo : null; } function isFiberMounted(fiber) { return getNearestMountedFiber(fiber) === fiber; } function isMounted(component) { { var owner = ReactCurrentOwner.current; if (owner !== null && owner.tag === ClassComponent) { var ownerFiber = owner; var instance = ownerFiber.stateNode; if (!instance._warnedAboutRefsInRender) { error('%s is accessing isMounted inside its render() function. ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', getComponentNameFromFiber(ownerFiber) || 'A component'); } instance._warnedAboutRefsInRender = true; } } var fiber = get(component); if (!fiber) { return false; } return getNearestMountedFiber(fiber) === fiber; } function assertIsMounted(fiber) { if (getNearestMountedFiber(fiber) !== fiber) { throw new Error('Unable to find node on an unmounted component.'); } } function findCurrentFiberUsingSlowPath(fiber) { var alternate = fiber.alternate; if (!alternate) { // If there is no alternate, then we only need to check if it is mounted. var nearestMounted = getNearestMountedFiber(fiber); if (nearestMounted === null) { throw new Error('Unable to find node on an unmounted component.'); } if (nearestMounted !== fiber) { return null; } return fiber; } // If we have two possible branches, we'll walk backwards up to the root // to see what path the root points to. On the way we may hit one of the // special cases and we'll deal with them. var a = fiber; var b = alternate; while (true) { var parentA = a.return; if (parentA === null) { // We're at the root. break; } var parentB = parentA.alternate; if (parentB === null) { // There is no alternate. This is an unusual case. Currently, it only // happens when a Suspense component is hidden. An extra fragment fiber // is inserted in between the Suspense fiber and its children. Skip // over this extra fragment fiber and proceed to the next parent. var nextParent = parentA.return; if (nextParent !== null) { a = b = nextParent; continue; } // If there's no parent, we're at the root. break; } // If both copies of the parent fiber point to the same child, we can // assume that the child is current. This happens when we bailout on low // priority: the bailed out fiber's child reuses the current child. if (parentA.child === parentB.child) { var child = parentA.child; while (child) { if (child === a) { // We've determined that A is the current branch. assertIsMounted(parentA); return fiber; } if (child === b) { // We've determined that B is the current branch. assertIsMounted(parentA); return alternate; } child = child.sibling; } // We should never have an alternate for any mounting node. So the only // way this could possibly happen is if this was unmounted, if at all. throw new Error('Unable to find node on an unmounted component.'); } if (a.return !== b.return) { // The return pointer of A and the return pointer of B point to different // fibers. We assume that return pointers never criss-cross, so A must // belong to the child set of A.return, and B must belong to the child // set of B.return. a = parentA; b = parentB; } else { // The return pointers point to the same fiber. We'll have to use the // default, slow path: scan the child sets of each parent alternate to see // which child belongs to which set. // // Search parent A's child set var didFindChild = false; var _child = parentA.child; while (_child) { if (_child === a) { didFindChild = true; a = parentA; b = parentB; break; } if (_child === b) { didFindChild = true; b = parentA; a = parentB; break; } _child = _child.sibling; } if (!didFindChild) { // Search parent B's child set _child = parentB.child; while (_child) { if (_child === a) { didFindChild = true; a = parentB; b = parentA; break; } if (_child === b) { didFindChild = true; b = parentB; a = parentA; break; } _child = _child.sibling; } if (!didFindChild) { throw new Error('Child was not found in either parent set. This indicates a bug ' + 'in React related to the return pointer. Please file an issue.'); } } } if (a.alternate !== b) { throw new Error("Return fibers should always be each others' alternates. " + 'This error is likely caused by a bug in React. Please file an issue.'); } } // If the root is not a host container, we're in a disconnected tree. I.e. // unmounted. if (a.tag !== HostRoot) { throw new Error('Unable to find node on an unmounted component.'); } if (a.stateNode.current === a) { // We've determined that A is the current branch. return fiber; } // Otherwise B has to be current branch. return alternate; } function findCurrentHostFiber(parent) { var currentParent = findCurrentFiberUsingSlowPath(parent); return currentParent !== null ? findCurrentHostFiberImpl(currentParent) : null; } function findCurrentHostFiberImpl(node) { // Next we'll drill down this component to find the first HostComponent/Text. if (node.tag === HostComponent || node.tag === HostText) { return node; } var child = node.child; while (child !== null) { var match = findCurrentHostFiberImpl(child); if (match !== null) { return match; } child = child.sibling; } return null; } function findCurrentHostFiberWithNoPortals(parent) { var currentParent = findCurrentFiberUsingSlowPath(parent); return currentParent !== null ? findCurrentHostFiberWithNoPortalsImpl(currentParent) : null; } function findCurrentHostFiberWithNoPortalsImpl(node) { // Next we'll drill down this component to find the first HostComponent/Text. if (node.tag === HostComponent || node.tag === HostText) { return node; } var child = node.child; while (child !== null) { if (child.tag !== HostPortal) { var match = findCurrentHostFiberWithNoPortalsImpl(child); if (match !== null) { return match; } } child = child.sibling; } return null; } // This module only exists as an ESM wrapper around the external CommonJS var scheduleCallback = Scheduler.unstable_scheduleCallback; var cancelCallback = Scheduler.unstable_cancelCallback; var shouldYield = Scheduler.unstable_shouldYield; var requestPaint = Scheduler.unstable_requestPaint; var now = Scheduler.unstable_now; var getCurrentPriorityLevel = Scheduler.unstable_getCurrentPriorityLevel; var ImmediatePriority = Scheduler.unstable_ImmediatePriority; var UserBlockingPriority = Scheduler.unstable_UserBlockingPriority; var NormalPriority = Scheduler.unstable_NormalPriority; var LowPriority = Scheduler.unstable_LowPriority; var IdlePriority = Scheduler.unstable_IdlePriority; // this doesn't actually exist on the scheduler, but it *does* // on scheduler/unstable_mock, which we'll need for internal testing var unstable_yieldValue = Scheduler.unstable_yieldValue; var unstable_setDisableYieldValue = Scheduler.unstable_setDisableYieldValue; var rendererID = null; var injectedHook = null; var injectedProfilingHooks = null; var hasLoggedError = false; var isDevToolsPresent = typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined'; function injectInternals(internals) { if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') { // No DevTools return false; } var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__; if (hook.isDisabled) { // This isn't a real property on the hook, but it can be set to opt out // of DevTools integration and associated warnings and logs. // https://github.com/facebook/react/issues/3877 return true; } if (!hook.supportsFiber) { { error('The installed version of React DevTools is too old and will not work ' + 'with the current version of React. Please update React DevTools. ' + 'https://reactjs.org/link/react-devtools'); } // DevTools exists, even though it doesn't support Fiber. return true; } try { if (enableSchedulingProfiler) { // Conditionally inject these hooks only if Timeline profiler is supported by this build. // This gives DevTools a way to feature detect that isn't tied to version number // (since profiling and timeline are controlled by different feature flags). internals = assign({}, internals, { getLaneLabelMap: getLaneLabelMap, injectProfilingHooks: injectProfilingHooks }); } rendererID = hook.inject(internals); // We have successfully injected, so now it is safe to set up hooks. injectedHook = hook; } catch (err) { // Catch all errors because it is unsafe to throw during initialization. { error('React instrumentation encountered an error: %s.', err); } } if (hook.checkDCE) { // This is the real DevTools. return true; } else { // This is likely a hook installed by Fast Refresh runtime. return false; } } function onScheduleRoot(root, children) { { if (injectedHook && typeof injectedHook.onScheduleFiberRoot === 'function') { try { injectedHook.onScheduleFiberRoot(rendererID, root, children); } catch (err) { if ( !hasLoggedError) { hasLoggedError = true; error('React instrumentation encountered an error: %s', err); } } } } } function onCommitRoot(root, eventPriority) { if (injectedHook && typeof injectedHook.onCommitFiberRoot === 'function') { try { var didError = (root.current.flags & DidCapture) === DidCapture; if (enableProfilerTimer) { var schedulerPriority; switch (eventPriority) { case DiscreteEventPriority: schedulerPriority = ImmediatePriority; break; case ContinuousEventPriority: schedulerPriority = UserBlockingPriority; break; case DefaultEventPriority: schedulerPriority = NormalPriority; break; case IdleEventPriority: schedulerPriority = IdlePriority; break; default: schedulerPriority = NormalPriority; break; } injectedHook.onCommitFiberRoot(rendererID, root, schedulerPriority, didError); } else { injectedHook.onCommitFiberRoot(rendererID, root, undefined, didError); } } catch (err) { { if (!hasLoggedError) { hasLoggedError = true; error('React instrumentation encountered an error: %s', err); } } } } } function onPostCommitRoot(root) { if (injectedHook && typeof injectedHook.onPostCommitFiberRoot === 'function') { try { injectedHook.onPostCommitFiberRoot(rendererID, root); } catch (err) { { if (!hasLoggedError) { hasLoggedError = true; error('React instrumentation encountered an error: %s', err); } } } } } function onCommitUnmount(fiber) { if (injectedHook && typeof injectedHook.onCommitFiberUnmount === 'function') { try { injectedHook.onCommitFiberUnmount(rendererID, fiber); } catch (err) { { if (!hasLoggedError) { hasLoggedError = true; error('React instrumentation encountered an error: %s', err); } } } } } function setIsStrictModeForDevtools(newIsStrictMode) { { if (typeof unstable_yieldValue === 'function') { // We're in a test because Scheduler.unstable_yieldValue only exists // in SchedulerMock. To reduce the noise in strict mode tests, // suppress warnings and disable scheduler yielding during the double render unstable_setDisableYieldValue(newIsStrictMode); setSuppressWarning(newIsStrictMode); } if (injectedHook && typeof injectedHook.setStrictMode === 'function') { try { injectedHook.setStrictMode(rendererID, newIsStrictMode); } catch (err) { { if (!hasLoggedError) { hasLoggedError = true; error('React instrumentation encountered an error: %s', err); } } } } } } // Profiler API hooks function injectProfilingHooks(profilingHooks) { injectedProfilingHooks = profilingHooks; } function getLaneLabelMap() { { var map = new Map(); var lane = 1; for (var index = 0; index < TotalLanes; index++) { var label = getLabelForLane(lane); map.set(lane, label); lane *= 2; } return map; } } function markCommitStarted(lanes) { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markCommitStarted === 'function') { injectedProfilingHooks.markCommitStarted(lanes); } } } function markCommitStopped() { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markCommitStopped === 'function') { injectedProfilingHooks.markCommitStopped(); } } } function markComponentRenderStarted(fiber) { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentRenderStarted === 'function') { injectedProfilingHooks.markComponentRenderStarted(fiber); } } } function markComponentRenderStopped() { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentRenderStopped === 'function') { injectedProfilingHooks.markComponentRenderStopped(); } } } function markComponentPassiveEffectMountStarted(fiber) { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectMountStarted === 'function') { injectedProfilingHooks.markComponentPassiveEffectMountStarted(fiber); } } } function markComponentPassiveEffectMountStopped() { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectMountStopped === 'function') { injectedProfilingHooks.markComponentPassiveEffectMountStopped(); } } } function markComponentPassiveEffectUnmountStarted(fiber) { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectUnmountStarted === 'function') { injectedProfilingHooks.markComponentPassiveEffectUnmountStarted(fiber); } } } function markComponentPassiveEffectUnmountStopped() { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectUnmountStopped === 'function') { injectedProfilingHooks.markComponentPassiveEffectUnmountStopped(); } } } function markComponentLayoutEffectMountStarted(fiber) { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectMountStarted === 'function') { injectedProfilingHooks.markComponentLayoutEffectMountStarted(fiber); } } } function markComponentLayoutEffectMountStopped() { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectMountStopped === 'function') { injectedProfilingHooks.markComponentLayoutEffectMountStopped(); } } } function markComponentLayoutEffectUnmountStarted(fiber) { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectUnmountStarted === 'function') { injectedProfilingHooks.markComponentLayoutEffectUnmountStarted(fiber); } } } function markComponentLayoutEffectUnmountStopped() { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectUnmountStopped === 'function') { injectedProfilingHooks.markComponentLayoutEffectUnmountStopped(); } } } function markComponentErrored(fiber, thrownValue, lanes) { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentErrored === 'function') { injectedProfilingHooks.markComponentErrored(fiber, thrownValue, lanes); } } } function markComponentSuspended(fiber, wakeable, lanes) { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentSuspended === 'function') { injectedProfilingHooks.markComponentSuspended(fiber, wakeable, lanes); } } } function markLayoutEffectsStarted(lanes) { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markLayoutEffectsStarted === 'function') { injectedProfilingHooks.markLayoutEffectsStarted(lanes); } } } function markLayoutEffectsStopped() { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markLayoutEffectsStopped === 'function') { injectedProfilingHooks.markLayoutEffectsStopped(); } } } function markPassiveEffectsStarted(lanes) { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markPassiveEffectsStarted === 'function') { injectedProfilingHooks.markPassiveEffectsStarted(lanes); } } } function markPassiveEffectsStopped() { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markPassiveEffectsStopped === 'function') { injectedProfilingHooks.markPassiveEffectsStopped(); } } } function markRenderStarted(lanes) { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderStarted === 'function') { injectedProfilingHooks.markRenderStarted(lanes); } } } function markRenderYielded() { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderYielded === 'function') { injectedProfilingHooks.markRenderYielded(); } } } function markRenderStopped() { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderStopped === 'function') { injectedProfilingHooks.markRenderStopped(); } } } function markRenderScheduled(lane) { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderScheduled === 'function') { injectedProfilingHooks.markRenderScheduled(lane); } } } function markForceUpdateScheduled(fiber, lane) { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markForceUpdateScheduled === 'function') { injectedProfilingHooks.markForceUpdateScheduled(fiber, lane); } } } function markStateUpdateScheduled(fiber, lane) { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markStateUpdateScheduled === 'function') { injectedProfilingHooks.markStateUpdateScheduled(fiber, lane); } } } var NoMode = /* */ 0; // TODO: Remove ConcurrentMode by reading from the root tag instead var ConcurrentMode = /* */ 1; var ProfileMode = /* */ 2; var StrictLegacyMode = /* */ 8; var StrictEffectsMode = /* */ 16; // TODO: This is pretty well supported by browsers. Maybe we can drop it. var clz32 = Math.clz32 ? Math.clz32 : clz32Fallback; // Count leading zeros. // Based on: // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32 var log = Math.log; var LN2 = Math.LN2; function clz32Fallback(x) { var asUint = x >>> 0; if (asUint === 0) { return 32; } return 31 - (log(asUint) / LN2 | 0) | 0; } // If those values are changed that package should be rebuilt and redeployed. var TotalLanes = 31; var NoLanes = /* */ 0; var NoLane = /* */ 0; var SyncLane = /* */ 1; var InputContinuousHydrationLane = /* */ 2; var InputContinuousLane = /* */ 4; var DefaultHydrationLane = /* */ 8; var DefaultLane = /* */ 16; var TransitionHydrationLane = /* */ 32; var TransitionLanes = /* */ 4194240; var TransitionLane1 = /* */ 64; var TransitionLane2 = /* */ 128; var TransitionLane3 = /* */ 256; var TransitionLane4 = /* */ 512; var TransitionLane5 = /* */ 1024; var TransitionLane6 = /* */ 2048; var TransitionLane7 = /* */ 4096; var TransitionLane8 = /* */ 8192; var TransitionLane9 = /* */ 16384; var TransitionLane10 = /* */ 32768; var TransitionLane11 = /* */ 65536; var TransitionLane12 = /* */ 131072; var TransitionLane13 = /* */ 262144; var TransitionLane14 = /* */ 524288; var TransitionLane15 = /* */ 1048576; var TransitionLane16 = /* */ 2097152; var RetryLanes = /* */ 130023424; var RetryLane1 = /* */ 4194304; var RetryLane2 = /* */ 8388608; var RetryLane3 = /* */ 16777216; var RetryLane4 = /* */ 33554432; var RetryLane5 = /* */ 67108864; var SomeRetryLane = RetryLane1; var SelectiveHydrationLane = /* */ 134217728; var NonIdleLanes = /* */ 268435455; var IdleHydrationLane = /* */ 268435456; var IdleLane = /* */ 536870912; var OffscreenLane = /* */ 1073741824; // This function is used for the experimental timeline (react-devtools-timeline) // It should be kept in sync with the Lanes values above. function getLabelForLane(lane) { { if (lane & SyncLane) { return 'Sync'; } if (lane & InputContinuousHydrationLane) { return 'InputContinuousHydration'; } if (lane & InputContinuousLane) { return 'InputContinuous'; } if (lane & DefaultHydrationLane) { return 'DefaultHydration'; } if (lane & DefaultLane) { return 'Default'; } if (lane & TransitionHydrationLane) { return 'TransitionHydration'; } if (lane & TransitionLanes) { return 'Transition'; } if (lane & RetryLanes) { return 'Retry'; } if (lane & SelectiveHydrationLane) { return 'SelectiveHydration'; } if (lane & IdleHydrationLane) { return 'IdleHydration'; } if (lane & IdleLane) { return 'Idle'; } if (lane & OffscreenLane) { return 'Offscreen'; } } } var NoTimestamp = -1; var nextTransitionLane = TransitionLane1; var nextRetryLane = RetryLane1; function getHighestPriorityLanes(lanes) { switch (getHighestPriorityLane(lanes)) { case SyncLane: return SyncLane; case InputContinuousHydrationLane: return InputContinuousHydrationLane; case InputContinuousLane: return InputContinuousLane; case DefaultHydrationLane: return DefaultHydrationLane; case DefaultLane: return DefaultLane; case TransitionHydrationLane: return TransitionHydrationLane; case TransitionLane1: case TransitionLane2: case TransitionLane3: case TransitionLane4: case TransitionLane5: case TransitionLane6: case TransitionLane7: case TransitionLane8: case TransitionLane9: case TransitionLane10: case TransitionLane11: case TransitionLane12: case TransitionLane13: case TransitionLane14: case TransitionLane15: case TransitionLane16: return lanes & TransitionLanes; case RetryLane1: case RetryLane2: case RetryLane3: case RetryLane4: case RetryLane5: return lanes & RetryLanes; case SelectiveHydrationLane: return SelectiveHydrationLane; case IdleHydrationLane: return IdleHydrationLane; case IdleLane: return IdleLane; case OffscreenLane: return OffscreenLane; default: { error('Should have found matching lanes. This is a bug in React.'); } // This shouldn't be reachable, but as a fallback, return the entire bitmask. return lanes; } } function getNextLanes(root, wipLanes) { // Early bailout if there's no pending work left. var pendingLanes = root.pendingLanes; if (pendingLanes === NoLanes) { return NoLanes; } var nextLanes = NoLanes; var suspendedLanes = root.suspendedLanes; var pingedLanes = root.pingedLanes; // Do not work on any idle work until all the non-idle work has finished, // even if the work is suspended. var nonIdlePendingLanes = pendingLanes & NonIdleLanes; if (nonIdlePendingLanes !== NoLanes) { var nonIdleUnblockedLanes = nonIdlePendingLanes & ~suspendedLanes; if (nonIdleUnblockedLanes !== NoLanes) { nextLanes = getHighestPriorityLanes(nonIdleUnblockedLanes); } else { var nonIdlePingedLanes = nonIdlePendingLanes & pingedLanes; if (nonIdlePingedLanes !== NoLanes) { nextLanes = getHighestPriorityLanes(nonIdlePingedLanes); } } } else { // The only remaining work is Idle. var unblockedLanes = pendingLanes & ~suspendedLanes; if (unblockedLanes !== NoLanes) { nextLanes = getHighestPriorityLanes(unblockedLanes); } else { if (pingedLanes !== NoLanes) { nextLanes = getHighestPriorityLanes(pingedLanes); } } } if (nextLanes === NoLanes) { // This should only be reachable if we're suspended // TODO: Consider warning in this path if a fallback timer is not scheduled. return NoLanes; } // If we're already in the middle of a render, switching lanes will interrupt // it and we'll lose our progress. We should only do this if the new lanes are // higher priority. if (wipLanes !== NoLanes && wipLanes !== nextLanes && // If we already suspended with a delay, then interrupting is fine. Don't // bother waiting until the root is complete. (wipLanes & suspendedLanes) === NoLanes) { var nextLane = getHighestPriorityLane(nextLanes); var wipLane = getHighestPriorityLane(wipLanes); if ( // Tests whether the next lane is equal or lower priority than the wip // one. This works because the bits decrease in priority as you go left. nextLane >= wipLane || // Default priority updates should not interrupt transition updates. The // only difference between default updates and transition updates is that // default updates do not support refresh transitions. nextLane === DefaultLane && (wipLane & TransitionLanes) !== NoLanes) { // Keep working on the existing in-progress tree. Do not interrupt. return wipLanes; } } if ((nextLanes & InputContinuousLane) !== NoLanes) { // When updates are sync by default, we entangle continuous priority updates // and default updates, so they render in the same batch. The only reason // they use separate lanes is because continuous updates should interrupt // transitions, but default updates should not. nextLanes |= pendingLanes & DefaultLane; } // Check for entangled lanes and add them to the batch. // // A lane is said to be entangled with another when it's not allowed to render // in a batch that does not also include the other lane. Typically we do this // when multiple updates have the same source, and we only want to respond to // the most recent event from that source. // // Note that we apply entanglements *after* checking for partial work above. // This means that if a lane is entangled during an interleaved event while // it's already rendering, we won't interrupt it. This is intentional, since // entanglement is usually "best effort": we'll try our best to render the // lanes in the same batch, but it's not worth throwing out partially // completed work in order to do it. // TODO: Reconsider this. The counter-argument is that the partial work // represents an intermediate state, which we don't want to show to the user. // And by spending extra time finishing it, we're increasing the amount of // time it takes to show the final state, which is what they are actually // waiting for. // // For those exceptions where entanglement is semantically important, like // useMutableSource, we should ensure that there is no partial work at the // time we apply the entanglement. var entangledLanes = root.entangledLanes; if (entangledLanes !== NoLanes) { var entanglements = root.entanglements; var lanes = nextLanes & entangledLanes; while (lanes > 0) { var index = pickArbitraryLaneIndex(lanes); var lane = 1 << index; nextLanes |= entanglements[index]; lanes &= ~lane; } } return nextLanes; } function getMostRecentEventTime(root, lanes) { var eventTimes = root.eventTimes; var mostRecentEventTime = NoTimestamp; while (lanes > 0) { var index = pickArbitraryLaneIndex(lanes); var lane = 1 << index; var eventTime = eventTimes[index]; if (eventTime > mostRecentEventTime) { mostRecentEventTime = eventTime; } lanes &= ~lane; } return mostRecentEventTime; } function computeExpirationTime(lane, currentTime) { switch (lane) { case SyncLane: case InputContinuousHydrationLane: case InputContinuousLane: // User interactions should expire slightly more quickly. // // NOTE: This is set to the corresponding constant as in Scheduler.js. // When we made it larger, a product metric in www regressed, suggesting // there's a user interaction that's being starved by a series of // synchronous updates. If that theory is correct, the proper solution is // to fix the starvation. However, this scenario supports the idea that // expiration times are an important safeguard when starvation // does happen. return currentTime + 250; case DefaultHydrationLane: case DefaultLane: case TransitionHydrationLane: case TransitionLane1: case TransitionLane2: case TransitionLane3: case TransitionLane4: case TransitionLane5: case TransitionLane6: case TransitionLane7: case TransitionLane8: case TransitionLane9: case TransitionLane10: case TransitionLane11: case TransitionLane12: case TransitionLane13: case TransitionLane14: case TransitionLane15: case TransitionLane16: return currentTime + 5000; case RetryLane1: case RetryLane2: case RetryLane3: case RetryLane4: case RetryLane5: // TODO: Retries should be allowed to expire if they are CPU bound for // too long, but when I made this change it caused a spike in browser // crashes. There must be some other underlying bug; not super urgent but // ideally should figure out why and fix it. Unfortunately we don't have // a repro for the crashes, only detected via production metrics. return NoTimestamp; case SelectiveHydrationLane: case IdleHydrationLane: case IdleLane: case OffscreenLane: // Anything idle priority or lower should never expire. return NoTimestamp; default: { error('Should have found matching lanes. This is a bug in React.'); } return NoTimestamp; } } function markStarvedLanesAsExpired(root, currentTime) { // TODO: This gets called every time we yield. We can optimize by storing // the earliest expiration time on the root. Then use that to quickly bail out // of this function. var pendingLanes = root.pendingLanes; var suspendedLanes = root.suspendedLanes; var pingedLanes = root.pingedLanes; var expirationTimes = root.expirationTimes; // Iterate through the pending lanes and check if we've reached their // expiration time. If so, we'll assume the update is being starved and mark // it as expired to force it to finish. var lanes = pendingLanes; while (lanes > 0) { var index = pickArbitraryLaneIndex(lanes); var lane = 1 << index; var expirationTime = expirationTimes[index]; if (expirationTime === NoTimestamp) { // Found a pending lane with no expiration time. If it's not suspended, or // if it's pinged, assume it's CPU-bound. Compute a new expiration time // using the current time. if ((lane & suspendedLanes) === NoLanes || (lane & pingedLanes) !== NoLanes) { // Assumes timestamps are monotonically increasing. expirationTimes[index] = computeExpirationTime(lane, currentTime); } } else if (expirationTime <= currentTime) { // This lane expired root.expiredLanes |= lane; } lanes &= ~lane; } } // This returns the highest priority pending lanes regardless of whether they // are suspended. function getHighestPriorityPendingLanes(root) { return getHighestPriorityLanes(root.pendingLanes); } function getLanesToRetrySynchronouslyOnError(root) { var everythingButOffscreen = root.pendingLanes & ~OffscreenLane; if (everythingButOffscreen !== NoLanes) { return everythingButOffscreen; } if (everythingButOffscreen & OffscreenLane) { return OffscreenLane; } return NoLanes; } function includesSyncLane(lanes) { return (lanes & SyncLane) !== NoLanes; } function includesNonIdleWork(lanes) { return (lanes & NonIdleLanes) !== NoLanes; } function includesOnlyRetries(lanes) { return (lanes & RetryLanes) === lanes; } function includesOnlyNonUrgentLanes(lanes) { var UrgentLanes = SyncLane | InputContinuousLane | DefaultLane; return (lanes & UrgentLanes) === NoLanes; } function includesOnlyTransitions(lanes) { return (lanes & TransitionLanes) === lanes; } function includesBlockingLane(root, lanes) { var SyncDefaultLanes = InputContinuousHydrationLane | InputContinuousLane | DefaultHydrationLane | DefaultLane; return (lanes & SyncDefaultLanes) !== NoLanes; } function includesExpiredLane(root, lanes) { // This is a separate check from includesBlockingLane because a lane can // expire after a render has already started. return (lanes & root.expiredLanes) !== NoLanes; } function isTransitionLane(lane) { return (lane & TransitionLanes) !== NoLanes; } function claimNextTransitionLane() { // Cycle through the lanes, assigning each new transition to the next lane. // In most cases, this means every transition gets its own lane, until we // run out of lanes and cycle back to the beginning. var lane = nextTransitionLane; nextTransitionLane <<= 1; if ((nextTransitionLane & TransitionLanes) === NoLanes) { nextTransitionLane = TransitionLane1; } return lane; } function claimNextRetryLane() { var lane = nextRetryLane; nextRetryLane <<= 1; if ((nextRetryLane & RetryLanes) === NoLanes) { nextRetryLane = RetryLane1; } return lane; } function getHighestPriorityLane(lanes) { return lanes & -lanes; } function pickArbitraryLane(lanes) { // This wrapper function gets inlined. Only exists so to communicate that it // doesn't matter which bit is selected; you can pick any bit without // affecting the algorithms where its used. Here I'm using // getHighestPriorityLane because it requires the fewest operations. return getHighestPriorityLane(lanes); } function pickArbitraryLaneIndex(lanes) { return 31 - clz32(lanes); } function laneToIndex(lane) { return pickArbitraryLaneIndex(lane); } function includesSomeLane(a, b) { return (a & b) !== NoLanes; } function isSubsetOfLanes(set, subset) { return (set & subset) === subset; } function mergeLanes(a, b) { return a | b; } function removeLanes(set, subset) { return set & ~subset; } function intersectLanes(a, b) { return a & b; } // Seems redundant, but it changes the type from a single lane (used for // updates) to a group of lanes (used for flushing work). function laneToLanes(lane) { return lane; } function higherPriorityLane(a, b) { // This works because the bit ranges decrease in priority as you go left. return a !== NoLane && a < b ? a : b; } function createLaneMap(initial) { // Intentionally pushing one by one. // https://v8.dev/blog/elements-kinds#avoid-creating-holes var laneMap = []; for (var i = 0; i < TotalLanes; i++) { laneMap.push(initial); } return laneMap; } function markRootUpdated(root, updateLane, eventTime) { root.pendingLanes |= updateLane; // If there are any suspended transitions, it's possible this new update // could unblock them. Clear the suspended lanes so that we can try rendering // them again. // // TODO: We really only need to unsuspend only lanes that are in the // `subtreeLanes` of the updated fiber, or the update lanes of the return // path. This would exclude suspended updates in an unrelated sibling tree, // since there's no way for this update to unblock it. // // We don't do this if the incoming update is idle, because we never process // idle updates until after all the regular updates have finished; there's no // way it could unblock a transition. if (updateLane !== IdleLane) { root.suspendedLanes = NoLanes; root.pingedLanes = NoLanes; } var eventTimes = root.eventTimes; var index = laneToIndex(updateLane); // We can always overwrite an existing timestamp because we prefer the most // recent event, and we assume time is monotonically increasing. eventTimes[index] = eventTime; } function markRootSuspended(root, suspendedLanes) { root.suspendedLanes |= suspendedLanes; root.pingedLanes &= ~suspendedLanes; // The suspended lanes are no longer CPU-bound. Clear their expiration times. var expirationTimes = root.expirationTimes; var lanes = suspendedLanes; while (lanes > 0) { var index = pickArbitraryLaneIndex(lanes); var lane = 1 << index; expirationTimes[index] = NoTimestamp; lanes &= ~lane; } } function markRootPinged(root, pingedLanes, eventTime) { root.pingedLanes |= root.suspendedLanes & pingedLanes; } function markRootFinished(root, remainingLanes) { var noLongerPendingLanes = root.pendingLanes & ~remainingLanes; root.pendingLanes = remainingLanes; // Let's try everything again root.suspendedLanes = NoLanes; root.pingedLanes = NoLanes; root.expiredLanes &= remainingLanes; root.mutableReadLanes &= remainingLanes; root.entangledLanes &= remainingLanes; var entanglements = root.entanglements; var eventTimes = root.eventTimes; var expirationTimes = root.expirationTimes; // Clear the lanes that no longer have pending work var lanes = noLongerPendingLanes; while (lanes > 0) { var index = pickArbitraryLaneIndex(lanes); var lane = 1 << index; entanglements[index] = NoLanes; eventTimes[index] = NoTimestamp; expirationTimes[index] = NoTimestamp; lanes &= ~lane; } } function markRootEntangled(root, entangledLanes) { // In addition to entangling each of the given lanes with each other, we also // have to consider _transitive_ entanglements. For each lane that is already // entangled with *any* of the given lanes, that lane is now transitively // entangled with *all* the given lanes. // // Translated: If C is entangled with A, then entangling A with B also // entangles C with B. // // If this is hard to grasp, it might help to intentionally break this // function and look at the tests that fail in ReactTransition-test.js. Try // commenting out one of the conditions below. var rootEntangledLanes = root.entangledLanes |= entangledLanes; var entanglements = root.entanglements; var lanes = rootEntangledLanes; while (lanes) { var index = pickArbitraryLaneIndex(lanes); var lane = 1 << index; if ( // Is this one of the newly entangled lanes? lane & entangledLanes | // Is this lane transitively entangled with the newly entangled lanes? entanglements[index] & entangledLanes) { entanglements[index] |= entangledLanes; } lanes &= ~lane; } } function getBumpedLaneForHydration(root, renderLanes) { var renderLane = getHighestPriorityLane(renderLanes); var lane; switch (renderLane) { case InputContinuousLane: lane = InputContinuousHydrationLane; break; case DefaultLane: lane = DefaultHydrationLane; break; case TransitionLane1: case TransitionLane2: case TransitionLane3: case TransitionLane4: case TransitionLane5: case TransitionLane6: case TransitionLane7: case TransitionLane8: case TransitionLane9: case TransitionLane10: case TransitionLane11: case TransitionLane12: case TransitionLane13: case TransitionLane14: case TransitionLane15: case TransitionLane16: case RetryLane1: case RetryLane2: case RetryLane3: case RetryLane4: case RetryLane5: lane = TransitionHydrationLane; break; case IdleLane: lane = IdleHydrationLane; break; default: // Everything else is already either a hydration lane, or shouldn't // be retried at a hydration lane. lane = NoLane; break; } // Check if the lane we chose is suspended. If so, that indicates that we // already attempted and failed to hydrate at that level. Also check if we're // already rendering that lane, which is rare but could happen. if ((lane & (root.suspendedLanes | renderLanes)) !== NoLane) { // Give up trying to hydrate and fall back to client render. return NoLane; } return lane; } function addFiberToLanesMap(root, fiber, lanes) { if (!isDevToolsPresent) { return; } var pendingUpdatersLaneMap = root.pendingUpdatersLaneMap; while (lanes > 0) { var index = laneToIndex(lanes); var lane = 1 << index; var updaters = pendingUpdatersLaneMap[index]; updaters.add(fiber); lanes &= ~lane; } } function movePendingFibersToMemoized(root, lanes) { if (!isDevToolsPresent) { return; } var pendingUpdatersLaneMap = root.pendingUpdatersLaneMap; var memoizedUpdaters = root.memoizedUpdaters; while (lanes > 0) { var index = laneToIndex(lanes); var lane = 1 << index; var updaters = pendingUpdatersLaneMap[index]; if (updaters.size > 0) { updaters.forEach(function (fiber) { var alternate = fiber.alternate; if (alternate === null || !memoizedUpdaters.has(alternate)) { memoizedUpdaters.add(fiber); } }); updaters.clear(); } lanes &= ~lane; } } function getTransitionsForLanes(root, lanes) { { return null; } } var DiscreteEventPriority = SyncLane; var ContinuousEventPriority = InputContinuousLane; var DefaultEventPriority = DefaultLane; var IdleEventPriority = IdleLane; var currentUpdatePriority = NoLane; function getCurrentUpdatePriority() { return currentUpdatePriority; } function setCurrentUpdatePriority(newPriority) { currentUpdatePriority = newPriority; } function runWithPriority(priority, fn) { var previousPriority = currentUpdatePriority; try { currentUpdatePriority = priority; return fn(); } finally { currentUpdatePriority = previousPriority; } } function higherEventPriority(a, b) { return a !== 0 && a < b ? a : b; } function lowerEventPriority(a, b) { return a === 0 || a > b ? a : b; } function isHigherEventPriority(a, b) { return a !== 0 && a < b; } function lanesToEventPriority(lanes) { var lane = getHighestPriorityLane(lanes); if (!isHigherEventPriority(DiscreteEventPriority, lane)) { return DiscreteEventPriority; } if (!isHigherEventPriority(ContinuousEventPriority, lane)) { return ContinuousEventPriority; } if (includesNonIdleWork(lane)) { return DefaultEventPriority; } return IdleEventPriority; } // This is imported by the event replaying implementation in React DOM. It's // in a separate file to break a circular dependency between the renderer and // the reconciler. function isRootDehydrated(root) { var currentState = root.current.memoizedState; return currentState.isDehydrated; } var _attemptSynchronousHydration; function setAttemptSynchronousHydration(fn) { _attemptSynchronousHydration = fn; } function attemptSynchronousHydration(fiber) { _attemptSynchronousHydration(fiber); } var attemptContinuousHydration; function setAttemptContinuousHydration(fn) { attemptContinuousHydration = fn; } var attemptHydrationAtCurrentPriority; function setAttemptHydrationAtCurrentPriority(fn) { attemptHydrationAtCurrentPriority = fn; } var getCurrentUpdatePriority$1; function setGetCurrentUpdatePriority(fn) { getCurrentUpdatePriority$1 = fn; } var attemptHydrationAtPriority; function setAttemptHydrationAtPriority(fn) { attemptHydrationAtPriority = fn; } // TODO: Upgrade this definition once we're on a newer version of Flow that // has this definition built-in. var hasScheduledReplayAttempt = false; // The queue of discrete events to be replayed. var queuedDiscreteEvents = []; // Indicates if any continuous event targets are non-null for early bailout. // if the last target was dehydrated. var queuedFocus = null; var queuedDrag = null; var queuedMouse = null; // For pointer events there can be one latest event per pointerId. var queuedPointers = new Map(); var queuedPointerCaptures = new Map(); // We could consider replaying selectionchange and touchmoves too. var queuedExplicitHydrationTargets = []; var discreteReplayableEvents = ['mousedown', 'mouseup', 'touchcancel', 'touchend', 'touchstart', 'auxclick', 'dblclick', 'pointercancel', 'pointerdown', 'pointerup', 'dragend', 'dragstart', 'drop', 'compositionend', 'compositionstart', 'keydown', 'keypress', 'keyup', 'input', 'textInput', // Intentionally camelCase 'copy', 'cut', 'paste', 'click', 'change', 'contextmenu', 'reset', 'submit']; function isDiscreteEventThatRequiresHydration(eventType) { return discreteReplayableEvents.indexOf(eventType) > -1; } function createQueuedReplayableEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent) { return { blockedOn: blockedOn, domEventName: domEventName, eventSystemFlags: eventSystemFlags, nativeEvent: nativeEvent, targetContainers: [targetContainer] }; } function clearIfContinuousEvent(domEventName, nativeEvent) { switch (domEventName) { case 'focusin': case 'focusout': queuedFocus = null; break; case 'dragenter': case 'dragleave': queuedDrag = null; break; case 'mouseover': case 'mouseout': queuedMouse = null; break; case 'pointerover': case 'pointerout': { var pointerId = nativeEvent.pointerId; queuedPointers.delete(pointerId); break; } case 'gotpointercapture': case 'lostpointercapture': { var _pointerId = nativeEvent.pointerId; queuedPointerCaptures.delete(_pointerId); break; } } } function accumulateOrCreateContinuousQueuedReplayableEvent(existingQueuedEvent, blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent) { if (existingQueuedEvent === null || existingQueuedEvent.nativeEvent !== nativeEvent) { var queuedEvent = createQueuedReplayableEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent); if (blockedOn !== null) { var _fiber2 = getInstanceFromNode(blockedOn); if (_fiber2 !== null) { // Attempt to increase the priority of this target. attemptContinuousHydration(_fiber2); } } return queuedEvent; } // If we have already queued this exact event, then it's because // the different event systems have different DOM event listeners. // We can accumulate the flags, and the targetContainers, and // store a single event to be replayed. existingQueuedEvent.eventSystemFlags |= eventSystemFlags; var targetContainers = existingQueuedEvent.targetContainers; if (targetContainer !== null && targetContainers.indexOf(targetContainer) === -1) { targetContainers.push(targetContainer); } return existingQueuedEvent; } function queueIfContinuousEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent) { // These set relatedTarget to null because the replayed event will be treated as if we // moved from outside the window (no target) onto the target once it hydrates. // Instead of mutating we could clone the event. switch (domEventName) { case 'focusin': { var focusEvent = nativeEvent; queuedFocus = accumulateOrCreateContinuousQueuedReplayableEvent(queuedFocus, blockedOn, domEventName, eventSystemFlags, targetContainer, focusEvent); return true; } case 'dragenter': { var dragEvent = nativeEvent; queuedDrag = accumulateOrCreateContinuousQueuedReplayableEvent(queuedDrag, blockedOn, domEventName, eventSystemFlags, targetContainer, dragEvent); return true; } case 'mouseover': { var mouseEvent = nativeEvent; queuedMouse = accumulateOrCreateContinuousQueuedReplayableEvent(queuedMouse, blockedOn, domEventName, eventSystemFlags, targetContainer, mouseEvent); return true; } case 'pointerover': { var pointerEvent = nativeEvent; var pointerId = pointerEvent.pointerId; queuedPointers.set(pointerId, accumulateOrCreateContinuousQueuedReplayableEvent(queuedPointers.get(pointerId) || null, blockedOn, domEventName, eventSystemFlags, targetContainer, pointerEvent)); return true; } case 'gotpointercapture': { var _pointerEvent = nativeEvent; var _pointerId2 = _pointerEvent.pointerId; queuedPointerCaptures.set(_pointerId2, accumulateOrCreateContinuousQueuedReplayableEvent(queuedPointerCaptures.get(_pointerId2) || null, blockedOn, domEventName, eventSystemFlags, targetContainer, _pointerEvent)); return true; } } return false; } // Check if this target is unblocked. Returns true if it's unblocked. function attemptExplicitHydrationTarget(queuedTarget) { // TODO: This function shares a lot of logic with findInstanceBlockingEvent. // Try to unify them. It's a bit tricky since it would require two return // values. var targetInst = getClosestInstanceFromNode(queuedTarget.target); if (targetInst !== null) { var nearestMounted = getNearestMountedFiber(targetInst); if (nearestMounted !== null) { var tag = nearestMounted.tag; if (tag === SuspenseComponent) { var instance = getSuspenseInstanceFromFiber(nearestMounted); if (instance !== null) { // We're blocked on hydrating this boundary. // Increase its priority. queuedTarget.blockedOn = instance; attemptHydrationAtPriority(queuedTarget.priority, function () { attemptHydrationAtCurrentPriority(nearestMounted); }); return; } } else if (tag === HostRoot) { var root = nearestMounted.stateNode; if (isRootDehydrated(root)) { queuedTarget.blockedOn = getContainerFromFiber(nearestMounted); // We don't currently have a way to increase the priority of // a root other than sync. return; } } } } queuedTarget.blockedOn = null; } function queueExplicitHydrationTarget(target) { // TODO: This will read the priority if it's dispatched by the React // event system but not native events. Should read window.event.type, like // we do for updates (getCurrentEventPriority). var updatePriority = getCurrentUpdatePriority$1(); var queuedTarget = { blockedOn: null, target: target, priority: updatePriority }; var i = 0; for (; i < queuedExplicitHydrationTargets.length; i++) { // Stop once we hit the first target with lower priority than if (!isHigherEventPriority(updatePriority, queuedExplicitHydrationTargets[i].priority)) { break; } } queuedExplicitHydrationTargets.splice(i, 0, queuedTarget); if (i === 0) { attemptExplicitHydrationTarget(queuedTarget); } } function attemptReplayContinuousQueuedEvent(queuedEvent) { if (queuedEvent.blockedOn !== null) { return false; } var targetContainers = queuedEvent.targetContainers; while (targetContainers.length > 0) { var targetContainer = targetContainers[0]; var nextBlockedOn = findInstanceBlockingEvent(queuedEvent.domEventName, queuedEvent.eventSystemFlags, targetContainer, queuedEvent.nativeEvent); if (nextBlockedOn === null) { { var nativeEvent = queuedEvent.nativeEvent; var nativeEventClone = new nativeEvent.constructor(nativeEvent.type, nativeEvent); setReplayingEvent(nativeEventClone); nativeEvent.target.dispatchEvent(nativeEventClone); resetReplayingEvent(); } } else { // We're still blocked. Try again later. var _fiber3 = getInstanceFromNode(nextBlockedOn); if (_fiber3 !== null) { attemptContinuousHydration(_fiber3); } queuedEvent.blockedOn = nextBlockedOn; return false; } // This target container was successfully dispatched. Try the next. targetContainers.shift(); } return true; } function attemptReplayContinuousQueuedEventInMap(queuedEvent, key, map) { if (attemptReplayContinuousQueuedEvent(queuedEvent)) { map.delete(key); } } function replayUnblockedEvents() { hasScheduledReplayAttempt = false; if (queuedFocus !== null && attemptReplayContinuousQueuedEvent(queuedFocus)) { queuedFocus = null; } if (queuedDrag !== null && attemptReplayContinuousQueuedEvent(queuedDrag)) { queuedDrag = null; } if (queuedMouse !== null && attemptReplayContinuousQueuedEvent(queuedMouse)) { queuedMouse = null; } queuedPointers.forEach(attemptReplayContinuousQueuedEventInMap); queuedPointerCaptures.forEach(attemptReplayContinuousQueuedEventInMap); } function scheduleCallbackIfUnblocked(queuedEvent, unblocked) { if (queuedEvent.blockedOn === unblocked) { queuedEvent.blockedOn = null; if (!hasScheduledReplayAttempt) { hasScheduledReplayAttempt = true; // Schedule a callback to attempt replaying as many events as are // now unblocked. This first might not actually be unblocked yet. // We could check it early to avoid scheduling an unnecessary callback. Scheduler.unstable_scheduleCallback(Scheduler.unstable_NormalPriority, replayUnblockedEvents); } } } function retryIfBlockedOn(unblocked) { // Mark anything that was blocked on this as no longer blocked // and eligible for a replay. if (queuedDiscreteEvents.length > 0) { scheduleCallbackIfUnblocked(queuedDiscreteEvents[0], unblocked); // This is a exponential search for each boundary that commits. I think it's // worth it because we expect very few discrete events to queue up and once // we are actually fully unblocked it will be fast to replay them. for (var i = 1; i < queuedDiscreteEvents.length; i++) { var queuedEvent = queuedDiscreteEvents[i]; if (queuedEvent.blockedOn === unblocked) { queuedEvent.blockedOn = null; } } } if (queuedFocus !== null) { scheduleCallbackIfUnblocked(queuedFocus, unblocked); } if (queuedDrag !== null) { scheduleCallbackIfUnblocked(queuedDrag, unblocked); } if (queuedMouse !== null) { scheduleCallbackIfUnblocked(queuedMouse, unblocked); } var unblock = function (queuedEvent) { return scheduleCallbackIfUnblocked(queuedEvent, unblocked); }; queuedPointers.forEach(unblock); queuedPointerCaptures.forEach(unblock); for (var _i = 0; _i < queuedExplicitHydrationTargets.length; _i++) { var queuedTarget = queuedExplicitHydrationTargets[_i]; if (queuedTarget.blockedOn === unblocked) { queuedTarget.blockedOn = null; } } while (queuedExplicitHydrationTargets.length > 0) { var nextExplicitTarget = queuedExplicitHydrationTargets[0]; if (nextExplicitTarget.blockedOn !== null) { // We're still blocked. break; } else { attemptExplicitHydrationTarget(nextExplicitTarget); if (nextExplicitTarget.blockedOn === null) { // We're unblocked. queuedExplicitHydrationTargets.shift(); } } } } var ReactCurrentBatchConfig = ReactSharedInternals.ReactCurrentBatchConfig; // TODO: can we stop exporting these? var _enabled = true; // This is exported in FB builds for use by legacy FB layer infra. // We'd like to remove this but it's not clear if this is safe. function setEnabled(enabled) { _enabled = !!enabled; } function isEnabled() { return _enabled; } function createEventListenerWrapperWithPriority(targetContainer, domEventName, eventSystemFlags) { var eventPriority = getEventPriority(domEventName); var listenerWrapper; switch (eventPriority) { case DiscreteEventPriority: listenerWrapper = dispatchDiscreteEvent; break; case ContinuousEventPriority: listenerWrapper = dispatchContinuousEvent; break; case DefaultEventPriority: default: listenerWrapper = dispatchEvent; break; } return listenerWrapper.bind(null, domEventName, eventSystemFlags, targetContainer); } function dispatchDiscreteEvent(domEventName, eventSystemFlags, container, nativeEvent) { var previousPriority = getCurrentUpdatePriority(); var prevTransition = ReactCurrentBatchConfig.transition; ReactCurrentBatchConfig.transition = null; try { setCurrentUpdatePriority(DiscreteEventPriority); dispatchEvent(domEventName, eventSystemFlags, container, nativeEvent); } finally { setCurrentUpdatePriority(previousPriority); ReactCurrentBatchConfig.transition = prevTransition; } } function dispatchContinuousEvent(domEventName, eventSystemFlags, container, nativeEvent) { var previousPriority = getCurrentUpdatePriority(); var prevTransition = ReactCurrentBatchConfig.transition; ReactCurrentBatchConfig.transition = null; try { setCurrentUpdatePriority(ContinuousEventPriority); dispatchEvent(domEventName, eventSystemFlags, container, nativeEvent); } finally { setCurrentUpdatePriority(previousPriority); ReactCurrentBatchConfig.transition = prevTransition; } } function dispatchEvent(domEventName, eventSystemFlags, targetContainer, nativeEvent) { if (!_enabled) { return; } { dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay(domEventName, eventSystemFlags, targetContainer, nativeEvent); } } function dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay(domEventName, eventSystemFlags, targetContainer, nativeEvent) { var blockedOn = findInstanceBlockingEvent(domEventName, eventSystemFlags, targetContainer, nativeEvent); if (blockedOn === null) { dispatchEventForPluginEventSystem(domEventName, eventSystemFlags, nativeEvent, return_targetInst, targetContainer); clearIfContinuousEvent(domEventName, nativeEvent); return; } if (queueIfContinuousEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent)) { nativeEvent.stopPropagation(); return; } // We need to clear only if we didn't queue because // queueing is accumulative. clearIfContinuousEvent(domEventName, nativeEvent); if (eventSystemFlags & IS_CAPTURE_PHASE && isDiscreteEventThatRequiresHydration(domEventName)) { while (blockedOn !== null) { var fiber = getInstanceFromNode(blockedOn); if (fiber !== null) { attemptSynchronousHydration(fiber); } var nextBlockedOn = findInstanceBlockingEvent(domEventName, eventSystemFlags, targetContainer, nativeEvent); if (nextBlockedOn === null) { dispatchEventForPluginEventSystem(domEventName, eventSystemFlags, nativeEvent, return_targetInst, targetContainer); } if (nextBlockedOn === blockedOn) { break; } blockedOn = nextBlockedOn; } if (blockedOn !== null) { nativeEvent.stopPropagation(); } return; } // This is not replayable so we'll invoke it but without a target, // in case the event system needs to trace it. dispatchEventForPluginEventSystem(domEventName, eventSystemFlags, nativeEvent, null, targetContainer); } var return_targetInst = null; // Returns a SuspenseInstance or Container if it's blocked. // The return_targetInst field above is conceptually part of the return value. function findInstanceBlockingEvent(domEventName, eventSystemFlags, targetContainer, nativeEvent) { // TODO: Warn if _enabled is false. return_targetInst = null; var nativeEventTarget = getEventTarget(nativeEvent); var targetInst = getClosestInstanceFromNode(nativeEventTarget); if (targetInst !== null) { var nearestMounted = getNearestMountedFiber(targetInst); if (nearestMounted === null) { // This tree has been unmounted already. Dispatch without a target. targetInst = null; } else { var tag = nearestMounted.tag; if (tag === SuspenseComponent) { var instance = getSuspenseInstanceFromFiber(nearestMounted); if (instance !== null) { // Queue the event to be replayed later. Abort dispatching since we // don't want this event dispatched twice through the event system. // TODO: If this is the first discrete event in the queue. Schedule an increased // priority for this boundary. return instance; } // This shouldn't happen, something went wrong but to avoid blocking // the whole system, dispatch the event without a target. // TODO: Warn. targetInst = null; } else if (tag === HostRoot) { var root = nearestMounted.stateNode; if (isRootDehydrated(root)) { // If this happens during a replay something went wrong and it might block // the whole system. return getContainerFromFiber(nearestMounted); } targetInst = null; } else if (nearestMounted !== targetInst) { // If we get an event (ex: img onload) before committing that // component's mount, ignore it for now (that is, treat it as if it was an // event on a non-React tree). We might also consider queueing events and // dispatching them after the mount. targetInst = null; } } } return_targetInst = targetInst; // We're not blocked on anything. return null; } function getEventPriority(domEventName) { switch (domEventName) { // Used by SimpleEventPlugin: case 'cancel': case 'click': case 'close': case 'contextmenu': case 'copy': case 'cut': case 'auxclick': case 'dblclick': case 'dragend': case 'dragstart': case 'drop': case 'focusin': case 'focusout': case 'input': case 'invalid': case 'keydown': case 'keypress': case 'keyup': case 'mousedown': case 'mouseup': case 'paste': case 'pause': case 'play': case 'pointercancel': case 'pointerdown': case 'pointerup': case 'ratechange': case 'reset': case 'resize': case 'seeked': case 'submit': case 'touchcancel': case 'touchend': case 'touchstart': case 'volumechange': // Used by polyfills: // eslint-disable-next-line no-fallthrough case 'change': case 'selectionchange': case 'textInput': case 'compositionstart': case 'compositionend': case 'compositionupdate': // Only enableCreateEventHandleAPI: // eslint-disable-next-line no-fallthrough case 'beforeblur': case 'afterblur': // Not used by React but could be by user code: // eslint-disable-next-line no-fallthrough case 'beforeinput': case 'blur': case 'fullscreenchange': case 'focus': case 'hashchange': case 'popstate': case 'select': case 'selectstart': return DiscreteEventPriority; case 'drag': case 'dragenter': case 'dragexit': case 'dragleave': case 'dragover': case 'mousemove': case 'mouseout': case 'mouseover': case 'pointermove': case 'pointerout': case 'pointerover': case 'scroll': case 'toggle': case 'touchmove': case 'wheel': // Not used by React but could be by user code: // eslint-disable-next-line no-fallthrough case 'mouseenter': case 'mouseleave': case 'pointerenter': case 'pointerleave': return ContinuousEventPriority; case 'message': { // We might be in the Scheduler callback. // Eventually this mechanism will be replaced by a check // of the current priority on the native scheduler. var schedulerPriority = getCurrentPriorityLevel(); switch (schedulerPriority) { case ImmediatePriority: return DiscreteEventPriority; case UserBlockingPriority: return ContinuousEventPriority; case NormalPriority: case LowPriority: // TODO: Handle LowSchedulerPriority, somehow. Maybe the same lane as hydration. return DefaultEventPriority; case IdlePriority: return IdleEventPriority; default: return DefaultEventPriority; } } default: return DefaultEventPriority; } } function addEventBubbleListener(target, eventType, listener) { target.addEventListener(eventType, listener, false); return listener; } function addEventCaptureListener(target, eventType, listener) { target.addEventListener(eventType, listener, true); return listener; } function addEventCaptureListenerWithPassiveFlag(target, eventType, listener, passive) { target.addEventListener(eventType, listener, { capture: true, passive: passive }); return listener; } function addEventBubbleListenerWithPassiveFlag(target, eventType, listener, passive) { target.addEventListener(eventType, listener, { passive: passive }); return listener; } /** * These variables store information about text content of a target node, * allowing comparison of content before and after a given event. * * Identify the node where selection currently begins, then observe * both its text content and its current position in the DOM. Since the * browser may natively replace the target node during composition, we can * use its position to find its replacement. * * */ var root = null; var startText = null; var fallbackText = null; function initialize(nativeEventTarget) { root = nativeEventTarget; startText = getText(); return true; } function reset() { root = null; startText = null; fallbackText = null; } function getData() { if (fallbackText) { return fallbackText; } var start; var startValue = startText; var startLength = startValue.length; var end; var endValue = getText(); var endLength = endValue.length; for (start = 0; start < startLength; start++) { if (startValue[start] !== endValue[start]) { break; } } var minEnd = startLength - start; for (end = 1; end <= minEnd; end++) { if (startValue[startLength - end] !== endValue[endLength - end]) { break; } } var sliceTail = end > 1 ? 1 - end : undefined; fallbackText = endValue.slice(start, sliceTail); return fallbackText; } function getText() { if ('value' in root) { return root.value; } return root.textContent; } /** * `charCode` represents the actual "character code" and is safe to use with * `String.fromCharCode`. As such, only keys that correspond to printable * characters produce a valid `charCode`, the only exception to this is Enter. * The Tab-key is considered non-printable and does not have a `charCode`, * presumably because it does not produce a tab-character in browsers. * * @param {object} nativeEvent Native browser event. * @return {number} Normalized `charCode` property. */ function getEventCharCode(nativeEvent) { var charCode; var keyCode = nativeEvent.keyCode; if ('charCode' in nativeEvent) { charCode = nativeEvent.charCode; // FF does not set `charCode` for the Enter-key, check against `keyCode`. if (charCode === 0 && keyCode === 13) { charCode = 13; } } else { // IE8 does not implement `charCode`, but `keyCode` has the correct value. charCode = keyCode; } // IE and Edge (on Windows) and Chrome / Safari (on Windows and Linux) // report Enter as charCode 10 when ctrl is pressed. if (charCode === 10) { charCode = 13; } // Some non-printable keys are reported in `charCode`/`keyCode`, discard them. // Must not discard the (non-)printable Enter-key. if (charCode >= 32 || charCode === 13) { return charCode; } return 0; } function functionThatReturnsTrue() { return true; } function functionThatReturnsFalse() { return false; } // This is intentionally a factory so that we have different returned constructors. // If we had a single constructor, it would be megamorphic and engines would deopt. function createSyntheticEvent(Interface) { /** * Synthetic events are dispatched by event plugins, typically in response to a * top-level event delegation handler. * * These systems should generally use pooling to reduce the frequency of garbage * collection. The system should check `isPersistent` to determine whether the * event should be released into the pool after being dispatched. Users that * need a persisted event should invoke `persist`. * * Synthetic events (and subclasses) implement the DOM Level 3 Events API by * normalizing browser quirks. Subclasses do not necessarily have to implement a * DOM interface; custom application-specific events can also subclass this. */ function SyntheticBaseEvent(reactName, reactEventType, targetInst, nativeEvent, nativeEventTarget) { this._reactName = reactName; this._targetInst = targetInst; this.type = reactEventType; this.nativeEvent = nativeEvent; this.target = nativeEventTarget; this.currentTarget = null; for (var _propName in Interface) { if (!Interface.hasOwnProperty(_propName)) { continue; } var normalize = Interface[_propName]; if (normalize) { this[_propName] = normalize(nativeEvent); } else { this[_propName] = nativeEvent[_propName]; } } var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false; if (defaultPrevented) { this.isDefaultPrevented = functionThatReturnsTrue; } else { this.isDefaultPrevented = functionThatReturnsFalse; } this.isPropagationStopped = functionThatReturnsFalse; return this; } assign(SyntheticBaseEvent.prototype, { preventDefault: function () { this.defaultPrevented = true; var event = this.nativeEvent; if (!event) { return; } if (event.preventDefault) { event.preventDefault(); // $FlowFixMe - flow is not aware of `unknown` in IE } else if (typeof event.returnValue !== 'unknown') { event.returnValue = false; } this.isDefaultPrevented = functionThatReturnsTrue; }, stopPropagation: function () { var event = this.nativeEvent; if (!event) { return; } if (event.stopPropagation) { event.stopPropagation(); // $FlowFixMe - flow is not aware of `unknown` in IE } else if (typeof event.cancelBubble !== 'unknown') { // The ChangeEventPlugin registers a "propertychange" event for // IE. This event does not support bubbling or cancelling, and // any references to cancelBubble throw "Member not found". A // typeof check of "unknown" circumvents this issue (and is also // IE specific). event.cancelBubble = true; } this.isPropagationStopped = functionThatReturnsTrue; }, /** * We release all dispatched `SyntheticEvent`s after each event loop, adding * them back into the pool. This allows a way to hold onto a reference that * won't be added back into the pool. */ persist: function () {// Modern event system doesn't use pooling. }, /** * Checks if this event should be released back into the pool. * * @return {boolean} True if this should not be released, false otherwise. */ isPersistent: functionThatReturnsTrue }); return SyntheticBaseEvent; } /** * @interface Event * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var EventInterface = { eventPhase: 0, bubbles: 0, cancelable: 0, timeStamp: function (event) { return event.timeStamp || Date.now(); }, defaultPrevented: 0, isTrusted: 0 }; var SyntheticEvent = createSyntheticEvent(EventInterface); var UIEventInterface = assign({}, EventInterface, { view: 0, detail: 0 }); var SyntheticUIEvent = createSyntheticEvent(UIEventInterface); var lastMovementX; var lastMovementY; var lastMouseEvent; function updateMouseMovementPolyfillState(event) { if (event !== lastMouseEvent) { if (lastMouseEvent && event.type === 'mousemove') { lastMovementX = event.screenX - lastMouseEvent.screenX; lastMovementY = event.screenY - lastMouseEvent.screenY; } else { lastMovementX = 0; lastMovementY = 0; } lastMouseEvent = event; } } /** * @interface MouseEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var MouseEventInterface = assign({}, UIEventInterface, { screenX: 0, screenY: 0, clientX: 0, clientY: 0, pageX: 0, pageY: 0, ctrlKey: 0, shiftKey: 0, altKey: 0, metaKey: 0, getModifierState: getEventModifierState, button: 0, buttons: 0, relatedTarget: function (event) { if (event.relatedTarget === undefined) return event.fromElement === event.srcElement ? event.toElement : event.fromElement; return event.relatedTarget; }, movementX: function (event) { if ('movementX' in event) { return event.movementX; } updateMouseMovementPolyfillState(event); return lastMovementX; }, movementY: function (event) { if ('movementY' in event) { return event.movementY; } // Don't need to call updateMouseMovementPolyfillState() here // because it's guaranteed to have already run when movementX // was copied. return lastMovementY; } }); var SyntheticMouseEvent = createSyntheticEvent(MouseEventInterface); /** * @interface DragEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var DragEventInterface = assign({}, MouseEventInterface, { dataTransfer: 0 }); var SyntheticDragEvent = createSyntheticEvent(DragEventInterface); /** * @interface FocusEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var FocusEventInterface = assign({}, UIEventInterface, { relatedTarget: 0 }); var SyntheticFocusEvent = createSyntheticEvent(FocusEventInterface); /** * @interface Event * @see http://www.w3.org/TR/css3-animations/#AnimationEvent-interface * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent */ var AnimationEventInterface = assign({}, EventInterface, { animationName: 0, elapsedTime: 0, pseudoElement: 0 }); var SyntheticAnimationEvent = createSyntheticEvent(AnimationEventInterface); /** * @interface Event * @see http://www.w3.org/TR/clipboard-apis/ */ var ClipboardEventInterface = assign({}, EventInterface, { clipboardData: function (event) { return 'clipboardData' in event ? event.clipboardData : window.clipboardData; } }); var SyntheticClipboardEvent = createSyntheticEvent(ClipboardEventInterface); /** * @interface Event * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents */ var CompositionEventInterface = assign({}, EventInterface, { data: 0 }); var SyntheticCompositionEvent = createSyntheticEvent(CompositionEventInterface); /** * @interface Event * @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105 * /#events-inputevents */ // Happens to share the same list for now. var SyntheticInputEvent = SyntheticCompositionEvent; /** * Normalization of deprecated HTML5 `key` values * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names */ var normalizeKey = { Esc: 'Escape', Spacebar: ' ', Left: 'ArrowLeft', Up: 'ArrowUp', Right: 'ArrowRight', Down: 'ArrowDown', Del: 'Delete', Win: 'OS', Menu: 'ContextMenu', Apps: 'ContextMenu', Scroll: 'ScrollLock', MozPrintableKey: 'Unidentified' }; /** * Translation from legacy `keyCode` to HTML5 `key` * Only special keys supported, all others depend on keyboard layout or browser * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names */ var translateToKey = { '8': 'Backspace', '9': 'Tab', '12': 'Clear', '13': 'Enter', '16': 'Shift', '17': 'Control', '18': 'Alt', '19': 'Pause', '20': 'CapsLock', '27': 'Escape', '32': ' ', '33': 'PageUp', '34': 'PageDown', '35': 'End', '36': 'Home', '37': 'ArrowLeft', '38': 'ArrowUp', '39': 'ArrowRight', '40': 'ArrowDown', '45': 'Insert', '46': 'Delete', '112': 'F1', '113': 'F2', '114': 'F3', '115': 'F4', '116': 'F5', '117': 'F6', '118': 'F7', '119': 'F8', '120': 'F9', '121': 'F10', '122': 'F11', '123': 'F12', '144': 'NumLock', '145': 'ScrollLock', '224': 'Meta' }; /** * @param {object} nativeEvent Native browser event. * @return {string} Normalized `key` property. */ function getEventKey(nativeEvent) { if (nativeEvent.key) { // Normalize inconsistent values reported by browsers due to // implementations of a working draft specification. // FireFox implements `key` but returns `MozPrintableKey` for all // printable characters (normalized to `Unidentified`), ignore it. var key = normalizeKey[nativeEvent.key] || nativeEvent.key; if (key !== 'Unidentified') { return key; } } // Browser does not implement `key`, polyfill as much of it as we can. if (nativeEvent.type === 'keypress') { var charCode = getEventCharCode(nativeEvent); // The enter-key is technically both printable and non-printable and can // thus be captured by `keypress`, no other non-printable key should. return charCode === 13 ? 'Enter' : String.fromCharCode(charCode); } if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') { // While user keyboard layout determines the actual meaning of each // `keyCode` value, almost all function keys have a universal value. return translateToKey[nativeEvent.keyCode] || 'Unidentified'; } return ''; } /** * Translation from modifier key to the associated property in the event. * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers */ var modifierKeyToProp = { Alt: 'altKey', Control: 'ctrlKey', Meta: 'metaKey', Shift: 'shiftKey' }; // Older browsers (Safari <= 10, iOS Safari <= 10.2) do not support // getModifierState. If getModifierState is not supported, we map it to a set of // modifier keys exposed by the event. In this case, Lock-keys are not supported. function modifierStateGetter(keyArg) { var syntheticEvent = this; var nativeEvent = syntheticEvent.nativeEvent; if (nativeEvent.getModifierState) { return nativeEvent.getModifierState(keyArg); } var keyProp = modifierKeyToProp[keyArg]; return keyProp ? !!nativeEvent[keyProp] : false; } function getEventModifierState(nativeEvent) { return modifierStateGetter; } /** * @interface KeyboardEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var KeyboardEventInterface = assign({}, UIEventInterface, { key: getEventKey, code: 0, location: 0, ctrlKey: 0, shiftKey: 0, altKey: 0, metaKey: 0, repeat: 0, locale: 0, getModifierState: getEventModifierState, // Legacy Interface charCode: function (event) { // `charCode` is the result of a KeyPress event and represents the value of // the actual printable character. // KeyPress is deprecated, but its replacement is not yet final and not // implemented in any major browser. Only KeyPress has charCode. if (event.type === 'keypress') { return getEventCharCode(event); } return 0; }, keyCode: function (event) { // `keyCode` is the result of a KeyDown/Up event and represents the value of // physical keyboard key. // The actual meaning of the value depends on the users' keyboard layout // which cannot be detected. Assuming that it is a US keyboard layout // provides a surprisingly accurate mapping for US and European users. // Due to this, it is left to the user to implement at this time. if (event.type === 'keydown' || event.type === 'keyup') { return event.keyCode; } return 0; }, which: function (event) { // `which` is an alias for either `keyCode` or `charCode` depending on the // type of the event. if (event.type === 'keypress') { return getEventCharCode(event); } if (event.type === 'keydown' || event.type === 'keyup') { return event.keyCode; } return 0; } }); var SyntheticKeyboardEvent = createSyntheticEvent(KeyboardEventInterface); /** * @interface PointerEvent * @see http://www.w3.org/TR/pointerevents/ */ var PointerEventInterface = assign({}, MouseEventInterface, { pointerId: 0, width: 0, height: 0, pressure: 0, tangentialPressure: 0, tiltX: 0, tiltY: 0, twist: 0, pointerType: 0, isPrimary: 0 }); var SyntheticPointerEvent = createSyntheticEvent(PointerEventInterface); /** * @interface TouchEvent * @see http://www.w3.org/TR/touch-events/ */ var TouchEventInterface = assign({}, UIEventInterface, { touches: 0, targetTouches: 0, changedTouches: 0, altKey: 0, metaKey: 0, ctrlKey: 0, shiftKey: 0, getModifierState: getEventModifierState }); var SyntheticTouchEvent = createSyntheticEvent(TouchEventInterface); /** * @interface Event * @see http://www.w3.org/TR/2009/WD-css3-transitions-20090320/#transition-events- * @see https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent */ var TransitionEventInterface = assign({}, EventInterface, { propertyName: 0, elapsedTime: 0, pseudoElement: 0 }); var SyntheticTransitionEvent = createSyntheticEvent(TransitionEventInterface); /** * @interface WheelEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var WheelEventInterface = assign({}, MouseEventInterface, { deltaX: function (event) { return 'deltaX' in event ? event.deltaX : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive). 'wheelDeltaX' in event ? -event.wheelDeltaX : 0; }, deltaY: function (event) { return 'deltaY' in event ? event.deltaY : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive). 'wheelDeltaY' in event ? -event.wheelDeltaY : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive). 'wheelDelta' in event ? -event.wheelDelta : 0; }, deltaZ: 0, // Browsers without "deltaMode" is reporting in raw wheel delta where one // notch on the scroll is always +/- 120, roughly equivalent to pixels. // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size. deltaMode: 0 }); var SyntheticWheelEvent = createSyntheticEvent(WheelEventInterface); var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space var START_KEYCODE = 229; var canUseCompositionEvent = canUseDOM && 'CompositionEvent' in window; var documentMode = null; if (canUseDOM && 'documentMode' in document) { documentMode = document.documentMode; } // Webkit offers a very useful `textInput` event that can be used to // directly represent `beforeInput`. The IE `textinput` event is not as // useful, so we don't use it. var canUseTextInputEvent = canUseDOM && 'TextEvent' in window && !documentMode; // In IE9+, we have access to composition events, but the data supplied // by the native compositionend event may be incorrect. Japanese ideographic // spaces, for instance (\u3000) are not recorded correctly. var useFallbackCompositionData = canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11); var SPACEBAR_CODE = 32; var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE); function registerEvents() { registerTwoPhaseEvent('onBeforeInput', ['compositionend', 'keypress', 'textInput', 'paste']); registerTwoPhaseEvent('onCompositionEnd', ['compositionend', 'focusout', 'keydown', 'keypress', 'keyup', 'mousedown']); registerTwoPhaseEvent('onCompositionStart', ['compositionstart', 'focusout', 'keydown', 'keypress', 'keyup', 'mousedown']); registerTwoPhaseEvent('onCompositionUpdate', ['compositionupdate', 'focusout', 'keydown', 'keypress', 'keyup', 'mousedown']); } // Track whether we've ever handled a keypress on the space key. var hasSpaceKeypress = false; /** * Return whether a native keypress event is assumed to be a command. * This is required because Firefox fires `keypress` events for key commands * (cut, copy, select-all, etc.) even though no character is inserted. */ function isKeypressCommand(nativeEvent) { return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) && // ctrlKey && altKey is equivalent to AltGr, and is not a command. !(nativeEvent.ctrlKey && nativeEvent.altKey); } /** * Translate native top level events into event types. */ function getCompositionEventType(domEventName) { switch (domEventName) { case 'compositionstart': return 'onCompositionStart'; case 'compositionend': return 'onCompositionEnd'; case 'compositionupdate': return 'onCompositionUpdate'; } } /** * Does our fallback best-guess model think this event signifies that * composition has begun? */ function isFallbackCompositionStart(domEventName, nativeEvent) { return domEventName === 'keydown' && nativeEvent.keyCode === START_KEYCODE; } /** * Does our fallback mode think that this event is the end of composition? */ function isFallbackCompositionEnd(domEventName, nativeEvent) { switch (domEventName) { case 'keyup': // Command keys insert or clear IME input. return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1; case 'keydown': // Expect IME keyCode on each keydown. If we get any other // code we must have exited earlier. return nativeEvent.keyCode !== START_KEYCODE; case 'keypress': case 'mousedown': case 'focusout': // Events are not possible without cancelling IME. return true; default: return false; } } /** * Google Input Tools provides composition data via a CustomEvent, * with the `data` property populated in the `detail` object. If this * is available on the event object, use it. If not, this is a plain * composition event and we have nothing special to extract. * * @param {object} nativeEvent * @return {?string} */ function getDataFromCustomEvent(nativeEvent) { var detail = nativeEvent.detail; if (typeof detail === 'object' && 'data' in detail) { return detail.data; } return null; } /** * Check if a composition event was triggered by Korean IME. * Our fallback mode does not work well with IE's Korean IME, * so just use native composition events when Korean IME is used. * Although CompositionEvent.locale property is deprecated, * it is available in IE, where our fallback mode is enabled. * * @param {object} nativeEvent * @return {boolean} */ function isUsingKoreanIME(nativeEvent) { return nativeEvent.locale === 'ko'; } // Track the current IME composition status, if any. var isComposing = false; /** * @return {?object} A SyntheticCompositionEvent. */ function extractCompositionEvent(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget) { var eventType; var fallbackData; if (canUseCompositionEvent) { eventType = getCompositionEventType(domEventName); } else if (!isComposing) { if (isFallbackCompositionStart(domEventName, nativeEvent)) { eventType = 'onCompositionStart'; } } else if (isFallbackCompositionEnd(domEventName, nativeEvent)) { eventType = 'onCompositionEnd'; } if (!eventType) { return null; } if (useFallbackCompositionData && !isUsingKoreanIME(nativeEvent)) { // The current composition is stored statically and must not be // overwritten while composition continues. if (!isComposing && eventType === 'onCompositionStart') { isComposing = initialize(nativeEventTarget); } else if (eventType === 'onCompositionEnd') { if (isComposing) { fallbackData = getData(); } } } var listeners = accumulateTwoPhaseListeners(targetInst, eventType); if (listeners.length > 0) { var event = new SyntheticCompositionEvent(eventType, domEventName, null, nativeEvent, nativeEventTarget); dispatchQueue.push({ event: event, listeners: listeners }); if (fallbackData) { // Inject data generated from fallback path into the synthetic event. // This matches the property of native CompositionEventInterface. event.data = fallbackData; } else { var customData = getDataFromCustomEvent(nativeEvent); if (customData !== null) { event.data = customData; } } } } function getNativeBeforeInputChars(domEventName, nativeEvent) { switch (domEventName) { case 'compositionend': return getDataFromCustomEvent(nativeEvent); case 'keypress': /** * If native `textInput` events are available, our goal is to make * use of them. However, there is a special case: the spacebar key. * In Webkit, preventing default on a spacebar `textInput` event * cancels character insertion, but it *also* causes the browser * to fall back to its default spacebar behavior of scrolling the * page. * * Tracking at: * https://code.google.com/p/chromium/issues/detail?id=355103 * * To avoid this issue, use the keypress event as if no `textInput` * event is available. */ var which = nativeEvent.which; if (which !== SPACEBAR_CODE) { return null; } hasSpaceKeypress = true; return SPACEBAR_CHAR; case 'textInput': // Record the characters to be added to the DOM. var chars = nativeEvent.data; // If it's a spacebar character, assume that we have already handled // it at the keypress level and bail immediately. Android Chrome // doesn't give us keycodes, so we need to ignore it. if (chars === SPACEBAR_CHAR && hasSpaceKeypress) { return null; } return chars; default: // For other native event types, do nothing. return null; } } /** * For browsers that do not provide the `textInput` event, extract the * appropriate string to use for SyntheticInputEvent. */ function getFallbackBeforeInputChars(domEventName, nativeEvent) { // If we are currently composing (IME) and using a fallback to do so, // try to extract the composed characters from the fallback object. // If composition event is available, we extract a string only at // compositionevent, otherwise extract it at fallback events. if (isComposing) { if (domEventName === 'compositionend' || !canUseCompositionEvent && isFallbackCompositionEnd(domEventName, nativeEvent)) { var chars = getData(); reset(); isComposing = false; return chars; } return null; } switch (domEventName) { case 'paste': // If a paste event occurs after a keypress, throw out the input // chars. Paste events should not lead to BeforeInput events. return null; case 'keypress': /** * As of v27, Firefox may fire keypress events even when no character * will be inserted. A few possibilities: * * - `which` is `0`. Arrow keys, Esc key, etc. * * - `which` is the pressed key code, but no char is available. * Ex: 'AltGr + d` in Polish. There is no modified character for * this key combination and no character is inserted into the * document, but FF fires the keypress for char code `100` anyway. * No `input` event will occur. * * - `which` is the pressed key code, but a command combination is * being used. Ex: `Cmd+C`. No character is inserted, and no * `input` event will occur. */ if (!isKeypressCommand(nativeEvent)) { // IE fires the `keypress` event when a user types an emoji via // Touch keyboard of Windows. In such a case, the `char` property // holds an emoji character like `\uD83D\uDE0A`. Because its length // is 2, the property `which` does not represent an emoji correctly. // In such a case, we directly return the `char` property instead of // using `which`. if (nativeEvent.char && nativeEvent.char.length > 1) { return nativeEvent.char; } else if (nativeEvent.which) { return String.fromCharCode(nativeEvent.which); } } return null; case 'compositionend': return useFallbackCompositionData && !isUsingKoreanIME(nativeEvent) ? null : nativeEvent.data; default: return null; } } /** * Extract a SyntheticInputEvent for `beforeInput`, based on either native * `textInput` or fallback behavior. * * @return {?object} A SyntheticInputEvent. */ function extractBeforeInputEvent(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget) { var chars; if (canUseTextInputEvent) { chars = getNativeBeforeInputChars(domEventName, nativeEvent); } else { chars = getFallbackBeforeInputChars(domEventName, nativeEvent); } // If no characters are being inserted, no BeforeInput event should // be fired. if (!chars) { return null; } var listeners = accumulateTwoPhaseListeners(targetInst, 'onBeforeInput'); if (listeners.length > 0) { var event = new SyntheticInputEvent('onBeforeInput', 'beforeinput', null, nativeEvent, nativeEventTarget); dispatchQueue.push({ event: event, listeners: listeners }); event.data = chars; } } /** * Create an `onBeforeInput` event to match * http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents. * * This event plugin is based on the native `textInput` event * available in Chrome, Safari, Opera, and IE. This event fires after * `onKeyPress` and `onCompositionEnd`, but before `onInput`. * * `beforeInput` is spec'd but not implemented in any browsers, and * the `input` event does not provide any useful information about what has * actually been added, contrary to the spec. Thus, `textInput` is the best * available event to identify the characters that have actually been inserted * into the target node. * * This plugin is also responsible for emitting `composition` events, thus * allowing us to share composition fallback code for both `beforeInput` and * `composition` event types. */ function extractEvents(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) { extractCompositionEvent(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget); extractBeforeInputEvent(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget); } /** * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary */ var supportedInputTypes = { color: true, date: true, datetime: true, 'datetime-local': true, email: true, month: true, number: true, password: true, range: true, search: true, tel: true, text: true, time: true, url: true, week: true }; function isTextInputElement(elem) { var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase(); if (nodeName === 'input') { return !!supportedInputTypes[elem.type]; } if (nodeName === 'textarea') { return true; } return false; } /** * Checks if an event is supported in the current execution environment. * * NOTE: This will not work correctly for non-generic events such as `change`, * `reset`, `load`, `error`, and `select`. * * Borrows from Modernizr. * * @param {string} eventNameSuffix Event name, e.g. "click". * @return {boolean} True if the event is supported. * @internal * @license Modernizr 3.0.0pre (Custom Build) | MIT */ function isEventSupported(eventNameSuffix) { if (!canUseDOM) { return false; } var eventName = 'on' + eventNameSuffix; var isSupported = (eventName in document); if (!isSupported) { var element = document.createElement('div'); element.setAttribute(eventName, 'return;'); isSupported = typeof element[eventName] === 'function'; } return isSupported; } function registerEvents$1() { registerTwoPhaseEvent('onChange', ['change', 'click', 'focusin', 'focusout', 'input', 'keydown', 'keyup', 'selectionchange']); } function createAndAccumulateChangeEvent(dispatchQueue, inst, nativeEvent, target) { // Flag this event loop as needing state restore. enqueueStateRestore(target); var listeners = accumulateTwoPhaseListeners(inst, 'onChange'); if (listeners.length > 0) { var event = new SyntheticEvent('onChange', 'change', null, nativeEvent, target); dispatchQueue.push({ event: event, listeners: listeners }); } } /** * For IE shims */ var activeElement = null; var activeElementInst = null; /** * SECTION: handle `change` event */ function shouldUseChangeEvent(elem) { var nodeName = elem.nodeName && elem.nodeName.toLowerCase(); return nodeName === 'select' || nodeName === 'input' && elem.type === 'file'; } function manualDispatchChangeEvent(nativeEvent) { var dispatchQueue = []; createAndAccumulateChangeEvent(dispatchQueue, activeElementInst, nativeEvent, getEventTarget(nativeEvent)); // If change and propertychange bubbled, we'd just bind to it like all the // other events and have it go through ReactBrowserEventEmitter. Since it // doesn't, we manually listen for the events and so we have to enqueue and // process the abstract event manually. // // Batching is necessary here in order to ensure that all event handlers run // before the next rerender (including event handlers attached to ancestor // elements instead of directly on the input). Without this, controlled // components don't work properly in conjunction with event bubbling because // the component is rerendered and the value reverted before all the event // handlers can run. See https://github.com/facebook/react/issues/708. batchedUpdates(runEventInBatch, dispatchQueue); } function runEventInBatch(dispatchQueue) { processDispatchQueue(dispatchQueue, 0); } function getInstIfValueChanged(targetInst) { var targetNode = getNodeFromInstance(targetInst); if (updateValueIfChanged(targetNode)) { return targetInst; } } function getTargetInstForChangeEvent(domEventName, targetInst) { if (domEventName === 'change') { return targetInst; } } /** * SECTION: handle `input` event */ var isInputEventSupported = false; if (canUseDOM) { // IE9 claims to support the input event but fails to trigger it when // deleting text, so we ignore its input events. isInputEventSupported = isEventSupported('input') && (!document.documentMode || document.documentMode > 9); } /** * (For IE <=9) Starts tracking propertychange events on the passed-in element * and override the value property so that we can distinguish user events from * value changes in JS. */ function startWatchingForValueChange(target, targetInst) { activeElement = target; activeElementInst = targetInst; activeElement.attachEvent('onpropertychange', handlePropertyChange); } /** * (For IE <=9) Removes the event listeners from the currently-tracked element, * if any exists. */ function stopWatchingForValueChange() { if (!activeElement) { return; } activeElement.detachEvent('onpropertychange', handlePropertyChange); activeElement = null; activeElementInst = null; } /** * (For IE <=9) Handles a propertychange event, sending a `change` event if * the value of the active element has changed. */ function handlePropertyChange(nativeEvent) { if (nativeEvent.propertyName !== 'value') { return; } if (getInstIfValueChanged(activeElementInst)) { manualDispatchChangeEvent(nativeEvent); } } function handleEventsForInputEventPolyfill(domEventName, target, targetInst) { if (domEventName === 'focusin') { // In IE9, propertychange fires for most input events but is buggy and // doesn't fire when text is deleted, but conveniently, selectionchange // appears to fire in all of the remaining cases so we catch those and // forward the event if the value has changed // In either case, we don't want to call the event handler if the value // is changed from JS so we redefine a setter for `.value` that updates // our activeElementValue variable, allowing us to ignore those changes // // stopWatching() should be a noop here but we call it just in case we // missed a blur event somehow. stopWatchingForValueChange(); startWatchingForValueChange(target, targetInst); } else if (domEventName === 'focusout') { stopWatchingForValueChange(); } } // For IE8 and IE9. function getTargetInstForInputEventPolyfill(domEventName, targetInst) { if (domEventName === 'selectionchange' || domEventName === 'keyup' || domEventName === 'keydown') { // On the selectionchange event, the target is just document which isn't // helpful for us so just check activeElement instead. // // 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire // propertychange on the first input event after setting `value` from a // script and fires only keydown, keypress, keyup. Catching keyup usually // gets it and catching keydown lets us fire an event for the first // keystroke if user does a key repeat (it'll be a little delayed: right // before the second keystroke). Other input methods (e.g., paste) seem to // fire selectionchange normally. return getInstIfValueChanged(activeElementInst); } } /** * SECTION: handle `click` event */ function shouldUseClickEvent(elem) { // Use the `click` event to detect changes to checkbox and radio inputs. // This approach works across all browsers, whereas `change` does not fire // until `blur` in IE8. var nodeName = elem.nodeName; return nodeName && nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio'); } function getTargetInstForClickEvent(domEventName, targetInst) { if (domEventName === 'click') { return getInstIfValueChanged(targetInst); } } function getTargetInstForInputOrChangeEvent(domEventName, targetInst) { if (domEventName === 'input' || domEventName === 'change') { return getInstIfValueChanged(targetInst); } } function handleControlledInputBlur(node) { var state = node._wrapperState; if (!state || !state.controlled || node.type !== 'number') { return; } { // If controlled, assign the value attribute to the current value on blur setDefaultValue(node, 'number', node.value); } } /** * This plugin creates an `onChange` event that normalizes change events * across form elements. This event fires at a time when it's possible to * change the element's value without seeing a flicker. * * Supported elements are: * - input (see `isTextInputElement`) * - textarea * - select */ function extractEvents$1(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) { var targetNode = targetInst ? getNodeFromInstance(targetInst) : window; var getTargetInstFunc, handleEventFunc; if (shouldUseChangeEvent(targetNode)) { getTargetInstFunc = getTargetInstForChangeEvent; } else if (isTextInputElement(targetNode)) { if (isInputEventSupported) { getTargetInstFunc = getTargetInstForInputOrChangeEvent; } else { getTargetInstFunc = getTargetInstForInputEventPolyfill; handleEventFunc = handleEventsForInputEventPolyfill; } } else if (shouldUseClickEvent(targetNode)) { getTargetInstFunc = getTargetInstForClickEvent; } if (getTargetInstFunc) { var inst = getTargetInstFunc(domEventName, targetInst); if (inst) { createAndAccumulateChangeEvent(dispatchQueue, inst, nativeEvent, nativeEventTarget); return; } } if (handleEventFunc) { handleEventFunc(domEventName, targetNode, targetInst); } // When blurring, set the value attribute for number inputs if (domEventName === 'focusout') { handleControlledInputBlur(targetNode); } } function registerEvents$2() { registerDirectEvent('onMouseEnter', ['mouseout', 'mouseover']); registerDirectEvent('onMouseLeave', ['mouseout', 'mouseover']); registerDirectEvent('onPointerEnter', ['pointerout', 'pointerover']); registerDirectEvent('onPointerLeave', ['pointerout', 'pointerover']); } /** * For almost every interaction we care about, there will be both a top-level * `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that * we do not extract duplicate events. However, moving the mouse into the * browser from outside will not fire a `mouseout` event. In this case, we use * the `mouseover` top-level event. */ function extractEvents$2(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) { var isOverEvent = domEventName === 'mouseover' || domEventName === 'pointerover'; var isOutEvent = domEventName === 'mouseout' || domEventName === 'pointerout'; if (isOverEvent && !isReplayingEvent(nativeEvent)) { // If this is an over event with a target, we might have already dispatched // the event in the out event of the other target. If this is replayed, // then it's because we couldn't dispatch against this target previously // so we have to do it now instead. var related = nativeEvent.relatedTarget || nativeEvent.fromElement; if (related) { // If the related node is managed by React, we can assume that we have // already dispatched the corresponding events during its mouseout. if (getClosestInstanceFromNode(related) || isContainerMarkedAsRoot(related)) { return; } } } if (!isOutEvent && !isOverEvent) { // Must not be a mouse or pointer in or out - ignoring. return; } var win; // TODO: why is this nullable in the types but we read from it? if (nativeEventTarget.window === nativeEventTarget) { // `nativeEventTarget` is probably a window object. win = nativeEventTarget; } else { // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. var doc = nativeEventTarget.ownerDocument; if (doc) { win = doc.defaultView || doc.parentWindow; } else { win = window; } } var from; var to; if (isOutEvent) { var _related = nativeEvent.relatedTarget || nativeEvent.toElement; from = targetInst; to = _related ? getClosestInstanceFromNode(_related) : null; if (to !== null) { var nearestMounted = getNearestMountedFiber(to); if (to !== nearestMounted || to.tag !== HostComponent && to.tag !== HostText) { to = null; } } } else { // Moving to a node from outside the window. from = null; to = targetInst; } if (from === to) { // Nothing pertains to our managed components. return; } var SyntheticEventCtor = SyntheticMouseEvent; var leaveEventType = 'onMouseLeave'; var enterEventType = 'onMouseEnter'; var eventTypePrefix = 'mouse'; if (domEventName === 'pointerout' || domEventName === 'pointerover') { SyntheticEventCtor = SyntheticPointerEvent; leaveEventType = 'onPointerLeave'; enterEventType = 'onPointerEnter'; eventTypePrefix = 'pointer'; } var fromNode = from == null ? win : getNodeFromInstance(from); var toNode = to == null ? win : getNodeFromInstance(to); var leave = new SyntheticEventCtor(leaveEventType, eventTypePrefix + 'leave', from, nativeEvent, nativeEventTarget); leave.target = fromNode; leave.relatedTarget = toNode; var enter = null; // We should only process this nativeEvent if we are processing // the first ancestor. Next time, we will ignore the event. var nativeTargetInst = getClosestInstanceFromNode(nativeEventTarget); if (nativeTargetInst === targetInst) { var enterEvent = new SyntheticEventCtor(enterEventType, eventTypePrefix + 'enter', to, nativeEvent, nativeEventTarget); enterEvent.target = toNode; enterEvent.relatedTarget = fromNode; enter = enterEvent; } accumulateEnterLeaveTwoPhaseListeners(dispatchQueue, leave, enter, from, to); } /** * inlined Object.is polyfill to avoid requiring consumers ship their own * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is */ function is(x, y) { return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare ; } var objectIs = typeof Object.is === 'function' ? Object.is : is; /** * Performs equality by iterating through keys on an object and returning false * when any key has values which are not strictly equal between the arguments. * Returns true when the values of all keys are strictly equal. */ function shallowEqual(objA, objB) { if (objectIs(objA, objB)) { return true; } if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) { return false; } var keysA = Object.keys(objA); var keysB = Object.keys(objB); if (keysA.length !== keysB.length) { return false; } // Test for A's keys different from B. for (var i = 0; i < keysA.length; i++) { var currentKey = keysA[i]; if (!hasOwnProperty.call(objB, currentKey) || !objectIs(objA[currentKey], objB[currentKey])) { return false; } } return true; } /** * Given any node return the first leaf node without children. * * @param {DOMElement|DOMTextNode} node * @return {DOMElement|DOMTextNode} */ function getLeafNode(node) { while (node && node.firstChild) { node = node.firstChild; } return node; } /** * Get the next sibling within a container. This will walk up the * DOM if a node's siblings have been exhausted. * * @param {DOMElement|DOMTextNode} node * @return {?DOMElement|DOMTextNode} */ function getSiblingNode(node) { while (node) { if (node.nextSibling) { return node.nextSibling; } node = node.parentNode; } } /** * Get object describing the nodes which contain characters at offset. * * @param {DOMElement|DOMTextNode} root * @param {number} offset * @return {?object} */ function getNodeForCharacterOffset(root, offset) { var node = getLeafNode(root); var nodeStart = 0; var nodeEnd = 0; while (node) { if (node.nodeType === TEXT_NODE) { nodeEnd = nodeStart + node.textContent.length; if (nodeStart <= offset && nodeEnd >= offset) { return { node: node, offset: offset - nodeStart }; } nodeStart = nodeEnd; } node = getLeafNode(getSiblingNode(node)); } } /** * @param {DOMElement} outerNode * @return {?object} */ function getOffsets(outerNode) { var ownerDocument = outerNode.ownerDocument; var win = ownerDocument && ownerDocument.defaultView || window; var selection = win.getSelection && win.getSelection(); if (!selection || selection.rangeCount === 0) { return null; } var anchorNode = selection.anchorNode, anchorOffset = selection.anchorOffset, focusNode = selection.focusNode, focusOffset = selection.focusOffset; // In Firefox, anchorNode and focusNode can be "anonymous divs", e.g. the // up/down buttons on an <input type="number">. Anonymous divs do not seem to // expose properties, triggering a "Permission denied error" if any of its // properties are accessed. The only seemingly possible way to avoid erroring // is to access a property that typically works for non-anonymous divs and // catch any error that may otherwise arise. See // https://bugzilla.mozilla.org/show_bug.cgi?id=208427 try { /* eslint-disable no-unused-expressions */ anchorNode.nodeType; focusNode.nodeType; /* eslint-enable no-unused-expressions */ } catch (e) { return null; } return getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset); } /** * Returns {start, end} where `start` is the character/codepoint index of * (anchorNode, anchorOffset) within the textContent of `outerNode`, and * `end` is the index of (focusNode, focusOffset). * * Returns null if you pass in garbage input but we should probably just crash. * * Exported only for testing. */ function getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset) { var length = 0; var start = -1; var end = -1; var indexWithinAnchor = 0; var indexWithinFocus = 0; var node = outerNode; var parentNode = null; outer: while (true) { var next = null; while (true) { if (node === anchorNode && (anchorOffset === 0 || node.nodeType === TEXT_NODE)) { start = length + anchorOffset; } if (node === focusNode && (focusOffset === 0 || node.nodeType === TEXT_NODE)) { end = length + focusOffset; } if (node.nodeType === TEXT_NODE) { length += node.nodeValue.length; } if ((next = node.firstChild) === null) { break; } // Moving from `node` to its first child `next`. parentNode = node; node = next; } while (true) { if (node === outerNode) { // If `outerNode` has children, this is always the second time visiting // it. If it has no children, this is still the first loop, and the only // valid selection is anchorNode and focusNode both equal to this node // and both offsets 0, in which case we will have handled above. break outer; } if (parentNode === anchorNode && ++indexWithinAnchor === anchorOffset) { start = length; } if (parentNode === focusNode && ++indexWithinFocus === focusOffset) { end = length; } if ((next = node.nextSibling) !== null) { break; } node = parentNode; parentNode = node.parentNode; } // Moving from `node` to its next sibling `next`. node = next; } if (start === -1 || end === -1) { // This should never happen. (Would happen if the anchor/focus nodes aren't // actually inside the passed-in node.) return null; } return { start: start, end: end }; } /** * 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 programmatically create a backward selection. Thus, for all IE * versions, we use the old IE API to create our selections. * * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ function setOffsets(node, offsets) { var doc = node.ownerDocument || document; var win = doc && doc.defaultView || window; // Edge fails with "Object expected" in some scenarios. // (For instance: TinyMCE editor used in a list component that supports pasting to add more, // fails when pasting 100+ items) if (!win.getSelection) { return; } var selection = win.getSelection(); var length = node.textContent.length; var start = Math.min(offsets.start, length); var end = offsets.end === undefined ? start : Math.min(offsets.end, length); // IE 11 uses modern selection, but doesn't support the extend method. // Flip backward selections, so we can set with a single range. if (!selection.extend && start > end) { var temp = end; end = start; start = temp; } var startMarker = getNodeForCharacterOffset(node, start); var endMarker = getNodeForCharacterOffset(node, end); if (startMarker && endMarker) { if (selection.rangeCount === 1 && selection.anchorNode === startMarker.node && selection.anchorOffset === startMarker.offset && selection.focusNode === endMarker.node && selection.focusOffset === endMarker.offset) { return; } var range = doc.createRange(); range.setStart(startMarker.node, startMarker.offset); selection.removeAllRanges(); if (start > end) { selection.addRange(range); selection.extend(endMarker.node, endMarker.offset); } else { range.setEnd(endMarker.node, endMarker.offset); selection.addRange(range); } } } function isTextNode(node) { return node && node.nodeType === TEXT_NODE; } function containsNode(outerNode, innerNode) { if (!outerNode || !innerNode) { return false; } else if (outerNode === innerNode) { return true; } else if (isTextNode(outerNode)) { return false; } else if (isTextNode(innerNode)) { return containsNode(outerNode, innerNode.parentNode); } else if ('contains' in outerNode) { return outerNode.contains(innerNode); } else if (outerNode.compareDocumentPosition) { return !!(outerNode.compareDocumentPosition(innerNode) & 16); } else { return false; } } function isInDocument(node) { return node && node.ownerDocument && containsNode(node.ownerDocument.documentElement, node); } function isSameOriginFrame(iframe) { try { // Accessing the contentDocument of a HTMLIframeElement can cause the browser // to throw, e.g. if it has a cross-origin src attribute. // Safari will show an error in the console when the access results in "Blocked a frame with origin". e.g: // iframe.contentDocument.defaultView; // A safety way is to access one of the cross origin properties: Window or Location // Which might result in "SecurityError" DOM Exception and it is compatible to Safari. // https://html.spec.whatwg.org/multipage/browsers.html#integration-with-idl return typeof iframe.contentWindow.location.href === 'string'; } catch (err) { return false; } } function getActiveElementDeep() { var win = window; var element = getActiveElement(); while (element instanceof win.HTMLIFrameElement) { if (isSameOriginFrame(element)) { win = element.contentWindow; } else { return element; } element = getActiveElement(win.document); } return element; } /** * @ReactInputSelection: React input selection module. Based on Selection.js, * but modified to be suitable for react and has a couple of bug fixes (doesn't * assume buttons have range selections allowed). * Input selection module for React. */ /** * @hasSelectionCapabilities: we get the element types that support selection * from https://html.spec.whatwg.org/#do-not-apply, looking at `selectionStart` * and `selectionEnd` rows. */ function hasSelectionCapabilities(elem) { var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase(); return nodeName && (nodeName === 'input' && (elem.type === 'text' || elem.type === 'search' || elem.type === 'tel' || elem.type === 'url' || elem.type === 'password') || nodeName === 'textarea' || elem.contentEditable === 'true'); } function getSelectionInformation() { var focusedElem = getActiveElementDeep(); return { focusedElem: focusedElem, selectionRange: hasSelectionCapabilities(focusedElem) ? getSelection(focusedElem) : null }; } /** * @restoreSelection: If any selection information was potentially lost, * restore it. This is useful when performing operations that could remove dom * nodes and place them back in, resulting in focus being lost. */ function restoreSelection(priorSelectionInformation) { var curFocusedElem = getActiveElementDeep(); var priorFocusedElem = priorSelectionInformation.focusedElem; var priorSelectionRange = priorSelectionInformation.selectionRange; if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) { if (priorSelectionRange !== null && hasSelectionCapabilities(priorFocusedElem)) { setSelection(priorFocusedElem, priorSelectionRange); } // Focusing a node can change the scroll position, which is undesirable var ancestors = []; var ancestor = priorFocusedElem; while (ancestor = ancestor.parentNode) { if (ancestor.nodeType === ELEMENT_NODE) { ancestors.push({ element: ancestor, left: ancestor.scrollLeft, top: ancestor.scrollTop }); } } if (typeof priorFocusedElem.focus === 'function') { priorFocusedElem.focus(); } for (var i = 0; i < ancestors.length; i++) { var info = ancestors[i]; info.element.scrollLeft = info.left; info.element.scrollTop = info.top; } } } /** * @getSelection: Gets the selection bounds of a focused textarea, input or * contentEditable node. * -@input: Look up selection bounds of this input * -@return {start: selectionStart, end: selectionEnd} */ function getSelection(input) { var selection; if ('selectionStart' in input) { // Modern browser with input or textarea. selection = { start: input.selectionStart, end: input.selectionEnd }; } else { // Content editable or old IE textarea. selection = getOffsets(input); } return selection || { start: 0, end: 0 }; } /** * @setSelection: Sets the selection bounds of a textarea or input and focuses * the input. * -@input Set selection bounds of this input or textarea * -@offsets Object of same form that is returned from get* */ function setSelection(input, offsets) { var start = offsets.start; var end = offsets.end; if (end === undefined) { end = start; } if ('selectionStart' in input) { input.selectionStart = start; input.selectionEnd = Math.min(end, input.value.length); } else { setOffsets(input, offsets); } } var skipSelectionChangeEvent = canUseDOM && 'documentMode' in document && document.documentMode <= 11; function registerEvents$3() { registerTwoPhaseEvent('onSelect', ['focusout', 'contextmenu', 'dragend', 'focusin', 'keydown', 'keyup', 'mousedown', 'mouseup', 'selectionchange']); } var activeElement$1 = null; var activeElementInst$1 = null; var lastSelection = null; var mouseDown = false; /** * Get an object which is a unique representation of the current selection. * * The return value will not be consistent across nodes or browsers, but * two identical selections on the same node will return identical objects. */ function getSelection$1(node) { if ('selectionStart' in node && hasSelectionCapabilities(node)) { return { start: node.selectionStart, end: node.selectionEnd }; } else { var win = node.ownerDocument && node.ownerDocument.defaultView || window; var selection = win.getSelection(); return { anchorNode: selection.anchorNode, anchorOffset: selection.anchorOffset, focusNode: selection.focusNode, focusOffset: selection.focusOffset }; } } /** * Get document associated with the event target. */ function getEventTargetDocument(eventTarget) { return eventTarget.window === eventTarget ? eventTarget.document : eventTarget.nodeType === DOCUMENT_NODE ? eventTarget : eventTarget.ownerDocument; } /** * Poll selection to see whether it's changed. * * @param {object} nativeEvent * @param {object} nativeEventTarget * @return {?SyntheticEvent} */ function constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget) { // Ensure we have the right element, and that the user is not dragging a // selection (this matches native `select` event behavior). In HTML5, select // fires only on input and textarea thus if there's no focused element we // won't dispatch. var doc = getEventTargetDocument(nativeEventTarget); if (mouseDown || activeElement$1 == null || activeElement$1 !== getActiveElement(doc)) { return; } // Only fire when selection has actually changed. var currentSelection = getSelection$1(activeElement$1); if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) { lastSelection = currentSelection; var listeners = accumulateTwoPhaseListeners(activeElementInst$1, 'onSelect'); if (listeners.length > 0) { var event = new SyntheticEvent('onSelect', 'select', null, nativeEvent, nativeEventTarget); dispatchQueue.push({ event: event, listeners: listeners }); event.target = activeElement$1; } } } /** * This plugin creates an `onSelect` event that normalizes select events * across form elements. * * Supported elements are: * - input (see `isTextInputElement`) * - textarea * - contentEditable * * This differs from native browser implementations in the following ways: * - Fires on contentEditable fields as well as inputs. * - Fires for collapsed selection. * - Fires after user input. */ function extractEvents$3(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) { var targetNode = targetInst ? getNodeFromInstance(targetInst) : window; switch (domEventName) { // Track the input node that has focus. case 'focusin': if (isTextInputElement(targetNode) || targetNode.contentEditable === 'true') { activeElement$1 = targetNode; activeElementInst$1 = targetInst; lastSelection = null; } break; case 'focusout': activeElement$1 = null; activeElementInst$1 = null; lastSelection = null; break; // Don't fire the event while the user is dragging. This matches the // semantics of the native select event. case 'mousedown': mouseDown = true; break; case 'contextmenu': case 'mouseup': case 'dragend': mouseDown = false; constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget); break; // Chrome and IE fire non-standard event when selection is changed (and // sometimes when it hasn't). IE's event fires out of order with respect // to key and input events on deletion, so we discard it. // // Firefox doesn't support selectionchange, so check selection status // after each key entry. The selection changes after keydown and before // keyup, but we check on keydown as well in the case of holding down a // key, when multiple keydown events are fired but only one keyup is. // This is also our approach for IE handling, for the reason above. case 'selectionchange': if (skipSelectionChangeEvent) { break; } // falls through case 'keydown': case 'keyup': constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget); } } /** * Generate a mapping of standard vendor prefixes using the defined style property and event name. * * @param {string} styleProp * @param {string} eventName * @returns {object} */ function makePrefixMap(styleProp, eventName) { var prefixes = {}; prefixes[styleProp.toLowerCase()] = eventName.toLowerCase(); prefixes['Webkit' + styleProp] = 'webkit' + eventName; prefixes['Moz' + styleProp] = 'moz' + eventName; return prefixes; } /** * A list of event names to a configurable list of vendor prefixes. */ var vendorPrefixes = { animationend: makePrefixMap('Animation', 'AnimationEnd'), animationiteration: makePrefixMap('Animation', 'AnimationIteration'), animationstart: makePrefixMap('Animation', 'AnimationStart'), transitionend: makePrefixMap('Transition', 'TransitionEnd') }; /** * Event names that have already been detected and prefixed (if applicable). */ var prefixedEventNames = {}; /** * Element to check for prefixes on. */ var style = {}; /** * Bootstrap if a DOM exists. */ if (canUseDOM) { style = document.createElement('div').style; // On some platforms, in particular some releases of Android 4.x, // the un-prefixed "animation" and "transition" properties are defined on the // style object but the events that fire will still be prefixed, so we need // to check if the un-prefixed events are usable, and if not remove them from the map. if (!('AnimationEvent' in window)) { delete vendorPrefixes.animationend.animation; delete vendorPrefixes.animationiteration.animation; delete vendorPrefixes.animationstart.animation; } // Same as above if (!('TransitionEvent' in window)) { delete vendorPrefixes.transitionend.transition; } } /** * Attempts to determine the correct vendor prefixed event name. * * @param {string} eventName * @returns {string} */ function getVendorPrefixedEventName(eventName) { if (prefixedEventNames[eventName]) { return prefixedEventNames[eventName]; } else if (!vendorPrefixes[eventName]) { return eventName; } var prefixMap = vendorPrefixes[eventName]; for (var styleProp in prefixMap) { if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) { return prefixedEventNames[eventName] = prefixMap[styleProp]; } } return eventName; } var ANIMATION_END = getVendorPrefixedEventName('animationend'); var ANIMATION_ITERATION = getVendorPrefixedEventName('animationiteration'); var ANIMATION_START = getVendorPrefixedEventName('animationstart'); var TRANSITION_END = getVendorPrefixedEventName('transitionend'); var topLevelEventsToReactNames = new Map(); // NOTE: Capitalization is important in this list! // // E.g. it needs "pointerDown", not "pointerdown". // This is because we derive both React name ("onPointerDown") // and DOM name ("pointerdown") from the same list. // // Exceptions that don't match this convention are listed separately. // // prettier-ignore var simpleEventPluginEvents = ['abort', 'auxClick', 'cancel', 'canPlay', 'canPlayThrough', 'click', 'close', 'contextMenu', 'copy', 'cut', 'drag', 'dragEnd', 'dragEnter', 'dragExit', 'dragLeave', 'dragOver', 'dragStart', 'drop', 'durationChange', 'emptied', 'encrypted', 'ended', 'error', 'gotPointerCapture', 'input', 'invalid', 'keyDown', 'keyPress', 'keyUp', 'load', 'loadedData', 'loadedMetadata', 'loadStart', 'lostPointerCapture', 'mouseDown', 'mouseMove', 'mouseOut', 'mouseOver', 'mouseUp', 'paste', 'pause', 'play', 'playing', 'pointerCancel', 'pointerDown', 'pointerMove', 'pointerOut', 'pointerOver', 'pointerUp', 'progress', 'rateChange', 'reset', 'resize', 'seeked', 'seeking', 'stalled', 'submit', 'suspend', 'timeUpdate', 'touchCancel', 'touchEnd', 'touchStart', 'volumeChange', 'scroll', 'toggle', 'touchMove', 'waiting', 'wheel']; function registerSimpleEvent(domEventName, reactName) { topLevelEventsToReactNames.set(domEventName, reactName); registerTwoPhaseEvent(reactName, [domEventName]); } function registerSimpleEvents() { for (var i = 0; i < simpleEventPluginEvents.length; i++) { var eventName = simpleEventPluginEvents[i]; var domEventName = eventName.toLowerCase(); var capitalizedEvent = eventName[0].toUpperCase() + eventName.slice(1); registerSimpleEvent(domEventName, 'on' + capitalizedEvent); } // Special cases where event names don't match. registerSimpleEvent(ANIMATION_END, 'onAnimationEnd'); registerSimpleEvent(ANIMATION_ITERATION, 'onAnimationIteration'); registerSimpleEvent(ANIMATION_START, 'onAnimationStart'); registerSimpleEvent('dblclick', 'onDoubleClick'); registerSimpleEvent('focusin', 'onFocus'); registerSimpleEvent('focusout', 'onBlur'); registerSimpleEvent(TRANSITION_END, 'onTransitionEnd'); } function extractEvents$4(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) { var reactName = topLevelEventsToReactNames.get(domEventName); if (reactName === undefined) { return; } var SyntheticEventCtor = SyntheticEvent; var reactEventType = domEventName; switch (domEventName) { case 'keypress': // Firefox creates a keypress event for function keys too. This removes // the unwanted keypress events. Enter is however both printable and // non-printable. One would expect Tab to be as well (but it isn't). if (getEventCharCode(nativeEvent) === 0) { return; } /* falls through */ case 'keydown': case 'keyup': SyntheticEventCtor = SyntheticKeyboardEvent; break; case 'focusin': reactEventType = 'focus'; SyntheticEventCtor = SyntheticFocusEvent; break; case 'focusout': reactEventType = 'blur'; SyntheticEventCtor = SyntheticFocusEvent; break; case 'beforeblur': case 'afterblur': SyntheticEventCtor = SyntheticFocusEvent; break; case 'click': // Firefox creates a click event on right mouse clicks. This removes the // unwanted click events. if (nativeEvent.button === 2) { return; } /* falls through */ case 'auxclick': case 'dblclick': case 'mousedown': case 'mousemove': case 'mouseup': // TODO: Disabled elements should not respond to mouse events /* falls through */ case 'mouseout': case 'mouseover': case 'contextmenu': SyntheticEventCtor = SyntheticMouseEvent; break; case 'drag': case 'dragend': case 'dragenter': case 'dragexit': case 'dragleave': case 'dragover': case 'dragstart': case 'drop': SyntheticEventCtor = SyntheticDragEvent; break; case 'touchcancel': case 'touchend': case 'touchmove': case 'touchstart': SyntheticEventCtor = SyntheticTouchEvent; break; case ANIMATION_END: case ANIMATION_ITERATION: case ANIMATION_START: SyntheticEventCtor = SyntheticAnimationEvent; break; case TRANSITION_END: SyntheticEventCtor = SyntheticTransitionEvent; break; case 'scroll': SyntheticEventCtor = SyntheticUIEvent; break; case 'wheel': SyntheticEventCtor = SyntheticWheelEvent; break; case 'copy': case 'cut': case 'paste': SyntheticEventCtor = SyntheticClipboardEvent; break; case 'gotpointercapture': case 'lostpointercapture': case 'pointercancel': case 'pointerdown': case 'pointermove': case 'pointerout': case 'pointerover': case 'pointerup': SyntheticEventCtor = SyntheticPointerEvent; break; } var inCapturePhase = (eventSystemFlags & IS_CAPTURE_PHASE) !== 0; { // Some events don't bubble in the browser. // In the past, React has always bubbled them, but this can be surprising. // We're going to try aligning closer to the browser behavior by not bubbling // them in React either. We'll start by not bubbling onScroll, and then expand. var accumulateTargetOnly = !inCapturePhase && // TODO: ideally, we'd eventually add all events from // nonDelegatedEvents list in DOMPluginEventSystem. // Then we can remove this special list. // This is a breaking change that can wait until React 18. domEventName === 'scroll'; var _listeners = accumulateSinglePhaseListeners(targetInst, reactName, nativeEvent.type, inCapturePhase, accumulateTargetOnly); if (_listeners.length > 0) { // Intentionally create event lazily. var _event = new SyntheticEventCtor(reactName, reactEventType, null, nativeEvent, nativeEventTarget); dispatchQueue.push({ event: _event, listeners: _listeners }); } } } // TODO: remove top-level side effect. registerSimpleEvents(); registerEvents$2(); registerEvents$1(); registerEvents$3(); registerEvents(); function extractEvents$5(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) { // TODO: we should remove the concept of a "SimpleEventPlugin". // This is the basic functionality of the event system. All // the other plugins are essentially polyfills. So the plugin // should probably be inlined somewhere and have its logic // be core the to event system. This would potentially allow // us to ship builds of React without the polyfilled plugins below. extractEvents$4(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags); var shouldProcessPolyfillPlugins = (eventSystemFlags & SHOULD_NOT_PROCESS_POLYFILL_EVENT_PLUGINS) === 0; // We don't process these events unless we are in the // event's native "bubble" phase, which means that we're // not in the capture phase. That's because we emulate // the capture phase here still. This is a trade-off, // because in an ideal world we would not emulate and use // the phases properly, like we do with the SimpleEvent // plugin. However, the plugins below either expect // emulation (EnterLeave) or use state localized to that // plugin (BeforeInput, Change, Select). The state in // these modules complicates things, as you'll essentially // get the case where the capture phase event might change // state, only for the following bubble event to come in // later and not trigger anything as the state now // invalidates the heuristics of the event plugin. We // could alter all these plugins to work in such ways, but // that might cause other unknown side-effects that we // can't foresee right now. if (shouldProcessPolyfillPlugins) { extractEvents$2(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget); extractEvents$1(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget); extractEvents$3(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget); extractEvents(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget); } } // List of events that need to be individually attached to media elements. var mediaEventTypes = ['abort', 'canplay', 'canplaythrough', 'durationchange', 'emptied', 'encrypted', 'ended', 'error', 'loadeddata', 'loadedmetadata', 'loadstart', 'pause', 'play', 'playing', 'progress', 'ratechange', 'resize', 'seeked', 'seeking', 'stalled', 'suspend', 'timeupdate', 'volumechange', 'waiting']; // We should not delegate these events to the container, but rather // set them on the actual target element itself. This is primarily // because these events do not consistently bubble in the DOM. var nonDelegatedEvents = new Set(['cancel', 'close', 'invalid', 'load', 'scroll', 'toggle'].concat(mediaEventTypes)); function executeDispatch(event, listener, currentTarget) { var type = event.type || 'unknown-event'; event.currentTarget = currentTarget; invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event); event.currentTarget = null; } function processDispatchQueueItemsInOrder(event, dispatchListeners, inCapturePhase) { var previousInstance; if (inCapturePhase) { for (var i = dispatchListeners.length - 1; i >= 0; i--) { var _dispatchListeners$i = dispatchListeners[i], instance = _dispatchListeners$i.instance, currentTarget = _dispatchListeners$i.currentTarget, listener = _dispatchListeners$i.listener; if (instance !== previousInstance && event.isPropagationStopped()) { return; } executeDispatch(event, listener, currentTarget); previousInstance = instance; } } else { for (var _i = 0; _i < dispatchListeners.length; _i++) { var _dispatchListeners$_i = dispatchListeners[_i], _instance = _dispatchListeners$_i.instance, _currentTarget = _dispatchListeners$_i.currentTarget, _listener = _dispatchListeners$_i.listener; if (_instance !== previousInstance && event.isPropagationStopped()) { return; } executeDispatch(event, _listener, _currentTarget); previousInstance = _instance; } } } function processDispatchQueue(dispatchQueue, eventSystemFlags) { var inCapturePhase = (eventSystemFlags & IS_CAPTURE_PHASE) !== 0; for (var i = 0; i < dispatchQueue.length; i++) { var _dispatchQueue$i = dispatchQueue[i], event = _dispatchQueue$i.event, listeners = _dispatchQueue$i.listeners; processDispatchQueueItemsInOrder(event, listeners, inCapturePhase); // event system doesn't use pooling. } // This would be a good time to rethrow if any of the event handlers threw. rethrowCaughtError(); } function dispatchEventsForPlugins(domEventName, eventSystemFlags, nativeEvent, targetInst, targetContainer) { var nativeEventTarget = getEventTarget(nativeEvent); var dispatchQueue = []; extractEvents$5(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags); processDispatchQueue(dispatchQueue, eventSystemFlags); } function listenToNonDelegatedEvent(domEventName, targetElement) { { if (!nonDelegatedEvents.has(domEventName)) { error('Did not expect a listenToNonDelegatedEvent() call for "%s". ' + 'This is a bug in React. Please file an issue.', domEventName); } } var isCapturePhaseListener = false; var listenerSet = getEventListenerSet(targetElement); var listenerSetKey = getListenerSetKey(domEventName, isCapturePhaseListener); if (!listenerSet.has(listenerSetKey)) { addTrappedEventListener(targetElement, domEventName, IS_NON_DELEGATED, isCapturePhaseListener); listenerSet.add(listenerSetKey); } } function listenToNativeEvent(domEventName, isCapturePhaseListener, target) { { if (nonDelegatedEvents.has(domEventName) && !isCapturePhaseListener) { error('Did not expect a listenToNativeEvent() call for "%s" in the bubble phase. ' + 'This is a bug in React. Please file an issue.', domEventName); } } var eventSystemFlags = 0; if (isCapturePhaseListener) { eventSystemFlags |= IS_CAPTURE_PHASE; } addTrappedEventListener(target, domEventName, eventSystemFlags, isCapturePhaseListener); } // This is only used by createEventHandle when the var listeningMarker = '_reactListening' + Math.random().toString(36).slice(2); function listenToAllSupportedEvents(rootContainerElement) { if (!rootContainerElement[listeningMarker]) { rootContainerElement[listeningMarker] = true; allNativeEvents.forEach(function (domEventName) { // We handle selectionchange separately because it // doesn't bubble and needs to be on the document. if (domEventName !== 'selectionchange') { if (!nonDelegatedEvents.has(domEventName)) { listenToNativeEvent(domEventName, false, rootContainerElement); } listenToNativeEvent(domEventName, true, rootContainerElement); } }); var ownerDocument = rootContainerElement.nodeType === DOCUMENT_NODE ? rootContainerElement : rootContainerElement.ownerDocument; if (ownerDocument !== null) { // The selectionchange event also needs deduplication // but it is attached to the document. if (!ownerDocument[listeningMarker]) { ownerDocument[listeningMarker] = true; listenToNativeEvent('selectionchange', false, ownerDocument); } } } } function addTrappedEventListener(targetContainer, domEventName, eventSystemFlags, isCapturePhaseListener, isDeferredListenerForLegacyFBSupport) { var listener = createEventListenerWrapperWithPriority(targetContainer, domEventName, eventSystemFlags); // If passive option is not supported, then the event will be // active and not passive. var isPassiveListener = undefined; if (passiveBrowserEventsSupported) { // Browsers introduced an intervention, making these events // passive by default on document. React doesn't bind them // to document anymore, but changing this now would undo // the performance wins from the change. So we emulate // the existing behavior manually on the roots now. // https://github.com/facebook/react/issues/19651 if (domEventName === 'touchstart' || domEventName === 'touchmove' || domEventName === 'wheel') { isPassiveListener = true; } } targetContainer = targetContainer; var unsubscribeListener; // When legacyFBSupport is enabled, it's for when we if (isCapturePhaseListener) { if (isPassiveListener !== undefined) { unsubscribeListener = addEventCaptureListenerWithPassiveFlag(targetContainer, domEventName, listener, isPassiveListener); } else { unsubscribeListener = addEventCaptureListener(targetContainer, domEventName, listener); } } else { if (isPassiveListener !== undefined) { unsubscribeListener = addEventBubbleListenerWithPassiveFlag(targetContainer, domEventName, listener, isPassiveListener); } else { unsubscribeListener = addEventBubbleListener(targetContainer, domEventName, listener); } } } function isMatchingRootContainer(grandContainer, targetContainer) { return grandContainer === targetContainer || grandContainer.nodeType === COMMENT_NODE && grandContainer.parentNode === targetContainer; } function dispatchEventForPluginEventSystem(domEventName, eventSystemFlags, nativeEvent, targetInst, targetContainer) { var ancestorInst = targetInst; if ((eventSystemFlags & IS_EVENT_HANDLE_NON_MANAGED_NODE) === 0 && (eventSystemFlags & IS_NON_DELEGATED) === 0) { var targetContainerNode = targetContainer; // If we are using the legacy FB support flag, we if (targetInst !== null) { // The below logic attempts to work out if we need to change // the target fiber to a different ancestor. We had similar logic // in the legacy event system, except the big difference between // systems is that the modern event system now has an event listener // attached to each React Root and React Portal Root. Together, // the DOM nodes representing these roots are the "rootContainer". // To figure out which ancestor instance we should use, we traverse // up the fiber tree from the target instance and attempt to find // root boundaries that match that of our current "rootContainer". // If we find that "rootContainer", we find the parent fiber // sub-tree for that root and make that our ancestor instance. var node = targetInst; mainLoop: while (true) { if (node === null) { return; } var nodeTag = node.tag; if (nodeTag === HostRoot || nodeTag === HostPortal) { var container = node.stateNode.containerInfo; if (isMatchingRootContainer(container, targetContainerNode)) { break; } if (nodeTag === HostPortal) { // The target is a portal, but it's not the rootContainer we're looking for. // Normally portals handle their own events all the way down to the root. // So we should be able to stop now. However, we don't know if this portal // was part of *our* root. var grandNode = node.return; while (grandNode !== null) { var grandTag = grandNode.tag; if (grandTag === HostRoot || grandTag === HostPortal) { var grandContainer = grandNode.stateNode.containerInfo; if (isMatchingRootContainer(grandContainer, targetContainerNode)) { // This is the rootContainer we're looking for and we found it as // a parent of the Portal. That means we can ignore it because the // Portal will bubble through to us. return; } } grandNode = grandNode.return; } } // Now we need to find it's corresponding host fiber in the other // tree. To do this we can use getClosestInstanceFromNode, but we // need to validate that the fiber is a host instance, otherwise // we need to traverse up through the DOM till we find the correct // node that is from the other tree. while (container !== null) { var parentNode = getClosestInstanceFromNode(container); if (parentNode === null) { return; } var parentTag = parentNode.tag; if (parentTag === HostComponent || parentTag === HostText) { node = ancestorInst = parentNode; continue mainLoop; } container = container.parentNode; } } node = node.return; } } } batchedUpdates(function () { return dispatchEventsForPlugins(domEventName, eventSystemFlags, nativeEvent, ancestorInst); }); } function createDispatchListener(instance, listener, currentTarget) { return { instance: instance, listener: listener, currentTarget: currentTarget }; } function accumulateSinglePhaseListeners(targetFiber, reactName, nativeEventType, inCapturePhase, accumulateTargetOnly, nativeEvent) { var captureName = reactName !== null ? reactName + 'Capture' : null; var reactEventName = inCapturePhase ? captureName : reactName; var listeners = []; var instance = targetFiber; var lastHostComponent = null; // Accumulate all instances and listeners via the target -> root path. while (instance !== null) { var _instance2 = instance, stateNode = _instance2.stateNode, tag = _instance2.tag; // Handle listeners that are on HostComponents (i.e. <div>) if (tag === HostComponent && stateNode !== null) { lastHostComponent = stateNode; // createEventHandle listeners if (reactEventName !== null) { var listener = getListener(instance, reactEventName); if (listener != null) { listeners.push(createDispatchListener(instance, listener, lastHostComponent)); } } } // If we are only accumulating events for the target, then we don't // continue to propagate through the React fiber tree to find other // listeners. if (accumulateTargetOnly) { break; } // If we are processing the onBeforeBlur event, then we need to take instance = instance.return; } return listeners; } // We should only use this function for: // - BeforeInputEventPlugin // - ChangeEventPlugin // - SelectEventPlugin // This is because we only process these plugins // in the bubble phase, so we need to accumulate two // phase event listeners (via emulation). function accumulateTwoPhaseListeners(targetFiber, reactName) { var captureName = reactName + 'Capture'; var listeners = []; var instance = targetFiber; // Accumulate all instances and listeners via the target -> root path. while (instance !== null) { var _instance3 = instance, stateNode = _instance3.stateNode, tag = _instance3.tag; // Handle listeners that are on HostComponents (i.e. <div>) if (tag === HostComponent && stateNode !== null) { var currentTarget = stateNode; var captureListener = getListener(instance, captureName); if (captureListener != null) { listeners.unshift(createDispatchListener(instance, captureListener, currentTarget)); } var bubbleListener = getListener(instance, reactName); if (bubbleListener != null) { listeners.push(createDispatchListener(instance, bubbleListener, currentTarget)); } } instance = instance.return; } return listeners; } function getParent(inst) { if (inst === null) { return null; } do { inst = inst.return; // TODO: If this is a HostRoot we might want to bail out. // That is depending on if we want nested subtrees (layers) to bubble // events to their parent. We could also go through parentNode on the // host node but that wouldn't work for React Native and doesn't let us // do the portal feature. } while (inst && inst.tag !== HostComponent); if (inst) { return inst; } return null; } /** * Return the lowest common ancestor of A and B, or null if they are in * different trees. */ function getLowestCommonAncestor(instA, instB) { var nodeA = instA; var nodeB = instB; var depthA = 0; for (var tempA = nodeA; tempA; tempA = getParent(tempA)) { depthA++; } var depthB = 0; for (var tempB = nodeB; tempB; tempB = getParent(tempB)) { depthB++; } // If A is deeper, crawl up. while (depthA - depthB > 0) { nodeA = getParent(nodeA); depthA--; } // If B is deeper, crawl up. while (depthB - depthA > 0) { nodeB = getParent(nodeB); depthB--; } // Walk in lockstep until we find a match. var depth = depthA; while (depth--) { if (nodeA === nodeB || nodeB !== null && nodeA === nodeB.alternate) { return nodeA; } nodeA = getParent(nodeA); nodeB = getParent(nodeB); } return null; } function accumulateEnterLeaveListenersForEvent(dispatchQueue, event, target, common, inCapturePhase) { var registrationName = event._reactName; var listeners = []; var instance = target; while (instance !== null) { if (instance === common) { break; } var _instance4 = instance, alternate = _instance4.alternate, stateNode = _instance4.stateNode, tag = _instance4.tag; if (alternate !== null && alternate === common) { break; } if (tag === HostComponent && stateNode !== null) { var currentTarget = stateNode; if (inCapturePhase) { var captureListener = getListener(instance, registrationName); if (captureListener != null) { listeners.unshift(createDispatchListener(instance, captureListener, currentTarget)); } } else if (!inCapturePhase) { var bubbleListener = getListener(instance, registrationName); if (bubbleListener != null) { listeners.push(createDispatchListener(instance, bubbleListener, currentTarget)); } } } instance = instance.return; } if (listeners.length !== 0) { dispatchQueue.push({ event: event, listeners: listeners }); } } // We should only use this function for: // - EnterLeaveEventPlugin // This is because we only process this plugin // in the bubble phase, so we need to accumulate two // phase event listeners. function accumulateEnterLeaveTwoPhaseListeners(dispatchQueue, leaveEvent, enterEvent, from, to) { var common = from && to ? getLowestCommonAncestor(from, to) : null; if (from !== null) { accumulateEnterLeaveListenersForEvent(dispatchQueue, leaveEvent, from, common, false); } if (to !== null && enterEvent !== null) { accumulateEnterLeaveListenersForEvent(dispatchQueue, enterEvent, to, common, true); } } function getListenerSetKey(domEventName, capture) { return domEventName + "__" + (capture ? 'capture' : 'bubble'); } var didWarnInvalidHydration = false; var DANGEROUSLY_SET_INNER_HTML = 'dangerouslySetInnerHTML'; var SUPPRESS_CONTENT_EDITABLE_WARNING = 'suppressContentEditableWarning'; var SUPPRESS_HYDRATION_WARNING = 'suppressHydrationWarning'; var AUTOFOCUS = 'autoFocus'; var CHILDREN = 'children'; var STYLE = 'style'; var HTML$1 = '__html'; var warnedUnknownTags; var validatePropertiesInDevelopment; var warnForPropDifference; var warnForExtraAttributes; var warnForInvalidEventListener; var canDiffStyleForHydrationWarning; var normalizeHTML; { warnedUnknownTags = { // There are working polyfills for <dialog>. Let people use it. dialog: true, // Electron ships a custom <webview> tag to display external web content in // an isolated frame and process. // This tag is not present in non Electron environments such as JSDom which // is often used for testing purposes. // @see https://electronjs.org/docs/api/webview-tag webview: true }; validatePropertiesInDevelopment = function (type, props) { validateProperties(type, props); validateProperties$1(type, props); validateProperties$2(type, props, { registrationNameDependencies: registrationNameDependencies, possibleRegistrationNames: possibleRegistrationNames }); }; // IE 11 parses & normalizes the style attribute as opposed to other // browsers. It adds spaces and sorts the properties in some // non-alphabetical order. Handling that would require sorting CSS // properties in the client & server versions or applying // `expectedStyle` to a temporary DOM node to read its `style` attribute // normalized. Since it only affects IE, we're skipping style warnings // in that browser completely in favor of doing all that work. // See https://github.com/facebook/react/issues/11807 canDiffStyleForHydrationWarning = canUseDOM && !document.documentMode; warnForPropDifference = function (propName, serverValue, clientValue) { if (didWarnInvalidHydration) { return; } var normalizedClientValue = normalizeMarkupForTextOrAttribute(clientValue); var normalizedServerValue = normalizeMarkupForTextOrAttribute(serverValue); if (normalizedServerValue === normalizedClientValue) { return; } didWarnInvalidHydration = true; error('Prop `%s` did not match. Server: %s Client: %s', propName, JSON.stringify(normalizedServerValue), JSON.stringify(normalizedClientValue)); }; warnForExtraAttributes = function (attributeNames) { if (didWarnInvalidHydration) { return; } didWarnInvalidHydration = true; var names = []; attributeNames.forEach(function (name) { names.push(name); }); error('Extra attributes from the server: %s', names); }; warnForInvalidEventListener = function (registrationName, listener) { if (listener === false) { error('Expected `%s` listener to be a function, instead got `false`.\n\n' + 'If you used to conditionally omit it with %s={condition && value}, ' + 'pass %s={condition ? value : undefined} instead.', registrationName, registrationName, registrationName); } else { error('Expected `%s` listener to be a function, instead got a value of `%s` type.', registrationName, typeof listener); } }; // Parse the HTML and read it back to normalize the HTML string so that it // can be used for comparison. normalizeHTML = function (parent, html) { // We could have created a separate document here to avoid // re-initializing custom elements if they exist. But this breaks // how <noscript> is being handled. So we use the same document. // See the discussion in https://github.com/facebook/react/pull/11157. var testElement = parent.namespaceURI === HTML_NAMESPACE ? parent.ownerDocument.createElement(parent.tagName) : parent.ownerDocument.createElementNS(parent.namespaceURI, parent.tagName); testElement.innerHTML = html; return testElement.innerHTML; }; } // HTML parsing normalizes CR and CRLF to LF. // It also can turn \u0000 into \uFFFD inside attributes. // https://www.w3.org/TR/html5/single-page.html#preprocessing-the-input-stream // If we have a mismatch, it might be caused by that. // We will still patch up in this case but not fire the warning. var NORMALIZE_NEWLINES_REGEX = /\r\n?/g; var NORMALIZE_NULL_AND_REPLACEMENT_REGEX = /\u0000|\uFFFD/g; function normalizeMarkupForTextOrAttribute(markup) { { checkHtmlStringCoercion(markup); } var markupString = typeof markup === 'string' ? markup : '' + markup; return markupString.replace(NORMALIZE_NEWLINES_REGEX, '\n').replace(NORMALIZE_NULL_AND_REPLACEMENT_REGEX, ''); } function checkForUnmatchedText(serverText, clientText, isConcurrentMode, shouldWarnDev) { var normalizedClientText = normalizeMarkupForTextOrAttribute(clientText); var normalizedServerText = normalizeMarkupForTextOrAttribute(serverText); if (normalizedServerText === normalizedClientText) { return; } if (shouldWarnDev) { { if (!didWarnInvalidHydration) { didWarnInvalidHydration = true; error('Text content did not match. Server: "%s" Client: "%s"', normalizedServerText, normalizedClientText); } } } if (isConcurrentMode && enableClientRenderFallbackOnTextMismatch) { // In concurrent roots, we throw when there's a text mismatch and revert to // client rendering, up to the nearest Suspense boundary. throw new Error('Text content does not match server-rendered HTML.'); } } function getOwnerDocumentFromRootContainer(rootContainerElement) { return rootContainerElement.nodeType === DOCUMENT_NODE ? rootContainerElement : rootContainerElement.ownerDocument; } function noop() {} function trapClickOnNonInteractiveElement(node) { // Mobile Safari does not fire properly bubble click events on // non-interactive elements, which means delegated click listeners do not // fire. The workaround for this bug involves attaching an empty click // listener on the target node. // https://www.quirksmode.org/blog/archives/2010/09/click_event_del.html // Just set it using the onclick property so that we don't have to manage any // bookkeeping for it. Not sure if we need to clear it when the listener is // removed. // TODO: Only do this for the relevant Safaris maybe? node.onclick = noop; } function setInitialDOMProperties(tag, domElement, rootContainerElement, nextProps, isCustomComponentTag) { for (var propKey in nextProps) { if (!nextProps.hasOwnProperty(propKey)) { continue; } var nextProp = nextProps[propKey]; if (propKey === STYLE) { { if (nextProp) { // Freeze the next style object so that we can assume it won't be // mutated. We have already warned for this in the past. Object.freeze(nextProp); } } // Relies on `updateStylesByID` not mutating `styleUpdates`. setValueForStyles(domElement, nextProp); } else if (propKey === DANGEROUSLY_SET_INNER_HTML) { var nextHtml = nextProp ? nextProp[HTML$1] : undefined; if (nextHtml != null) { setInnerHTML(domElement, nextHtml); } } else if (propKey === CHILDREN) { if (typeof nextProp === 'string') { // Avoid setting initial textContent when the text is empty. In IE11 setting // textContent on a <textarea> will cause the placeholder to not // show within the <textarea> until it has been focused and blurred again. // https://github.com/facebook/react/issues/6731#issuecomment-254874553 var canSetTextContent = tag !== 'textarea' || nextProp !== ''; if (canSetTextContent) { setTextContent(domElement, nextProp); } } else if (typeof nextProp === 'number') { setTextContent(domElement, '' + nextProp); } } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING) ; else if (propKey === AUTOFOCUS) ; else if (registrationNameDependencies.hasOwnProperty(propKey)) { if (nextProp != null) { if ( typeof nextProp !== 'function') { warnForInvalidEventListener(propKey, nextProp); } if (propKey === 'onScroll') { listenToNonDelegatedEvent('scroll', domElement); } } } else if (nextProp != null) { setValueForProperty(domElement, propKey, nextProp, isCustomComponentTag); } } } function updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag) { // TODO: Handle wasCustomComponentTag for (var i = 0; i < updatePayload.length; i += 2) { var propKey = updatePayload[i]; var propValue = updatePayload[i + 1]; if (propKey === STYLE) { setValueForStyles(domElement, propValue); } else if (propKey === DANGEROUSLY_SET_INNER_HTML) { setInnerHTML(domElement, propValue); } else if (propKey === CHILDREN) { setTextContent(domElement, propValue); } else { setValueForProperty(domElement, propKey, propValue, isCustomComponentTag); } } } function createElement(type, props, rootContainerElement, parentNamespace) { var isCustomComponentTag; // We create tags in the namespace of their parent container, except HTML // tags get no namespace. var ownerDocument = getOwnerDocumentFromRootContainer(rootContainerElement); var domElement; var namespaceURI = parentNamespace; if (namespaceURI === HTML_NAMESPACE) { namespaceURI = getIntrinsicNamespace(type); } if (namespaceURI === HTML_NAMESPACE) { { isCustomComponentTag = isCustomComponent(type, props); // Should this check be gated by parent namespace? Not sure we want to // allow <SVG> or <mATH>. if (!isCustomComponentTag && type !== type.toLowerCase()) { error('<%s /> is using incorrect casing. ' + 'Use PascalCase for React components, ' + 'or lowercase for HTML elements.', type); } } if (type === 'script') { // Create the script via .innerHTML so its "parser-inserted" flag is // set to true and it does not execute var div = ownerDocument.createElement('div'); div.innerHTML = '<script><' + '/script>'; // eslint-disable-line // This is guaranteed to yield a script element. var firstChild = div.firstChild; domElement = div.removeChild(firstChild); } else if (typeof props.is === 'string') { // $FlowIssue `createElement` should be updated for Web Components domElement = ownerDocument.createElement(type, { is: props.is }); } else { // Separate else branch instead of using `props.is || undefined` above because of a Firefox bug. // See discussion in https://github.com/facebook/react/pull/6896 // and discussion in https://bugzilla.mozilla.org/show_bug.cgi?id=1276240 domElement = ownerDocument.createElement(type); // Normally attributes are assigned in `setInitialDOMProperties`, however the `multiple` and `size` // attributes on `select`s needs to be added before `option`s are inserted. // This prevents: // - a bug where the `select` does not scroll to the correct option because singular // `select` elements automatically pick the first item #13222 // - a bug where the `select` set the first item as selected despite the `size` attribute #14239 // See https://github.com/facebook/react/issues/13222 // and https://github.com/facebook/react/issues/14239 if (type === 'select') { var node = domElement; if (props.multiple) { node.multiple = true; } else if (props.size) { // Setting a size greater than 1 causes a select to behave like `multiple=true`, where // it is possible that no option is selected. // // This is only necessary when a select in "single selection mode". node.size = props.size; } } } } else { domElement = ownerDocument.createElementNS(namespaceURI, type); } { if (namespaceURI === HTML_NAMESPACE) { if (!isCustomComponentTag && Object.prototype.toString.call(domElement) === '[object HTMLUnknownElement]' && !hasOwnProperty.call(warnedUnknownTags, type)) { warnedUnknownTags[type] = true; error('The tag <%s> is unrecognized in this browser. ' + 'If you meant to render a React component, start its name with ' + 'an uppercase letter.', type); } } } return domElement; } function createTextNode(text, rootContainerElement) { return getOwnerDocumentFromRootContainer(rootContainerElement).createTextNode(text); } function setInitialProperties(domElement, tag, rawProps, rootContainerElement) { var isCustomComponentTag = isCustomComponent(tag, rawProps); { validatePropertiesInDevelopment(tag, rawProps); } // TODO: Make sure that we check isMounted before firing any of these events. var props; switch (tag) { case 'dialog': listenToNonDelegatedEvent('cancel', domElement); listenToNonDelegatedEvent('close', domElement); props = rawProps; break; case 'iframe': case 'object': case 'embed': // We listen to this event in case to ensure emulated bubble // listeners still fire for the load event. listenToNonDelegatedEvent('load', domElement); props = rawProps; break; case 'video': case 'audio': // We listen to these events in case to ensure emulated bubble // listeners still fire for all the media events. for (var i = 0; i < mediaEventTypes.length; i++) { listenToNonDelegatedEvent(mediaEventTypes[i], domElement); } props = rawProps; break; case 'source': // We listen to this event in case to ensure emulated bubble // listeners still fire for the error event. listenToNonDelegatedEvent('error', domElement); props = rawProps; break; case 'img': case 'image': case 'link': // We listen to these events in case to ensure emulated bubble // listeners still fire for error and load events. listenToNonDelegatedEvent('error', domElement); listenToNonDelegatedEvent('load', domElement); props = rawProps; break; case 'details': // We listen to this event in case to ensure emulated bubble // listeners still fire for the toggle event. listenToNonDelegatedEvent('toggle', domElement); props = rawProps; break; case 'input': initWrapperState(domElement, rawProps); props = getHostProps(domElement, rawProps); // We listen to this event in case to ensure emulated bubble // listeners still fire for the invalid event. listenToNonDelegatedEvent('invalid', domElement); break; case 'option': validateProps(domElement, rawProps); props = rawProps; break; case 'select': initWrapperState$1(domElement, rawProps); props = getHostProps$1(domElement, rawProps); // We listen to this event in case to ensure emulated bubble // listeners still fire for the invalid event. listenToNonDelegatedEvent('invalid', domElement); break; case 'textarea': initWrapperState$2(domElement, rawProps); props = getHostProps$2(domElement, rawProps); // We listen to this event in case to ensure emulated bubble // listeners still fire for the invalid event. listenToNonDelegatedEvent('invalid', domElement); break; default: props = rawProps; } assertValidProps(tag, props); setInitialDOMProperties(tag, domElement, rootContainerElement, props, isCustomComponentTag); switch (tag) { case 'input': // TODO: Make sure we check if this is still unmounted or do any clean // up necessary since we never stop tracking anymore. track(domElement); postMountWrapper(domElement, rawProps, false); break; case 'textarea': // TODO: Make sure we check if this is still unmounted or do any clean // up necessary since we never stop tracking anymore. track(domElement); postMountWrapper$3(domElement); break; case 'option': postMountWrapper$1(domElement, rawProps); break; case 'select': postMountWrapper$2(domElement, rawProps); break; default: if (typeof props.onClick === 'function') { // TODO: This cast may not be sound for SVG, MathML or custom elements. trapClickOnNonInteractiveElement(domElement); } break; } } // Calculate the diff between the two objects. function diffProperties(domElement, tag, lastRawProps, nextRawProps, rootContainerElement) { { validatePropertiesInDevelopment(tag, nextRawProps); } var updatePayload = null; var lastProps; var nextProps; switch (tag) { case 'input': lastProps = getHostProps(domElement, lastRawProps); nextProps = getHostProps(domElement, nextRawProps); updatePayload = []; break; case 'select': lastProps = getHostProps$1(domElement, lastRawProps); nextProps = getHostProps$1(domElement, nextRawProps); updatePayload = []; break; case 'textarea': lastProps = getHostProps$2(domElement, lastRawProps); nextProps = getHostProps$2(domElement, nextRawProps); updatePayload = []; break; default: lastProps = lastRawProps; nextProps = nextRawProps; if (typeof lastProps.onClick !== 'function' && typeof nextProps.onClick === 'function') { // TODO: This cast may not be sound for SVG, MathML or custom elements. trapClickOnNonInteractiveElement(domElement); } break; } assertValidProps(tag, nextProps); var propKey; var styleName; var styleUpdates = null; for (propKey in lastProps) { if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey) || lastProps[propKey] == null) { continue; } if (propKey === STYLE) { var lastStyle = lastProps[propKey]; for (styleName in lastStyle) { if (lastStyle.hasOwnProperty(styleName)) { if (!styleUpdates) { styleUpdates = {}; } styleUpdates[styleName] = ''; } } } else if (propKey === DANGEROUSLY_SET_INNER_HTML || propKey === CHILDREN) ; else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING) ; else if (propKey === AUTOFOCUS) ; else if (registrationNameDependencies.hasOwnProperty(propKey)) { // This is a special case. If any listener updates we need to ensure // that the "current" fiber pointer gets updated so we need a commit // to update this element. if (!updatePayload) { updatePayload = []; } } else { // For all other deleted properties we add it to the queue. We use // the allowed property list in the commit phase instead. (updatePayload = updatePayload || []).push(propKey, null); } } for (propKey in nextProps) { var nextProp = nextProps[propKey]; var lastProp = lastProps != null ? lastProps[propKey] : undefined; if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp || nextProp == null && lastProp == null) { continue; } if (propKey === STYLE) { { if (nextProp) { // Freeze the next style object so that we can assume it won't be // mutated. We have already warned for this in the past. Object.freeze(nextProp); } } if (lastProp) { // Unset styles on `lastProp` but not on `nextProp`. for (styleName in lastProp) { if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) { if (!styleUpdates) { styleUpdates = {}; } styleUpdates[styleName] = ''; } } // Update styles that changed since `lastProp`. for (styleName in nextProp) { if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) { if (!styleUpdates) { styleUpdates = {}; } styleUpdates[styleName] = nextProp[styleName]; } } } else { // Relies on `updateStylesByID` not mutating `styleUpdates`. if (!styleUpdates) { if (!updatePayload) { updatePayload = []; } updatePayload.push(propKey, styleUpdates); } styleUpdates = nextProp; } } else if (propKey === DANGEROUSLY_SET_INNER_HTML) { var nextHtml = nextProp ? nextProp[HTML$1] : undefined; var lastHtml = lastProp ? lastProp[HTML$1] : undefined; if (nextHtml != null) { if (lastHtml !== nextHtml) { (updatePayload = updatePayload || []).push(propKey, nextHtml); } } } else if (propKey === CHILDREN) { if (typeof nextProp === 'string' || typeof nextProp === 'number') { (updatePayload = updatePayload || []).push(propKey, '' + nextProp); } } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING) ; else if (registrationNameDependencies.hasOwnProperty(propKey)) { if (nextProp != null) { // We eagerly listen to this even though we haven't committed yet. if ( typeof nextProp !== 'function') { warnForInvalidEventListener(propKey, nextProp); } if (propKey === 'onScroll') { listenToNonDelegatedEvent('scroll', domElement); } } if (!updatePayload && lastProp !== nextProp) { // This is a special case. If any listener updates we need to ensure // that the "current" props pointer gets updated so we need a commit // to update this element. updatePayload = []; } } else { // For any other property we always add it to the queue and then we // filter it out using the allowed property list during the commit. (updatePayload = updatePayload || []).push(propKey, nextProp); } } if (styleUpdates) { { validateShorthandPropertyCollisionInDev(styleUpdates, nextProps[STYLE]); } (updatePayload = updatePayload || []).push(STYLE, styleUpdates); } return updatePayload; } // Apply the diff. function updateProperties(domElement, updatePayload, tag, lastRawProps, nextRawProps) { // Update checked *before* name. // In the middle of an update, it is possible to have multiple checked. // When a checked radio tries to change name, browser makes another radio's checked false. if (tag === 'input' && nextRawProps.type === 'radio' && nextRawProps.name != null) { updateChecked(domElement, nextRawProps); } var wasCustomComponentTag = isCustomComponent(tag, lastRawProps); var isCustomComponentTag = isCustomComponent(tag, nextRawProps); // Apply the diff. updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag); // TODO: Ensure that an update gets scheduled if any of the special props // changed. switch (tag) { case 'input': // Update the wrapper around inputs *after* updating props. This has to // happen after `updateDOMProperties`. Otherwise HTML5 input validations // raise warnings and prevent the new value from being assigned. updateWrapper(domElement, nextRawProps); break; case 'textarea': updateWrapper$1(domElement, nextRawProps); break; case 'select': // <select> value update needs to occur after <option> children // reconciliation postUpdateWrapper(domElement, nextRawProps); break; } } function getPossibleStandardName(propName) { { var lowerCasedName = propName.toLowerCase(); if (!possibleStandardNames.hasOwnProperty(lowerCasedName)) { return null; } return possibleStandardNames[lowerCasedName] || null; } } function diffHydratedProperties(domElement, tag, rawProps, parentNamespace, rootContainerElement, isConcurrentMode, shouldWarnDev) { var isCustomComponentTag; var extraAttributeNames; { isCustomComponentTag = isCustomComponent(tag, rawProps); validatePropertiesInDevelopment(tag, rawProps); } // TODO: Make sure that we check isMounted before firing any of these events. switch (tag) { case 'dialog': listenToNonDelegatedEvent('cancel', domElement); listenToNonDelegatedEvent('close', domElement); break; case 'iframe': case 'object': case 'embed': // We listen to this event in case to ensure emulated bubble // listeners still fire for the load event. listenToNonDelegatedEvent('load', domElement); break; case 'video': case 'audio': // We listen to these events in case to ensure emulated bubble // listeners still fire for all the media events. for (var i = 0; i < mediaEventTypes.length; i++) { listenToNonDelegatedEvent(mediaEventTypes[i], domElement); } break; case 'source': // We listen to this event in case to ensure emulated bubble // listeners still fire for the error event. listenToNonDelegatedEvent('error', domElement); break; case 'img': case 'image': case 'link': // We listen to these events in case to ensure emulated bubble // listeners still fire for error and load events. listenToNonDelegatedEvent('error', domElement); listenToNonDelegatedEvent('load', domElement); break; case 'details': // We listen to this event in case to ensure emulated bubble // listeners still fire for the toggle event. listenToNonDelegatedEvent('toggle', domElement); break; case 'input': initWrapperState(domElement, rawProps); // We listen to this event in case to ensure emulated bubble // listeners still fire for the invalid event. listenToNonDelegatedEvent('invalid', domElement); break; case 'option': validateProps(domElement, rawProps); break; case 'select': initWrapperState$1(domElement, rawProps); // We listen to this event in case to ensure emulated bubble // listeners still fire for the invalid event. listenToNonDelegatedEvent('invalid', domElement); break; case 'textarea': initWrapperState$2(domElement, rawProps); // We listen to this event in case to ensure emulated bubble // listeners still fire for the invalid event. listenToNonDelegatedEvent('invalid', domElement); break; } assertValidProps(tag, rawProps); { extraAttributeNames = new Set(); var attributes = domElement.attributes; for (var _i = 0; _i < attributes.length; _i++) { var name = attributes[_i].name.toLowerCase(); switch (name) { // Controlled attributes are not validated // TODO: Only ignore them on controlled tags. case 'value': break; case 'checked': break; case 'selected': break; default: // Intentionally use the original name. // See discussion in https://github.com/facebook/react/pull/10676. extraAttributeNames.add(attributes[_i].name); } } } var updatePayload = null; for (var propKey in rawProps) { if (!rawProps.hasOwnProperty(propKey)) { continue; } var nextProp = rawProps[propKey]; if (propKey === CHILDREN) { // For text content children we compare against textContent. This // might match additional HTML that is hidden when we read it using // textContent. E.g. "foo" will match "f<span>oo</span>" but that still // satisfies our requirement. Our requirement is not to produce perfect // HTML and attributes. Ideally we should preserve structure but it's // ok not to if the visible content is still enough to indicate what // even listeners these nodes might be wired up to. // TODO: Warn if there is more than a single textNode as a child. // TODO: Should we use domElement.firstChild.nodeValue to compare? if (typeof nextProp === 'string') { if (domElement.textContent !== nextProp) { if (rawProps[SUPPRESS_HYDRATION_WARNING] !== true) { checkForUnmatchedText(domElement.textContent, nextProp, isConcurrentMode, shouldWarnDev); } updatePayload = [CHILDREN, nextProp]; } } else if (typeof nextProp === 'number') { if (domElement.textContent !== '' + nextProp) { if (rawProps[SUPPRESS_HYDRATION_WARNING] !== true) { checkForUnmatchedText(domElement.textContent, nextProp, isConcurrentMode, shouldWarnDev); } updatePayload = [CHILDREN, '' + nextProp]; } } } else if (registrationNameDependencies.hasOwnProperty(propKey)) { if (nextProp != null) { if ( typeof nextProp !== 'function') { warnForInvalidEventListener(propKey, nextProp); } if (propKey === 'onScroll') { listenToNonDelegatedEvent('scroll', domElement); } } } else if (shouldWarnDev && true && // Convince Flow we've calculated it (it's DEV-only in this method.) typeof isCustomComponentTag === 'boolean') { // Validate that the properties correspond to their expected values. var serverValue = void 0; var propertyInfo = isCustomComponentTag && enableCustomElementPropertySupport ? null : getPropertyInfo(propKey); if (rawProps[SUPPRESS_HYDRATION_WARNING] === true) ; else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING || // Controlled attributes are not validated // TODO: Only ignore them on controlled tags. propKey === 'value' || propKey === 'checked' || propKey === 'selected') ; else if (propKey === DANGEROUSLY_SET_INNER_HTML) { var serverHTML = domElement.innerHTML; var nextHtml = nextProp ? nextProp[HTML$1] : undefined; if (nextHtml != null) { var expectedHTML = normalizeHTML(domElement, nextHtml); if (expectedHTML !== serverHTML) { warnForPropDifference(propKey, serverHTML, expectedHTML); } } } else if (propKey === STYLE) { // $FlowFixMe - Should be inferred as not undefined. extraAttributeNames.delete(propKey); if (canDiffStyleForHydrationWarning) { var expectedStyle = createDangerousStringForStyles(nextProp); serverValue = domElement.getAttribute('style'); if (expectedStyle !== serverValue) { warnForPropDifference(propKey, serverValue, expectedStyle); } } } else if (isCustomComponentTag && !enableCustomElementPropertySupport) { // $FlowFixMe - Should be inferred as not undefined. extraAttributeNames.delete(propKey.toLowerCase()); serverValue = getValueForAttribute(domElement, propKey, nextProp); if (nextProp !== serverValue) { warnForPropDifference(propKey, serverValue, nextProp); } } else if (!shouldIgnoreAttribute(propKey, propertyInfo, isCustomComponentTag) && !shouldRemoveAttribute(propKey, nextProp, propertyInfo, isCustomComponentTag)) { var isMismatchDueToBadCasing = false; if (propertyInfo !== null) { // $FlowFixMe - Should be inferred as not undefined. extraAttributeNames.delete(propertyInfo.attributeName); serverValue = getValueForProperty(domElement, propKey, nextProp, propertyInfo); } else { var ownNamespace = parentNamespace; if (ownNamespace === HTML_NAMESPACE) { ownNamespace = getIntrinsicNamespace(tag); } if (ownNamespace === HTML_NAMESPACE) { // $FlowFixMe - Should be inferred as not undefined. extraAttributeNames.delete(propKey.toLowerCase()); } else { var standardName = getPossibleStandardName(propKey); if (standardName !== null && standardName !== propKey) { // If an SVG prop is supplied with bad casing, it will // be successfully parsed from HTML, but will produce a mismatch // (and would be incorrectly rendered on the client). // However, we already warn about bad casing elsewhere. // So we'll skip the misleading extra mismatch warning in this case. isMismatchDueToBadCasing = true; // $FlowFixMe - Should be inferred as not undefined. extraAttributeNames.delete(standardName); } // $FlowFixMe - Should be inferred as not undefined. extraAttributeNames.delete(propKey); } serverValue = getValueForAttribute(domElement, propKey, nextProp); } var dontWarnCustomElement = enableCustomElementPropertySupport ; if (!dontWarnCustomElement && nextProp !== serverValue && !isMismatchDueToBadCasing) { warnForPropDifference(propKey, serverValue, nextProp); } } } } { if (shouldWarnDev) { if ( // $FlowFixMe - Should be inferred as not undefined. extraAttributeNames.size > 0 && rawProps[SUPPRESS_HYDRATION_WARNING] !== true) { // $FlowFixMe - Should be inferred as not undefined. warnForExtraAttributes(extraAttributeNames); } } } switch (tag) { case 'input': // TODO: Make sure we check if this is still unmounted or do any clean // up necessary since we never stop tracking anymore. track(domElement); postMountWrapper(domElement, rawProps, true); break; case 'textarea': // TODO: Make sure we check if this is still unmounted or do any clean // up necessary since we never stop tracking anymore. track(domElement); postMountWrapper$3(domElement); break; case 'select': case 'option': // For input and textarea we current always set the value property at // post mount to force it to diverge from attributes. However, for // option and select we don't quite do the same thing and select // is not resilient to the DOM state changing so we don't do that here. // TODO: Consider not doing this for input and textarea. break; default: if (typeof rawProps.onClick === 'function') { // TODO: This cast may not be sound for SVG, MathML or custom elements. trapClickOnNonInteractiveElement(domElement); } break; } return updatePayload; } function diffHydratedText(textNode, text, isConcurrentMode) { var isDifferent = textNode.nodeValue !== text; return isDifferent; } function warnForDeletedHydratableElement(parentNode, child) { { if (didWarnInvalidHydration) { return; } didWarnInvalidHydration = true; error('Did not expect server HTML to contain a <%s> in <%s>.', child.nodeName.toLowerCase(), parentNode.nodeName.toLowerCase()); } } function warnForDeletedHydratableText(parentNode, child) { { if (didWarnInvalidHydration) { return; } didWarnInvalidHydration = true; error('Did not expect server HTML to contain the text node "%s" in <%s>.', child.nodeValue, parentNode.nodeName.toLowerCase()); } } function warnForInsertedHydratedElement(parentNode, tag, props) { { if (didWarnInvalidHydration) { return; } didWarnInvalidHydration = true; error('Expected server HTML to contain a matching <%s> in <%s>.', tag, parentNode.nodeName.toLowerCase()); } } function warnForInsertedHydratedText(parentNode, text) { { if (text === '') { // We expect to insert empty text nodes since they're not represented in // the HTML. // TODO: Remove this special case if we can just avoid inserting empty // text nodes. return; } if (didWarnInvalidHydration) { return; } didWarnInvalidHydration = true; error('Expected server HTML to contain a matching text node for "%s" in <%s>.', text, parentNode.nodeName.toLowerCase()); } } function restoreControlledState$3(domElement, tag, props) { switch (tag) { case 'input': restoreControlledState(domElement, props); return; case 'textarea': restoreControlledState$2(domElement, props); return; case 'select': restoreControlledState$1(domElement, props); return; } } var validateDOMNesting = function () {}; var updatedAncestorInfo = function () {}; { // This validation code was written based on the HTML5 parsing spec: // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope // // Note: this does not catch all invalid nesting, nor does it try to (as it's // not clear what practical benefit doing so provides); instead, we warn only // for cases where the parser will give a parse tree differing from what React // intended. For example, <b><div></div></b> is invalid but we don't warn // because it still parses correctly; we do warn for other cases like nested // <p> tags where the beginning of the second element implicitly closes the // first, causing a confusing mess. // https://html.spec.whatwg.org/multipage/syntax.html#special var specialTags = ['address', 'applet', 'area', 'article', 'aside', 'base', 'basefont', 'bgsound', 'blockquote', 'body', 'br', 'button', 'caption', 'center', 'col', 'colgroup', 'dd', 'details', 'dir', 'div', 'dl', 'dt', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'iframe', 'img', 'input', 'isindex', 'li', 'link', 'listing', 'main', 'marquee', 'menu', 'menuitem', 'meta', 'nav', 'noembed', 'noframes', 'noscript', 'object', 'ol', 'p', 'param', 'plaintext', 'pre', 'script', 'section', 'select', 'source', 'style', 'summary', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul', 'wbr', 'xmp']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope var inScopeTags = ['applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object', 'template', // https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point // TODO: Distinguish by namespace here -- for <title>, including it here // errs on the side of fewer warnings 'foreignObject', 'desc', 'title']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope var buttonScopeTags = inScopeTags.concat(['button']); // https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags var impliedEndTags = ['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt']; var emptyAncestorInfo = { current: null, formTag: null, aTagInScope: null, buttonTagInScope: null, nobrTagInScope: null, pTagInButtonScope: null, listItemTagAutoclosing: null, dlItemTagAutoclosing: null }; updatedAncestorInfo = function (oldInfo, tag) { var ancestorInfo = assign({}, oldInfo || emptyAncestorInfo); var info = { tag: tag }; if (inScopeTags.indexOf(tag) !== -1) { ancestorInfo.aTagInScope = null; ancestorInfo.buttonTagInScope = null; ancestorInfo.nobrTagInScope = null; } if (buttonScopeTags.indexOf(tag) !== -1) { ancestorInfo.pTagInButtonScope = null; } // See rules for 'li', 'dd', 'dt' start tags in // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody if (specialTags.indexOf(tag) !== -1 && tag !== 'address' && tag !== 'div' && tag !== 'p') { ancestorInfo.listItemTagAutoclosing = null; ancestorInfo.dlItemTagAutoclosing = null; } ancestorInfo.current = info; if (tag === 'form') { ancestorInfo.formTag = info; } if (tag === 'a') { ancestorInfo.aTagInScope = info; } if (tag === 'button') { ancestorInfo.buttonTagInScope = info; } if (tag === 'nobr') { ancestorInfo.nobrTagInScope = info; } if (tag === 'p') { ancestorInfo.pTagInButtonScope = info; } if (tag === 'li') { ancestorInfo.listItemTagAutoclosing = info; } if (tag === 'dd' || tag === 'dt') { ancestorInfo.dlItemTagAutoclosing = info; } return ancestorInfo; }; /** * Returns whether */ var isTagValidWithParent = function (tag, parentTag) { // First, let's check if we're in an unusual parsing mode... switch (parentTag) { // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect case 'select': return tag === 'option' || tag === 'optgroup' || tag === '#text'; case 'optgroup': return tag === 'option' || tag === '#text'; // Strictly speaking, seeing an <option> doesn't mean we're in a <select> // but case 'option': return tag === '#text'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption // No special behavior since these rules fall back to "in body" mode for // all except special table nodes which cause bad parsing behavior anyway. // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr case 'tr': return tag === 'th' || tag === 'td' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody case 'tbody': case 'thead': case 'tfoot': return tag === 'tr' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup case 'colgroup': return tag === 'col' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable case 'table': return tag === 'caption' || tag === 'colgroup' || tag === 'tbody' || tag === 'tfoot' || tag === 'thead' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead case 'head': return tag === 'base' || tag === 'basefont' || tag === 'bgsound' || tag === 'link' || tag === 'meta' || tag === 'title' || tag === 'noscript' || tag === 'noframes' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/semantics.html#the-html-element case 'html': return tag === 'head' || tag === 'body' || tag === 'frameset'; case 'frameset': return tag === 'frame'; case '#document': return tag === 'html'; } // Probably in the "in body" parsing mode, so we outlaw only tag combos // where the parsing rules cause implicit opens or closes to be added. // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody switch (tag) { case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': return parentTag !== 'h1' && parentTag !== 'h2' && parentTag !== 'h3' && parentTag !== 'h4' && parentTag !== 'h5' && parentTag !== 'h6'; case 'rp': case 'rt': return impliedEndTags.indexOf(parentTag) === -1; case 'body': case 'caption': case 'col': case 'colgroup': case 'frameset': case 'frame': case 'head': case 'html': case 'tbody': case 'td': case 'tfoot': case 'th': case 'thead': case 'tr': // These tags are only valid with a few parents that have special child // parsing rules -- if we're down here, then none of those matched and // so we allow it only if we don't know what the parent is, as all other // cases are invalid. return parentTag == null; } return true; }; /** * Returns whether */ var findInvalidAncestorForTag = function (tag, ancestorInfo) { switch (tag) { case 'address': case 'article': case 'aside': case 'blockquote': case 'center': case 'details': case 'dialog': case 'dir': case 'div': case 'dl': case 'fieldset': case 'figcaption': case 'figure': case 'footer': case 'header': case 'hgroup': case 'main': case 'menu': case 'nav': case 'ol': case 'p': case 'section': case 'summary': case 'ul': case 'pre': case 'listing': case 'table': case 'hr': case 'xmp': case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': return ancestorInfo.pTagInButtonScope; case 'form': return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope; case 'li': return ancestorInfo.listItemTagAutoclosing; case 'dd': case 'dt': return ancestorInfo.dlItemTagAutoclosing; case 'button': return ancestorInfo.buttonTagInScope; case 'a': // Spec says something about storing a list of markers, but it sounds // equivalent to this check. return ancestorInfo.aTagInScope; case 'nobr': return ancestorInfo.nobrTagInScope; } return null; }; var didWarn$1 = {}; validateDOMNesting = function (childTag, childText, ancestorInfo) { ancestorInfo = ancestorInfo || emptyAncestorInfo; var parentInfo = ancestorInfo.current; var parentTag = parentInfo && parentInfo.tag; if (childText != null) { if (childTag != null) { error('validateDOMNesting: when childText is passed, childTag should be null'); } childTag = '#text'; } var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo; var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo); var invalidParentOrAncestor = invalidParent || invalidAncestor; if (!invalidParentOrAncestor) { return; } var ancestorTag = invalidParentOrAncestor.tag; var warnKey = !!invalidParent + '|' + childTag + '|' + ancestorTag; if (didWarn$1[warnKey]) { return; } didWarn$1[warnKey] = true; var tagDisplayName = childTag; var whitespaceInfo = ''; if (childTag === '#text') { if (/\S/.test(childText)) { tagDisplayName = 'Text nodes'; } else { tagDisplayName = 'Whitespace text nodes'; whitespaceInfo = " Make sure you don't have any extra whitespace between tags on " + 'each line of your source code.'; } } else { tagDisplayName = '<' + childTag + '>'; } if (invalidParent) { var info = ''; if (ancestorTag === 'table' && childTag === 'tr') { info += ' Add a <tbody>, <thead> or <tfoot> to your code to match the DOM tree generated by ' + 'the browser.'; } error('validateDOMNesting(...): %s cannot appear as a child of <%s>.%s%s', tagDisplayName, ancestorTag, whitespaceInfo, info); } else { error('validateDOMNesting(...): %s cannot appear as a descendant of ' + '<%s>.', tagDisplayName, ancestorTag); } }; } var SUPPRESS_HYDRATION_WARNING$1 = 'suppressHydrationWarning'; var SUSPENSE_START_DATA = '$'; var SUSPENSE_END_DATA = '/$'; var SUSPENSE_PENDING_START_DATA = '$?'; var SUSPENSE_FALLBACK_START_DATA = '$!'; var STYLE$1 = 'style'; var eventsEnabled = null; var selectionInformation = null; function getRootHostContext(rootContainerInstance) { var type; var namespace; var nodeType = rootContainerInstance.nodeType; switch (nodeType) { case DOCUMENT_NODE: case DOCUMENT_FRAGMENT_NODE: { type = nodeType === DOCUMENT_NODE ? '#document' : '#fragment'; var root = rootContainerInstance.documentElement; namespace = root ? root.namespaceURI : getChildNamespace(null, ''); break; } default: { var container = nodeType === COMMENT_NODE ? rootContainerInstance.parentNode : rootContainerInstance; var ownNamespace = container.namespaceURI || null; type = container.tagName; namespace = getChildNamespace(ownNamespace, type); break; } } { var validatedTag = type.toLowerCase(); var ancestorInfo = updatedAncestorInfo(null, validatedTag); return { namespace: namespace, ancestorInfo: ancestorInfo }; } } function getChildHostContext(parentHostContext, type, rootContainerInstance) { { var parentHostContextDev = parentHostContext; var namespace = getChildNamespace(parentHostContextDev.namespace, type); var ancestorInfo = updatedAncestorInfo(parentHostContextDev.ancestorInfo, type); return { namespace: namespace, ancestorInfo: ancestorInfo }; } } function getPublicInstance(instance) { return instance; } function prepareForCommit(containerInfo) { eventsEnabled = isEnabled(); selectionInformation = getSelectionInformation(); var activeInstance = null; setEnabled(false); return activeInstance; } function resetAfterCommit(containerInfo) { restoreSelection(selectionInformation); setEnabled(eventsEnabled); eventsEnabled = null; selectionInformation = null; } function createInstance(type, props, rootContainerInstance, hostContext, internalInstanceHandle) { var parentNamespace; { // TODO: take namespace into account when validating. var hostContextDev = hostContext; validateDOMNesting(type, null, hostContextDev.ancestorInfo); if (typeof props.children === 'string' || typeof props.children === 'number') { var string = '' + props.children; var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type); validateDOMNesting(null, string, ownAncestorInfo); } parentNamespace = hostContextDev.namespace; } var domElement = createElement(type, props, rootContainerInstance, parentNamespace); precacheFiberNode(internalInstanceHandle, domElement); updateFiberProps(domElement, props); return domElement; } function appendInitialChild(parentInstance, child) { parentInstance.appendChild(child); } function finalizeInitialChildren(domElement, type, props, rootContainerInstance, hostContext) { setInitialProperties(domElement, type, props, rootContainerInstance); switch (type) { case 'button': case 'input': case 'select': case 'textarea': return !!props.autoFocus; case 'img': return true; default: return false; } } function prepareUpdate(domElement, type, oldProps, newProps, rootContainerInstance, hostContext) { { var hostContextDev = hostContext; if (typeof newProps.children !== typeof oldProps.children && (typeof newProps.children === 'string' || typeof newProps.children === 'number')) { var string = '' + newProps.children; var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type); validateDOMNesting(null, string, ownAncestorInfo); } } return diffProperties(domElement, type, oldProps, newProps); } function shouldSetTextContent(type, props) { return type === 'textarea' || type === 'noscript' || typeof props.children === 'string' || typeof props.children === 'number' || typeof props.dangerouslySetInnerHTML === 'object' && props.dangerouslySetInnerHTML !== null && props.dangerouslySetInnerHTML.__html != null; } function createTextInstance(text, rootContainerInstance, hostContext, internalInstanceHandle) { { var hostContextDev = hostContext; validateDOMNesting(null, text, hostContextDev.ancestorInfo); } var textNode = createTextNode(text, rootContainerInstance); precacheFiberNode(internalInstanceHandle, textNode); return textNode; } function getCurrentEventPriority() { var currentEvent = window.event; if (currentEvent === undefined) { return DefaultEventPriority; } return getEventPriority(currentEvent.type); } // if a component just imports ReactDOM (e.g. for findDOMNode). // Some environments might not have setTimeout or clearTimeout. var scheduleTimeout = typeof setTimeout === 'function' ? setTimeout : undefined; var cancelTimeout = typeof clearTimeout === 'function' ? clearTimeout : undefined; var noTimeout = -1; var localPromise = typeof Promise === 'function' ? Promise : undefined; // ------------------- var scheduleMicrotask = typeof queueMicrotask === 'function' ? queueMicrotask : typeof localPromise !== 'undefined' ? function (callback) { return localPromise.resolve(null).then(callback).catch(handleErrorInNextTick); } : scheduleTimeout; // TODO: Determine the best fallback here. function handleErrorInNextTick(error) { setTimeout(function () { throw error; }); } // ------------------- function commitMount(domElement, type, newProps, internalInstanceHandle) { // Despite the naming that might imply otherwise, this method only // fires if there is an `Update` effect scheduled during mounting. // This happens if `finalizeInitialChildren` returns `true` (which it // does to implement the `autoFocus` attribute on the client). But // there are also other cases when this might happen (such as patching // up text content during hydration mismatch). So we'll check this again. switch (type) { case 'button': case 'input': case 'select': case 'textarea': if (newProps.autoFocus) { domElement.focus(); } return; case 'img': { if (newProps.src) { domElement.src = newProps.src; } return; } } } function commitUpdate(domElement, updatePayload, type, oldProps, newProps, internalInstanceHandle) { // Apply the diff to the DOM node. updateProperties(domElement, updatePayload, type, oldProps, newProps); // Update the props handle so that we know which props are the ones with // with current event handlers. updateFiberProps(domElement, newProps); } function resetTextContent(domElement) { setTextContent(domElement, ''); } function commitTextUpdate(textInstance, oldText, newText) { textInstance.nodeValue = newText; } function appendChild(parentInstance, child) { parentInstance.appendChild(child); } function appendChildToContainer(container, child) { var parentNode; if (container.nodeType === COMMENT_NODE) { parentNode = container.parentNode; parentNode.insertBefore(child, container); } else { parentNode = container; parentNode.appendChild(child); } // This container might be used for a portal. // If something inside a portal is clicked, that click should bubble // through the React tree. However, on Mobile Safari the click would // never bubble through the *DOM* tree unless an ancestor with onclick // event exists. So we wouldn't see it and dispatch it. // This is why we ensure that non React root containers have inline onclick // defined. // https://github.com/facebook/react/issues/11918 var reactRootContainer = container._reactRootContainer; if ((reactRootContainer === null || reactRootContainer === undefined) && parentNode.onclick === null) { // TODO: This cast may not be sound for SVG, MathML or custom elements. trapClickOnNonInteractiveElement(parentNode); } } function insertBefore(parentInstance, child, beforeChild) { parentInstance.insertBefore(child, beforeChild); } function insertInContainerBefore(container, child, beforeChild) { if (container.nodeType === COMMENT_NODE) { container.parentNode.insertBefore(child, beforeChild); } else { container.insertBefore(child, beforeChild); } } function removeChild(parentInstance, child) { parentInstance.removeChild(child); } function removeChildFromContainer(container, child) { if (container.nodeType === COMMENT_NODE) { container.parentNode.removeChild(child); } else { container.removeChild(child); } } function clearSuspenseBoundary(parentInstance, suspenseInstance) { var node = suspenseInstance; // Delete all nodes within this suspense boundary. // There might be nested nodes so we need to keep track of how // deep we are and only break out when we're back on top. var depth = 0; do { var nextNode = node.nextSibling; parentInstance.removeChild(node); if (nextNode && nextNode.nodeType === COMMENT_NODE) { var data = nextNode.data; if (data === SUSPENSE_END_DATA) { if (depth === 0) { parentInstance.removeChild(nextNode); // Retry if any event replaying was blocked on this. retryIfBlockedOn(suspenseInstance); return; } else { depth--; } } else if (data === SUSPENSE_START_DATA || data === SUSPENSE_PENDING_START_DATA || data === SUSPENSE_FALLBACK_START_DATA) { depth++; } } node = nextNode; } while (node); // TODO: Warn, we didn't find the end comment boundary. // Retry if any event replaying was blocked on this. retryIfBlockedOn(suspenseInstance); } function clearSuspenseBoundaryFromContainer(container, suspenseInstance) { if (container.nodeType === COMMENT_NODE) { clearSuspenseBoundary(container.parentNode, suspenseInstance); } else if (container.nodeType === ELEMENT_NODE) { clearSuspenseBoundary(container, suspenseInstance); } // Retry if any event replaying was blocked on this. retryIfBlockedOn(container); } function hideInstance(instance) { // TODO: Does this work for all element types? What about MathML? Should we // pass host context to this method? instance = instance; var style = instance.style; if (typeof style.setProperty === 'function') { style.setProperty('display', 'none', 'important'); } else { style.display = 'none'; } } function hideTextInstance(textInstance) { textInstance.nodeValue = ''; } function unhideInstance(instance, props) { instance = instance; var styleProp = props[STYLE$1]; var display = styleProp !== undefined && styleProp !== null && styleProp.hasOwnProperty('display') ? styleProp.display : null; instance.style.display = dangerousStyleValue('display', display); } function unhideTextInstance(textInstance, text) { textInstance.nodeValue = text; } function clearContainer(container) { if (container.nodeType === ELEMENT_NODE) { container.textContent = ''; } else if (container.nodeType === DOCUMENT_NODE) { if (container.documentElement) { container.removeChild(container.documentElement); } } } // ------------------- function canHydrateInstance(instance, type, props) { if (instance.nodeType !== ELEMENT_NODE || type.toLowerCase() !== instance.nodeName.toLowerCase()) { return null; } // This has now been refined to an element node. return instance; } function canHydrateTextInstance(instance, text) { if (text === '' || instance.nodeType !== TEXT_NODE) { // Empty strings are not parsed by HTML so there won't be a correct match here. return null; } // This has now been refined to a text node. return instance; } function canHydrateSuspenseInstance(instance) { if (instance.nodeType !== COMMENT_NODE) { // Empty strings are not parsed by HTML so there won't be a correct match here. return null; } // This has now been refined to a suspense node. return instance; } function isSuspenseInstancePending(instance) { return instance.data === SUSPENSE_PENDING_START_DATA; } function isSuspenseInstanceFallback(instance) { return instance.data === SUSPENSE_FALLBACK_START_DATA; } function getSuspenseInstanceFallbackErrorDetails(instance) { var dataset = instance.nextSibling && instance.nextSibling.dataset; var digest, message, stack; if (dataset) { digest = dataset.dgst; { message = dataset.msg; stack = dataset.stck; } } { return { message: message, digest: digest, stack: stack }; } // let value = {message: undefined, hash: undefined}; // const nextSibling = instance.nextSibling; // if (nextSibling) { // const dataset = ((nextSibling: any): HTMLTemplateElement).dataset; // value.message = dataset.msg; // value.hash = dataset.hash; // if (true) { // value.stack = dataset.stack; // } // } // return value; } function registerSuspenseInstanceRetry(instance, callback) { instance._reactRetry = callback; } function getNextHydratable(node) { // Skip non-hydratable nodes. for (; node != null; node = node.nextSibling) { var nodeType = node.nodeType; if (nodeType === ELEMENT_NODE || nodeType === TEXT_NODE) { break; } if (nodeType === COMMENT_NODE) { var nodeData = node.data; if (nodeData === SUSPENSE_START_DATA || nodeData === SUSPENSE_FALLBACK_START_DATA || nodeData === SUSPENSE_PENDING_START_DATA) { break; } if (nodeData === SUSPENSE_END_DATA) { return null; } } } return node; } function getNextHydratableSibling(instance) { return getNextHydratable(instance.nextSibling); } function getFirstHydratableChild(parentInstance) { return getNextHydratable(parentInstance.firstChild); } function getFirstHydratableChildWithinContainer(parentContainer) { return getNextHydratable(parentContainer.firstChild); } function getFirstHydratableChildWithinSuspenseInstance(parentInstance) { return getNextHydratable(parentInstance.nextSibling); } function hydrateInstance(instance, type, props, rootContainerInstance, hostContext, internalInstanceHandle, shouldWarnDev) { precacheFiberNode(internalInstanceHandle, instance); // TODO: Possibly defer this until the commit phase where all the events // get attached. updateFiberProps(instance, props); var parentNamespace; { var hostContextDev = hostContext; parentNamespace = hostContextDev.namespace; } // TODO: Temporary hack to check if we're in a concurrent root. We can delete // when the legacy root API is removed. var isConcurrentMode = (internalInstanceHandle.mode & ConcurrentMode) !== NoMode; return diffHydratedProperties(instance, type, props, parentNamespace, rootContainerInstance, isConcurrentMode, shouldWarnDev); } function hydrateTextInstance(textInstance, text, internalInstanceHandle, shouldWarnDev) { precacheFiberNode(internalInstanceHandle, textInstance); // TODO: Temporary hack to check if we're in a concurrent root. We can delete // when the legacy root API is removed. var isConcurrentMode = (internalInstanceHandle.mode & ConcurrentMode) !== NoMode; return diffHydratedText(textInstance, text); } function hydrateSuspenseInstance(suspenseInstance, internalInstanceHandle) { precacheFiberNode(internalInstanceHandle, suspenseInstance); } function getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance) { var node = suspenseInstance.nextSibling; // Skip past all nodes within this suspense boundary. // There might be nested nodes so we need to keep track of how // deep we are and only break out when we're back on top. var depth = 0; while (node) { if (node.nodeType === COMMENT_NODE) { var data = node.data; if (data === SUSPENSE_END_DATA) { if (depth === 0) { return getNextHydratableSibling(node); } else { depth--; } } else if (data === SUSPENSE_START_DATA || data === SUSPENSE_FALLBACK_START_DATA || data === SUSPENSE_PENDING_START_DATA) { depth++; } } node = node.nextSibling; } // TODO: Warn, we didn't find the end comment boundary. return null; } // Returns the SuspenseInstance if this node is a direct child of a // SuspenseInstance. I.e. if its previous sibling is a Comment with // SUSPENSE_x_START_DATA. Otherwise, null. function getParentSuspenseInstance(targetInstance) { var node = targetInstance.previousSibling; // Skip past all nodes within this suspense boundary. // There might be nested nodes so we need to keep track of how // deep we are and only break out when we're back on top. var depth = 0; while (node) { if (node.nodeType === COMMENT_NODE) { var data = node.data; if (data === SUSPENSE_START_DATA || data === SUSPENSE_FALLBACK_START_DATA || data === SUSPENSE_PENDING_START_DATA) { if (depth === 0) { return node; } else { depth--; } } else if (data === SUSPENSE_END_DATA) { depth++; } } node = node.previousSibling; } return null; } function commitHydratedContainer(container) { // Retry if any event replaying was blocked on this. retryIfBlockedOn(container); } function commitHydratedSuspenseInstance(suspenseInstance) { // Retry if any event replaying was blocked on this. retryIfBlockedOn(suspenseInstance); } function shouldDeleteUnhydratedTailInstances(parentType) { return parentType !== 'head' && parentType !== 'body'; } function didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, text, isConcurrentMode) { var shouldWarnDev = true; checkForUnmatchedText(textInstance.nodeValue, text, isConcurrentMode, shouldWarnDev); } function didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, text, isConcurrentMode) { if (parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) { var shouldWarnDev = true; checkForUnmatchedText(textInstance.nodeValue, text, isConcurrentMode, shouldWarnDev); } } function didNotHydrateInstanceWithinContainer(parentContainer, instance) { { if (instance.nodeType === ELEMENT_NODE) { warnForDeletedHydratableElement(parentContainer, instance); } else if (instance.nodeType === COMMENT_NODE) ; else { warnForDeletedHydratableText(parentContainer, instance); } } } function didNotHydrateInstanceWithinSuspenseInstance(parentInstance, instance) { { // $FlowFixMe: Only Element or Document can be parent nodes. var parentNode = parentInstance.parentNode; if (parentNode !== null) { if (instance.nodeType === ELEMENT_NODE) { warnForDeletedHydratableElement(parentNode, instance); } else if (instance.nodeType === COMMENT_NODE) ; else { warnForDeletedHydratableText(parentNode, instance); } } } } function didNotHydrateInstance(parentType, parentProps, parentInstance, instance, isConcurrentMode) { { if (isConcurrentMode || parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) { if (instance.nodeType === ELEMENT_NODE) { warnForDeletedHydratableElement(parentInstance, instance); } else if (instance.nodeType === COMMENT_NODE) ; else { warnForDeletedHydratableText(parentInstance, instance); } } } } function didNotFindHydratableInstanceWithinContainer(parentContainer, type, props) { { warnForInsertedHydratedElement(parentContainer, type); } } function didNotFindHydratableTextInstanceWithinContainer(parentContainer, text) { { warnForInsertedHydratedText(parentContainer, text); } } function didNotFindHydratableInstanceWithinSuspenseInstance(parentInstance, type, props) { { // $FlowFixMe: Only Element or Document can be parent nodes. var parentNode = parentInstance.parentNode; if (parentNode !== null) warnForInsertedHydratedElement(parentNode, type); } } function didNotFindHydratableTextInstanceWithinSuspenseInstance(parentInstance, text) { { // $FlowFixMe: Only Element or Document can be parent nodes. var parentNode = parentInstance.parentNode; if (parentNode !== null) warnForInsertedHydratedText(parentNode, text); } } function didNotFindHydratableInstance(parentType, parentProps, parentInstance, type, props, isConcurrentMode) { { if (isConcurrentMode || parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) { warnForInsertedHydratedElement(parentInstance, type); } } } function didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, text, isConcurrentMode) { { if (isConcurrentMode || parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) { warnForInsertedHydratedText(parentInstance, text); } } } function errorHydratingContainer(parentContainer) { { // TODO: This gets logged by onRecoverableError, too, so we should be // able to remove it. error('An error occurred during hydration. The server HTML was replaced with client content in <%s>.', parentContainer.nodeName.toLowerCase()); } } function preparePortalMount(portalInstance) { listenToAllSupportedEvents(portalInstance); } var randomKey = Math.random().toString(36).slice(2); var internalInstanceKey = '__reactFiber$' + randomKey; var internalPropsKey = '__reactProps$' + randomKey; var internalContainerInstanceKey = '__reactContainer$' + randomKey; var internalEventHandlersKey = '__reactEvents$' + randomKey; var internalEventHandlerListenersKey = '__reactListeners$' + randomKey; var internalEventHandlesSetKey = '__reactHandles$' + randomKey; function detachDeletedInstance(node) { // TODO: This function is only called on host components. I don't think all of // these fields are relevant. delete node[internalInstanceKey]; delete node[internalPropsKey]; delete node[internalEventHandlersKey]; delete node[internalEventHandlerListenersKey]; delete node[internalEventHandlesSetKey]; } function precacheFiberNode(hostInst, node) { node[internalInstanceKey] = hostInst; } function markContainerAsRoot(hostRoot, node) { node[internalContainerInstanceKey] = hostRoot; } function unmarkContainerAsRoot(node) { node[internalContainerInstanceKey] = null; } function isContainerMarkedAsRoot(node) { return !!node[internalContainerInstanceKey]; } // Given a DOM node, return the closest HostComponent or HostText fiber ancestor. // If the target node is part of a hydrated or not yet rendered subtree, then // this may also return a SuspenseComponent or HostRoot to indicate that. // Conceptually the HostRoot fiber is a child of the Container node. So if you // pass the Container node as the targetNode, you will not actually get the // HostRoot back. To get to the HostRoot, you need to pass a child of it. // The same thing applies to Suspense boundaries. function getClosestInstanceFromNode(targetNode) { var targetInst = targetNode[internalInstanceKey]; if (targetInst) { // Don't return HostRoot or SuspenseComponent here. return targetInst; } // If the direct event target isn't a React owned DOM node, we need to look // to see if one of its parents is a React owned DOM node. var parentNode = targetNode.parentNode; while (parentNode) { // We'll check if this is a container root that could include // React nodes in the future. We need to check this first because // if we're a child of a dehydrated container, we need to first // find that inner container before moving on to finding the parent // instance. Note that we don't check this field on the targetNode // itself because the fibers are conceptually between the container // node and the first child. It isn't surrounding the container node. // If it's not a container, we check if it's an instance. targetInst = parentNode[internalContainerInstanceKey] || parentNode[internalInstanceKey]; if (targetInst) { // Since this wasn't the direct target of the event, we might have // stepped past dehydrated DOM nodes to get here. However they could // also have been non-React nodes. We need to answer which one. // If we the instance doesn't have any children, then there can't be // a nested suspense boundary within it. So we can use this as a fast // bailout. Most of the time, when people add non-React children to // the tree, it is using a ref to a child-less DOM node. // Normally we'd only need to check one of the fibers because if it // has ever gone from having children to deleting them or vice versa // it would have deleted the dehydrated boundary nested inside already. // However, since the HostRoot starts out with an alternate it might // have one on the alternate so we need to check in case this was a // root. var alternate = targetInst.alternate; if (targetInst.child !== null || alternate !== null && alternate.child !== null) { // Next we need to figure out if the node that skipped past is // nested within a dehydrated boundary and if so, which one. var suspenseInstance = getParentSuspenseInstance(targetNode); while (suspenseInstance !== null) { // We found a suspense instance. That means that we haven't // hydrated it yet. Even though we leave the comments in the // DOM after hydrating, and there are boundaries in the DOM // that could already be hydrated, we wouldn't have found them // through this pass since if the target is hydrated it would // have had an internalInstanceKey on it. // Let's get the fiber associated with the SuspenseComponent // as the deepest instance. var targetSuspenseInst = suspenseInstance[internalInstanceKey]; if (targetSuspenseInst) { return targetSuspenseInst; } // If we don't find a Fiber on the comment, it might be because // we haven't gotten to hydrate it yet. There might still be a // parent boundary that hasn't above this one so we need to find // the outer most that is known. suspenseInstance = getParentSuspenseInstance(suspenseInstance); // If we don't find one, then that should mean that the parent // host component also hasn't hydrated yet. We can return it // below since it will bail out on the isMounted check later. } } return targetInst; } targetNode = parentNode; parentNode = targetNode.parentNode; } return null; } /** * Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent * instance, or null if the node was not rendered by this React. */ function getInstanceFromNode(node) { var inst = node[internalInstanceKey] || node[internalContainerInstanceKey]; if (inst) { if (inst.tag === HostComponent || inst.tag === HostText || inst.tag === SuspenseComponent || inst.tag === HostRoot) { return inst; } else { return null; } } return null; } /** * Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding * DOM node. */ function getNodeFromInstance(inst) { if (inst.tag === HostComponent || inst.tag === HostText) { // In Fiber this, is just the state node right now. We assume it will be // a host component or host text. return inst.stateNode; } // Without this first invariant, passing a non-DOM-component triggers the next // invariant for a missing parent, which is super confusing. throw new Error('getNodeFromInstance: Invalid argument.'); } function getFiberCurrentPropsFromNode(node) { return node[internalPropsKey] || null; } function updateFiberProps(node, props) { node[internalPropsKey] = props; } function getEventListenerSet(node) { var elementListenerSet = node[internalEventHandlersKey]; if (elementListenerSet === undefined) { elementListenerSet = node[internalEventHandlersKey] = new Set(); } return elementListenerSet; } var loggedTypeFailures = {}; var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; function setCurrentlyValidatingElement(element) { { if (element) { var owner = element._owner; var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); ReactDebugCurrentFrame$1.setExtraStackFrame(stack); } else { ReactDebugCurrentFrame$1.setExtraStackFrame(null); } } } function checkPropTypes(typeSpecs, values, location, componentName, element) { { // $FlowFixMe This is okay but Flow doesn't know it. var has = Function.call.bind(hasOwnProperty); for (var typeSpecName in typeSpecs) { if (has(typeSpecs, typeSpecName)) { var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. if (typeof typeSpecs[typeSpecName] !== 'function') { // eslint-disable-next-line react-internal/prod-error-codes var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.'); err.name = 'Invariant Violation'; throw err; } error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'); } catch (ex) { error$1 = ex; } if (error$1 && !(error$1 instanceof Error)) { setCurrentlyValidatingElement(element); error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1); setCurrentlyValidatingElement(null); } if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error$1.message] = true; setCurrentlyValidatingElement(element); error('Failed %s type: %s', location, error$1.message); setCurrentlyValidatingElement(null); } } } } } var valueStack = []; var fiberStack; { fiberStack = []; } var index = -1; function createCursor(defaultValue) { return { current: defaultValue }; } function pop(cursor, fiber) { if (index < 0) { { error('Unexpected pop.'); } return; } { if (fiber !== fiberStack[index]) { error('Unexpected Fiber popped.'); } } cursor.current = valueStack[index]; valueStack[index] = null; { fiberStack[index] = null; } index--; } function push(cursor, value, fiber) { index++; valueStack[index] = cursor.current; { fiberStack[index] = fiber; } cursor.current = value; } var warnedAboutMissingGetChildContext; { warnedAboutMissingGetChildContext = {}; } var emptyContextObject = {}; { Object.freeze(emptyContextObject); } // A cursor to the current merged context object on the stack. var contextStackCursor = createCursor(emptyContextObject); // A cursor to a boolean indicating whether the context has changed. var didPerformWorkStackCursor = createCursor(false); // Keep track of the previous context object that was on the stack. // We use this to get access to the parent context after we have already // pushed the next context provider, and now need to merge their contexts. var previousContext = emptyContextObject; function getUnmaskedContext(workInProgress, Component, didPushOwnContextIfProvider) { { if (didPushOwnContextIfProvider && isContextProvider(Component)) { // If the fiber is a context provider itself, when we read its context // we may have already pushed its own child context on the stack. A context // provider should not "see" its own child context. Therefore we read the // previous (parent) context instead for a context provider. return previousContext; } return contextStackCursor.current; } } function cacheContext(workInProgress, unmaskedContext, maskedContext) { { var instance = workInProgress.stateNode; instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext; instance.__reactInternalMemoizedMaskedChildContext = maskedContext; } } function getMaskedContext(workInProgress, unmaskedContext) { { var type = workInProgress.type; var contextTypes = type.contextTypes; if (!contextTypes) { return emptyContextObject; } // Avoid recreating masked context unless unmasked context has changed. // Failing to do this will result in unnecessary calls to componentWillReceiveProps. // This may trigger infinite loops if componentWillReceiveProps calls setState. var instance = workInProgress.stateNode; if (instance && instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext) { return instance.__reactInternalMemoizedMaskedChildContext; } var context = {}; for (var key in contextTypes) { context[key] = unmaskedContext[key]; } { var name = getComponentNameFromFiber(workInProgress) || 'Unknown'; checkPropTypes(contextTypes, context, 'context', name); } // Cache unmasked context so we can avoid recreating masked context unless necessary. // Context is created before the class component is instantiated so check for instance. if (instance) { cacheContext(workInProgress, unmaskedContext, context); } return context; } } function hasContextChanged() { { return didPerformWorkStackCursor.current; } } function isContextProvider(type) { { var childContextTypes = type.childContextTypes; return childContextTypes !== null && childContextTypes !== undefined; } } function popContext(fiber) { { pop(didPerformWorkStackCursor, fiber); pop(contextStackCursor, fiber); } } function popTopLevelContextObject(fiber) { { pop(didPerformWorkStackCursor, fiber); pop(contextStackCursor, fiber); } } function pushTopLevelContextObject(fiber, context, didChange) { { if (contextStackCursor.current !== emptyContextObject) { throw new Error('Unexpected context found on stack. ' + 'This error is likely caused by a bug in React. Please file an issue.'); } push(contextStackCursor, context, fiber); push(didPerformWorkStackCursor, didChange, fiber); } } function processChildContext(fiber, type, parentContext) { { var instance = fiber.stateNode; var childContextTypes = type.childContextTypes; // TODO (bvaughn) Replace this behavior with an invariant() in the future. // It has only been added in Fiber to match the (unintentional) behavior in Stack. if (typeof instance.getChildContext !== 'function') { { var componentName = getComponentNameFromFiber(fiber) || 'Unknown'; if (!warnedAboutMissingGetChildContext[componentName]) { warnedAboutMissingGetChildContext[componentName] = true; error('%s.childContextTypes is specified but there is no getChildContext() method ' + 'on the instance. You can either define getChildContext() on %s or remove ' + 'childContextTypes from it.', componentName, componentName); } } return parentContext; } var childContext = instance.getChildContext(); for (var contextKey in childContext) { if (!(contextKey in childContextTypes)) { throw new Error((getComponentNameFromFiber(fiber) || 'Unknown') + ".getChildContext(): key \"" + contextKey + "\" is not defined in childContextTypes."); } } { var name = getComponentNameFromFiber(fiber) || 'Unknown'; checkPropTypes(childContextTypes, childContext, 'child context', name); } return assign({}, parentContext, childContext); } } function pushContextProvider(workInProgress) { { var instance = workInProgress.stateNode; // We push the context as early as possible to ensure stack integrity. // If the instance does not exist yet, we will push null at first, // and replace it on the stack later when invalidating the context. var memoizedMergedChildContext = instance && instance.__reactInternalMemoizedMergedChildContext || emptyContextObject; // Remember the parent context so we can merge with it later. // Inherit the parent's did-perform-work value to avoid inadvertently blocking updates. previousContext = contextStackCursor.current; push(contextStackCursor, memoizedMergedChildContext, workInProgress); push(didPerformWorkStackCursor, didPerformWorkStackCursor.current, workInProgress); return true; } } function invalidateContextProvider(workInProgress, type, didChange) { { var instance = workInProgress.stateNode; if (!instance) { throw new Error('Expected to have an instance by this point. ' + 'This error is likely caused by a bug in React. Please file an issue.'); } if (didChange) { // Merge parent and own context. // Skip this if we're not updating due to sCU. // This avoids unnecessarily recomputing memoized values. var mergedContext = processChildContext(workInProgress, type, previousContext); instance.__reactInternalMemoizedMergedChildContext = mergedContext; // Replace the old (or empty) context with the new one. // It is important to unwind the context in the reverse order. pop(didPerformWorkStackCursor, workInProgress); pop(contextStackCursor, workInProgress); // Now push the new context and mark that it has changed. push(contextStackCursor, mergedContext, workInProgress); push(didPerformWorkStackCursor, didChange, workInProgress); } else { pop(didPerformWorkStackCursor, workInProgress); push(didPerformWorkStackCursor, didChange, workInProgress); } } } function findCurrentUnmaskedContext(fiber) { { // Currently this is only used with renderSubtreeIntoContainer; not sure if it // makes sense elsewhere if (!isFiberMounted(fiber) || fiber.tag !== ClassComponent) { throw new Error('Expected subtree parent to be a mounted class component. ' + 'This error is likely caused by a bug in React. Please file an issue.'); } var node = fiber; do { switch (node.tag) { case HostRoot: return node.stateNode.context; case ClassComponent: { var Component = node.type; if (isContextProvider(Component)) { return node.stateNode.__reactInternalMemoizedMergedChildContext; } break; } } node = node.return; } while (node !== null); throw new Error('Found unexpected detached subtree parent. ' + 'This error is likely caused by a bug in React. Please file an issue.'); } } var LegacyRoot = 0; var ConcurrentRoot = 1; var syncQueue = null; var includesLegacySyncCallbacks = false; var isFlushingSyncQueue = false; function scheduleSyncCallback(callback) { // Push this callback into an internal queue. We'll flush these either in // the next tick, or earlier if something calls `flushSyncCallbackQueue`. if (syncQueue === null) { syncQueue = [callback]; } else { // Push onto existing queue. Don't need to schedule a callback because // we already scheduled one when we created the queue. syncQueue.push(callback); } } function scheduleLegacySyncCallback(callback) { includesLegacySyncCallbacks = true; scheduleSyncCallback(callback); } function flushSyncCallbacksOnlyInLegacyMode() { // Only flushes the queue if there's a legacy sync callback scheduled. // TODO: There's only a single type of callback: performSyncOnWorkOnRoot. So // it might make more sense for the queue to be a list of roots instead of a // list of generic callbacks. Then we can have two: one for legacy roots, one // for concurrent roots. And this method would only flush the legacy ones. if (includesLegacySyncCallbacks) { flushSyncCallbacks(); } } function flushSyncCallbacks() { if (!isFlushingSyncQueue && syncQueue !== null) { // Prevent re-entrance. isFlushingSyncQueue = true; var i = 0; var previousUpdatePriority = getCurrentUpdatePriority(); try { var isSync = true; var queue = syncQueue; // TODO: Is this necessary anymore? The only user code that runs in this // queue is in the render or commit phases. setCurrentUpdatePriority(DiscreteEventPriority); for (; i < queue.length; i++) { var callback = queue[i]; do { callback = callback(isSync); } while (callback !== null); } syncQueue = null; includesLegacySyncCallbacks = false; } catch (error) { // If something throws, leave the remaining callbacks on the queue. if (syncQueue !== null) { syncQueue = syncQueue.slice(i + 1); } // Resume flushing in the next tick scheduleCallback(ImmediatePriority, flushSyncCallbacks); throw error; } finally { setCurrentUpdatePriority(previousUpdatePriority); isFlushingSyncQueue = false; } } return null; } // TODO: Use the unified fiber stack module instead of this local one? // Intentionally not using it yet to derisk the initial implementation, because // the way we push/pop these values is a bit unusual. If there's a mistake, I'd // rather the ids be wrong than crash the whole reconciler. var forkStack = []; var forkStackIndex = 0; var treeForkProvider = null; var treeForkCount = 0; var idStack = []; var idStackIndex = 0; var treeContextProvider = null; var treeContextId = 1; var treeContextOverflow = ''; function isForkedChild(workInProgress) { warnIfNotHydrating(); return (workInProgress.flags & Forked) !== NoFlags; } function getForksAtLevel(workInProgress) { warnIfNotHydrating(); return treeForkCount; } function getTreeId() { var overflow = treeContextOverflow; var idWithLeadingBit = treeContextId; var id = idWithLeadingBit & ~getLeadingBit(idWithLeadingBit); return id.toString(32) + overflow; } function pushTreeFork(workInProgress, totalChildren) { // This is called right after we reconcile an array (or iterator) of child // fibers, because that's the only place where we know how many children in // the whole set without doing extra work later, or storing addtional // information on the fiber. // // That's why this function is separate from pushTreeId — it's called during // the render phase of the fork parent, not the child, which is where we push // the other context values. // // In the Fizz implementation this is much simpler because the child is // rendered in the same callstack as the parent. // // It might be better to just add a `forks` field to the Fiber type. It would // make this module simpler. warnIfNotHydrating(); forkStack[forkStackIndex++] = treeForkCount; forkStack[forkStackIndex++] = treeForkProvider; treeForkProvider = workInProgress; treeForkCount = totalChildren; } function pushTreeId(workInProgress, totalChildren, index) { warnIfNotHydrating(); idStack[idStackIndex++] = treeContextId; idStack[idStackIndex++] = treeContextOverflow; idStack[idStackIndex++] = treeContextProvider; treeContextProvider = workInProgress; var baseIdWithLeadingBit = treeContextId; var baseOverflow = treeContextOverflow; // The leftmost 1 marks the end of the sequence, non-inclusive. It's not part // of the id; we use it to account for leading 0s. var baseLength = getBitLength(baseIdWithLeadingBit) - 1; var baseId = baseIdWithLeadingBit & ~(1 << baseLength); var slot = index + 1; var length = getBitLength(totalChildren) + baseLength; // 30 is the max length we can store without overflowing, taking into // consideration the leading 1 we use to mark the end of the sequence. if (length > 30) { // We overflowed the bitwise-safe range. Fall back to slower algorithm. // This branch assumes the length of the base id is greater than 5; it won't // work for smaller ids, because you need 5 bits per character. // // We encode the id in multiple steps: first the base id, then the // remaining digits. // // Each 5 bit sequence corresponds to a single base 32 character. So for // example, if the current id is 23 bits long, we can convert 20 of those // bits into a string of 4 characters, with 3 bits left over. // // First calculate how many bits in the base id represent a complete // sequence of characters. var numberOfOverflowBits = baseLength - baseLength % 5; // Then create a bitmask that selects only those bits. var newOverflowBits = (1 << numberOfOverflowBits) - 1; // Select the bits, and convert them to a base 32 string. var newOverflow = (baseId & newOverflowBits).toString(32); // Now we can remove those bits from the base id. var restOfBaseId = baseId >> numberOfOverflowBits; var restOfBaseLength = baseLength - numberOfOverflowBits; // Finally, encode the rest of the bits using the normal algorithm. Because // we made more room, this time it won't overflow. var restOfLength = getBitLength(totalChildren) + restOfBaseLength; var restOfNewBits = slot << restOfBaseLength; var id = restOfNewBits | restOfBaseId; var overflow = newOverflow + baseOverflow; treeContextId = 1 << restOfLength | id; treeContextOverflow = overflow; } else { // Normal path var newBits = slot << baseLength; var _id = newBits | baseId; var _overflow = baseOverflow; treeContextId = 1 << length | _id; treeContextOverflow = _overflow; } } function pushMaterializedTreeId(workInProgress) { warnIfNotHydrating(); // This component materialized an id. This will affect any ids that appear // in its children. var returnFiber = workInProgress.return; if (returnFiber !== null) { var numberOfForks = 1; var slotIndex = 0; pushTreeFork(workInProgress, numberOfForks); pushTreeId(workInProgress, numberOfForks, slotIndex); } } function getBitLength(number) { return 32 - clz32(number); } function getLeadingBit(id) { return 1 << getBitLength(id) - 1; } function popTreeContext(workInProgress) { // Restore the previous values. // This is a bit more complicated than other context-like modules in Fiber // because the same Fiber may appear on the stack multiple times and for // different reasons. We have to keep popping until the work-in-progress is // no longer at the top of the stack. while (workInProgress === treeForkProvider) { treeForkProvider = forkStack[--forkStackIndex]; forkStack[forkStackIndex] = null; treeForkCount = forkStack[--forkStackIndex]; forkStack[forkStackIndex] = null; } while (workInProgress === treeContextProvider) { treeContextProvider = idStack[--idStackIndex]; idStack[idStackIndex] = null; treeContextOverflow = idStack[--idStackIndex]; idStack[idStackIndex] = null; treeContextId = idStack[--idStackIndex]; idStack[idStackIndex] = null; } } function getSuspendedTreeContext() { warnIfNotHydrating(); if (treeContextProvider !== null) { return { id: treeContextId, overflow: treeContextOverflow }; } else { return null; } } function restoreSuspendedTreeContext(workInProgress, suspendedContext) { warnIfNotHydrating(); idStack[idStackIndex++] = treeContextId; idStack[idStackIndex++] = treeContextOverflow; idStack[idStackIndex++] = treeContextProvider; treeContextId = suspendedContext.id; treeContextOverflow = suspendedContext.overflow; treeContextProvider = workInProgress; } function warnIfNotHydrating() { { if (!getIsHydrating()) { error('Expected to be hydrating. This is a bug in React. Please file ' + 'an issue.'); } } } // This may have been an insertion or a hydration. var hydrationParentFiber = null; var nextHydratableInstance = null; var isHydrating = false; // This flag allows for warning supression when we expect there to be mismatches // due to earlier mismatches or a suspended fiber. var didSuspendOrErrorDEV = false; // Hydration errors that were thrown inside this boundary var hydrationErrors = null; function warnIfHydrating() { { if (isHydrating) { error('We should not be hydrating here. This is a bug in React. Please file a bug.'); } } } function markDidThrowWhileHydratingDEV() { { didSuspendOrErrorDEV = true; } } function didSuspendOrErrorWhileHydratingDEV() { { return didSuspendOrErrorDEV; } } function enterHydrationState(fiber) { var parentInstance = fiber.stateNode.containerInfo; nextHydratableInstance = getFirstHydratableChildWithinContainer(parentInstance); hydrationParentFiber = fiber; isHydrating = true; hydrationErrors = null; didSuspendOrErrorDEV = false; return true; } function reenterHydrationStateFromDehydratedSuspenseInstance(fiber, suspenseInstance, treeContext) { nextHydratableInstance = getFirstHydratableChildWithinSuspenseInstance(suspenseInstance); hydrationParentFiber = fiber; isHydrating = true; hydrationErrors = null; didSuspendOrErrorDEV = false; if (treeContext !== null) { restoreSuspendedTreeContext(fiber, treeContext); } return true; } function warnUnhydratedInstance(returnFiber, instance) { { switch (returnFiber.tag) { case HostRoot: { didNotHydrateInstanceWithinContainer(returnFiber.stateNode.containerInfo, instance); break; } case HostComponent: { var isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode; didNotHydrateInstance(returnFiber.type, returnFiber.memoizedProps, returnFiber.stateNode, instance, // TODO: Delete this argument when we remove the legacy root API. isConcurrentMode); break; } case SuspenseComponent: { var suspenseState = returnFiber.memoizedState; if (suspenseState.dehydrated !== null) didNotHydrateInstanceWithinSuspenseInstance(suspenseState.dehydrated, instance); break; } } } } function deleteHydratableInstance(returnFiber, instance) { warnUnhydratedInstance(returnFiber, instance); var childToDelete = createFiberFromHostInstanceForDeletion(); childToDelete.stateNode = instance; childToDelete.return = returnFiber; var deletions = returnFiber.deletions; if (deletions === null) { returnFiber.deletions = [childToDelete]; returnFiber.flags |= ChildDeletion; } else { deletions.push(childToDelete); } } function warnNonhydratedInstance(returnFiber, fiber) { { if (didSuspendOrErrorDEV) { // Inside a boundary that already suspended. We're currently rendering the // siblings of a suspended node. The mismatch may be due to the missing // data, so it's probably a false positive. return; } switch (returnFiber.tag) { case HostRoot: { var parentContainer = returnFiber.stateNode.containerInfo; switch (fiber.tag) { case HostComponent: var type = fiber.type; var props = fiber.pendingProps; didNotFindHydratableInstanceWithinContainer(parentContainer, type); break; case HostText: var text = fiber.pendingProps; didNotFindHydratableTextInstanceWithinContainer(parentContainer, text); break; } break; } case HostComponent: { var parentType = returnFiber.type; var parentProps = returnFiber.memoizedProps; var parentInstance = returnFiber.stateNode; switch (fiber.tag) { case HostComponent: { var _type = fiber.type; var _props = fiber.pendingProps; var isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode; didNotFindHydratableInstance(parentType, parentProps, parentInstance, _type, _props, // TODO: Delete this argument when we remove the legacy root API. isConcurrentMode); break; } case HostText: { var _text = fiber.pendingProps; var _isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode; didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, _text, // TODO: Delete this argument when we remove the legacy root API. _isConcurrentMode); break; } } break; } case SuspenseComponent: { var suspenseState = returnFiber.memoizedState; var _parentInstance = suspenseState.dehydrated; if (_parentInstance !== null) switch (fiber.tag) { case HostComponent: var _type2 = fiber.type; var _props2 = fiber.pendingProps; didNotFindHydratableInstanceWithinSuspenseInstance(_parentInstance, _type2); break; case HostText: var _text2 = fiber.pendingProps; didNotFindHydratableTextInstanceWithinSuspenseInstance(_parentInstance, _text2); break; } break; } default: return; } } } function insertNonHydratedInstance(returnFiber, fiber) { fiber.flags = fiber.flags & ~Hydrating | Placement; warnNonhydratedInstance(returnFiber, fiber); } function tryHydrate(fiber, nextInstance) { switch (fiber.tag) { case HostComponent: { var type = fiber.type; var props = fiber.pendingProps; var instance = canHydrateInstance(nextInstance, type); if (instance !== null) { fiber.stateNode = instance; hydrationParentFiber = fiber; nextHydratableInstance = getFirstHydratableChild(instance); return true; } return false; } case HostText: { var text = fiber.pendingProps; var textInstance = canHydrateTextInstance(nextInstance, text); if (textInstance !== null) { fiber.stateNode = textInstance; hydrationParentFiber = fiber; // Text Instances don't have children so there's nothing to hydrate. nextHydratableInstance = null; return true; } return false; } case SuspenseComponent: { var suspenseInstance = canHydrateSuspenseInstance(nextInstance); if (suspenseInstance !== null) { var suspenseState = { dehydrated: suspenseInstance, treeContext: getSuspendedTreeContext(), retryLane: OffscreenLane }; fiber.memoizedState = suspenseState; // Store the dehydrated fragment as a child fiber. // This simplifies the code for getHostSibling and deleting nodes, // since it doesn't have to consider all Suspense boundaries and // check if they're dehydrated ones or not. var dehydratedFragment = createFiberFromDehydratedFragment(suspenseInstance); dehydratedFragment.return = fiber; fiber.child = dehydratedFragment; hydrationParentFiber = fiber; // While a Suspense Instance does have children, we won't step into // it during the first pass. Instead, we'll reenter it later. nextHydratableInstance = null; return true; } return false; } default: return false; } } function shouldClientRenderOnMismatch(fiber) { return (fiber.mode & ConcurrentMode) !== NoMode && (fiber.flags & DidCapture) === NoFlags; } function throwOnHydrationMismatch(fiber) { throw new Error('Hydration failed because the initial UI does not match what was ' + 'rendered on the server.'); } function tryToClaimNextHydratableInstance(fiber) { if (!isHydrating) { return; } var nextInstance = nextHydratableInstance; if (!nextInstance) { if (shouldClientRenderOnMismatch(fiber)) { warnNonhydratedInstance(hydrationParentFiber, fiber); throwOnHydrationMismatch(); } // Nothing to hydrate. Make it an insertion. insertNonHydratedInstance(hydrationParentFiber, fiber); isHydrating = false; hydrationParentFiber = fiber; return; } var firstAttemptedInstance = nextInstance; if (!tryHydrate(fiber, nextInstance)) { if (shouldClientRenderOnMismatch(fiber)) { warnNonhydratedInstance(hydrationParentFiber, fiber); throwOnHydrationMismatch(); } // If we can't hydrate this instance let's try the next one. // We use this as a heuristic. It's based on intuition and not data so it // might be flawed or unnecessary. nextInstance = getNextHydratableSibling(firstAttemptedInstance); var prevHydrationParentFiber = hydrationParentFiber; if (!nextInstance || !tryHydrate(fiber, nextInstance)) { // Nothing to hydrate. Make it an insertion. insertNonHydratedInstance(hydrationParentFiber, fiber); isHydrating = false; hydrationParentFiber = fiber; return; } // We matched the next one, we'll now assume that the first one was // superfluous and we'll delete it. Since we can't eagerly delete it // we'll have to schedule a deletion. To do that, this node needs a dummy // fiber associated with it. deleteHydratableInstance(prevHydrationParentFiber, firstAttemptedInstance); } } function prepareToHydrateHostInstance(fiber, rootContainerInstance, hostContext) { var instance = fiber.stateNode; var shouldWarnIfMismatchDev = !didSuspendOrErrorDEV; var updatePayload = hydrateInstance(instance, fiber.type, fiber.memoizedProps, rootContainerInstance, hostContext, fiber, shouldWarnIfMismatchDev); // TODO: Type this specific to this type of component. fiber.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there // is a new ref we mark this as an update. if (updatePayload !== null) { return true; } return false; } function prepareToHydrateHostTextInstance(fiber) { var textInstance = fiber.stateNode; var textContent = fiber.memoizedProps; var shouldUpdate = hydrateTextInstance(textInstance, textContent, fiber); if (shouldUpdate) { // We assume that prepareToHydrateHostTextInstance is called in a context where the // hydration parent is the parent host component of this host text. var returnFiber = hydrationParentFiber; if (returnFiber !== null) { switch (returnFiber.tag) { case HostRoot: { var parentContainer = returnFiber.stateNode.containerInfo; var isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode; didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, textContent, // TODO: Delete this argument when we remove the legacy root API. isConcurrentMode); break; } case HostComponent: { var parentType = returnFiber.type; var parentProps = returnFiber.memoizedProps; var parentInstance = returnFiber.stateNode; var _isConcurrentMode2 = (returnFiber.mode & ConcurrentMode) !== NoMode; didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, textContent, // TODO: Delete this argument when we remove the legacy root API. _isConcurrentMode2); break; } } } } return shouldUpdate; } function prepareToHydrateHostSuspenseInstance(fiber) { var suspenseState = fiber.memoizedState; var suspenseInstance = suspenseState !== null ? suspenseState.dehydrated : null; if (!suspenseInstance) { throw new Error('Expected to have a hydrated suspense instance. ' + 'This error is likely caused by a bug in React. Please file an issue.'); } hydrateSuspenseInstance(suspenseInstance, fiber); } function skipPastDehydratedSuspenseInstance(fiber) { var suspenseState = fiber.memoizedState; var suspenseInstance = suspenseState !== null ? suspenseState.dehydrated : null; if (!suspenseInstance) { throw new Error('Expected to have a hydrated suspense instance. ' + 'This error is likely caused by a bug in React. Please file an issue.'); } return getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance); } function popToNextHostParent(fiber) { var parent = fiber.return; while (parent !== null && parent.tag !== HostComponent && parent.tag !== HostRoot && parent.tag !== SuspenseComponent) { parent = parent.return; } hydrationParentFiber = parent; } function popHydrationState(fiber) { if (fiber !== hydrationParentFiber) { // We're deeper than the current hydration context, inside an inserted // tree. return false; } if (!isHydrating) { // If we're not currently hydrating but we're in a hydration context, then // we were an insertion and now need to pop up reenter hydration of our // siblings. popToNextHostParent(fiber); isHydrating = true; return false; } // If we have any remaining hydratable nodes, we need to delete them now. // We only do this deeper than head and body since they tend to have random // other nodes in them. We also ignore components with pure text content in // side of them. We also don't delete anything inside the root container. if (fiber.tag !== HostRoot && (fiber.tag !== HostComponent || shouldDeleteUnhydratedTailInstances(fiber.type) && !shouldSetTextContent(fiber.type, fiber.memoizedProps))) { var nextInstance = nextHydratableInstance; if (nextInstance) { if (shouldClientRenderOnMismatch(fiber)) { warnIfUnhydratedTailNodes(fiber); throwOnHydrationMismatch(); } else { while (nextInstance) { deleteHydratableInstance(fiber, nextInstance); nextInstance = getNextHydratableSibling(nextInstance); } } } } popToNextHostParent(fiber); if (fiber.tag === SuspenseComponent) { nextHydratableInstance = skipPastDehydratedSuspenseInstance(fiber); } else { nextHydratableInstance = hydrationParentFiber ? getNextHydratableSibling(fiber.stateNode) : null; } return true; } function hasUnhydratedTailNodes() { return isHydrating && nextHydratableInstance !== null; } function warnIfUnhydratedTailNodes(fiber) { var nextInstance = nextHydratableInstance; while (nextInstance) { warnUnhydratedInstance(fiber, nextInstance); nextInstance = getNextHydratableSibling(nextInstance); } } function resetHydrationState() { hydrationParentFiber = null; nextHydratableInstance = null; isHydrating = false; didSuspendOrErrorDEV = false; } function upgradeHydrationErrorsToRecoverable() { if (hydrationErrors !== null) { // Successfully completed a forced client render. The errors that occurred // during the hydration attempt are now recovered. We will log them in // commit phase, once the entire tree has finished. queueRecoverableErrors(hydrationErrors); hydrationErrors = null; } } function getIsHydrating() { return isHydrating; } function queueHydrationError(error) { if (hydrationErrors === null) { hydrationErrors = [error]; } else { hydrationErrors.push(error); } } var ReactCurrentBatchConfig$1 = ReactSharedInternals.ReactCurrentBatchConfig; var NoTransition = null; function requestCurrentTransition() { return ReactCurrentBatchConfig$1.transition; } var ReactStrictModeWarnings = { recordUnsafeLifecycleWarnings: function (fiber, instance) {}, flushPendingUnsafeLifecycleWarnings: function () {}, recordLegacyContextWarning: function (fiber, instance) {}, flushLegacyContextWarning: function () {}, discardPendingWarnings: function () {} }; { var findStrictRoot = function (fiber) { var maybeStrictRoot = null; var node = fiber; while (node !== null) { if (node.mode & StrictLegacyMode) { maybeStrictRoot = node; } node = node.return; } return maybeStrictRoot; }; var setToSortedString = function (set) { var array = []; set.forEach(function (value) { array.push(value); }); return array.sort().join(', '); }; var pendingComponentWillMountWarnings = []; var pendingUNSAFE_ComponentWillMountWarnings = []; var pendingComponentWillReceivePropsWarnings = []; var pendingUNSAFE_ComponentWillReceivePropsWarnings = []; var pendingComponentWillUpdateWarnings = []; var pendingUNSAFE_ComponentWillUpdateWarnings = []; // Tracks components we have already warned about. var didWarnAboutUnsafeLifecycles = new Set(); ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function (fiber, instance) { // Dedupe strategy: Warn once per component. if (didWarnAboutUnsafeLifecycles.has(fiber.type)) { return; } if (typeof instance.componentWillMount === 'function' && // Don't warn about react-lifecycles-compat polyfilled components. instance.componentWillMount.__suppressDeprecationWarning !== true) { pendingComponentWillMountWarnings.push(fiber); } if (fiber.mode & StrictLegacyMode && typeof instance.UNSAFE_componentWillMount === 'function') { pendingUNSAFE_ComponentWillMountWarnings.push(fiber); } if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) { pendingComponentWillReceivePropsWarnings.push(fiber); } if (fiber.mode & StrictLegacyMode && typeof instance.UNSAFE_componentWillReceiveProps === 'function') { pendingUNSAFE_ComponentWillReceivePropsWarnings.push(fiber); } if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) { pendingComponentWillUpdateWarnings.push(fiber); } if (fiber.mode & StrictLegacyMode && typeof instance.UNSAFE_componentWillUpdate === 'function') { pendingUNSAFE_ComponentWillUpdateWarnings.push(fiber); } }; ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function () { // We do an initial pass to gather component names var componentWillMountUniqueNames = new Set(); if (pendingComponentWillMountWarnings.length > 0) { pendingComponentWillMountWarnings.forEach(function (fiber) { componentWillMountUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); didWarnAboutUnsafeLifecycles.add(fiber.type); }); pendingComponentWillMountWarnings = []; } var UNSAFE_componentWillMountUniqueNames = new Set(); if (pendingUNSAFE_ComponentWillMountWarnings.length > 0) { pendingUNSAFE_ComponentWillMountWarnings.forEach(function (fiber) { UNSAFE_componentWillMountUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); didWarnAboutUnsafeLifecycles.add(fiber.type); }); pendingUNSAFE_ComponentWillMountWarnings = []; } var componentWillReceivePropsUniqueNames = new Set(); if (pendingComponentWillReceivePropsWarnings.length > 0) { pendingComponentWillReceivePropsWarnings.forEach(function (fiber) { componentWillReceivePropsUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); didWarnAboutUnsafeLifecycles.add(fiber.type); }); pendingComponentWillReceivePropsWarnings = []; } var UNSAFE_componentWillReceivePropsUniqueNames = new Set(); if (pendingUNSAFE_ComponentWillReceivePropsWarnings.length > 0) { pendingUNSAFE_ComponentWillReceivePropsWarnings.forEach(function (fiber) { UNSAFE_componentWillReceivePropsUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); didWarnAboutUnsafeLifecycles.add(fiber.type); }); pendingUNSAFE_ComponentWillReceivePropsWarnings = []; } var componentWillUpdateUniqueNames = new Set(); if (pendingComponentWillUpdateWarnings.length > 0) { pendingComponentWillUpdateWarnings.forEach(function (fiber) { componentWillUpdateUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); didWarnAboutUnsafeLifecycles.add(fiber.type); }); pendingComponentWillUpdateWarnings = []; } var UNSAFE_componentWillUpdateUniqueNames = new Set(); if (pendingUNSAFE_ComponentWillUpdateWarnings.length > 0) { pendingUNSAFE_ComponentWillUpdateWarnings.forEach(function (fiber) { UNSAFE_componentWillUpdateUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); didWarnAboutUnsafeLifecycles.add(fiber.type); }); pendingUNSAFE_ComponentWillUpdateWarnings = []; } // Finally, we flush all the warnings // UNSAFE_ ones before the deprecated ones, since they'll be 'louder' if (UNSAFE_componentWillMountUniqueNames.size > 0) { var sortedNames = setToSortedString(UNSAFE_componentWillMountUniqueNames); error('Using UNSAFE_componentWillMount in strict mode is not recommended and may indicate bugs in your code. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move code with side effects to componentDidMount, and set initial state in the constructor.\n' + '\nPlease update the following components: %s', sortedNames); } if (UNSAFE_componentWillReceivePropsUniqueNames.size > 0) { var _sortedNames = setToSortedString(UNSAFE_componentWillReceivePropsUniqueNames); error('Using UNSAFE_componentWillReceiveProps in strict mode is not recommended ' + 'and may indicate bugs in your code. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + "* If you're updating state whenever props change, " + 'refactor your code to use memoization techniques or move it to ' + 'static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n' + '\nPlease update the following components: %s', _sortedNames); } if (UNSAFE_componentWillUpdateUniqueNames.size > 0) { var _sortedNames2 = setToSortedString(UNSAFE_componentWillUpdateUniqueNames); error('Using UNSAFE_componentWillUpdate in strict mode is not recommended ' + 'and may indicate bugs in your code. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + '\nPlease update the following components: %s', _sortedNames2); } if (componentWillMountUniqueNames.size > 0) { var _sortedNames3 = setToSortedString(componentWillMountUniqueNames); warn('componentWillMount has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move code with side effects to componentDidMount, and set initial state in the constructor.\n' + '* Rename componentWillMount to UNSAFE_componentWillMount to suppress ' + 'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames3); } if (componentWillReceivePropsUniqueNames.size > 0) { var _sortedNames4 = setToSortedString(componentWillReceivePropsUniqueNames); warn('componentWillReceiveProps has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + "* If you're updating state whenever props change, refactor your " + 'code to use memoization techniques or move it to ' + 'static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n' + '* Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress ' + 'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames4); } if (componentWillUpdateUniqueNames.size > 0) { var _sortedNames5 = setToSortedString(componentWillUpdateUniqueNames); warn('componentWillUpdate has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + '* Rename componentWillUpdate to UNSAFE_componentWillUpdate to suppress ' + 'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames5); } }; var pendingLegacyContextWarning = new Map(); // Tracks components we have already warned about. var didWarnAboutLegacyContext = new Set(); ReactStrictModeWarnings.recordLegacyContextWarning = function (fiber, instance) { var strictRoot = findStrictRoot(fiber); if (strictRoot === null) { error('Expected to find a StrictMode component in a strict mode tree. ' + 'This error is likely caused by a bug in React. Please file an issue.'); return; } // Dedup strategy: Warn once per component. if (didWarnAboutLegacyContext.has(fiber.type)) { return; } var warningsForRoot = pendingLegacyContextWarning.get(strictRoot); if (fiber.type.contextTypes != null || fiber.type.childContextTypes != null || instance !== null && typeof instance.getChildContext === 'function') { if (warningsForRoot === undefined) { warningsForRoot = []; pendingLegacyContextWarning.set(strictRoot, warningsForRoot); } warningsForRoot.push(fiber); } }; ReactStrictModeWarnings.flushLegacyContextWarning = function () { pendingLegacyContextWarning.forEach(function (fiberArray, strictRoot) { if (fiberArray.length === 0) { return; } var firstFiber = fiberArray[0]; var uniqueNames = new Set(); fiberArray.forEach(function (fiber) { uniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); didWarnAboutLegacyContext.add(fiber.type); }); var sortedNames = setToSortedString(uniqueNames); try { setCurrentFiber(firstFiber); error('Legacy context API has been detected within a strict-mode tree.' + '\n\nThe old API will be supported in all 16.x releases, but applications ' + 'using it should migrate to the new version.' + '\n\nPlease update the following components: %s' + '\n\nLearn more about this warning here: https://reactjs.org/link/legacy-context', sortedNames); } finally { resetCurrentFiber(); } }); }; ReactStrictModeWarnings.discardPendingWarnings = function () { pendingComponentWillMountWarnings = []; pendingUNSAFE_ComponentWillMountWarnings = []; pendingComponentWillReceivePropsWarnings = []; pendingUNSAFE_ComponentWillReceivePropsWarnings = []; pendingComponentWillUpdateWarnings = []; pendingUNSAFE_ComponentWillUpdateWarnings = []; pendingLegacyContextWarning = new Map(); }; } function resolveDefaultProps(Component, baseProps) { if (Component && Component.defaultProps) { // Resolve default props. Taken from ReactElement var props = assign({}, baseProps); var defaultProps = Component.defaultProps; for (var propName in defaultProps) { if (props[propName] === undefined) { props[propName] = defaultProps[propName]; } } return props; } return baseProps; } var valueCursor = createCursor(null); var rendererSigil; { // Use this to detect multiple renderers using the same context rendererSigil = {}; } var currentlyRenderingFiber = null; var lastContextDependency = null; var lastFullyObservedContext = null; var isDisallowedContextReadInDEV = false; function resetContextDependencies() { // This is called right before React yields execution, to ensure `readContext` // cannot be called outside the render phase. currentlyRenderingFiber = null; lastContextDependency = null; lastFullyObservedContext = null; { isDisallowedContextReadInDEV = false; } } function enterDisallowedContextReadInDEV() { { isDisallowedContextReadInDEV = true; } } function exitDisallowedContextReadInDEV() { { isDisallowedContextReadInDEV = false; } } function pushProvider(providerFiber, context, nextValue) { { push(valueCursor, context._currentValue, providerFiber); context._currentValue = nextValue; { if (context._currentRenderer !== undefined && context._currentRenderer !== null && context._currentRenderer !== rendererSigil) { error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.'); } context._currentRenderer = rendererSigil; } } } function popProvider(context, providerFiber) { var currentValue = valueCursor.current; pop(valueCursor, providerFiber); { { context._currentValue = currentValue; } } } function scheduleContextWorkOnParentPath(parent, renderLanes, propagationRoot) { // Update the child lanes of all the ancestors, including the alternates. var node = parent; while (node !== null) { var alternate = node.alternate; if (!isSubsetOfLanes(node.childLanes, renderLanes)) { node.childLanes = mergeLanes(node.childLanes, renderLanes); if (alternate !== null) { alternate.childLanes = mergeLanes(alternate.childLanes, renderLanes); } } else if (alternate !== null && !isSubsetOfLanes(alternate.childLanes, renderLanes)) { alternate.childLanes = mergeLanes(alternate.childLanes, renderLanes); } if (node === propagationRoot) { break; } node = node.return; } { if (node !== propagationRoot) { error('Expected to find the propagation root when scheduling context work. ' + 'This error is likely caused by a bug in React. Please file an issue.'); } } } function propagateContextChange(workInProgress, context, renderLanes) { { propagateContextChange_eager(workInProgress, context, renderLanes); } } function propagateContextChange_eager(workInProgress, context, renderLanes) { var fiber = workInProgress.child; if (fiber !== null) { // Set the return pointer of the child to the work-in-progress fiber. fiber.return = workInProgress; } while (fiber !== null) { var nextFiber = void 0; // Visit this fiber. var list = fiber.dependencies; if (list !== null) { nextFiber = fiber.child; var dependency = list.firstContext; while (dependency !== null) { // Check if the context matches. if (dependency.context === context) { // Match! Schedule an update on this fiber. if (fiber.tag === ClassComponent) { // Schedule a force update on the work-in-progress. var lane = pickArbitraryLane(renderLanes); var update = createUpdate(NoTimestamp, lane); update.tag = ForceUpdate; // TODO: Because we don't have a work-in-progress, this will add the // update to the current fiber, too, which means it will persist even if // this render is thrown away. Since it's a race condition, not sure it's // worth fixing. // Inlined `enqueueUpdate` to remove interleaved update check var updateQueue = fiber.updateQueue; if (updateQueue === null) ; else { var sharedQueue = updateQueue.shared; var pending = sharedQueue.pending; if (pending === null) { // This is the first update. Create a circular list. update.next = update; } else { update.next = pending.next; pending.next = update; } sharedQueue.pending = update; } } fiber.lanes = mergeLanes(fiber.lanes, renderLanes); var alternate = fiber.alternate; if (alternate !== null) { alternate.lanes = mergeLanes(alternate.lanes, renderLanes); } scheduleContextWorkOnParentPath(fiber.return, renderLanes, workInProgress); // Mark the updated lanes on the list, too. list.lanes = mergeLanes(list.lanes, renderLanes); // Since we already found a match, we can stop traversing the // dependency list. break; } dependency = dependency.next; } } else if (fiber.tag === ContextProvider) { // Don't scan deeper if this is a matching provider nextFiber = fiber.type === workInProgress.type ? null : fiber.child; } else if (fiber.tag === DehydratedFragment) { // If a dehydrated suspense boundary is in this subtree, we don't know // if it will have any context consumers in it. The best we can do is // mark it as having updates. var parentSuspense = fiber.return; if (parentSuspense === null) { throw new Error('We just came from a parent so we must have had a parent. This is a bug in React.'); } parentSuspense.lanes = mergeLanes(parentSuspense.lanes, renderLanes); var _alternate = parentSuspense.alternate; if (_alternate !== null) { _alternate.lanes = mergeLanes(_alternate.lanes, renderLanes); } // This is intentionally passing this fiber as the parent // because we want to schedule this fiber as having work // on its children. We'll use the childLanes on // this fiber to indicate that a context has changed. scheduleContextWorkOnParentPath(parentSuspense, renderLanes, workInProgress); nextFiber = fiber.sibling; } else { // Traverse down. nextFiber = fiber.child; } if (nextFiber !== null) { // Set the return pointer of the child to the work-in-progress fiber. nextFiber.return = fiber; } else { // No child. Traverse to next sibling. nextFiber = fiber; while (nextFiber !== null) { if (nextFiber === workInProgress) { // We're back to the root of this subtree. Exit. nextFiber = null; break; } var sibling = nextFiber.sibling; if (sibling !== null) { // Set the return pointer of the sibling to the work-in-progress fiber. sibling.return = nextFiber.return; nextFiber = sibling; break; } // No more siblings. Traverse up. nextFiber = nextFiber.return; } } fiber = nextFiber; } } function prepareToReadContext(workInProgress, renderLanes) { currentlyRenderingFiber = workInProgress; lastContextDependency = null; lastFullyObservedContext = null; var dependencies = workInProgress.dependencies; if (dependencies !== null) { { var firstContext = dependencies.firstContext; if (firstContext !== null) { if (includesSomeLane(dependencies.lanes, renderLanes)) { // Context list has a pending update. Mark that this fiber performed work. markWorkInProgressReceivedUpdate(); } // Reset the work-in-progress list dependencies.firstContext = null; } } } } function readContext(context) { { // This warning would fire if you read context inside a Hook like useMemo. // Unlike the class check below, it's not enforced in production for perf. if (isDisallowedContextReadInDEV) { error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().'); } } var value = context._currentValue ; if (lastFullyObservedContext === context) ; else { var contextItem = { context: context, memoizedValue: value, next: null }; if (lastContextDependency === null) { if (currentlyRenderingFiber === null) { throw new Error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().'); } // This is the first dependency for this component. Create a new list. lastContextDependency = contextItem; currentlyRenderingFiber.dependencies = { lanes: NoLanes, firstContext: contextItem }; } else { // Append a new context item. lastContextDependency = lastContextDependency.next = contextItem; } } return value; } // render. When this render exits, either because it finishes or because it is // interrupted, the interleaved updates will be transferred onto the main part // of the queue. var concurrentQueues = null; function pushConcurrentUpdateQueue(queue) { if (concurrentQueues === null) { concurrentQueues = [queue]; } else { concurrentQueues.push(queue); } } function finishQueueingConcurrentUpdates() { // Transfer the interleaved updates onto the main queue. Each queue has a // `pending` field and an `interleaved` field. When they are not null, they // point to the last node in a circular linked list. We need to append the // interleaved list to the end of the pending list by joining them into a // single, circular list. if (concurrentQueues !== null) { for (var i = 0; i < concurrentQueues.length; i++) { var queue = concurrentQueues[i]; var lastInterleavedUpdate = queue.interleaved; if (lastInterleavedUpdate !== null) { queue.interleaved = null; var firstInterleavedUpdate = lastInterleavedUpdate.next; var lastPendingUpdate = queue.pending; if (lastPendingUpdate !== null) { var firstPendingUpdate = lastPendingUpdate.next; lastPendingUpdate.next = firstInterleavedUpdate; lastInterleavedUpdate.next = firstPendingUpdate; } queue.pending = lastInterleavedUpdate; } } concurrentQueues = null; } } function enqueueConcurrentHookUpdate(fiber, queue, update, lane) { var interleaved = queue.interleaved; if (interleaved === null) { // This is the first update. Create a circular list. update.next = update; // At the end of the current render, this queue's interleaved updates will // be transferred to the pending queue. pushConcurrentUpdateQueue(queue); } else { update.next = interleaved.next; interleaved.next = update; } queue.interleaved = update; return markUpdateLaneFromFiberToRoot(fiber, lane); } function enqueueConcurrentHookUpdateAndEagerlyBailout(fiber, queue, update, lane) { var interleaved = queue.interleaved; if (interleaved === null) { // This is the first update. Create a circular list. update.next = update; // At the end of the current render, this queue's interleaved updates will // be transferred to the pending queue. pushConcurrentUpdateQueue(queue); } else { update.next = interleaved.next; interleaved.next = update; } queue.interleaved = update; } function enqueueConcurrentClassUpdate(fiber, queue, update, lane) { var interleaved = queue.interleaved; if (interleaved === null) { // This is the first update. Create a circular list. update.next = update; // At the end of the current render, this queue's interleaved updates will // be transferred to the pending queue. pushConcurrentUpdateQueue(queue); } else { update.next = interleaved.next; interleaved.next = update; } queue.interleaved = update; return markUpdateLaneFromFiberToRoot(fiber, lane); } function enqueueConcurrentRenderForLane(fiber, lane) { return markUpdateLaneFromFiberToRoot(fiber, lane); } // Calling this function outside this module should only be done for backwards // compatibility and should always be accompanied by a warning. var unsafe_markUpdateLaneFromFiberToRoot = markUpdateLaneFromFiberToRoot; function markUpdateLaneFromFiberToRoot(sourceFiber, lane) { // Update the source fiber's lanes sourceFiber.lanes = mergeLanes(sourceFiber.lanes, lane); var alternate = sourceFiber.alternate; if (alternate !== null) { alternate.lanes = mergeLanes(alternate.lanes, lane); } { if (alternate === null && (sourceFiber.flags & (Placement | Hydrating)) !== NoFlags) { warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber); } } // Walk the parent path to the root and update the child lanes. var node = sourceFiber; var parent = sourceFiber.return; while (parent !== null) { parent.childLanes = mergeLanes(parent.childLanes, lane); alternate = parent.alternate; if (alternate !== null) { alternate.childLanes = mergeLanes(alternate.childLanes, lane); } else { { if ((parent.flags & (Placement | Hydrating)) !== NoFlags) { warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber); } } } node = parent; parent = parent.return; } if (node.tag === HostRoot) { var root = node.stateNode; return root; } else { return null; } } var UpdateState = 0; var ReplaceState = 1; var ForceUpdate = 2; var CaptureUpdate = 3; // Global state that is reset at the beginning of calling `processUpdateQueue`. // It should only be read right after calling `processUpdateQueue`, via // `checkHasForceUpdateAfterProcessing`. var hasForceUpdate = false; var didWarnUpdateInsideUpdate; var currentlyProcessingQueue; { didWarnUpdateInsideUpdate = false; currentlyProcessingQueue = null; } function initializeUpdateQueue(fiber) { var queue = { baseState: fiber.memoizedState, firstBaseUpdate: null, lastBaseUpdate: null, shared: { pending: null, interleaved: null, lanes: NoLanes }, effects: null }; fiber.updateQueue = queue; } function cloneUpdateQueue(current, workInProgress) { // Clone the update queue from current. Unless it's already a clone. var queue = workInProgress.updateQueue; var currentQueue = current.updateQueue; if (queue === currentQueue) { var clone = { baseState: currentQueue.baseState, firstBaseUpdate: currentQueue.firstBaseUpdate, lastBaseUpdate: currentQueue.lastBaseUpdate, shared: currentQueue.shared, effects: currentQueue.effects }; workInProgress.updateQueue = clone; } } function createUpdate(eventTime, lane) { var update = { eventTime: eventTime, lane: lane, tag: UpdateState, payload: null, callback: null, next: null }; return update; } function enqueueUpdate(fiber, update, lane) { var updateQueue = fiber.updateQueue; if (updateQueue === null) { // Only occurs if the fiber has been unmounted. return null; } var sharedQueue = updateQueue.shared; { if (currentlyProcessingQueue === sharedQueue && !didWarnUpdateInsideUpdate) { error('An update (setState, replaceState, or forceUpdate) was scheduled ' + 'from inside an update function. Update functions should be pure, ' + 'with zero side-effects. Consider using componentDidUpdate or a ' + 'callback.'); didWarnUpdateInsideUpdate = true; } } if (isUnsafeClassRenderPhaseUpdate()) { // This is an unsafe render phase update. Add directly to the update // queue so we can process it immediately during the current render. var pending = sharedQueue.pending; if (pending === null) { // This is the first update. Create a circular list. update.next = update; } else { update.next = pending.next; pending.next = update; } sharedQueue.pending = update; // Update the childLanes even though we're most likely already rendering // this fiber. This is for backwards compatibility in the case where you // update a different component during render phase than the one that is // currently renderings (a pattern that is accompanied by a warning). return unsafe_markUpdateLaneFromFiberToRoot(fiber, lane); } else { return enqueueConcurrentClassUpdate(fiber, sharedQueue, update, lane); } } function entangleTransitions(root, fiber, lane) { var updateQueue = fiber.updateQueue; if (updateQueue === null) { // Only occurs if the fiber has been unmounted. return; } var sharedQueue = updateQueue.shared; if (isTransitionLane(lane)) { var queueLanes = sharedQueue.lanes; // If any entangled lanes are no longer pending on the root, then they must // have finished. We can remove them from the shared queue, which represents // a superset of the actually pending lanes. In some cases we may entangle // more than we need to, but that's OK. In fact it's worse if we *don't* // entangle when we should. queueLanes = intersectLanes(queueLanes, root.pendingLanes); // Entangle the new transition lane with the other transition lanes. var newQueueLanes = mergeLanes(queueLanes, lane); sharedQueue.lanes = newQueueLanes; // Even if queue.lanes already include lane, we don't know for certain if // the lane finished since the last time we entangled it. So we need to // entangle it again, just to be sure. markRootEntangled(root, newQueueLanes); } } function enqueueCapturedUpdate(workInProgress, capturedUpdate) { // Captured updates are updates that are thrown by a child during the render // phase. They should be discarded if the render is aborted. Therefore, // we should only put them on the work-in-progress queue, not the current one. var queue = workInProgress.updateQueue; // Check if the work-in-progress queue is a clone. var current = workInProgress.alternate; if (current !== null) { var currentQueue = current.updateQueue; if (queue === currentQueue) { // The work-in-progress queue is the same as current. This happens when // we bail out on a parent fiber that then captures an error thrown by // a child. Since we want to append the update only to the work-in // -progress queue, we need to clone the updates. We usually clone during // processUpdateQueue, but that didn't happen in this case because we // skipped over the parent when we bailed out. var newFirst = null; var newLast = null; var firstBaseUpdate = queue.firstBaseUpdate; if (firstBaseUpdate !== null) { // Loop through the updates and clone them. var update = firstBaseUpdate; do { var clone = { eventTime: update.eventTime, lane: update.lane, tag: update.tag, payload: update.payload, callback: update.callback, next: null }; if (newLast === null) { newFirst = newLast = clone; } else { newLast.next = clone; newLast = clone; } update = update.next; } while (update !== null); // Append the captured update the end of the cloned list. if (newLast === null) { newFirst = newLast = capturedUpdate; } else { newLast.next = capturedUpdate; newLast = capturedUpdate; } } else { // There are no base updates. newFirst = newLast = capturedUpdate; } queue = { baseState: currentQueue.baseState, firstBaseUpdate: newFirst, lastBaseUpdate: newLast, shared: currentQueue.shared, effects: currentQueue.effects }; workInProgress.updateQueue = queue; return; } } // Append the update to the end of the list. var lastBaseUpdate = queue.lastBaseUpdate; if (lastBaseUpdate === null) { queue.firstBaseUpdate = capturedUpdate; } else { lastBaseUpdate.next = capturedUpdate; } queue.lastBaseUpdate = capturedUpdate; } function getStateFromUpdate(workInProgress, queue, update, prevState, nextProps, instance) { switch (update.tag) { case ReplaceState: { var payload = update.payload; if (typeof payload === 'function') { // Updater function { enterDisallowedContextReadInDEV(); } var nextState = payload.call(instance, prevState, nextProps); { if ( workInProgress.mode & StrictLegacyMode) { setIsStrictModeForDevtools(true); try { payload.call(instance, prevState, nextProps); } finally { setIsStrictModeForDevtools(false); } } exitDisallowedContextReadInDEV(); } return nextState; } // State object return payload; } case CaptureUpdate: { workInProgress.flags = workInProgress.flags & ~ShouldCapture | DidCapture; } // Intentional fallthrough case UpdateState: { var _payload = update.payload; var partialState; if (typeof _payload === 'function') { // Updater function { enterDisallowedContextReadInDEV(); } partialState = _payload.call(instance, prevState, nextProps); { if ( workInProgress.mode & StrictLegacyMode) { setIsStrictModeForDevtools(true); try { _payload.call(instance, prevState, nextProps); } finally { setIsStrictModeForDevtools(false); } } exitDisallowedContextReadInDEV(); } } else { // Partial state object partialState = _payload; } if (partialState === null || partialState === undefined) { // Null and undefined are treated as no-ops. return prevState; } // Merge the partial state and the previous state. return assign({}, prevState, partialState); } case ForceUpdate: { hasForceUpdate = true; return prevState; } } return prevState; } function processUpdateQueue(workInProgress, props, instance, renderLanes) { // This is always non-null on a ClassComponent or HostRoot var queue = workInProgress.updateQueue; hasForceUpdate = false; { currentlyProcessingQueue = queue.shared; } var firstBaseUpdate = queue.firstBaseUpdate; var lastBaseUpdate = queue.lastBaseUpdate; // Check if there are pending updates. If so, transfer them to the base queue. var pendingQueue = queue.shared.pending; if (pendingQueue !== null) { queue.shared.pending = null; // The pending queue is circular. Disconnect the pointer between first // and last so that it's non-circular. var lastPendingUpdate = pendingQueue; var firstPendingUpdate = lastPendingUpdate.next; lastPendingUpdate.next = null; // Append pending updates to base queue if (lastBaseUpdate === null) { firstBaseUpdate = firstPendingUpdate; } else { lastBaseUpdate.next = firstPendingUpdate; } lastBaseUpdate = lastPendingUpdate; // If there's a current queue, and it's different from the base queue, then // we need to transfer the updates to that queue, too. Because the base // queue is a singly-linked list with no cycles, we can append to both // lists and take advantage of structural sharing. // TODO: Pass `current` as argument var current = workInProgress.alternate; if (current !== null) { // This is always non-null on a ClassComponent or HostRoot var currentQueue = current.updateQueue; var currentLastBaseUpdate = currentQueue.lastBaseUpdate; if (currentLastBaseUpdate !== lastBaseUpdate) { if (currentLastBaseUpdate === null) { currentQueue.firstBaseUpdate = firstPendingUpdate; } else { currentLastBaseUpdate.next = firstPendingUpdate; } currentQueue.lastBaseUpdate = lastPendingUpdate; } } } // These values may change as we process the queue. if (firstBaseUpdate !== null) { // Iterate through the list of updates to compute the result. var newState = queue.baseState; // TODO: Don't need to accumulate this. Instead, we can remove renderLanes // from the original lanes. var newLanes = NoLanes; var newBaseState = null; var newFirstBaseUpdate = null; var newLastBaseUpdate = null; var update = firstBaseUpdate; do { var updateLane = update.lane; var updateEventTime = update.eventTime; if (!isSubsetOfLanes(renderLanes, updateLane)) { // Priority is insufficient. Skip this update. If this is the first // skipped update, the previous update/state is the new base // update/state. var clone = { eventTime: updateEventTime, lane: updateLane, tag: update.tag, payload: update.payload, callback: update.callback, next: null }; if (newLastBaseUpdate === null) { newFirstBaseUpdate = newLastBaseUpdate = clone; newBaseState = newState; } else { newLastBaseUpdate = newLastBaseUpdate.next = clone; } // Update the remaining priority in the queue. newLanes = mergeLanes(newLanes, updateLane); } else { // This update does have sufficient priority. if (newLastBaseUpdate !== null) { var _clone = { eventTime: updateEventTime, // This update is going to be committed so we never want uncommit // it. Using NoLane works because 0 is a subset of all bitmasks, so // this will never be skipped by the check above. lane: NoLane, tag: update.tag, payload: update.payload, callback: update.callback, next: null }; newLastBaseUpdate = newLastBaseUpdate.next = _clone; } // Process this update. newState = getStateFromUpdate(workInProgress, queue, update, newState, props, instance); var callback = update.callback; if (callback !== null && // If the update was already committed, we should not queue its // callback again. update.lane !== NoLane) { workInProgress.flags |= Callback; var effects = queue.effects; if (effects === null) { queue.effects = [update]; } else { effects.push(update); } } } update = update.next; if (update === null) { pendingQueue = queue.shared.pending; if (pendingQueue === null) { break; } else { // An update was scheduled from inside a reducer. Add the new // pending updates to the end of the list and keep processing. var _lastPendingUpdate = pendingQueue; // Intentionally unsound. Pending updates form a circular list, but we // unravel them when transferring them to the base queue. var _firstPendingUpdate = _lastPendingUpdate.next; _lastPendingUpdate.next = null; update = _firstPendingUpdate; queue.lastBaseUpdate = _lastPendingUpdate; queue.shared.pending = null; } } } while (true); if (newLastBaseUpdate === null) { newBaseState = newState; } queue.baseState = newBaseState; queue.firstBaseUpdate = newFirstBaseUpdate; queue.lastBaseUpdate = newLastBaseUpdate; // Interleaved updates are stored on a separate queue. We aren't going to // process them during this render, but we do need to track which lanes // are remaining. var lastInterleaved = queue.shared.interleaved; if (lastInterleaved !== null) { var interleaved = lastInterleaved; do { newLanes = mergeLanes(newLanes, interleaved.lane); interleaved = interleaved.next; } while (interleaved !== lastInterleaved); } else if (firstBaseUpdate === null) { // `queue.lanes` is used for entangling transitions. We can set it back to // zero once the queue is empty. queue.shared.lanes = NoLanes; } // Set the remaining expiration time to be whatever is remaining in the queue. // This should be fine because the only two other things that contribute to // expiration time are props and context. We're already in the middle of the // begin phase by the time we start processing the queue, so we've already // dealt with the props. Context in components that specify // shouldComponentUpdate is tricky; but we'll have to account for // that regardless. markSkippedUpdateLanes(newLanes); workInProgress.lanes = newLanes; workInProgress.memoizedState = newState; } { currentlyProcessingQueue = null; } } function callCallback(callback, context) { if (typeof callback !== 'function') { throw new Error('Invalid argument passed as callback. Expected a function. Instead ' + ("received: " + callback)); } callback.call(context); } function resetHasForceUpdateBeforeProcessing() { hasForceUpdate = false; } function checkHasForceUpdateAfterProcessing() { return hasForceUpdate; } function commitUpdateQueue(finishedWork, finishedQueue, instance) { // Commit the effects var effects = finishedQueue.effects; finishedQueue.effects = null; if (effects !== null) { for (var i = 0; i < effects.length; i++) { var effect = effects[i]; var callback = effect.callback; if (callback !== null) { effect.callback = null; callCallback(callback, instance); } } } } var fakeInternalInstance = {}; // React.Component uses a shared frozen object by default. // We'll use it to determine whether we need to initialize legacy refs. var emptyRefsObject = new React.Component().refs; var didWarnAboutStateAssignmentForComponent; var didWarnAboutUninitializedState; var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate; var didWarnAboutLegacyLifecyclesAndDerivedState; var didWarnAboutUndefinedDerivedState; var warnOnUndefinedDerivedState; var warnOnInvalidCallback; var didWarnAboutDirectlyAssigningPropsToState; var didWarnAboutContextTypeAndContextTypes; var didWarnAboutInvalidateContextType; { didWarnAboutStateAssignmentForComponent = new Set(); didWarnAboutUninitializedState = new Set(); didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set(); didWarnAboutLegacyLifecyclesAndDerivedState = new Set(); didWarnAboutDirectlyAssigningPropsToState = new Set(); didWarnAboutUndefinedDerivedState = new Set(); didWarnAboutContextTypeAndContextTypes = new Set(); didWarnAboutInvalidateContextType = new Set(); var didWarnOnInvalidCallback = new Set(); warnOnInvalidCallback = function (callback, callerName) { if (callback === null || typeof callback === 'function') { return; } var key = callerName + '_' + callback; if (!didWarnOnInvalidCallback.has(key)) { didWarnOnInvalidCallback.add(key); error('%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback); } }; warnOnUndefinedDerivedState = function (type, partialState) { if (partialState === undefined) { var componentName = getComponentNameFromType(type) || 'Component'; if (!didWarnAboutUndefinedDerivedState.has(componentName)) { didWarnAboutUndefinedDerivedState.add(componentName); error('%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName); } } }; // This is so gross but it's at least non-critical and can be removed if // it causes problems. This is meant to give a nicer error message for // ReactDOM15.unstable_renderSubtreeIntoContainer(reactDOM16Component, // ...)) which otherwise throws a "_processChildContext is not a function" // exception. Object.defineProperty(fakeInternalInstance, '_processChildContext', { enumerable: false, value: function () { throw new Error('_processChildContext is not available in React 16+. This likely ' + 'means you have multiple copies of React and are attempting to nest ' + 'a React 15 tree inside a React 16 tree using ' + "unstable_renderSubtreeIntoContainer, which isn't supported. Try " + 'to make sure you have only one copy of React (and ideally, switch ' + 'to ReactDOM.createPortal).'); } }); Object.freeze(fakeInternalInstance); } function applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, nextProps) { var prevState = workInProgress.memoizedState; var partialState = getDerivedStateFromProps(nextProps, prevState); { if ( workInProgress.mode & StrictLegacyMode) { setIsStrictModeForDevtools(true); try { // Invoke the function an extra time to help detect side-effects. partialState = getDerivedStateFromProps(nextProps, prevState); } finally { setIsStrictModeForDevtools(false); } } warnOnUndefinedDerivedState(ctor, partialState); } // Merge the partial state and the previous state. var memoizedState = partialState === null || partialState === undefined ? prevState : assign({}, prevState, partialState); workInProgress.memoizedState = memoizedState; // Once the update queue is empty, persist the derived state onto the // base state. if (workInProgress.lanes === NoLanes) { // Queue is always non-null for classes var updateQueue = workInProgress.updateQueue; updateQueue.baseState = memoizedState; } } var classComponentUpdater = { isMounted: isMounted, enqueueSetState: function (inst, payload, callback) { var fiber = get(inst); var eventTime = requestEventTime(); var lane = requestUpdateLane(fiber); var update = createUpdate(eventTime, lane); update.payload = payload; if (callback !== undefined && callback !== null) { { warnOnInvalidCallback(callback, 'setState'); } update.callback = callback; } var root = enqueueUpdate(fiber, update, lane); if (root !== null) { scheduleUpdateOnFiber(root, fiber, lane, eventTime); entangleTransitions(root, fiber, lane); } { markStateUpdateScheduled(fiber, lane); } }, enqueueReplaceState: function (inst, payload, callback) { var fiber = get(inst); var eventTime = requestEventTime(); var lane = requestUpdateLane(fiber); var update = createUpdate(eventTime, lane); update.tag = ReplaceState; update.payload = payload; if (callback !== undefined && callback !== null) { { warnOnInvalidCallback(callback, 'replaceState'); } update.callback = callback; } var root = enqueueUpdate(fiber, update, lane); if (root !== null) { scheduleUpdateOnFiber(root, fiber, lane, eventTime); entangleTransitions(root, fiber, lane); } { markStateUpdateScheduled(fiber, lane); } }, enqueueForceUpdate: function (inst, callback) { var fiber = get(inst); var eventTime = requestEventTime(); var lane = requestUpdateLane(fiber); var update = createUpdate(eventTime, lane); update.tag = ForceUpdate; if (callback !== undefined && callback !== null) { { warnOnInvalidCallback(callback, 'forceUpdate'); } update.callback = callback; } var root = enqueueUpdate(fiber, update, lane); if (root !== null) { scheduleUpdateOnFiber(root, fiber, lane, eventTime); entangleTransitions(root, fiber, lane); } { markForceUpdateScheduled(fiber, lane); } } }; function checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext) { var instance = workInProgress.stateNode; if (typeof instance.shouldComponentUpdate === 'function') { var shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext); { if ( workInProgress.mode & StrictLegacyMode) { setIsStrictModeForDevtools(true); try { // Invoke the function an extra time to help detect side-effects. shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext); } finally { setIsStrictModeForDevtools(false); } } if (shouldUpdate === undefined) { error('%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', getComponentNameFromType(ctor) || 'Component'); } } return shouldUpdate; } if (ctor.prototype && ctor.prototype.isPureReactComponent) { return !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState); } return true; } function checkClassInstance(workInProgress, ctor, newProps) { var instance = workInProgress.stateNode; { var name = getComponentNameFromType(ctor) || 'Component'; var renderPresent = instance.render; if (!renderPresent) { if (ctor.prototype && typeof ctor.prototype.render === 'function') { error('%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name); } else { error('%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name); } } if (instance.getInitialState && !instance.getInitialState.isReactClassApproved && !instance.state) { error('getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', name); } if (instance.getDefaultProps && !instance.getDefaultProps.isReactClassApproved) { error('getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', name); } if (instance.propTypes) { error('propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name); } if (instance.contextType) { error('contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name); } { if (instance.contextTypes) { error('contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name); } if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) { didWarnAboutContextTypeAndContextTypes.add(ctor); error('%s declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', name); } } if (typeof instance.componentShouldUpdate === 'function') { error('%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', name); } if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') { error('%s has a method called shouldComponentUpdate(). ' + 'shouldComponentUpdate should not be used when extending React.PureComponent. ' + 'Please extend React.Component if shouldComponentUpdate is used.', getComponentNameFromType(ctor) || 'A pure component'); } if (typeof instance.componentDidUnmount === 'function') { error('%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name); } if (typeof instance.componentDidReceiveProps === 'function') { error('%s has a method called ' + 'componentDidReceiveProps(). But there is no such lifecycle method. ' + 'If you meant to update the state in response to changing props, ' + 'use componentWillReceiveProps(). If you meant to fetch data or ' + 'run side-effects or mutations after React has updated the UI, use componentDidUpdate().', name); } if (typeof instance.componentWillRecieveProps === 'function') { error('%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name); } if (typeof instance.UNSAFE_componentWillRecieveProps === 'function') { error('%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name); } var hasMutatedProps = instance.props !== newProps; if (instance.props !== undefined && hasMutatedProps) { error('%s(...): When calling super() in `%s`, make sure to pass ' + "up the same props that your component's constructor was passed.", name, name); } if (instance.defaultProps) { error('Setting defaultProps as an instance property on %s is not supported and will be ignored.' + ' Instead, define defaultProps as a static property on %s.', name, name); } if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) { didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor); error('%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentNameFromType(ctor)); } if (typeof instance.getDerivedStateFromProps === 'function') { error('%s: getDerivedStateFromProps() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name); } if (typeof instance.getDerivedStateFromError === 'function') { error('%s: getDerivedStateFromError() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name); } if (typeof ctor.getSnapshotBeforeUpdate === 'function') { error('%s: getSnapshotBeforeUpdate() is defined as a static method ' + 'and will be ignored. Instead, declare it as an instance method.', name); } var _state = instance.state; if (_state && (typeof _state !== 'object' || isArray(_state))) { error('%s.state: must be set to an object or null', name); } if (typeof instance.getChildContext === 'function' && typeof ctor.childContextTypes !== 'object') { error('%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name); } } } function adoptClassInstance(workInProgress, instance) { instance.updater = classComponentUpdater; workInProgress.stateNode = instance; // The instance needs access to the fiber so that it can schedule updates set(instance, workInProgress); { instance._reactInternalInstance = fakeInternalInstance; } } function constructClassInstance(workInProgress, ctor, props) { var isLegacyContextConsumer = false; var unmaskedContext = emptyContextObject; var context = emptyContextObject; var contextType = ctor.contextType; { if ('contextType' in ctor) { var isValid = // Allow null for conditional declaration contextType === null || contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === undefined; // Not a <Context.Consumer> if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) { didWarnAboutInvalidateContextType.add(ctor); var addendum = ''; if (contextType === undefined) { addendum = ' However, it is set to undefined. ' + 'This can be caused by a typo or by mixing up named and default imports. ' + 'This can also happen due to a circular dependency, so ' + 'try moving the createContext() call to a separate file.'; } else if (typeof contextType !== 'object') { addendum = ' However, it is set to a ' + typeof contextType + '.'; } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) { addendum = ' Did you accidentally pass the Context.Provider instead?'; } else if (contextType._context !== undefined) { // <Context.Consumer> addendum = ' Did you accidentally pass the Context.Consumer instead?'; } else { addendum = ' However, it is set to an object with keys {' + Object.keys(contextType).join(', ') + '}.'; } error('%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext().%s', getComponentNameFromType(ctor) || 'Component', addendum); } } } if (typeof contextType === 'object' && contextType !== null) { context = readContext(contextType); } else { unmaskedContext = getUnmaskedContext(workInProgress, ctor, true); var contextTypes = ctor.contextTypes; isLegacyContextConsumer = contextTypes !== null && contextTypes !== undefined; context = isLegacyContextConsumer ? getMaskedContext(workInProgress, unmaskedContext) : emptyContextObject; } var instance = new ctor(props, context); // Instantiate twice to help detect side-effects. { if ( workInProgress.mode & StrictLegacyMode) { setIsStrictModeForDevtools(true); try { instance = new ctor(props, context); // eslint-disable-line no-new } finally { setIsStrictModeForDevtools(false); } } } var state = workInProgress.memoizedState = instance.state !== null && instance.state !== undefined ? instance.state : null; adoptClassInstance(workInProgress, instance); { if (typeof ctor.getDerivedStateFromProps === 'function' && state === null) { var componentName = getComponentNameFromType(ctor) || 'Component'; if (!didWarnAboutUninitializedState.has(componentName)) { didWarnAboutUninitializedState.add(componentName); error('`%s` uses `getDerivedStateFromProps` but its initial state is ' + '%s. This is not recommended. Instead, define the initial state by ' + 'assigning an object to `this.state` in the constructor of `%s`. ' + 'This ensures that `getDerivedStateFromProps` arguments have a consistent shape.', componentName, instance.state === null ? 'null' : 'undefined', componentName); } } // If new component APIs are defined, "unsafe" lifecycles won't be called. // Warn about these lifecycles if they are present. // Don't warn about react-lifecycles-compat polyfilled methods though. if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') { var foundWillMountName = null; var foundWillReceivePropsName = null; var foundWillUpdateName = null; if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) { foundWillMountName = 'componentWillMount'; } else if (typeof instance.UNSAFE_componentWillMount === 'function') { foundWillMountName = 'UNSAFE_componentWillMount'; } if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) { foundWillReceivePropsName = 'componentWillReceiveProps'; } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') { foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps'; } if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) { foundWillUpdateName = 'componentWillUpdate'; } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') { foundWillUpdateName = 'UNSAFE_componentWillUpdate'; } if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) { var _componentName = getComponentNameFromType(ctor) || 'Component'; var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()'; if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) { didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName); error('Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' + '%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n' + 'The above lifecycles should be removed. Learn more about this warning here:\n' + 'https://reactjs.org/link/unsafe-component-lifecycles', _componentName, newApiName, foundWillMountName !== null ? "\n " + foundWillMountName : '', foundWillReceivePropsName !== null ? "\n " + foundWillReceivePropsName : '', foundWillUpdateName !== null ? "\n " + foundWillUpdateName : ''); } } } } // Cache unmasked context so we can avoid recreating masked context unless necessary. // ReactFiberContext usually updates this cache but can't for newly-created instances. if (isLegacyContextConsumer) { cacheContext(workInProgress, unmaskedContext, context); } return instance; } function callComponentWillMount(workInProgress, instance) { var oldState = instance.state; if (typeof instance.componentWillMount === 'function') { instance.componentWillMount(); } if (typeof instance.UNSAFE_componentWillMount === 'function') { instance.UNSAFE_componentWillMount(); } if (oldState !== instance.state) { { error('%s.componentWillMount(): Assigning directly to this.state is ' + "deprecated (except inside a component's " + 'constructor). Use setState instead.', getComponentNameFromFiber(workInProgress) || 'Component'); } classComponentUpdater.enqueueReplaceState(instance, instance.state, null); } } function callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext) { var oldState = instance.state; if (typeof instance.componentWillReceiveProps === 'function') { instance.componentWillReceiveProps(newProps, nextContext); } if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') { instance.UNSAFE_componentWillReceiveProps(newProps, nextContext); } if (instance.state !== oldState) { { var componentName = getComponentNameFromFiber(workInProgress) || 'Component'; if (!didWarnAboutStateAssignmentForComponent.has(componentName)) { didWarnAboutStateAssignmentForComponent.add(componentName); error('%s.componentWillReceiveProps(): Assigning directly to ' + "this.state is deprecated (except inside a component's " + 'constructor). Use setState instead.', componentName); } } classComponentUpdater.enqueueReplaceState(instance, instance.state, null); } } // Invokes the mount life-cycles on a previously never rendered instance. function mountClassInstance(workInProgress, ctor, newProps, renderLanes) { { checkClassInstance(workInProgress, ctor, newProps); } var instance = workInProgress.stateNode; instance.props = newProps; instance.state = workInProgress.memoizedState; instance.refs = emptyRefsObject; initializeUpdateQueue(workInProgress); var contextType = ctor.contextType; if (typeof contextType === 'object' && contextType !== null) { instance.context = readContext(contextType); } else { var unmaskedContext = getUnmaskedContext(workInProgress, ctor, true); instance.context = getMaskedContext(workInProgress, unmaskedContext); } { if (instance.state === newProps) { var componentName = getComponentNameFromType(ctor) || 'Component'; if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) { didWarnAboutDirectlyAssigningPropsToState.add(componentName); error('%s: It is not recommended to assign props directly to state ' + "because updates to props won't be reflected in state. " + 'In most cases, it is better to use props directly.', componentName); } } if (workInProgress.mode & StrictLegacyMode) { ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, instance); } { ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(workInProgress, instance); } } instance.state = workInProgress.memoizedState; var getDerivedStateFromProps = ctor.getDerivedStateFromProps; if (typeof getDerivedStateFromProps === 'function') { applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps); instance.state = workInProgress.memoizedState; } // In order to support react-lifecycles-compat polyfilled components, // Unsafe lifecycles should not be invoked for components using the new APIs. if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) { callComponentWillMount(workInProgress, instance); // If we had additional state updates during this life-cycle, let's // process them now. processUpdateQueue(workInProgress, newProps, instance, renderLanes); instance.state = workInProgress.memoizedState; } if (typeof instance.componentDidMount === 'function') { var fiberFlags = Update; { fiberFlags |= LayoutStatic; } if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) { fiberFlags |= MountLayoutDev; } workInProgress.flags |= fiberFlags; } } function resumeMountClassInstance(workInProgress, ctor, newProps, renderLanes) { var instance = workInProgress.stateNode; var oldProps = workInProgress.memoizedProps; instance.props = oldProps; var oldContext = instance.context; var contextType = ctor.contextType; var nextContext = emptyContextObject; if (typeof contextType === 'object' && contextType !== null) { nextContext = readContext(contextType); } else { var nextLegacyUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true); nextContext = getMaskedContext(workInProgress, nextLegacyUnmaskedContext); } var getDerivedStateFromProps = ctor.getDerivedStateFromProps; var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what // ever the previously attempted to render - not the "current". However, // during componentDidUpdate we pass the "current" props. // In order to support react-lifecycles-compat polyfilled components, // Unsafe lifecycles should not be invoked for components using the new APIs. if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) { if (oldProps !== newProps || oldContext !== nextContext) { callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext); } } resetHasForceUpdateBeforeProcessing(); var oldState = workInProgress.memoizedState; var newState = instance.state = oldState; processUpdateQueue(workInProgress, newProps, instance, renderLanes); newState = workInProgress.memoizedState; if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) { // If an update was already in progress, we should schedule an Update // effect even though we're bailing out, so that cWU/cDU are called. if (typeof instance.componentDidMount === 'function') { var fiberFlags = Update; { fiberFlags |= LayoutStatic; } if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) { fiberFlags |= MountLayoutDev; } workInProgress.flags |= fiberFlags; } return false; } if (typeof getDerivedStateFromProps === 'function') { applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps); newState = workInProgress.memoizedState; } var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext); if (shouldUpdate) { // In order to support react-lifecycles-compat polyfilled components, // Unsafe lifecycles should not be invoked for components using the new APIs. if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) { if (typeof instance.componentWillMount === 'function') { instance.componentWillMount(); } if (typeof instance.UNSAFE_componentWillMount === 'function') { instance.UNSAFE_componentWillMount(); } } if (typeof instance.componentDidMount === 'function') { var _fiberFlags = Update; { _fiberFlags |= LayoutStatic; } if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) { _fiberFlags |= MountLayoutDev; } workInProgress.flags |= _fiberFlags; } } else { // If an update was already in progress, we should schedule an Update // effect even though we're bailing out, so that cWU/cDU are called. if (typeof instance.componentDidMount === 'function') { var _fiberFlags2 = Update; { _fiberFlags2 |= LayoutStatic; } if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) { _fiberFlags2 |= MountLayoutDev; } workInProgress.flags |= _fiberFlags2; } // If shouldComponentUpdate returned false, we should still update the // memoized state to indicate that this work can be reused. workInProgress.memoizedProps = newProps; workInProgress.memoizedState = newState; } // Update the existing instance's state, props, and context pointers even // if shouldComponentUpdate returns false. instance.props = newProps; instance.state = newState; instance.context = nextContext; return shouldUpdate; } // Invokes the update life-cycles and returns false if it shouldn't rerender. function updateClassInstance(current, workInProgress, ctor, newProps, renderLanes) { var instance = workInProgress.stateNode; cloneUpdateQueue(current, workInProgress); var unresolvedOldProps = workInProgress.memoizedProps; var oldProps = workInProgress.type === workInProgress.elementType ? unresolvedOldProps : resolveDefaultProps(workInProgress.type, unresolvedOldProps); instance.props = oldProps; var unresolvedNewProps = workInProgress.pendingProps; var oldContext = instance.context; var contextType = ctor.contextType; var nextContext = emptyContextObject; if (typeof contextType === 'object' && contextType !== null) { nextContext = readContext(contextType); } else { var nextUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true); nextContext = getMaskedContext(workInProgress, nextUnmaskedContext); } var getDerivedStateFromProps = ctor.getDerivedStateFromProps; var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what // ever the previously attempted to render - not the "current". However, // during componentDidUpdate we pass the "current" props. // In order to support react-lifecycles-compat polyfilled components, // Unsafe lifecycles should not be invoked for components using the new APIs. if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) { if (unresolvedOldProps !== unresolvedNewProps || oldContext !== nextContext) { callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext); } } resetHasForceUpdateBeforeProcessing(); var oldState = workInProgress.memoizedState; var newState = instance.state = oldState; processUpdateQueue(workInProgress, newProps, instance, renderLanes); newState = workInProgress.memoizedState; if (unresolvedOldProps === unresolvedNewProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing() && !(enableLazyContextPropagation )) { // If an update was already in progress, we should schedule an Update // effect even though we're bailing out, so that cWU/cDU are called. if (typeof instance.componentDidUpdate === 'function') { if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) { workInProgress.flags |= Update; } } if (typeof instance.getSnapshotBeforeUpdate === 'function') { if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) { workInProgress.flags |= Snapshot; } } return false; } if (typeof getDerivedStateFromProps === 'function') { applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps); newState = workInProgress.memoizedState; } var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext) || // TODO: In some cases, we'll end up checking if context has changed twice, // both before and after `shouldComponentUpdate` has been called. Not ideal, // but I'm loath to refactor this function. This only happens for memoized // components so it's not that common. enableLazyContextPropagation ; if (shouldUpdate) { // In order to support react-lifecycles-compat polyfilled components, // Unsafe lifecycles should not be invoked for components using the new APIs. if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillUpdate === 'function' || typeof instance.componentWillUpdate === 'function')) { if (typeof instance.componentWillUpdate === 'function') { instance.componentWillUpdate(newProps, newState, nextContext); } if (typeof instance.UNSAFE_componentWillUpdate === 'function') { instance.UNSAFE_componentWillUpdate(newProps, newState, nextContext); } } if (typeof instance.componentDidUpdate === 'function') { workInProgress.flags |= Update; } if (typeof instance.getSnapshotBeforeUpdate === 'function') { workInProgress.flags |= Snapshot; } } else { // If an update was already in progress, we should schedule an Update // effect even though we're bailing out, so that cWU/cDU are called. if (typeof instance.componentDidUpdate === 'function') { if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) { workInProgress.flags |= Update; } } if (typeof instance.getSnapshotBeforeUpdate === 'function') { if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) { workInProgress.flags |= Snapshot; } } // If shouldComponentUpdate returned false, we should still update the // memoized props/state to indicate that this work can be reused. workInProgress.memoizedProps = newProps; workInProgress.memoizedState = newState; } // Update the existing instance's state, props, and context pointers even // if shouldComponentUpdate returns false. instance.props = newProps; instance.state = newState; instance.context = nextContext; return shouldUpdate; } var didWarnAboutMaps; var didWarnAboutGenerators; var didWarnAboutStringRefs; var ownerHasKeyUseWarning; var ownerHasFunctionTypeWarning; var warnForMissingKey = function (child, returnFiber) {}; { didWarnAboutMaps = false; didWarnAboutGenerators = false; didWarnAboutStringRefs = {}; /** * Warn if there's no key explicitly set on dynamic arrays of children or * object keys are not valid. This allows us to keep track of children between * updates. */ ownerHasKeyUseWarning = {}; ownerHasFunctionTypeWarning = {}; warnForMissingKey = function (child, returnFiber) { if (child === null || typeof child !== 'object') { return; } if (!child._store || child._store.validated || child.key != null) { return; } if (typeof child._store !== 'object') { throw new Error('React Component in warnForMissingKey should have a _store. ' + 'This error is likely caused by a bug in React. Please file an issue.'); } child._store.validated = true; var componentName = getComponentNameFromFiber(returnFiber) || 'Component'; if (ownerHasKeyUseWarning[componentName]) { return; } ownerHasKeyUseWarning[componentName] = true; error('Each child in a list should have a unique ' + '"key" prop. See https://reactjs.org/link/warning-keys for ' + 'more information.'); }; } function coerceRef(returnFiber, current, element) { var mixedRef = element.ref; if (mixedRef !== null && typeof mixedRef !== 'function' && typeof mixedRef !== 'object') { { // TODO: Clean this up once we turn on the string ref warning for // everyone, because the strict mode case will no longer be relevant if ((returnFiber.mode & StrictLegacyMode || warnAboutStringRefs) && // We warn in ReactElement.js if owner and self are equal for string refs // because these cannot be automatically converted to an arrow function // using a codemod. Therefore, we don't have to warn about string refs again. !(element._owner && element._self && element._owner.stateNode !== element._self)) { var componentName = getComponentNameFromFiber(returnFiber) || 'Component'; if (!didWarnAboutStringRefs[componentName]) { { error('A string ref, "%s", has been found within a strict mode tree. ' + 'String refs are a source of potential bugs and should be avoided. ' + 'We recommend using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', mixedRef); } didWarnAboutStringRefs[componentName] = true; } } } if (element._owner) { var owner = element._owner; var inst; if (owner) { var ownerFiber = owner; if (ownerFiber.tag !== ClassComponent) { throw new Error('Function components cannot have string refs. ' + 'We recommend using useRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref'); } inst = ownerFiber.stateNode; } if (!inst) { throw new Error("Missing owner for string ref " + mixedRef + ". This error is likely caused by a " + 'bug in React. Please file an issue.'); } // Assigning this to a const so Flow knows it won't change in the closure var resolvedInst = inst; { checkPropStringCoercion(mixedRef, 'ref'); } var stringRef = '' + mixedRef; // Check if previous string ref matches new string ref if (current !== null && current.ref !== null && typeof current.ref === 'function' && current.ref._stringRef === stringRef) { return current.ref; } var ref = function (value) { var refs = resolvedInst.refs; if (refs === emptyRefsObject) { // This is a lazy pooled frozen object, so we need to initialize. refs = resolvedInst.refs = {}; } if (value === null) { delete refs[stringRef]; } else { refs[stringRef] = value; } }; ref._stringRef = stringRef; return ref; } else { if (typeof mixedRef !== 'string') { throw new Error('Expected ref to be a function, a string, an object returned by React.createRef(), or null.'); } if (!element._owner) { throw new Error("Element ref was specified as a string (" + mixedRef + ") but no owner was set. This could happen for one of" + ' the following reasons:\n' + '1. You may be adding a ref to a function component\n' + "2. You may be adding a ref to a component that was not created inside a component's render method\n" + '3. You have multiple copies of React loaded\n' + 'See https://reactjs.org/link/refs-must-have-owner for more information.'); } } } return mixedRef; } function throwOnInvalidObjectType(returnFiber, newChild) { var childString = Object.prototype.toString.call(newChild); throw new Error("Objects are not valid as a React child (found: " + (childString === '[object Object]' ? 'object with keys {' + Object.keys(newChild).join(', ') + '}' : childString) + "). " + 'If you meant to render a collection of children, use an array ' + 'instead.'); } function warnOnFunctionType(returnFiber) { { var componentName = getComponentNameFromFiber(returnFiber) || 'Component'; if (ownerHasFunctionTypeWarning[componentName]) { return; } ownerHasFunctionTypeWarning[componentName] = true; error('Functions are not valid as a React child. This may happen if ' + 'you return a Component instead of <Component /> from render. ' + 'Or maybe you meant to call this function rather than return it.'); } } function resolveLazy(lazyType) { var payload = lazyType._payload; var init = lazyType._init; return init(payload); } // This wrapper function exists because I expect to clone the code in each path // to be able to optimize each path individually by branching early. This needs // a compiler or we can do it manually. Helpers that don't need this branching // live outside of this function. function ChildReconciler(shouldTrackSideEffects) { function deleteChild(returnFiber, childToDelete) { if (!shouldTrackSideEffects) { // Noop. return; } var deletions = returnFiber.deletions; if (deletions === null) { returnFiber.deletions = [childToDelete]; returnFiber.flags |= ChildDeletion; } else { deletions.push(childToDelete); } } function deleteRemainingChildren(returnFiber, currentFirstChild) { if (!shouldTrackSideEffects) { // Noop. return null; } // TODO: For the shouldClone case, this could be micro-optimized a bit by // assuming that after the first child we've already added everything. var childToDelete = currentFirstChild; while (childToDelete !== null) { deleteChild(returnFiber, childToDelete); childToDelete = childToDelete.sibling; } return null; } function mapRemainingChildren(returnFiber, currentFirstChild) { // Add the remaining children to a temporary map so that we can find them by // keys quickly. Implicit (null) keys get added to this set with their index // instead. var existingChildren = new Map(); var existingChild = currentFirstChild; while (existingChild !== null) { if (existingChild.key !== null) { existingChildren.set(existingChild.key, existingChild); } else { existingChildren.set(existingChild.index, existingChild); } existingChild = existingChild.sibling; } return existingChildren; } function useFiber(fiber, pendingProps) { // We currently set sibling to null and index to 0 here because it is easy // to forget to do before returning it. E.g. for the single child case. var clone = createWorkInProgress(fiber, pendingProps); clone.index = 0; clone.sibling = null; return clone; } function placeChild(newFiber, lastPlacedIndex, newIndex) { newFiber.index = newIndex; if (!shouldTrackSideEffects) { // During hydration, the useId algorithm needs to know which fibers are // part of a list of children (arrays, iterators). newFiber.flags |= Forked; return lastPlacedIndex; } var current = newFiber.alternate; if (current !== null) { var oldIndex = current.index; if (oldIndex < lastPlacedIndex) { // This is a move. newFiber.flags |= Placement; return lastPlacedIndex; } else { // This item can stay in place. return oldIndex; } } else { // This is an insertion. newFiber.flags |= Placement; return lastPlacedIndex; } } function placeSingleChild(newFiber) { // This is simpler for the single child case. We only need to do a // placement for inserting new children. if (shouldTrackSideEffects && newFiber.alternate === null) { newFiber.flags |= Placement; } return newFiber; } function updateTextNode(returnFiber, current, textContent, lanes) { if (current === null || current.tag !== HostText) { // Insert var created = createFiberFromText(textContent, returnFiber.mode, lanes); created.return = returnFiber; return created; } else { // Update var existing = useFiber(current, textContent); existing.return = returnFiber; return existing; } } function updateElement(returnFiber, current, element, lanes) { var elementType = element.type; if (elementType === REACT_FRAGMENT_TYPE) { return updateFragment(returnFiber, current, element.props.children, lanes, element.key); } if (current !== null) { if (current.elementType === elementType || ( // Keep this check inline so it only runs on the false path: isCompatibleFamilyForHotReloading(current, element) ) || // Lazy types should reconcile their resolved type. // We need to do this after the Hot Reloading check above, // because hot reloading has different semantics than prod because // it doesn't resuspend. So we can't let the call below suspend. typeof elementType === 'object' && elementType !== null && elementType.$$typeof === REACT_LAZY_TYPE && resolveLazy(elementType) === current.type) { // Move based on index var existing = useFiber(current, element.props); existing.ref = coerceRef(returnFiber, current, element); existing.return = returnFiber; { existing._debugSource = element._source; existing._debugOwner = element._owner; } return existing; } } // Insert var created = createFiberFromElement(element, returnFiber.mode, lanes); created.ref = coerceRef(returnFiber, current, element); created.return = returnFiber; return created; } function updatePortal(returnFiber, current, portal, lanes) { if (current === null || current.tag !== HostPortal || current.stateNode.containerInfo !== portal.containerInfo || current.stateNode.implementation !== portal.implementation) { // Insert var created = createFiberFromPortal(portal, returnFiber.mode, lanes); created.return = returnFiber; return created; } else { // Update var existing = useFiber(current, portal.children || []); existing.return = returnFiber; return existing; } } function updateFragment(returnFiber, current, fragment, lanes, key) { if (current === null || current.tag !== Fragment) { // Insert var created = createFiberFromFragment(fragment, returnFiber.mode, lanes, key); created.return = returnFiber; return created; } else { // Update var existing = useFiber(current, fragment); existing.return = returnFiber; return existing; } } function createChild(returnFiber, newChild, lanes) { if (typeof newChild === 'string' && newChild !== '' || typeof newChild === 'number') { // Text nodes don't have keys. If the previous node is implicitly keyed // we can continue to replace it without aborting even if it is not a text // node. var created = createFiberFromText('' + newChild, returnFiber.mode, lanes); created.return = returnFiber; return created; } if (typeof newChild === 'object' && newChild !== null) { switch (newChild.$$typeof) { case REACT_ELEMENT_TYPE: { var _created = createFiberFromElement(newChild, returnFiber.mode, lanes); _created.ref = coerceRef(returnFiber, null, newChild); _created.return = returnFiber; return _created; } case REACT_PORTAL_TYPE: { var _created2 = createFiberFromPortal(newChild, returnFiber.mode, lanes); _created2.return = returnFiber; return _created2; } case REACT_LAZY_TYPE: { var payload = newChild._payload; var init = newChild._init; return createChild(returnFiber, init(payload), lanes); } } if (isArray(newChild) || getIteratorFn(newChild)) { var _created3 = createFiberFromFragment(newChild, returnFiber.mode, lanes, null); _created3.return = returnFiber; return _created3; } throwOnInvalidObjectType(returnFiber, newChild); } { if (typeof newChild === 'function') { warnOnFunctionType(returnFiber); } } return null; } function updateSlot(returnFiber, oldFiber, newChild, lanes) { // Update the fiber if the keys match, otherwise return null. var key = oldFiber !== null ? oldFiber.key : null; if (typeof newChild === 'string' && newChild !== '' || typeof newChild === 'number') { // Text nodes don't have keys. If the previous node is implicitly keyed // we can continue to replace it without aborting even if it is not a text // node. if (key !== null) { return null; } return updateTextNode(returnFiber, oldFiber, '' + newChild, lanes); } if (typeof newChild === 'object' && newChild !== null) { switch (newChild.$$typeof) { case REACT_ELEMENT_TYPE: { if (newChild.key === key) { return updateElement(returnFiber, oldFiber, newChild, lanes); } else { return null; } } case REACT_PORTAL_TYPE: { if (newChild.key === key) { return updatePortal(returnFiber, oldFiber, newChild, lanes); } else { return null; } } case REACT_LAZY_TYPE: { var payload = newChild._payload; var init = newChild._init; return updateSlot(returnFiber, oldFiber, init(payload), lanes); } } if (isArray(newChild) || getIteratorFn(newChild)) { if (key !== null) { return null; } return updateFragment(returnFiber, oldFiber, newChild, lanes, null); } throwOnInvalidObjectType(returnFiber, newChild); } { if (typeof newChild === 'function') { warnOnFunctionType(returnFiber); } } return null; } function updateFromMap(existingChildren, returnFiber, newIdx, newChild, lanes) { if (typeof newChild === 'string' && newChild !== '' || typeof newChild === 'number') { // Text nodes don't have keys, so we neither have to check the old nor // new node for the key. If both are text nodes, they match. var matchedFiber = existingChildren.get(newIdx) || null; return updateTextNode(returnFiber, matchedFiber, '' + newChild, lanes); } if (typeof newChild === 'object' && newChild !== null) { switch (newChild.$$typeof) { case REACT_ELEMENT_TYPE: { var _matchedFiber = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null; return updateElement(returnFiber, _matchedFiber, newChild, lanes); } case REACT_PORTAL_TYPE: { var _matchedFiber2 = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null; return updatePortal(returnFiber, _matchedFiber2, newChild, lanes); } case REACT_LAZY_TYPE: var payload = newChild._payload; var init = newChild._init; return updateFromMap(existingChildren, returnFiber, newIdx, init(payload), lanes); } if (isArray(newChild) || getIteratorFn(newChild)) { var _matchedFiber3 = existingChildren.get(newIdx) || null; return updateFragment(returnFiber, _matchedFiber3, newChild, lanes, null); } throwOnInvalidObjectType(returnFiber, newChild); } { if (typeof newChild === 'function') { warnOnFunctionType(returnFiber); } } return null; } /** * Warns if there is a duplicate or missing key */ function warnOnInvalidKey(child, knownKeys, returnFiber) { { if (typeof child !== 'object' || child === null) { return knownKeys; } switch (child.$$typeof) { case REACT_ELEMENT_TYPE: case REACT_PORTAL_TYPE: warnForMissingKey(child, returnFiber); var key = child.key; if (typeof key !== 'string') { break; } if (knownKeys === null) { knownKeys = new Set(); knownKeys.add(key); break; } if (!knownKeys.has(key)) { knownKeys.add(key); break; } error('Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.', key); break; case REACT_LAZY_TYPE: var payload = child._payload; var init = child._init; warnOnInvalidKey(init(payload), knownKeys, returnFiber); break; } } return knownKeys; } function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, lanes) { // This algorithm can't optimize by searching from both ends since we // don't have backpointers on fibers. I'm trying to see how far we can get // with that model. If it ends up not being worth the tradeoffs, we can // add it later. // Even with a two ended optimization, we'd want to optimize for the case // where there are few changes and brute force the comparison instead of // going for the Map. It'd like to explore hitting that path first in // forward-only mode and only go for the Map once we notice that we need // lots of look ahead. This doesn't handle reversal as well as two ended // search but that's unusual. Besides, for the two ended optimization to // work on Iterables, we'd need to copy the whole set. // In this first iteration, we'll just live with hitting the bad case // (adding everything to a Map) in for every insert/move. // If you change this code, also update reconcileChildrenIterator() which // uses the same algorithm. { // First, validate keys. var knownKeys = null; for (var i = 0; i < newChildren.length; i++) { var child = newChildren[i]; knownKeys = warnOnInvalidKey(child, knownKeys, returnFiber); } } var resultingFirstChild = null; var previousNewFiber = null; var oldFiber = currentFirstChild; var lastPlacedIndex = 0; var newIdx = 0; var nextOldFiber = null; for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) { if (oldFiber.index > newIdx) { nextOldFiber = oldFiber; oldFiber = null; } else { nextOldFiber = oldFiber.sibling; } var newFiber = updateSlot(returnFiber, oldFiber, newChildren[newIdx], lanes); if (newFiber === null) { // TODO: This breaks on empty slots like null children. That's // unfortunate because it triggers the slow path all the time. We need // a better way to communicate whether this was a miss or null, // boolean, undefined, etc. if (oldFiber === null) { oldFiber = nextOldFiber; } break; } if (shouldTrackSideEffects) { if (oldFiber && newFiber.alternate === null) { // We matched the slot, but we didn't reuse the existing fiber, so we // need to delete the existing child. deleteChild(returnFiber, oldFiber); } } lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); if (previousNewFiber === null) { // TODO: Move out of the loop. This only happens for the first run. resultingFirstChild = newFiber; } else { // TODO: Defer siblings if we're not at the right index for this slot. // I.e. if we had null values before, then we want to defer this // for each null value. However, we also don't want to call updateSlot // with the previous one. previousNewFiber.sibling = newFiber; } previousNewFiber = newFiber; oldFiber = nextOldFiber; } if (newIdx === newChildren.length) { // We've reached the end of the new children. We can delete the rest. deleteRemainingChildren(returnFiber, oldFiber); if (getIsHydrating()) { var numberOfForks = newIdx; pushTreeFork(returnFiber, numberOfForks); } return resultingFirstChild; } if (oldFiber === null) { // If we don't have any more existing children we can choose a fast path // since the rest will all be insertions. for (; newIdx < newChildren.length; newIdx++) { var _newFiber = createChild(returnFiber, newChildren[newIdx], lanes); if (_newFiber === null) { continue; } lastPlacedIndex = placeChild(_newFiber, lastPlacedIndex, newIdx); if (previousNewFiber === null) { // TODO: Move out of the loop. This only happens for the first run. resultingFirstChild = _newFiber; } else { previousNewFiber.sibling = _newFiber; } previousNewFiber = _newFiber; } if (getIsHydrating()) { var _numberOfForks = newIdx; pushTreeFork(returnFiber, _numberOfForks); } return resultingFirstChild; } // Add all children to a key map for quick lookups. var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves. for (; newIdx < newChildren.length; newIdx++) { var _newFiber2 = updateFromMap(existingChildren, returnFiber, newIdx, newChildren[newIdx], lanes); if (_newFiber2 !== null) { if (shouldTrackSideEffects) { if (_newFiber2.alternate !== null) { // The new fiber is a work in progress, but if there exists a // current, that means that we reused the fiber. We need to delete // it from the child list so that we don't add it to the deletion // list. existingChildren.delete(_newFiber2.key === null ? newIdx : _newFiber2.key); } } lastPlacedIndex = placeChild(_newFiber2, lastPlacedIndex, newIdx); if (previousNewFiber === null) { resultingFirstChild = _newFiber2; } else { previousNewFiber.sibling = _newFiber2; } previousNewFiber = _newFiber2; } } if (shouldTrackSideEffects) { // Any existing children that weren't consumed above were deleted. We need // to add them to the deletion list. existingChildren.forEach(function (child) { return deleteChild(returnFiber, child); }); } if (getIsHydrating()) { var _numberOfForks2 = newIdx; pushTreeFork(returnFiber, _numberOfForks2); } return resultingFirstChild; } function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildrenIterable, lanes) { // This is the same implementation as reconcileChildrenArray(), // but using the iterator instead. var iteratorFn = getIteratorFn(newChildrenIterable); if (typeof iteratorFn !== 'function') { throw new Error('An object is not an iterable. This error is likely caused by a bug in ' + 'React. Please file an issue.'); } { // We don't support rendering Generators because it's a mutation. // See https://github.com/facebook/react/issues/12995 if (typeof Symbol === 'function' && // $FlowFixMe Flow doesn't know about toStringTag newChildrenIterable[Symbol.toStringTag] === 'Generator') { if (!didWarnAboutGenerators) { error('Using Generators as children is unsupported and will likely yield ' + 'unexpected results because enumerating a generator mutates it. ' + 'You may convert it to an array with `Array.from()` or the ' + '`[...spread]` operator before rendering. Keep in mind ' + 'you might need to polyfill these features for older browsers.'); } didWarnAboutGenerators = true; } // Warn about using Maps as children if (newChildrenIterable.entries === iteratorFn) { if (!didWarnAboutMaps) { error('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.'); } didWarnAboutMaps = true; } // First, validate keys. // We'll get a different iterator later for the main pass. var _newChildren = iteratorFn.call(newChildrenIterable); if (_newChildren) { var knownKeys = null; var _step = _newChildren.next(); for (; !_step.done; _step = _newChildren.next()) { var child = _step.value; knownKeys = warnOnInvalidKey(child, knownKeys, returnFiber); } } } var newChildren = iteratorFn.call(newChildrenIterable); if (newChildren == null) { throw new Error('An iterable object provided no iterator.'); } var resultingFirstChild = null; var previousNewFiber = null; var oldFiber = currentFirstChild; var lastPlacedIndex = 0; var newIdx = 0; var nextOldFiber = null; var step = newChildren.next(); for (; oldFiber !== null && !step.done; newIdx++, step = newChildren.next()) { if (oldFiber.index > newIdx) { nextOldFiber = oldFiber; oldFiber = null; } else { nextOldFiber = oldFiber.sibling; } var newFiber = updateSlot(returnFiber, oldFiber, step.value, lanes); if (newFiber === null) { // TODO: This breaks on empty slots like null children. That's // unfortunate because it triggers the slow path all the time. We need // a better way to communicate whether this was a miss or null, // boolean, undefined, etc. if (oldFiber === null) { oldFiber = nextOldFiber; } break; } if (shouldTrackSideEffects) { if (oldFiber && newFiber.alternate === null) { // We matched the slot, but we didn't reuse the existing fiber, so we // need to delete the existing child. deleteChild(returnFiber, oldFiber); } } lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); if (previousNewFiber === null) { // TODO: Move out of the loop. This only happens for the first run. resultingFirstChild = newFiber; } else { // TODO: Defer siblings if we're not at the right index for this slot. // I.e. if we had null values before, then we want to defer this // for each null value. However, we also don't want to call updateSlot // with the previous one. previousNewFiber.sibling = newFiber; } previousNewFiber = newFiber; oldFiber = nextOldFiber; } if (step.done) { // We've reached the end of the new children. We can delete the rest. deleteRemainingChildren(returnFiber, oldFiber); if (getIsHydrating()) { var numberOfForks = newIdx; pushTreeFork(returnFiber, numberOfForks); } return resultingFirstChild; } if (oldFiber === null) { // If we don't have any more existing children we can choose a fast path // since the rest will all be insertions. for (; !step.done; newIdx++, step = newChildren.next()) { var _newFiber3 = createChild(returnFiber, step.value, lanes); if (_newFiber3 === null) { continue; } lastPlacedIndex = placeChild(_newFiber3, lastPlacedIndex, newIdx); if (previousNewFiber === null) { // TODO: Move out of the loop. This only happens for the first run. resultingFirstChild = _newFiber3; } else { previousNewFiber.sibling = _newFiber3; } previousNewFiber = _newFiber3; } if (getIsHydrating()) { var _numberOfForks3 = newIdx; pushTreeFork(returnFiber, _numberOfForks3); } return resultingFirstChild; } // Add all children to a key map for quick lookups. var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves. for (; !step.done; newIdx++, step = newChildren.next()) { var _newFiber4 = updateFromMap(existingChildren, returnFiber, newIdx, step.value, lanes); if (_newFiber4 !== null) { if (shouldTrackSideEffects) { if (_newFiber4.alternate !== null) { // The new fiber is a work in progress, but if there exists a // current, that means that we reused the fiber. We need to delete // it from the child list so that we don't add it to the deletion // list. existingChildren.delete(_newFiber4.key === null ? newIdx : _newFiber4.key); } } lastPlacedIndex = placeChild(_newFiber4, lastPlacedIndex, newIdx); if (previousNewFiber === null) { resultingFirstChild = _newFiber4; } else { previousNewFiber.sibling = _newFiber4; } previousNewFiber = _newFiber4; } } if (shouldTrackSideEffects) { // Any existing children that weren't consumed above were deleted. We need // to add them to the deletion list. existingChildren.forEach(function (child) { return deleteChild(returnFiber, child); }); } if (getIsHydrating()) { var _numberOfForks4 = newIdx; pushTreeFork(returnFiber, _numberOfForks4); } return resultingFirstChild; } function reconcileSingleTextNode(returnFiber, currentFirstChild, textContent, lanes) { // There's no need to check for keys on text nodes since we don't have a // way to define them. if (currentFirstChild !== null && currentFirstChild.tag === HostText) { // We already have an existing node so let's just update it and delete // the rest. deleteRemainingChildren(returnFiber, currentFirstChild.sibling); var existing = useFiber(currentFirstChild, textContent); existing.return = returnFiber; return existing; } // The existing first child is not a text node so we need to create one // and delete the existing ones. deleteRemainingChildren(returnFiber, currentFirstChild); var created = createFiberFromText(textContent, returnFiber.mode, lanes); created.return = returnFiber; return created; } function reconcileSingleElement(returnFiber, currentFirstChild, element, lanes) { var key = element.key; var child = currentFirstChild; while (child !== null) { // TODO: If key === null and child.key === null, then this only applies to // the first item in the list. if (child.key === key) { var elementType = element.type; if (elementType === REACT_FRAGMENT_TYPE) { if (child.tag === Fragment) { deleteRemainingChildren(returnFiber, child.sibling); var existing = useFiber(child, element.props.children); existing.return = returnFiber; { existing._debugSource = element._source; existing._debugOwner = element._owner; } return existing; } } else { if (child.elementType === elementType || ( // Keep this check inline so it only runs on the false path: isCompatibleFamilyForHotReloading(child, element) ) || // Lazy types should reconcile their resolved type. // We need to do this after the Hot Reloading check above, // because hot reloading has different semantics than prod because // it doesn't resuspend. So we can't let the call below suspend. typeof elementType === 'object' && elementType !== null && elementType.$$typeof === REACT_LAZY_TYPE && resolveLazy(elementType) === child.type) { deleteRemainingChildren(returnFiber, child.sibling); var _existing = useFiber(child, element.props); _existing.ref = coerceRef(returnFiber, child, element); _existing.return = returnFiber; { _existing._debugSource = element._source; _existing._debugOwner = element._owner; } return _existing; } } // Didn't match. deleteRemainingChildren(returnFiber, child); break; } else { deleteChild(returnFiber, child); } child = child.sibling; } if (element.type === REACT_FRAGMENT_TYPE) { var created = createFiberFromFragment(element.props.children, returnFiber.mode, lanes, element.key); created.return = returnFiber; return created; } else { var _created4 = createFiberFromElement(element, returnFiber.mode, lanes); _created4.ref = coerceRef(returnFiber, currentFirstChild, element); _created4.return = returnFiber; return _created4; } } function reconcileSinglePortal(returnFiber, currentFirstChild, portal, lanes) { var key = portal.key; var child = currentFirstChild; while (child !== null) { // TODO: If key === null and child.key === null, then this only applies to // the first item in the list. if (child.key === key) { if (child.tag === HostPortal && child.stateNode.containerInfo === portal.containerInfo && child.stateNode.implementation === portal.implementation) { deleteRemainingChildren(returnFiber, child.sibling); var existing = useFiber(child, portal.children || []); existing.return = returnFiber; return existing; } else { deleteRemainingChildren(returnFiber, child); break; } } else { deleteChild(returnFiber, child); } child = child.sibling; } var created = createFiberFromPortal(portal, returnFiber.mode, lanes); created.return = returnFiber; return created; } // This API will tag the children with the side-effect of the reconciliation // itself. They will be added to the side-effect list as we pass through the // children and the parent. function reconcileChildFibers(returnFiber, currentFirstChild, newChild, lanes) { // This function is not recursive. // If the top level item is an array, we treat it as a set of children, // not as a fragment. Nested arrays on the other hand will be treated as // fragment nodes. Recursion happens at the normal flow. // Handle top level unkeyed fragments as if they were arrays. // This leads to an ambiguity between <>{[...]}</> and <>...</>. // We treat the ambiguous cases above the same. var isUnkeyedTopLevelFragment = typeof newChild === 'object' && newChild !== null && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null; if (isUnkeyedTopLevelFragment) { newChild = newChild.props.children; } // Handle object types if (typeof newChild === 'object' && newChild !== null) { switch (newChild.$$typeof) { case REACT_ELEMENT_TYPE: return placeSingleChild(reconcileSingleElement(returnFiber, currentFirstChild, newChild, lanes)); case REACT_PORTAL_TYPE: return placeSingleChild(reconcileSinglePortal(returnFiber, currentFirstChild, newChild, lanes)); case REACT_LAZY_TYPE: var payload = newChild._payload; var init = newChild._init; // TODO: This function is supposed to be non-recursive. return reconcileChildFibers(returnFiber, currentFirstChild, init(payload), lanes); } if (isArray(newChild)) { return reconcileChildrenArray(returnFiber, currentFirstChild, newChild, lanes); } if (getIteratorFn(newChild)) { return reconcileChildrenIterator(returnFiber, currentFirstChild, newChild, lanes); } throwOnInvalidObjectType(returnFiber, newChild); } if (typeof newChild === 'string' && newChild !== '' || typeof newChild === 'number') { return placeSingleChild(reconcileSingleTextNode(returnFiber, currentFirstChild, '' + newChild, lanes)); } { if (typeof newChild === 'function') { warnOnFunctionType(returnFiber); } } // Remaining cases are all treated as empty. return deleteRemainingChildren(returnFiber, currentFirstChild); } return reconcileChildFibers; } var reconcileChildFibers = ChildReconciler(true); var mountChildFibers = ChildReconciler(false); function cloneChildFibers(current, workInProgress) { if (current !== null && workInProgress.child !== current.child) { throw new Error('Resuming work not yet implemented.'); } if (workInProgress.child === null) { return; } var currentChild = workInProgress.child; var newChild = createWorkInProgress(currentChild, currentChild.pendingProps); workInProgress.child = newChild; newChild.return = workInProgress; while (currentChild.sibling !== null) { currentChild = currentChild.sibling; newChild = newChild.sibling = createWorkInProgress(currentChild, currentChild.pendingProps); newChild.return = workInProgress; } newChild.sibling = null; } // Reset a workInProgress child set to prepare it for a second pass. function resetChildFibers(workInProgress, lanes) { var child = workInProgress.child; while (child !== null) { resetWorkInProgress(child, lanes); child = child.sibling; } } var NO_CONTEXT = {}; var contextStackCursor$1 = createCursor(NO_CONTEXT); var contextFiberStackCursor = createCursor(NO_CONTEXT); var rootInstanceStackCursor = createCursor(NO_CONTEXT); function requiredContext(c) { if (c === NO_CONTEXT) { throw new Error('Expected host context to exist. This error is likely caused by a bug ' + 'in React. Please file an issue.'); } return c; } function getRootHostContainer() { var rootInstance = requiredContext(rootInstanceStackCursor.current); return rootInstance; } function pushHostContainer(fiber, nextRootInstance) { // Push current root instance onto the stack; // This allows us to reset root when portals are popped. push(rootInstanceStackCursor, nextRootInstance, fiber); // Track the context and the Fiber that provided it. // This enables us to pop only Fibers that provide unique contexts. push(contextFiberStackCursor, fiber, fiber); // Finally, we need to push the host context to the stack. // However, we can't just call getRootHostContext() and push it because // we'd have a different number of entries on the stack depending on // whether getRootHostContext() throws somewhere in renderer code or not. // So we push an empty value first. This lets us safely unwind on errors. push(contextStackCursor$1, NO_CONTEXT, fiber); var nextRootContext = getRootHostContext(nextRootInstance); // Now that we know this function doesn't throw, replace it. pop(contextStackCursor$1, fiber); push(contextStackCursor$1, nextRootContext, fiber); } function popHostContainer(fiber) { pop(contextStackCursor$1, fiber); pop(contextFiberStackCursor, fiber); pop(rootInstanceStackCursor, fiber); } function getHostContext() { var context = requiredContext(contextStackCursor$1.current); return context; } function pushHostContext(fiber) { var rootInstance = requiredContext(rootInstanceStackCursor.current); var context = requiredContext(contextStackCursor$1.current); var nextContext = getChildHostContext(context, fiber.type); // Don't push this Fiber's context unless it's unique. if (context === nextContext) { return; } // Track the context and the Fiber that provided it. // This enables us to pop only Fibers that provide unique contexts. push(contextFiberStackCursor, fiber, fiber); push(contextStackCursor$1, nextContext, fiber); } function popHostContext(fiber) { // Do not pop unless this Fiber provided the current context. // pushHostContext() only pushes Fibers that provide unique contexts. if (contextFiberStackCursor.current !== fiber) { return; } pop(contextStackCursor$1, fiber); pop(contextFiberStackCursor, fiber); } var DefaultSuspenseContext = 0; // The Suspense Context is split into two parts. The lower bits is // inherited deeply down the subtree. The upper bits only affect // this immediate suspense boundary and gets reset each new // boundary or suspense list. var SubtreeSuspenseContextMask = 1; // Subtree Flags: // InvisibleParentSuspenseContext indicates that one of our parent Suspense // boundaries is not currently showing visible main content. // Either because it is already showing a fallback or is not mounted at all. // We can use this to determine if it is desirable to trigger a fallback at // the parent. If not, then we might need to trigger undesirable boundaries // and/or suspend the commit to avoid hiding the parent content. var InvisibleParentSuspenseContext = 1; // Shallow Flags: // ForceSuspenseFallback can be used by SuspenseList to force newly added // items into their fallback state during one of the render passes. var ForceSuspenseFallback = 2; var suspenseStackCursor = createCursor(DefaultSuspenseContext); function hasSuspenseContext(parentContext, flag) { return (parentContext & flag) !== 0; } function setDefaultShallowSuspenseContext(parentContext) { return parentContext & SubtreeSuspenseContextMask; } function setShallowSuspenseContext(parentContext, shallowContext) { return parentContext & SubtreeSuspenseContextMask | shallowContext; } function addSubtreeSuspenseContext(parentContext, subtreeContext) { return parentContext | subtreeContext; } function pushSuspenseContext(fiber, newContext) { push(suspenseStackCursor, newContext, fiber); } function popSuspenseContext(fiber) { pop(suspenseStackCursor, fiber); } function shouldCaptureSuspense(workInProgress, hasInvisibleParent) { // If it was the primary children that just suspended, capture and render the // fallback. Otherwise, don't capture and bubble to the next boundary. var nextState = workInProgress.memoizedState; if (nextState !== null) { if (nextState.dehydrated !== null) { // A dehydrated boundary always captures. return true; } return false; } var props = workInProgress.memoizedProps; // Regular boundaries always capture. { return true; } // If it's a boundary we should avoid, then we prefer to bubble up to the } function findFirstSuspended(row) { var node = row; while (node !== null) { if (node.tag === SuspenseComponent) { var state = node.memoizedState; if (state !== null) { var dehydrated = state.dehydrated; if (dehydrated === null || isSuspenseInstancePending(dehydrated) || isSuspenseInstanceFallback(dehydrated)) { return node; } } } else if (node.tag === SuspenseListComponent && // revealOrder undefined can't be trusted because it don't // keep track of whether it suspended or not. node.memoizedProps.revealOrder !== undefined) { var didSuspend = (node.flags & DidCapture) !== NoFlags; if (didSuspend) { return node; } } else if (node.child !== null) { node.child.return = node; node = node.child; continue; } if (node === row) { return null; } while (node.sibling === null) { if (node.return === null || node.return === row) { return null; } node = node.return; } node.sibling.return = node.return; node = node.sibling; } return null; } var NoFlags$1 = /* */ 0; // Represents whether effect should fire. var HasEffect = /* */ 1; // Represents the phase in which the effect (not the clean-up) fires. var Insertion = /* */ 2; var Layout = /* */ 4; var Passive$1 = /* */ 8; // and should be reset before starting a new render. // This tracks which mutable sources need to be reset after a render. var workInProgressSources = []; function resetWorkInProgressVersions() { for (var i = 0; i < workInProgressSources.length; i++) { var mutableSource = workInProgressSources[i]; { mutableSource._workInProgressVersionPrimary = null; } } workInProgressSources.length = 0; } // This ensures that the version used for server rendering matches the one // that is eventually read during hydration. // If they don't match there's a potential tear and a full deopt render is required. function registerMutableSourceForHydration(root, mutableSource) { var getVersion = mutableSource._getVersion; var version = getVersion(mutableSource._source); // TODO Clear this data once all pending hydration work is finished. // Retaining it forever may interfere with GC. if (root.mutableSourceEagerHydrationData == null) { root.mutableSourceEagerHydrationData = [mutableSource, version]; } else { root.mutableSourceEagerHydrationData.push(mutableSource, version); } } var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher, ReactCurrentBatchConfig$2 = ReactSharedInternals.ReactCurrentBatchConfig; var didWarnAboutMismatchedHooksForComponent; var didWarnUncachedGetSnapshot; { didWarnAboutMismatchedHooksForComponent = new Set(); } // These are set right before calling the component. var renderLanes = NoLanes; // The work-in-progress fiber. I've named it differently to distinguish it from // the work-in-progress hook. var currentlyRenderingFiber$1 = null; // Hooks are stored as a linked list on the fiber's memoizedState field. The // current hook list is the list that belongs to the current fiber. The // work-in-progress hook list is a new list that will be added to the // work-in-progress fiber. var currentHook = null; var workInProgressHook = null; // Whether an update was scheduled at any point during the render phase. This // does not get reset if we do another render pass; only when we're completely // finished evaluating this component. This is an optimization so we know // whether we need to clear render phase updates after a throw. var didScheduleRenderPhaseUpdate = false; // Where an update was scheduled only during the current render pass. This // gets reset after each attempt. // TODO: Maybe there's some way to consolidate this with // `didScheduleRenderPhaseUpdate`. Or with `numberOfReRenders`. var didScheduleRenderPhaseUpdateDuringThisPass = false; // Counts the number of useId hooks in this component. var localIdCounter = 0; // Used for ids that are generated completely client-side (i.e. not during // hydration). This counter is global, so client ids are not stable across // render attempts. var globalClientIdCounter = 0; var RE_RENDER_LIMIT = 25; // In DEV, this is the name of the currently executing primitive hook var currentHookNameInDev = null; // In DEV, this list ensures that hooks are called in the same order between renders. // The list stores the order of hooks used during the initial render (mount). // Subsequent renders (updates) reference this list. var hookTypesDev = null; var hookTypesUpdateIndexDev = -1; // In DEV, this tracks whether currently rendering component needs to ignore // the dependencies for Hooks that need them (e.g. useEffect or useMemo). // When true, such Hooks will always be "remounted". Only used during hot reload. var ignorePreviousDependencies = false; function mountHookTypesDev() { { var hookName = currentHookNameInDev; if (hookTypesDev === null) { hookTypesDev = [hookName]; } else { hookTypesDev.push(hookName); } } } function updateHookTypesDev() { { var hookName = currentHookNameInDev; if (hookTypesDev !== null) { hookTypesUpdateIndexDev++; if (hookTypesDev[hookTypesUpdateIndexDev] !== hookName) { warnOnHookMismatchInDev(hookName); } } } } function checkDepsAreArrayDev(deps) { { if (deps !== undefined && deps !== null && !isArray(deps)) { // Verify deps, but only on mount to avoid extra checks. // It's unlikely their type would change as usually you define them inline. error('%s received a final argument that is not an array (instead, received `%s`). When ' + 'specified, the final argument must be an array.', currentHookNameInDev, typeof deps); } } } function warnOnHookMismatchInDev(currentHookName) { { var componentName = getComponentNameFromFiber(currentlyRenderingFiber$1); if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) { didWarnAboutMismatchedHooksForComponent.add(componentName); if (hookTypesDev !== null) { var table = ''; var secondColumnStart = 30; for (var i = 0; i <= hookTypesUpdateIndexDev; i++) { var oldHookName = hookTypesDev[i]; var newHookName = i === hookTypesUpdateIndexDev ? currentHookName : oldHookName; var row = i + 1 + ". " + oldHookName; // Extra space so second column lines up // lol @ IE not supporting String#repeat while (row.length < secondColumnStart) { row += ' '; } row += newHookName + '\n'; table += row; } error('React has detected a change in the order of Hooks called by %s. ' + 'This will lead to bugs and errors if not fixed. ' + 'For more information, read the Rules of Hooks: https://reactjs.org/link/rules-of-hooks\n\n' + ' Previous render Next render\n' + ' ------------------------------------------------------\n' + '%s' + ' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n', componentName, table); } } } } function throwInvalidHookError() { throw new Error('Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + ' one of the following reasons:\n' + '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' + '2. You might be breaking the Rules of Hooks\n' + '3. You might have more than one copy of React in the same app\n' + 'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.'); } function areHookInputsEqual(nextDeps, prevDeps) { { if (ignorePreviousDependencies) { // Only true when this component is being hot reloaded. return false; } } if (prevDeps === null) { { error('%s received a final argument during this render, but not during ' + 'the previous render. Even though the final argument is optional, ' + 'its type cannot change between renders.', currentHookNameInDev); } return false; } { // Don't bother comparing lengths in prod because these arrays should be // passed inline. if (nextDeps.length !== prevDeps.length) { error('The final argument passed to %s changed size between renders. The ' + 'order and size of this array must remain constant.\n\n' + 'Previous: %s\n' + 'Incoming: %s', currentHookNameInDev, "[" + prevDeps.join(', ') + "]", "[" + nextDeps.join(', ') + "]"); } } for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) { if (objectIs(nextDeps[i], prevDeps[i])) { continue; } return false; } return true; } function renderWithHooks(current, workInProgress, Component, props, secondArg, nextRenderLanes) { renderLanes = nextRenderLanes; currentlyRenderingFiber$1 = workInProgress; { hookTypesDev = current !== null ? current._debugHookTypes : null; hookTypesUpdateIndexDev = -1; // Used for hot reloading: ignorePreviousDependencies = current !== null && current.type !== workInProgress.type; } workInProgress.memoizedState = null; workInProgress.updateQueue = null; workInProgress.lanes = NoLanes; // The following should have already been reset // currentHook = null; // workInProgressHook = null; // didScheduleRenderPhaseUpdate = false; // localIdCounter = 0; // TODO Warn if no hooks are used at all during mount, then some are used during update. // Currently we will identify the update render as a mount because memoizedState === null. // This is tricky because it's valid for certain types of components (e.g. React.lazy) // Using memoizedState to differentiate between mount/update only works if at least one stateful hook is used. // Non-stateful hooks (e.g. context) don't get added to memoizedState, // so memoizedState would be null during updates and mounts. { if (current !== null && current.memoizedState !== null) { ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV; } else if (hookTypesDev !== null) { // This dispatcher handles an edge case where a component is updating, // but no stateful hooks have been used. // We want to match the production code behavior (which will use HooksDispatcherOnMount), // but with the extra DEV validation to ensure hooks ordering hasn't changed. // This dispatcher does that. ReactCurrentDispatcher$1.current = HooksDispatcherOnMountWithHookTypesInDEV; } else { ReactCurrentDispatcher$1.current = HooksDispatcherOnMountInDEV; } } var children = Component(props, secondArg); // Check if there was a render phase update if (didScheduleRenderPhaseUpdateDuringThisPass) { // Keep rendering in a loop for as long as render phase updates continue to // be scheduled. Use a counter to prevent infinite loops. var numberOfReRenders = 0; do { didScheduleRenderPhaseUpdateDuringThisPass = false; localIdCounter = 0; if (numberOfReRenders >= RE_RENDER_LIMIT) { throw new Error('Too many re-renders. React limits the number of renders to prevent ' + 'an infinite loop.'); } numberOfReRenders += 1; { // Even when hot reloading, allow dependencies to stabilize // after first render to prevent infinite render phase updates. ignorePreviousDependencies = false; } // Start over from the beginning of the list currentHook = null; workInProgressHook = null; workInProgress.updateQueue = null; { // Also validate hook order for cascading updates. hookTypesUpdateIndexDev = -1; } ReactCurrentDispatcher$1.current = HooksDispatcherOnRerenderInDEV ; children = Component(props, secondArg); } while (didScheduleRenderPhaseUpdateDuringThisPass); } // We can assume the previous dispatcher is always this one, since we set it // at the beginning of the render phase and there's no re-entrance. ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; { workInProgress._debugHookTypes = hookTypesDev; } // This check uses currentHook so that it works the same in DEV and prod bundles. // hookTypesDev could catch more cases (e.g. context) but only in DEV bundles. var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null; renderLanes = NoLanes; currentlyRenderingFiber$1 = null; currentHook = null; workInProgressHook = null; { currentHookNameInDev = null; hookTypesDev = null; hookTypesUpdateIndexDev = -1; // Confirm that a static flag was not added or removed since the last // render. If this fires, it suggests that we incorrectly reset the static // flags in some other part of the codebase. This has happened before, for // example, in the SuspenseList implementation. if (current !== null && (current.flags & StaticMask) !== (workInProgress.flags & StaticMask) && // Disable this warning in legacy mode, because legacy Suspense is weird // and creates false positives. To make this work in legacy mode, we'd // need to mark fibers that commit in an incomplete state, somehow. For // now I'll disable the warning that most of the bugs that would trigger // it are either exclusive to concurrent mode or exist in both. (current.mode & ConcurrentMode) !== NoMode) { error('Internal React error: Expected static flag was missing. Please ' + 'notify the React team.'); } } didScheduleRenderPhaseUpdate = false; // This is reset by checkDidRenderIdHook // localIdCounter = 0; if (didRenderTooFewHooks) { throw new Error('Rendered fewer hooks than expected. This may be caused by an accidental ' + 'early return statement.'); } return children; } function checkDidRenderIdHook() { // This should be called immediately after every renderWithHooks call. // Conceptually, it's part of the return value of renderWithHooks; it's only a // separate function to avoid using an array tuple. var didRenderIdHook = localIdCounter !== 0; localIdCounter = 0; return didRenderIdHook; } function bailoutHooks(current, workInProgress, lanes) { workInProgress.updateQueue = current.updateQueue; // TODO: Don't need to reset the flags here, because they're reset in the // complete phase (bubbleProperties). if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) { workInProgress.flags &= ~(MountPassiveDev | MountLayoutDev | Passive | Update); } else { workInProgress.flags &= ~(Passive | Update); } current.lanes = removeLanes(current.lanes, lanes); } function resetHooksAfterThrow() { // We can assume the previous dispatcher is always this one, since we set it // at the beginning of the render phase and there's no re-entrance. ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; if (didScheduleRenderPhaseUpdate) { // There were render phase updates. These are only valid for this render // phase, which we are now aborting. Remove the updates from the queues so // they do not persist to the next render. Do not remove updates from hooks // that weren't processed. // // Only reset the updates from the queue if it has a clone. If it does // not have a clone, that means it wasn't processed, and the updates were // scheduled before we entered the render phase. var hook = currentlyRenderingFiber$1.memoizedState; while (hook !== null) { var queue = hook.queue; if (queue !== null) { queue.pending = null; } hook = hook.next; } didScheduleRenderPhaseUpdate = false; } renderLanes = NoLanes; currentlyRenderingFiber$1 = null; currentHook = null; workInProgressHook = null; { hookTypesDev = null; hookTypesUpdateIndexDev = -1; currentHookNameInDev = null; isUpdatingOpaqueValueInRenderPhase = false; } didScheduleRenderPhaseUpdateDuringThisPass = false; localIdCounter = 0; } function mountWorkInProgressHook() { var hook = { memoizedState: null, baseState: null, baseQueue: null, queue: null, next: null }; if (workInProgressHook === null) { // This is the first hook in the list currentlyRenderingFiber$1.memoizedState = workInProgressHook = hook; } else { // Append to the end of the list workInProgressHook = workInProgressHook.next = hook; } return workInProgressHook; } function updateWorkInProgressHook() { // This function is used both for updates and for re-renders triggered by a // render phase update. It assumes there is either a current hook we can // clone, or a work-in-progress hook from a previous render pass that we can // use as a base. When we reach the end of the base list, we must switch to // the dispatcher used for mounts. var nextCurrentHook; if (currentHook === null) { var current = currentlyRenderingFiber$1.alternate; if (current !== null) { nextCurrentHook = current.memoizedState; } else { nextCurrentHook = null; } } else { nextCurrentHook = currentHook.next; } var nextWorkInProgressHook; if (workInProgressHook === null) { nextWorkInProgressHook = currentlyRenderingFiber$1.memoizedState; } else { nextWorkInProgressHook = workInProgressHook.next; } if (nextWorkInProgressHook !== null) { // There's already a work-in-progress. Reuse it. workInProgressHook = nextWorkInProgressHook; nextWorkInProgressHook = workInProgressHook.next; currentHook = nextCurrentHook; } else { // Clone from the current hook. if (nextCurrentHook === null) { throw new Error('Rendered more hooks than during the previous render.'); } currentHook = nextCurrentHook; var newHook = { memoizedState: currentHook.memoizedState, baseState: currentHook.baseState, baseQueue: currentHook.baseQueue, queue: currentHook.queue, next: null }; if (workInProgressHook === null) { // This is the first hook in the list. currentlyRenderingFiber$1.memoizedState = workInProgressHook = newHook; } else { // Append to the end of the list. workInProgressHook = workInProgressHook.next = newHook; } } return workInProgressHook; } function createFunctionComponentUpdateQueue() { return { lastEffect: null, stores: null }; } function basicStateReducer(state, action) { // $FlowFixMe: Flow doesn't like mixed types return typeof action === 'function' ? action(state) : action; } function mountReducer(reducer, initialArg, init) { var hook = mountWorkInProgressHook(); var initialState; if (init !== undefined) { initialState = init(initialArg); } else { initialState = initialArg; } hook.memoizedState = hook.baseState = initialState; var queue = { pending: null, interleaved: null, lanes: NoLanes, dispatch: null, lastRenderedReducer: reducer, lastRenderedState: initialState }; hook.queue = queue; var dispatch = queue.dispatch = dispatchReducerAction.bind(null, currentlyRenderingFiber$1, queue); return [hook.memoizedState, dispatch]; } function updateReducer(reducer, initialArg, init) { var hook = updateWorkInProgressHook(); var queue = hook.queue; if (queue === null) { throw new Error('Should have a queue. This is likely a bug in React. Please file an issue.'); } queue.lastRenderedReducer = reducer; var current = currentHook; // The last rebase update that is NOT part of the base state. var baseQueue = current.baseQueue; // The last pending update that hasn't been processed yet. var pendingQueue = queue.pending; if (pendingQueue !== null) { // We have new updates that haven't been processed yet. // We'll add them to the base queue. if (baseQueue !== null) { // Merge the pending queue and the base queue. var baseFirst = baseQueue.next; var pendingFirst = pendingQueue.next; baseQueue.next = pendingFirst; pendingQueue.next = baseFirst; } { if (current.baseQueue !== baseQueue) { // Internal invariant that should never happen, but feasibly could in // the future if we implement resuming, or some form of that. error('Internal error: Expected work-in-progress queue to be a clone. ' + 'This is a bug in React.'); } } current.baseQueue = baseQueue = pendingQueue; queue.pending = null; } if (baseQueue !== null) { // We have a queue to process. var first = baseQueue.next; var newState = current.baseState; var newBaseState = null; var newBaseQueueFirst = null; var newBaseQueueLast = null; var update = first; do { var updateLane = update.lane; if (!isSubsetOfLanes(renderLanes, updateLane)) { // Priority is insufficient. Skip this update. If this is the first // skipped update, the previous update/state is the new base // update/state. var clone = { lane: updateLane, action: update.action, hasEagerState: update.hasEagerState, eagerState: update.eagerState, next: null }; if (newBaseQueueLast === null) { newBaseQueueFirst = newBaseQueueLast = clone; newBaseState = newState; } else { newBaseQueueLast = newBaseQueueLast.next = clone; } // Update the remaining priority in the queue. // TODO: Don't need to accumulate this. Instead, we can remove // renderLanes from the original lanes. currentlyRenderingFiber$1.lanes = mergeLanes(currentlyRenderingFiber$1.lanes, updateLane); markSkippedUpdateLanes(updateLane); } else { // This update does have sufficient priority. if (newBaseQueueLast !== null) { var _clone = { // This update is going to be committed so we never want uncommit // it. Using NoLane works because 0 is a subset of all bitmasks, so // this will never be skipped by the check above. lane: NoLane, action: update.action, hasEagerState: update.hasEagerState, eagerState: update.eagerState, next: null }; newBaseQueueLast = newBaseQueueLast.next = _clone; } // Process this update. if (update.hasEagerState) { // If this update is a state update (not a reducer) and was processed eagerly, // we can use the eagerly computed state newState = update.eagerState; } else { var action = update.action; newState = reducer(newState, action); } } update = update.next; } while (update !== null && update !== first); if (newBaseQueueLast === null) { newBaseState = newState; } else { newBaseQueueLast.next = newBaseQueueFirst; } // Mark that the fiber performed work, but only if the new state is // different from the current state. if (!objectIs(newState, hook.memoizedState)) { markWorkInProgressReceivedUpdate(); } hook.memoizedState = newState; hook.baseState = newBaseState; hook.baseQueue = newBaseQueueLast; queue.lastRenderedState = newState; } // Interleaved updates are stored on a separate queue. We aren't going to // process them during this render, but we do need to track which lanes // are remaining. var lastInterleaved = queue.interleaved; if (lastInterleaved !== null) { var interleaved = lastInterleaved; do { var interleavedLane = interleaved.lane; currentlyRenderingFiber$1.lanes = mergeLanes(currentlyRenderingFiber$1.lanes, interleavedLane); markSkippedUpdateLanes(interleavedLane); interleaved = interleaved.next; } while (interleaved !== lastInterleaved); } else if (baseQueue === null) { // `queue.lanes` is used for entangling transitions. We can set it back to // zero once the queue is empty. queue.lanes = NoLanes; } var dispatch = queue.dispatch; return [hook.memoizedState, dispatch]; } function rerenderReducer(reducer, initialArg, init) { var hook = updateWorkInProgressHook(); var queue = hook.queue; if (queue === null) { throw new Error('Should have a queue. This is likely a bug in React. Please file an issue.'); } queue.lastRenderedReducer = reducer; // This is a re-render. Apply the new render phase updates to the previous // work-in-progress hook. var dispatch = queue.dispatch; var lastRenderPhaseUpdate = queue.pending; var newState = hook.memoizedState; if (lastRenderPhaseUpdate !== null) { // The queue doesn't persist past this render pass. queue.pending = null; var firstRenderPhaseUpdate = lastRenderPhaseUpdate.next; var update = firstRenderPhaseUpdate; do { // Process this render phase update. We don't have to check the // priority because it will always be the same as the current // render's. var action = update.action; newState = reducer(newState, action); update = update.next; } while (update !== firstRenderPhaseUpdate); // Mark that the fiber performed work, but only if the new state is // different from the current state. if (!objectIs(newState, hook.memoizedState)) { markWorkInProgressReceivedUpdate(); } hook.memoizedState = newState; // Don't persist the state accumulated from the render phase updates to // the base state unless the queue is empty. // TODO: Not sure if this is the desired semantics, but it's what we // do for gDSFP. I can't remember why. if (hook.baseQueue === null) { hook.baseState = newState; } queue.lastRenderedState = newState; } return [newState, dispatch]; } function mountMutableSource(source, getSnapshot, subscribe) { { return undefined; } } function updateMutableSource(source, getSnapshot, subscribe) { { return undefined; } } function mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { var fiber = currentlyRenderingFiber$1; var hook = mountWorkInProgressHook(); var nextSnapshot; var isHydrating = getIsHydrating(); if (isHydrating) { if (getServerSnapshot === undefined) { throw new Error('Missing getServerSnapshot, which is required for ' + 'server-rendered content. Will revert to client rendering.'); } nextSnapshot = getServerSnapshot(); { if (!didWarnUncachedGetSnapshot) { if (nextSnapshot !== getServerSnapshot()) { error('The result of getServerSnapshot should be cached to avoid an infinite loop'); didWarnUncachedGetSnapshot = true; } } } } else { nextSnapshot = getSnapshot(); { if (!didWarnUncachedGetSnapshot) { var cachedSnapshot = getSnapshot(); if (!objectIs(nextSnapshot, cachedSnapshot)) { error('The result of getSnapshot should be cached to avoid an infinite loop'); didWarnUncachedGetSnapshot = true; } } } // Unless we're rendering a blocking lane, schedule a consistency check. // Right before committing, we will walk the tree and check if any of the // stores were mutated. // // We won't do this if we're hydrating server-rendered content, because if // the content is stale, it's already visible anyway. Instead we'll patch // it up in a passive effect. var root = getWorkInProgressRoot(); if (root === null) { throw new Error('Expected a work-in-progress root. This is a bug in React. Please file an issue.'); } if (!includesBlockingLane(root, renderLanes)) { pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot); } } // Read the current snapshot from the store on every render. This breaks the // normal rules of React, and only works because store updates are // always synchronous. hook.memoizedState = nextSnapshot; var inst = { value: nextSnapshot, getSnapshot: getSnapshot }; hook.queue = inst; // Schedule an effect to subscribe to the store. mountEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [subscribe]); // Schedule an effect to update the mutable instance fields. We will update // this whenever subscribe, getSnapshot, or value changes. Because there's no // clean-up function, and we track the deps correctly, we can call pushEffect // directly, without storing any additional state. For the same reason, we // don't need to set a static flag, either. // TODO: We can move this to the passive phase once we add a pre-commit // consistency check. See the next comment. fiber.flags |= Passive; pushEffect(HasEffect | Passive$1, updateStoreInstance.bind(null, fiber, inst, nextSnapshot, getSnapshot), undefined, null); return nextSnapshot; } function updateSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { var fiber = currentlyRenderingFiber$1; var hook = updateWorkInProgressHook(); // Read the current snapshot from the store on every render. This breaks the // normal rules of React, and only works because store updates are // always synchronous. var nextSnapshot = getSnapshot(); { if (!didWarnUncachedGetSnapshot) { var cachedSnapshot = getSnapshot(); if (!objectIs(nextSnapshot, cachedSnapshot)) { error('The result of getSnapshot should be cached to avoid an infinite loop'); didWarnUncachedGetSnapshot = true; } } } var prevSnapshot = hook.memoizedState; var snapshotChanged = !objectIs(prevSnapshot, nextSnapshot); if (snapshotChanged) { hook.memoizedState = nextSnapshot; markWorkInProgressReceivedUpdate(); } var inst = hook.queue; updateEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [subscribe]); // Whenever getSnapshot or subscribe changes, we need to check in the // commit phase if there was an interleaved mutation. In concurrent mode // this can happen all the time, but even in synchronous mode, an earlier // effect may have mutated the store. if (inst.getSnapshot !== getSnapshot || snapshotChanged || // Check if the susbcribe function changed. We can save some memory by // checking whether we scheduled a subscription effect above. workInProgressHook !== null && workInProgressHook.memoizedState.tag & HasEffect) { fiber.flags |= Passive; pushEffect(HasEffect | Passive$1, updateStoreInstance.bind(null, fiber, inst, nextSnapshot, getSnapshot), undefined, null); // Unless we're rendering a blocking lane, schedule a consistency check. // Right before committing, we will walk the tree and check if any of the // stores were mutated. var root = getWorkInProgressRoot(); if (root === null) { throw new Error('Expected a work-in-progress root. This is a bug in React. Please file an issue.'); } if (!includesBlockingLane(root, renderLanes)) { pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot); } } return nextSnapshot; } function pushStoreConsistencyCheck(fiber, getSnapshot, renderedSnapshot) { fiber.flags |= StoreConsistency; var check = { getSnapshot: getSnapshot, value: renderedSnapshot }; var componentUpdateQueue = currentlyRenderingFiber$1.updateQueue; if (componentUpdateQueue === null) { componentUpdateQueue = createFunctionComponentUpdateQueue(); currentlyRenderingFiber$1.updateQueue = componentUpdateQueue; componentUpdateQueue.stores = [check]; } else { var stores = componentUpdateQueue.stores; if (stores === null) { componentUpdateQueue.stores = [check]; } else { stores.push(check); } } } function updateStoreInstance(fiber, inst, nextSnapshot, getSnapshot) { // These are updated in the passive phase inst.value = nextSnapshot; inst.getSnapshot = getSnapshot; // Something may have been mutated in between render and commit. This could // have been in an event that fired before the passive effects, or it could // have been in a layout effect. In that case, we would have used the old // snapsho and getSnapshot values to bail out. We need to check one more time. if (checkIfSnapshotChanged(inst)) { // Force a re-render. forceStoreRerender(fiber); } } function subscribeToStore(fiber, inst, subscribe) { var handleStoreChange = function () { // The store changed. Check if the snapshot changed since the last time we // read from the store. if (checkIfSnapshotChanged(inst)) { // Force a re-render. forceStoreRerender(fiber); } }; // Subscribe to the store and return a clean-up function. return subscribe(handleStoreChange); } function checkIfSnapshotChanged(inst) { var latestGetSnapshot = inst.getSnapshot; var prevValue = inst.value; try { var nextValue = latestGetSnapshot(); return !objectIs(prevValue, nextValue); } catch (error) { return true; } } function forceStoreRerender(fiber) { var root = enqueueConcurrentRenderForLane(fiber, SyncLane); if (root !== null) { scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); } } function mountState(initialState) { var hook = mountWorkInProgressHook(); if (typeof initialState === 'function') { // $FlowFixMe: Flow doesn't like mixed types initialState = initialState(); } hook.memoizedState = hook.baseState = initialState; var queue = { pending: null, interleaved: null, lanes: NoLanes, dispatch: null, lastRenderedReducer: basicStateReducer, lastRenderedState: initialState }; hook.queue = queue; var dispatch = queue.dispatch = dispatchSetState.bind(null, currentlyRenderingFiber$1, queue); return [hook.memoizedState, dispatch]; } function updateState(initialState) { return updateReducer(basicStateReducer); } function rerenderState(initialState) { return rerenderReducer(basicStateReducer); } function pushEffect(tag, create, destroy, deps) { var effect = { tag: tag, create: create, destroy: destroy, deps: deps, // Circular next: null }; var componentUpdateQueue = currentlyRenderingFiber$1.updateQueue; if (componentUpdateQueue === null) { componentUpdateQueue = createFunctionComponentUpdateQueue(); currentlyRenderingFiber$1.updateQueue = componentUpdateQueue; componentUpdateQueue.lastEffect = effect.next = effect; } else { var lastEffect = componentUpdateQueue.lastEffect; if (lastEffect === null) { componentUpdateQueue.lastEffect = effect.next = effect; } else { var firstEffect = lastEffect.next; lastEffect.next = effect; effect.next = firstEffect; componentUpdateQueue.lastEffect = effect; } } return effect; } function mountRef(initialValue) { var hook = mountWorkInProgressHook(); { var _ref2 = { current: initialValue }; hook.memoizedState = _ref2; return _ref2; } } function updateRef(initialValue) { var hook = updateWorkInProgressHook(); return hook.memoizedState; } function mountEffectImpl(fiberFlags, hookFlags, create, deps) { var hook = mountWorkInProgressHook(); var nextDeps = deps === undefined ? null : deps; currentlyRenderingFiber$1.flags |= fiberFlags; hook.memoizedState = pushEffect(HasEffect | hookFlags, create, undefined, nextDeps); } function updateEffectImpl(fiberFlags, hookFlags, create, deps) { var hook = updateWorkInProgressHook(); var nextDeps = deps === undefined ? null : deps; var destroy = undefined; if (currentHook !== null) { var prevEffect = currentHook.memoizedState; destroy = prevEffect.destroy; if (nextDeps !== null) { var prevDeps = prevEffect.deps; if (areHookInputsEqual(nextDeps, prevDeps)) { hook.memoizedState = pushEffect(hookFlags, create, destroy, nextDeps); return; } } } currentlyRenderingFiber$1.flags |= fiberFlags; hook.memoizedState = pushEffect(HasEffect | hookFlags, create, destroy, nextDeps); } function mountEffect(create, deps) { if ( (currentlyRenderingFiber$1.mode & StrictEffectsMode) !== NoMode) { return mountEffectImpl(MountPassiveDev | Passive | PassiveStatic, Passive$1, create, deps); } else { return mountEffectImpl(Passive | PassiveStatic, Passive$1, create, deps); } } function updateEffect(create, deps) { return updateEffectImpl(Passive, Passive$1, create, deps); } function mountInsertionEffect(create, deps) { return mountEffectImpl(Update, Insertion, create, deps); } function updateInsertionEffect(create, deps) { return updateEffectImpl(Update, Insertion, create, deps); } function mountLayoutEffect(create, deps) { var fiberFlags = Update; { fiberFlags |= LayoutStatic; } if ( (currentlyRenderingFiber$1.mode & StrictEffectsMode) !== NoMode) { fiberFlags |= MountLayoutDev; } return mountEffectImpl(fiberFlags, Layout, create, deps); } function updateLayoutEffect(create, deps) { return updateEffectImpl(Update, Layout, create, deps); } function imperativeHandleEffect(create, ref) { if (typeof ref === 'function') { var refCallback = ref; var _inst = create(); refCallback(_inst); return function () { refCallback(null); }; } else if (ref !== null && ref !== undefined) { var refObject = ref; { if (!refObject.hasOwnProperty('current')) { error('Expected useImperativeHandle() first argument to either be a ' + 'ref callback or React.createRef() object. Instead received: %s.', 'an object with keys {' + Object.keys(refObject).join(', ') + '}'); } } var _inst2 = create(); refObject.current = _inst2; return function () { refObject.current = null; }; } } function mountImperativeHandle(ref, create, deps) { { if (typeof create !== 'function') { error('Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: %s.', create !== null ? typeof create : 'null'); } } // TODO: If deps are provided, should we skip comparing the ref itself? var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null; var fiberFlags = Update; { fiberFlags |= LayoutStatic; } if ( (currentlyRenderingFiber$1.mode & StrictEffectsMode) !== NoMode) { fiberFlags |= MountLayoutDev; } return mountEffectImpl(fiberFlags, Layout, imperativeHandleEffect.bind(null, create, ref), effectDeps); } function updateImperativeHandle(ref, create, deps) { { if (typeof create !== 'function') { error('Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: %s.', create !== null ? typeof create : 'null'); } } // TODO: If deps are provided, should we skip comparing the ref itself? var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null; return updateEffectImpl(Update, Layout, imperativeHandleEffect.bind(null, create, ref), effectDeps); } function mountDebugValue(value, formatterFn) {// This hook is normally a no-op. // The react-debug-hooks package injects its own implementation // so that e.g. DevTools can display custom hook values. } var updateDebugValue = mountDebugValue; function mountCallback(callback, deps) { var hook = mountWorkInProgressHook(); var nextDeps = deps === undefined ? null : deps; hook.memoizedState = [callback, nextDeps]; return callback; } function updateCallback(callback, deps) { var hook = updateWorkInProgressHook(); var nextDeps = deps === undefined ? null : deps; var prevState = hook.memoizedState; if (prevState !== null) { if (nextDeps !== null) { var prevDeps = prevState[1]; if (areHookInputsEqual(nextDeps, prevDeps)) { return prevState[0]; } } } hook.memoizedState = [callback, nextDeps]; return callback; } function mountMemo(nextCreate, deps) { var hook = mountWorkInProgressHook(); var nextDeps = deps === undefined ? null : deps; var nextValue = nextCreate(); hook.memoizedState = [nextValue, nextDeps]; return nextValue; } function updateMemo(nextCreate, deps) { var hook = updateWorkInProgressHook(); var nextDeps = deps === undefined ? null : deps; var prevState = hook.memoizedState; if (prevState !== null) { // Assume these are defined. If they're not, areHookInputsEqual will warn. if (nextDeps !== null) { var prevDeps = prevState[1]; if (areHookInputsEqual(nextDeps, prevDeps)) { return prevState[0]; } } } var nextValue = nextCreate(); hook.memoizedState = [nextValue, nextDeps]; return nextValue; } function mountDeferredValue(value) { var hook = mountWorkInProgressHook(); hook.memoizedState = value; return value; } function updateDeferredValue(value) { var hook = updateWorkInProgressHook(); var resolvedCurrentHook = currentHook; var prevValue = resolvedCurrentHook.memoizedState; return updateDeferredValueImpl(hook, prevValue, value); } function rerenderDeferredValue(value) { var hook = updateWorkInProgressHook(); if (currentHook === null) { // This is a rerender during a mount. hook.memoizedState = value; return value; } else { // This is a rerender during an update. var prevValue = currentHook.memoizedState; return updateDeferredValueImpl(hook, prevValue, value); } } function updateDeferredValueImpl(hook, prevValue, value) { var shouldDeferValue = !includesOnlyNonUrgentLanes(renderLanes); if (shouldDeferValue) { // This is an urgent update. If the value has changed, keep using the // previous value and spawn a deferred render to update it later. if (!objectIs(value, prevValue)) { // Schedule a deferred render var deferredLane = claimNextTransitionLane(); currentlyRenderingFiber$1.lanes = mergeLanes(currentlyRenderingFiber$1.lanes, deferredLane); markSkippedUpdateLanes(deferredLane); // Set this to true to indicate that the rendered value is inconsistent // from the latest value. The name "baseState" doesn't really match how we // use it because we're reusing a state hook field instead of creating a // new one. hook.baseState = true; } // Reuse the previous value return prevValue; } else { // This is not an urgent update, so we can use the latest value regardless // of what it is. No need to defer it. // However, if we're currently inside a spawned render, then we need to mark // this as an update to prevent the fiber from bailing out. // // `baseState` is true when the current value is different from the rendered // value. The name doesn't really match how we use it because we're reusing // a state hook field instead of creating a new one. if (hook.baseState) { // Flip this back to false. hook.baseState = false; markWorkInProgressReceivedUpdate(); } hook.memoizedState = value; return value; } } function startTransition(setPending, callback, options) { var previousPriority = getCurrentUpdatePriority(); setCurrentUpdatePriority(higherEventPriority(previousPriority, ContinuousEventPriority)); setPending(true); var prevTransition = ReactCurrentBatchConfig$2.transition; ReactCurrentBatchConfig$2.transition = {}; var currentTransition = ReactCurrentBatchConfig$2.transition; { ReactCurrentBatchConfig$2.transition._updatedFibers = new Set(); } try { setPending(false); callback(); } finally { setCurrentUpdatePriority(previousPriority); ReactCurrentBatchConfig$2.transition = prevTransition; { if (prevTransition === null && currentTransition._updatedFibers) { var updatedFibersCount = currentTransition._updatedFibers.size; if (updatedFibersCount > 10) { warn('Detected a large number of updates inside startTransition. ' + 'If this is due to a subscription please re-write it to use React provided hooks. ' + 'Otherwise concurrent mode guarantees are off the table.'); } currentTransition._updatedFibers.clear(); } } } } function mountTransition() { var _mountState = mountState(false), isPending = _mountState[0], setPending = _mountState[1]; // The `start` method never changes. var start = startTransition.bind(null, setPending); var hook = mountWorkInProgressHook(); hook.memoizedState = start; return [isPending, start]; } function updateTransition() { var _updateState = updateState(), isPending = _updateState[0]; var hook = updateWorkInProgressHook(); var start = hook.memoizedState; return [isPending, start]; } function rerenderTransition() { var _rerenderState = rerenderState(), isPending = _rerenderState[0]; var hook = updateWorkInProgressHook(); var start = hook.memoizedState; return [isPending, start]; } var isUpdatingOpaqueValueInRenderPhase = false; function getIsUpdatingOpaqueValueInRenderPhaseInDEV() { { return isUpdatingOpaqueValueInRenderPhase; } } function mountId() { var hook = mountWorkInProgressHook(); var root = getWorkInProgressRoot(); // TODO: In Fizz, id generation is specific to each server config. Maybe we // should do this in Fiber, too? Deferring this decision for now because // there's no other place to store the prefix except for an internal field on // the public createRoot object, which the fiber tree does not currently have // a reference to. var identifierPrefix = root.identifierPrefix; var id; if (getIsHydrating()) { var treeId = getTreeId(); // Use a captial R prefix for server-generated ids. id = ':' + identifierPrefix + 'R' + treeId; // Unless this is the first id at this level, append a number at the end // that represents the position of this useId hook among all the useId // hooks for this fiber. var localId = localIdCounter++; if (localId > 0) { id += 'H' + localId.toString(32); } id += ':'; } else { // Use a lowercase r prefix for client-generated ids. var globalClientId = globalClientIdCounter++; id = ':' + identifierPrefix + 'r' + globalClientId.toString(32) + ':'; } hook.memoizedState = id; return id; } function updateId() { var hook = updateWorkInProgressHook(); var id = hook.memoizedState; return id; } function dispatchReducerAction(fiber, queue, action) { { if (typeof arguments[3] === 'function') { error("State updates from the useState() and useReducer() Hooks don't support the " + 'second callback argument. To execute a side effect after ' + 'rendering, declare it in the component body with useEffect().'); } } var lane = requestUpdateLane(fiber); var update = { lane: lane, action: action, hasEagerState: false, eagerState: null, next: null }; if (isRenderPhaseUpdate(fiber)) { enqueueRenderPhaseUpdate(queue, update); } else { var root = enqueueConcurrentHookUpdate(fiber, queue, update, lane); if (root !== null) { var eventTime = requestEventTime(); scheduleUpdateOnFiber(root, fiber, lane, eventTime); entangleTransitionUpdate(root, queue, lane); } } markUpdateInDevTools(fiber, lane); } function dispatchSetState(fiber, queue, action) { { if (typeof arguments[3] === 'function') { error("State updates from the useState() and useReducer() Hooks don't support the " + 'second callback argument. To execute a side effect after ' + 'rendering, declare it in the component body with useEffect().'); } } var lane = requestUpdateLane(fiber); var update = { lane: lane, action: action, hasEagerState: false, eagerState: null, next: null }; if (isRenderPhaseUpdate(fiber)) { enqueueRenderPhaseUpdate(queue, update); } else { var alternate = fiber.alternate; if (fiber.lanes === NoLanes && (alternate === null || alternate.lanes === NoLanes)) { // The queue is currently empty, which means we can eagerly compute the // next state before entering the render phase. If the new state is the // same as the current state, we may be able to bail out entirely. var lastRenderedReducer = queue.lastRenderedReducer; if (lastRenderedReducer !== null) { var prevDispatcher; { prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; } try { var currentState = queue.lastRenderedState; var eagerState = lastRenderedReducer(currentState, action); // Stash the eagerly computed state, and the reducer used to compute // it, on the update object. If the reducer hasn't changed by the // time we enter the render phase, then the eager state can be used // without calling the reducer again. update.hasEagerState = true; update.eagerState = eagerState; if (objectIs(eagerState, currentState)) { // Fast path. We can bail out without scheduling React to re-render. // It's still possible that we'll need to rebase this update later, // if the component re-renders for a different reason and by that // time the reducer has changed. // TODO: Do we still need to entangle transitions in this case? enqueueConcurrentHookUpdateAndEagerlyBailout(fiber, queue, update, lane); return; } } catch (error) {// Suppress the error. It will throw again in the render phase. } finally { { ReactCurrentDispatcher$1.current = prevDispatcher; } } } } var root = enqueueConcurrentHookUpdate(fiber, queue, update, lane); if (root !== null) { var eventTime = requestEventTime(); scheduleUpdateOnFiber(root, fiber, lane, eventTime); entangleTransitionUpdate(root, queue, lane); } } markUpdateInDevTools(fiber, lane); } function isRenderPhaseUpdate(fiber) { var alternate = fiber.alternate; return fiber === currentlyRenderingFiber$1 || alternate !== null && alternate === currentlyRenderingFiber$1; } function enqueueRenderPhaseUpdate(queue, update) { // This is a render phase update. Stash it in a lazily-created map of // queue -> linked list of updates. After this render pass, we'll restart // and apply the stashed updates on top of the work-in-progress hook. didScheduleRenderPhaseUpdateDuringThisPass = didScheduleRenderPhaseUpdate = true; var pending = queue.pending; if (pending === null) { // This is the first update. Create a circular list. update.next = update; } else { update.next = pending.next; pending.next = update; } queue.pending = update; } // TODO: Move to ReactFiberConcurrentUpdates? function entangleTransitionUpdate(root, queue, lane) { if (isTransitionLane(lane)) { var queueLanes = queue.lanes; // If any entangled lanes are no longer pending on the root, then they // must have finished. We can remove them from the shared queue, which // represents a superset of the actually pending lanes. In some cases we // may entangle more than we need to, but that's OK. In fact it's worse if // we *don't* entangle when we should. queueLanes = intersectLanes(queueLanes, root.pendingLanes); // Entangle the new transition lane with the other transition lanes. var newQueueLanes = mergeLanes(queueLanes, lane); queue.lanes = newQueueLanes; // Even if queue.lanes already include lane, we don't know for certain if // the lane finished since the last time we entangled it. So we need to // entangle it again, just to be sure. markRootEntangled(root, newQueueLanes); } } function markUpdateInDevTools(fiber, lane, action) { { markStateUpdateScheduled(fiber, lane); } } var ContextOnlyDispatcher = { readContext: readContext, useCallback: throwInvalidHookError, useContext: throwInvalidHookError, useEffect: throwInvalidHookError, useImperativeHandle: throwInvalidHookError, useInsertionEffect: throwInvalidHookError, useLayoutEffect: throwInvalidHookError, useMemo: throwInvalidHookError, useReducer: throwInvalidHookError, useRef: throwInvalidHookError, useState: throwInvalidHookError, useDebugValue: throwInvalidHookError, useDeferredValue: throwInvalidHookError, useTransition: throwInvalidHookError, useMutableSource: throwInvalidHookError, useSyncExternalStore: throwInvalidHookError, useId: throwInvalidHookError, unstable_isNewReconciler: enableNewReconciler }; var HooksDispatcherOnMountInDEV = null; var HooksDispatcherOnMountWithHookTypesInDEV = null; var HooksDispatcherOnUpdateInDEV = null; var HooksDispatcherOnRerenderInDEV = null; var InvalidNestedHooksDispatcherOnMountInDEV = null; var InvalidNestedHooksDispatcherOnUpdateInDEV = null; var InvalidNestedHooksDispatcherOnRerenderInDEV = null; { var warnInvalidContextAccess = function () { error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().'); }; var warnInvalidHookAccess = function () { error('Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. ' + 'You can only call Hooks at the top level of your React function. ' + 'For more information, see ' + 'https://reactjs.org/link/rules-of-hooks'); }; HooksDispatcherOnMountInDEV = { readContext: function (context) { return readContext(context); }, useCallback: function (callback, deps) { currentHookNameInDev = 'useCallback'; mountHookTypesDev(); checkDepsAreArrayDev(deps); return mountCallback(callback, deps); }, useContext: function (context) { currentHookNameInDev = 'useContext'; mountHookTypesDev(); return readContext(context); }, useEffect: function (create, deps) { currentHookNameInDev = 'useEffect'; mountHookTypesDev(); checkDepsAreArrayDev(deps); return mountEffect(create, deps); }, useImperativeHandle: function (ref, create, deps) { currentHookNameInDev = 'useImperativeHandle'; mountHookTypesDev(); checkDepsAreArrayDev(deps); return mountImperativeHandle(ref, create, deps); }, useInsertionEffect: function (create, deps) { currentHookNameInDev = 'useInsertionEffect'; mountHookTypesDev(); checkDepsAreArrayDev(deps); return mountInsertionEffect(create, deps); }, useLayoutEffect: function (create, deps) { currentHookNameInDev = 'useLayoutEffect'; mountHookTypesDev(); checkDepsAreArrayDev(deps); return mountLayoutEffect(create, deps); }, useMemo: function (create, deps) { currentHookNameInDev = 'useMemo'; mountHookTypesDev(); checkDepsAreArrayDev(deps); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; try { return mountMemo(create, deps); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useReducer: function (reducer, initialArg, init) { currentHookNameInDev = 'useReducer'; mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; try { return mountReducer(reducer, initialArg, init); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useRef: function (initialValue) { currentHookNameInDev = 'useRef'; mountHookTypesDev(); return mountRef(initialValue); }, useState: function (initialState) { currentHookNameInDev = 'useState'; mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; try { return mountState(initialState); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useDebugValue: function (value, formatterFn) { currentHookNameInDev = 'useDebugValue'; mountHookTypesDev(); return mountDebugValue(); }, useDeferredValue: function (value) { currentHookNameInDev = 'useDeferredValue'; mountHookTypesDev(); return mountDeferredValue(value); }, useTransition: function () { currentHookNameInDev = 'useTransition'; mountHookTypesDev(); return mountTransition(); }, useMutableSource: function (source, getSnapshot, subscribe) { currentHookNameInDev = 'useMutableSource'; mountHookTypesDev(); return mountMutableSource(); }, useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { currentHookNameInDev = 'useSyncExternalStore'; mountHookTypesDev(); return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); }, useId: function () { currentHookNameInDev = 'useId'; mountHookTypesDev(); return mountId(); }, unstable_isNewReconciler: enableNewReconciler }; HooksDispatcherOnMountWithHookTypesInDEV = { readContext: function (context) { return readContext(context); }, useCallback: function (callback, deps) { currentHookNameInDev = 'useCallback'; updateHookTypesDev(); return mountCallback(callback, deps); }, useContext: function (context) { currentHookNameInDev = 'useContext'; updateHookTypesDev(); return readContext(context); }, useEffect: function (create, deps) { currentHookNameInDev = 'useEffect'; updateHookTypesDev(); return mountEffect(create, deps); }, useImperativeHandle: function (ref, create, deps) { currentHookNameInDev = 'useImperativeHandle'; updateHookTypesDev(); return mountImperativeHandle(ref, create, deps); }, useInsertionEffect: function (create, deps) { currentHookNameInDev = 'useInsertionEffect'; updateHookTypesDev(); return mountInsertionEffect(create, deps); }, useLayoutEffect: function (create, deps) { currentHookNameInDev = 'useLayoutEffect'; updateHookTypesDev(); return mountLayoutEffect(create, deps); }, useMemo: function (create, deps) { currentHookNameInDev = 'useMemo'; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; try { return mountMemo(create, deps); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useReducer: function (reducer, initialArg, init) { currentHookNameInDev = 'useReducer'; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; try { return mountReducer(reducer, initialArg, init); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useRef: function (initialValue) { currentHookNameInDev = 'useRef'; updateHookTypesDev(); return mountRef(initialValue); }, useState: function (initialState) { currentHookNameInDev = 'useState'; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; try { return mountState(initialState); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useDebugValue: function (value, formatterFn) { currentHookNameInDev = 'useDebugValue'; updateHookTypesDev(); return mountDebugValue(); }, useDeferredValue: function (value) { currentHookNameInDev = 'useDeferredValue'; updateHookTypesDev(); return mountDeferredValue(value); }, useTransition: function () { currentHookNameInDev = 'useTransition'; updateHookTypesDev(); return mountTransition(); }, useMutableSource: function (source, getSnapshot, subscribe) { currentHookNameInDev = 'useMutableSource'; updateHookTypesDev(); return mountMutableSource(); }, useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { currentHookNameInDev = 'useSyncExternalStore'; updateHookTypesDev(); return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); }, useId: function () { currentHookNameInDev = 'useId'; updateHookTypesDev(); return mountId(); }, unstable_isNewReconciler: enableNewReconciler }; HooksDispatcherOnUpdateInDEV = { readContext: function (context) { return readContext(context); }, useCallback: function (callback, deps) { currentHookNameInDev = 'useCallback'; updateHookTypesDev(); return updateCallback(callback, deps); }, useContext: function (context) { currentHookNameInDev = 'useContext'; updateHookTypesDev(); return readContext(context); }, useEffect: function (create, deps) { currentHookNameInDev = 'useEffect'; updateHookTypesDev(); return updateEffect(create, deps); }, useImperativeHandle: function (ref, create, deps) { currentHookNameInDev = 'useImperativeHandle'; updateHookTypesDev(); return updateImperativeHandle(ref, create, deps); }, useInsertionEffect: function (create, deps) { currentHookNameInDev = 'useInsertionEffect'; updateHookTypesDev(); return updateInsertionEffect(create, deps); }, useLayoutEffect: function (create, deps) { currentHookNameInDev = 'useLayoutEffect'; updateHookTypesDev(); return updateLayoutEffect(create, deps); }, useMemo: function (create, deps) { currentHookNameInDev = 'useMemo'; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { return updateMemo(create, deps); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useReducer: function (reducer, initialArg, init) { currentHookNameInDev = 'useReducer'; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { return updateReducer(reducer, initialArg, init); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useRef: function (initialValue) { currentHookNameInDev = 'useRef'; updateHookTypesDev(); return updateRef(); }, useState: function (initialState) { currentHookNameInDev = 'useState'; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { return updateState(initialState); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useDebugValue: function (value, formatterFn) { currentHookNameInDev = 'useDebugValue'; updateHookTypesDev(); return updateDebugValue(); }, useDeferredValue: function (value) { currentHookNameInDev = 'useDeferredValue'; updateHookTypesDev(); return updateDeferredValue(value); }, useTransition: function () { currentHookNameInDev = 'useTransition'; updateHookTypesDev(); return updateTransition(); }, useMutableSource: function (source, getSnapshot, subscribe) { currentHookNameInDev = 'useMutableSource'; updateHookTypesDev(); return updateMutableSource(); }, useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { currentHookNameInDev = 'useSyncExternalStore'; updateHookTypesDev(); return updateSyncExternalStore(subscribe, getSnapshot); }, useId: function () { currentHookNameInDev = 'useId'; updateHookTypesDev(); return updateId(); }, unstable_isNewReconciler: enableNewReconciler }; HooksDispatcherOnRerenderInDEV = { readContext: function (context) { return readContext(context); }, useCallback: function (callback, deps) { currentHookNameInDev = 'useCallback'; updateHookTypesDev(); return updateCallback(callback, deps); }, useContext: function (context) { currentHookNameInDev = 'useContext'; updateHookTypesDev(); return readContext(context); }, useEffect: function (create, deps) { currentHookNameInDev = 'useEffect'; updateHookTypesDev(); return updateEffect(create, deps); }, useImperativeHandle: function (ref, create, deps) { currentHookNameInDev = 'useImperativeHandle'; updateHookTypesDev(); return updateImperativeHandle(ref, create, deps); }, useInsertionEffect: function (create, deps) { currentHookNameInDev = 'useInsertionEffect'; updateHookTypesDev(); return updateInsertionEffect(create, deps); }, useLayoutEffect: function (create, deps) { currentHookNameInDev = 'useLayoutEffect'; updateHookTypesDev(); return updateLayoutEffect(create, deps); }, useMemo: function (create, deps) { currentHookNameInDev = 'useMemo'; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV; try { return updateMemo(create, deps); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useReducer: function (reducer, initialArg, init) { currentHookNameInDev = 'useReducer'; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV; try { return rerenderReducer(reducer, initialArg, init); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useRef: function (initialValue) { currentHookNameInDev = 'useRef'; updateHookTypesDev(); return updateRef(); }, useState: function (initialState) { currentHookNameInDev = 'useState'; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV; try { return rerenderState(initialState); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useDebugValue: function (value, formatterFn) { currentHookNameInDev = 'useDebugValue'; updateHookTypesDev(); return updateDebugValue(); }, useDeferredValue: function (value) { currentHookNameInDev = 'useDeferredValue'; updateHookTypesDev(); return rerenderDeferredValue(value); }, useTransition: function () { currentHookNameInDev = 'useTransition'; updateHookTypesDev(); return rerenderTransition(); }, useMutableSource: function (source, getSnapshot, subscribe) { currentHookNameInDev = 'useMutableSource'; updateHookTypesDev(); return updateMutableSource(); }, useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { currentHookNameInDev = 'useSyncExternalStore'; updateHookTypesDev(); return updateSyncExternalStore(subscribe, getSnapshot); }, useId: function () { currentHookNameInDev = 'useId'; updateHookTypesDev(); return updateId(); }, unstable_isNewReconciler: enableNewReconciler }; InvalidNestedHooksDispatcherOnMountInDEV = { readContext: function (context) { warnInvalidContextAccess(); return readContext(context); }, useCallback: function (callback, deps) { currentHookNameInDev = 'useCallback'; warnInvalidHookAccess(); mountHookTypesDev(); return mountCallback(callback, deps); }, useContext: function (context) { currentHookNameInDev = 'useContext'; warnInvalidHookAccess(); mountHookTypesDev(); return readContext(context); }, useEffect: function (create, deps) { currentHookNameInDev = 'useEffect'; warnInvalidHookAccess(); mountHookTypesDev(); return mountEffect(create, deps); }, useImperativeHandle: function (ref, create, deps) { currentHookNameInDev = 'useImperativeHandle'; warnInvalidHookAccess(); mountHookTypesDev(); return mountImperativeHandle(ref, create, deps); }, useInsertionEffect: function (create, deps) { currentHookNameInDev = 'useInsertionEffect'; warnInvalidHookAccess(); mountHookTypesDev(); return mountInsertionEffect(create, deps); }, useLayoutEffect: function (create, deps) { currentHookNameInDev = 'useLayoutEffect'; warnInvalidHookAccess(); mountHookTypesDev(); return mountLayoutEffect(create, deps); }, useMemo: function (create, deps) { currentHookNameInDev = 'useMemo'; warnInvalidHookAccess(); mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; try { return mountMemo(create, deps); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useReducer: function (reducer, initialArg, init) { currentHookNameInDev = 'useReducer'; warnInvalidHookAccess(); mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; try { return mountReducer(reducer, initialArg, init); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useRef: function (initialValue) { currentHookNameInDev = 'useRef'; warnInvalidHookAccess(); mountHookTypesDev(); return mountRef(initialValue); }, useState: function (initialState) { currentHookNameInDev = 'useState'; warnInvalidHookAccess(); mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; try { return mountState(initialState); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useDebugValue: function (value, formatterFn) { currentHookNameInDev = 'useDebugValue'; warnInvalidHookAccess(); mountHookTypesDev(); return mountDebugValue(); }, useDeferredValue: function (value) { currentHookNameInDev = 'useDeferredValue'; warnInvalidHookAccess(); mountHookTypesDev(); return mountDeferredValue(value); }, useTransition: function () { currentHookNameInDev = 'useTransition'; warnInvalidHookAccess(); mountHookTypesDev(); return mountTransition(); }, useMutableSource: function (source, getSnapshot, subscribe) { currentHookNameInDev = 'useMutableSource'; warnInvalidHookAccess(); mountHookTypesDev(); return mountMutableSource(); }, useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { currentHookNameInDev = 'useSyncExternalStore'; warnInvalidHookAccess(); mountHookTypesDev(); return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); }, useId: function () { currentHookNameInDev = 'useId'; warnInvalidHookAccess(); mountHookTypesDev(); return mountId(); }, unstable_isNewReconciler: enableNewReconciler }; InvalidNestedHooksDispatcherOnUpdateInDEV = { readContext: function (context) { warnInvalidContextAccess(); return readContext(context); }, useCallback: function (callback, deps) { currentHookNameInDev = 'useCallback'; warnInvalidHookAccess(); updateHookTypesDev(); return updateCallback(callback, deps); }, useContext: function (context) { currentHookNameInDev = 'useContext'; warnInvalidHookAccess(); updateHookTypesDev(); return readContext(context); }, useEffect: function (create, deps) { currentHookNameInDev = 'useEffect'; warnInvalidHookAccess(); updateHookTypesDev(); return updateEffect(create, deps); }, useImperativeHandle: function (ref, create, deps) { currentHookNameInDev = 'useImperativeHandle'; warnInvalidHookAccess(); updateHookTypesDev(); return updateImperativeHandle(ref, create, deps); }, useInsertionEffect: function (create, deps) { currentHookNameInDev = 'useInsertionEffect'; warnInvalidHookAccess(); updateHookTypesDev(); return updateInsertionEffect(create, deps); }, useLayoutEffect: function (create, deps) { currentHookNameInDev = 'useLayoutEffect'; warnInvalidHookAccess(); updateHookTypesDev(); return updateLayoutEffect(create, deps); }, useMemo: function (create, deps) { currentHookNameInDev = 'useMemo'; warnInvalidHookAccess(); updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { return updateMemo(create, deps); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useReducer: function (reducer, initialArg, init) { currentHookNameInDev = 'useReducer'; warnInvalidHookAccess(); updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { return updateReducer(reducer, initialArg, init); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useRef: function (initialValue) { currentHookNameInDev = 'useRef'; warnInvalidHookAccess(); updateHookTypesDev(); return updateRef(); }, useState: function (initialState) { currentHookNameInDev = 'useState'; warnInvalidHookAccess(); updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { return updateState(initialState); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useDebugValue: function (value, formatterFn) { currentHookNameInDev = 'useDebugValue'; warnInvalidHookAccess(); updateHookTypesDev(); return updateDebugValue(); }, useDeferredValue: function (value) { currentHookNameInDev = 'useDeferredValue'; warnInvalidHookAccess(); updateHookTypesDev(); return updateDeferredValue(value); }, useTransition: function () { currentHookNameInDev = 'useTransition'; warnInvalidHookAccess(); updateHookTypesDev(); return updateTransition(); }, useMutableSource: function (source, getSnapshot, subscribe) { currentHookNameInDev = 'useMutableSource'; warnInvalidHookAccess(); updateHookTypesDev(); return updateMutableSource(); }, useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { currentHookNameInDev = 'useSyncExternalStore'; warnInvalidHookAccess(); updateHookTypesDev(); return updateSyncExternalStore(subscribe, getSnapshot); }, useId: function () { currentHookNameInDev = 'useId'; warnInvalidHookAccess(); updateHookTypesDev(); return updateId(); }, unstable_isNewReconciler: enableNewReconciler }; InvalidNestedHooksDispatcherOnRerenderInDEV = { readContext: function (context) { warnInvalidContextAccess(); return readContext(context); }, useCallback: function (callback, deps) { currentHookNameInDev = 'useCallback'; warnInvalidHookAccess(); updateHookTypesDev(); return updateCallback(callback, deps); }, useContext: function (context) { currentHookNameInDev = 'useContext'; warnInvalidHookAccess(); updateHookTypesDev(); return readContext(context); }, useEffect: function (create, deps) { currentHookNameInDev = 'useEffect'; warnInvalidHookAccess(); updateHookTypesDev(); return updateEffect(create, deps); }, useImperativeHandle: function (ref, create, deps) { currentHookNameInDev = 'useImperativeHandle'; warnInvalidHookAccess(); updateHookTypesDev(); return updateImperativeHandle(ref, create, deps); }, useInsertionEffect: function (create, deps) { currentHookNameInDev = 'useInsertionEffect'; warnInvalidHookAccess(); updateHookTypesDev(); return updateInsertionEffect(create, deps); }, useLayoutEffect: function (create, deps) { currentHookNameInDev = 'useLayoutEffect'; warnInvalidHookAccess(); updateHookTypesDev(); return updateLayoutEffect(create, deps); }, useMemo: function (create, deps) { currentHookNameInDev = 'useMemo'; warnInvalidHookAccess(); updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { return updateMemo(create, deps); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useReducer: function (reducer, initialArg, init) { currentHookNameInDev = 'useReducer'; warnInvalidHookAccess(); updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { return rerenderReducer(reducer, initialArg, init); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useRef: function (initialValue) { currentHookNameInDev = 'useRef'; warnInvalidHookAccess(); updateHookTypesDev(); return updateRef(); }, useState: function (initialState) { currentHookNameInDev = 'useState'; warnInvalidHookAccess(); updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { return rerenderState(initialState); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useDebugValue: function (value, formatterFn) { currentHookNameInDev = 'useDebugValue'; warnInvalidHookAccess(); updateHookTypesDev(); return updateDebugValue(); }, useDeferredValue: function (value) { currentHookNameInDev = 'useDeferredValue'; warnInvalidHookAccess(); updateHookTypesDev(); return rerenderDeferredValue(value); }, useTransition: function () { currentHookNameInDev = 'useTransition'; warnInvalidHookAccess(); updateHookTypesDev(); return rerenderTransition(); }, useMutableSource: function (source, getSnapshot, subscribe) { currentHookNameInDev = 'useMutableSource'; warnInvalidHookAccess(); updateHookTypesDev(); return updateMutableSource(); }, useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { currentHookNameInDev = 'useSyncExternalStore'; warnInvalidHookAccess(); updateHookTypesDev(); return updateSyncExternalStore(subscribe, getSnapshot); }, useId: function () { currentHookNameInDev = 'useId'; warnInvalidHookAccess(); updateHookTypesDev(); return updateId(); }, unstable_isNewReconciler: enableNewReconciler }; } var now$1 = Scheduler.unstable_now; var commitTime = 0; var layoutEffectStartTime = -1; var profilerStartTime = -1; var passiveEffectStartTime = -1; /** * Tracks whether the current update was a nested/cascading update (scheduled from a layout effect). * * The overall sequence is: * 1. render * 2. commit (and call `onRender`, `onCommit`) * 3. check for nested updates * 4. flush passive effects (and call `onPostCommit`) * * Nested updates are identified in step 3 above, * but step 4 still applies to the work that was just committed. * We use two flags to track nested updates then: * one tracks whether the upcoming update is a nested update, * and the other tracks whether the current update was a nested update. * The first value gets synced to the second at the start of the render phase. */ var currentUpdateIsNested = false; var nestedUpdateScheduled = false; function isCurrentUpdateNested() { return currentUpdateIsNested; } function markNestedUpdateScheduled() { { nestedUpdateScheduled = true; } } function resetNestedUpdateFlag() { { currentUpdateIsNested = false; nestedUpdateScheduled = false; } } function syncNestedUpdateFlag() { { currentUpdateIsNested = nestedUpdateScheduled; nestedUpdateScheduled = false; } } function getCommitTime() { return commitTime; } function recordCommitTime() { commitTime = now$1(); } function startProfilerTimer(fiber) { profilerStartTime = now$1(); if (fiber.actualStartTime < 0) { fiber.actualStartTime = now$1(); } } function stopProfilerTimerIfRunning(fiber) { profilerStartTime = -1; } function stopProfilerTimerIfRunningAndRecordDelta(fiber, overrideBaseTime) { if (profilerStartTime >= 0) { var elapsedTime = now$1() - profilerStartTime; fiber.actualDuration += elapsedTime; if (overrideBaseTime) { fiber.selfBaseDuration = elapsedTime; } profilerStartTime = -1; } } function recordLayoutEffectDuration(fiber) { if (layoutEffectStartTime >= 0) { var elapsedTime = now$1() - layoutEffectStartTime; layoutEffectStartTime = -1; // Store duration on the next nearest Profiler ancestor // Or the root (for the DevTools Profiler to read) var parentFiber = fiber.return; while (parentFiber !== null) { switch (parentFiber.tag) { case HostRoot: var root = parentFiber.stateNode; root.effectDuration += elapsedTime; return; case Profiler: var parentStateNode = parentFiber.stateNode; parentStateNode.effectDuration += elapsedTime; return; } parentFiber = parentFiber.return; } } } function recordPassiveEffectDuration(fiber) { if (passiveEffectStartTime >= 0) { var elapsedTime = now$1() - passiveEffectStartTime; passiveEffectStartTime = -1; // Store duration on the next nearest Profiler ancestor // Or the root (for the DevTools Profiler to read) var parentFiber = fiber.return; while (parentFiber !== null) { switch (parentFiber.tag) { case HostRoot: var root = parentFiber.stateNode; if (root !== null) { root.passiveEffectDuration += elapsedTime; } return; case Profiler: var parentStateNode = parentFiber.stateNode; if (parentStateNode !== null) { // Detached fibers have their state node cleared out. // In this case, the return pointer is also cleared out, // so we won't be able to report the time spent in this Profiler's subtree. parentStateNode.passiveEffectDuration += elapsedTime; } return; } parentFiber = parentFiber.return; } } } function startLayoutEffectTimer() { layoutEffectStartTime = now$1(); } function startPassiveEffectTimer() { passiveEffectStartTime = now$1(); } function transferActualDuration(fiber) { // Transfer time spent rendering these children so we don't lose it // after we rerender. This is used as a helper in special cases // where we should count the work of multiple passes. var child = fiber.child; while (child) { fiber.actualDuration += child.actualDuration; child = child.sibling; } } function createCapturedValueAtFiber(value, source) { // If the value is an error, call this function immediately after it is thrown // so the stack is accurate. return { value: value, source: source, stack: getStackByFiberInDevAndProd(source), digest: null }; } function createCapturedValue(value, digest, stack) { return { value: value, source: null, stack: stack != null ? stack : null, digest: digest != null ? digest : null }; } // This module is forked in different environments. // By default, return `true` to log errors to the console. // Forks can return `false` if this isn't desirable. function showErrorDialog(boundary, errorInfo) { return true; } function logCapturedError(boundary, errorInfo) { try { var logError = showErrorDialog(boundary, errorInfo); // Allow injected showErrorDialog() to prevent default console.error logging. // This enables renderers like ReactNative to better manage redbox behavior. if (logError === false) { return; } var error = errorInfo.value; if (true) { var source = errorInfo.source; var stack = errorInfo.stack; var componentStack = stack !== null ? stack : ''; // Browsers support silencing uncaught errors by calling // `preventDefault()` in window `error` handler. // We record this information as an expando on the error. if (error != null && error._suppressLogging) { if (boundary.tag === ClassComponent) { // The error is recoverable and was silenced. // Ignore it and don't print the stack addendum. // This is handy for testing error boundaries without noise. return; } // The error is fatal. Since the silencing might have // been accidental, we'll surface it anyway. // However, the browser would have silenced the original error // so we'll print it first, and then print the stack addendum. console['error'](error); // Don't transform to our wrapper // For a more detailed description of this block, see: // https://github.com/facebook/react/pull/13384 } var componentName = source ? getComponentNameFromFiber(source) : null; var componentNameMessage = componentName ? "The above error occurred in the <" + componentName + "> component:" : 'The above error occurred in one of your React components:'; var errorBoundaryMessage; if (boundary.tag === HostRoot) { errorBoundaryMessage = 'Consider adding an error boundary to your tree to customize error handling behavior.\n' + 'Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.'; } else { var errorBoundaryName = getComponentNameFromFiber(boundary) || 'Anonymous'; errorBoundaryMessage = "React will try to recreate this component tree from scratch " + ("using the error boundary you provided, " + errorBoundaryName + "."); } var combinedMessage = componentNameMessage + "\n" + componentStack + "\n\n" + ("" + errorBoundaryMessage); // In development, we provide our own message with just the component stack. // We don't include the original error message and JS stack because the browser // has already printed it. Even if the application swallows the error, it is still // displayed by the browser thanks to the DEV-only fake event trick in ReactErrorUtils. console['error'](combinedMessage); // Don't transform to our wrapper } else {} } catch (e) { // This method must not throw, or React internal state will get messed up. // If console.error is overridden, or logCapturedError() shows a dialog that throws, // we want to report this error outside of the normal stack as a last resort. // https://github.com/facebook/react/issues/13188 setTimeout(function () { throw e; }); } } var PossiblyWeakMap$1 = typeof WeakMap === 'function' ? WeakMap : Map; function createRootErrorUpdate(fiber, errorInfo, lane) { var update = createUpdate(NoTimestamp, lane); // Unmount the root by rendering null. update.tag = CaptureUpdate; // Caution: React DevTools currently depends on this property // being called "element". update.payload = { element: null }; var error = errorInfo.value; update.callback = function () { onUncaughtError(error); logCapturedError(fiber, errorInfo); }; return update; } function createClassErrorUpdate(fiber, errorInfo, lane) { var update = createUpdate(NoTimestamp, lane); update.tag = CaptureUpdate; var getDerivedStateFromError = fiber.type.getDerivedStateFromError; if (typeof getDerivedStateFromError === 'function') { var error$1 = errorInfo.value; update.payload = function () { return getDerivedStateFromError(error$1); }; update.callback = function () { { markFailedErrorBoundaryForHotReloading(fiber); } logCapturedError(fiber, errorInfo); }; } var inst = fiber.stateNode; if (inst !== null && typeof inst.componentDidCatch === 'function') { update.callback = function callback() { { markFailedErrorBoundaryForHotReloading(fiber); } logCapturedError(fiber, errorInfo); if (typeof getDerivedStateFromError !== 'function') { // To preserve the preexisting retry behavior of error boundaries, // we keep track of which ones already failed during this batch. // This gets reset before we yield back to the browser. // TODO: Warn in strict mode if getDerivedStateFromError is // not defined. markLegacyErrorBoundaryAsFailed(this); } var error$1 = errorInfo.value; var stack = errorInfo.stack; this.componentDidCatch(error$1, { componentStack: stack !== null ? stack : '' }); { if (typeof getDerivedStateFromError !== 'function') { // If componentDidCatch is the only error boundary method defined, // then it needs to call setState to recover from errors. // If no state update is scheduled then the boundary will swallow the error. if (!includesSomeLane(fiber.lanes, SyncLane)) { error('%s: Error boundaries should implement getDerivedStateFromError(). ' + 'In that method, return a state update to display an error message or fallback UI.', getComponentNameFromFiber(fiber) || 'Unknown'); } } } }; } return update; } function attachPingListener(root, wakeable, lanes) { // Attach a ping listener // // The data might resolve before we have a chance to commit the fallback. Or, // in the case of a refresh, we'll never commit a fallback. So we need to // attach a listener now. When it resolves ("pings"), we can decide whether to // try rendering the tree again. // // Only attach a listener if one does not already exist for the lanes // we're currently rendering (which acts like a "thread ID" here). // // We only need to do this in concurrent mode. Legacy Suspense always // commits fallbacks synchronously, so there are no pings. var pingCache = root.pingCache; var threadIDs; if (pingCache === null) { pingCache = root.pingCache = new PossiblyWeakMap$1(); threadIDs = new Set(); pingCache.set(wakeable, threadIDs); } else { threadIDs = pingCache.get(wakeable); if (threadIDs === undefined) { threadIDs = new Set(); pingCache.set(wakeable, threadIDs); } } if (!threadIDs.has(lanes)) { // Memoize using the thread ID to prevent redundant listeners. threadIDs.add(lanes); var ping = pingSuspendedRoot.bind(null, root, wakeable, lanes); { if (isDevToolsPresent) { // If we have pending work still, restore the original updaters restorePendingUpdaters(root, lanes); } } wakeable.then(ping, ping); } } function attachRetryListener(suspenseBoundary, root, wakeable, lanes) { // Retry listener // // If the fallback does commit, we need to attach a different type of // listener. This one schedules an update on the Suspense boundary to turn // the fallback state off. // // Stash the wakeable on the boundary fiber so we can access it in the // commit phase. // // When the wakeable resolves, we'll attempt to render the boundary // again ("retry"). var wakeables = suspenseBoundary.updateQueue; if (wakeables === null) { var updateQueue = new Set(); updateQueue.add(wakeable); suspenseBoundary.updateQueue = updateQueue; } else { wakeables.add(wakeable); } } function resetSuspendedComponent(sourceFiber, rootRenderLanes) { // A legacy mode Suspense quirk, only relevant to hook components. var tag = sourceFiber.tag; if ((sourceFiber.mode & ConcurrentMode) === NoMode && (tag === FunctionComponent || tag === ForwardRef || tag === SimpleMemoComponent)) { var currentSource = sourceFiber.alternate; if (currentSource) { sourceFiber.updateQueue = currentSource.updateQueue; sourceFiber.memoizedState = currentSource.memoizedState; sourceFiber.lanes = currentSource.lanes; } else { sourceFiber.updateQueue = null; sourceFiber.memoizedState = null; } } } function getNearestSuspenseBoundaryToCapture(returnFiber) { var node = returnFiber; do { if (node.tag === SuspenseComponent && shouldCaptureSuspense(node)) { return node; } // This boundary already captured during this render. Continue to the next // boundary. node = node.return; } while (node !== null); return null; } function markSuspenseBoundaryShouldCapture(suspenseBoundary, returnFiber, sourceFiber, root, rootRenderLanes) { // This marks a Suspense boundary so that when we're unwinding the stack, // it captures the suspended "exception" and does a second (fallback) pass. if ((suspenseBoundary.mode & ConcurrentMode) === NoMode) { // Legacy Mode Suspense // // If the boundary is in legacy mode, we should *not* // suspend the commit. Pretend as if the suspended component rendered // null and keep rendering. When the Suspense boundary completes, // we'll do a second pass to render the fallback. if (suspenseBoundary === returnFiber) { // Special case where we suspended while reconciling the children of // a Suspense boundary's inner Offscreen wrapper fiber. This happens // when a React.lazy component is a direct child of a // Suspense boundary. // // Suspense boundaries are implemented as multiple fibers, but they // are a single conceptual unit. The legacy mode behavior where we // pretend the suspended fiber committed as `null` won't work, // because in this case the "suspended" fiber is the inner // Offscreen wrapper. // // Because the contents of the boundary haven't started rendering // yet (i.e. nothing in the tree has partially rendered) we can // switch to the regular, concurrent mode behavior: mark the // boundary with ShouldCapture and enter the unwind phase. suspenseBoundary.flags |= ShouldCapture; } else { suspenseBoundary.flags |= DidCapture; sourceFiber.flags |= ForceUpdateForLegacySuspense; // We're going to commit this fiber even though it didn't complete. // But we shouldn't call any lifecycle methods or callbacks. Remove // all lifecycle effect tags. sourceFiber.flags &= ~(LifecycleEffectMask | Incomplete); if (sourceFiber.tag === ClassComponent) { var currentSourceFiber = sourceFiber.alternate; if (currentSourceFiber === null) { // This is a new mount. Change the tag so it's not mistaken for a // completed class component. For example, we should not call // componentWillUnmount if it is deleted. sourceFiber.tag = IncompleteClassComponent; } else { // When we try rendering again, we should not reuse the current fiber, // since it's known to be in an inconsistent state. Use a force update to // prevent a bail out. var update = createUpdate(NoTimestamp, SyncLane); update.tag = ForceUpdate; enqueueUpdate(sourceFiber, update, SyncLane); } } // The source fiber did not complete. Mark it with Sync priority to // indicate that it still has pending work. sourceFiber.lanes = mergeLanes(sourceFiber.lanes, SyncLane); } return suspenseBoundary; } // Confirmed that the boundary is in a concurrent mode tree. Continue // with the normal suspend path. // // After this we'll use a set of heuristics to determine whether this // render pass will run to completion or restart or "suspend" the commit. // The actual logic for this is spread out in different places. // // This first principle is that if we're going to suspend when we complete // a root, then we should also restart if we get an update or ping that // might unsuspend it, and vice versa. The only reason to suspend is // because you think you might want to restart before committing. However, // it doesn't make sense to restart only while in the period we're suspended. // // Restarting too aggressively is also not good because it starves out any // intermediate loading state. So we use heuristics to determine when. // Suspense Heuristics // // If nothing threw a Promise or all the same fallbacks are already showing, // then don't suspend/restart. // // If this is an initial render of a new tree of Suspense boundaries and // those trigger a fallback, then don't suspend/restart. We want to ensure // that we can show the initial loading state as quickly as possible. // // If we hit a "Delayed" case, such as when we'd switch from content back into // a fallback, then we should always suspend/restart. Transitions apply // to this case. If none is defined, JND is used instead. // // If we're already showing a fallback and it gets "retried", allowing us to show // another level, but there's still an inner boundary that would show a fallback, // then we suspend/restart for 500ms since the last time we showed a fallback // anywhere in the tree. This effectively throttles progressive loading into a // consistent train of commits. This also gives us an opportunity to restart to // get to the completed state slightly earlier. // // If there's ambiguity due to batching it's resolved in preference of: // 1) "delayed", 2) "initial render", 3) "retry". // // We want to ensure that a "busy" state doesn't get force committed. We want to // ensure that new initial loading states can commit as soon as possible. suspenseBoundary.flags |= ShouldCapture; // TODO: I think we can remove this, since we now use `DidCapture` in // the begin phase to prevent an early bailout. suspenseBoundary.lanes = rootRenderLanes; return suspenseBoundary; } function throwException(root, returnFiber, sourceFiber, value, rootRenderLanes) { // The source fiber did not complete. sourceFiber.flags |= Incomplete; { if (isDevToolsPresent) { // If we have pending work still, restore the original updaters restorePendingUpdaters(root, rootRenderLanes); } } if (value !== null && typeof value === 'object' && typeof value.then === 'function') { // This is a wakeable. The component suspended. var wakeable = value; resetSuspendedComponent(sourceFiber); { if (getIsHydrating() && sourceFiber.mode & ConcurrentMode) { markDidThrowWhileHydratingDEV(); } } var suspenseBoundary = getNearestSuspenseBoundaryToCapture(returnFiber); if (suspenseBoundary !== null) { suspenseBoundary.flags &= ~ForceClientRender; markSuspenseBoundaryShouldCapture(suspenseBoundary, returnFiber, sourceFiber, root, rootRenderLanes); // We only attach ping listeners in concurrent mode. Legacy Suspense always // commits fallbacks synchronously, so there are no pings. if (suspenseBoundary.mode & ConcurrentMode) { attachPingListener(root, wakeable, rootRenderLanes); } attachRetryListener(suspenseBoundary, root, wakeable); return; } else { // No boundary was found. Unless this is a sync update, this is OK. // We can suspend and wait for more data to arrive. if (!includesSyncLane(rootRenderLanes)) { // This is not a sync update. Suspend. Since we're not activating a // Suspense boundary, this will unwind all the way to the root without // performing a second pass to render a fallback. (This is arguably how // refresh transitions should work, too, since we're not going to commit // the fallbacks anyway.) // // This case also applies to initial hydration. attachPingListener(root, wakeable, rootRenderLanes); renderDidSuspendDelayIfPossible(); return; } // This is a sync/discrete update. We treat this case like an error // because discrete renders are expected to produce a complete tree // synchronously to maintain consistency with external state. var uncaughtSuspenseError = new Error('A component suspended while responding to synchronous input. This ' + 'will cause the UI to be replaced with a loading indicator. To ' + 'fix, updates that suspend should be wrapped ' + 'with startTransition.'); // If we're outside a transition, fall through to the regular error path. // The error will be caught by the nearest suspense boundary. value = uncaughtSuspenseError; } } else { // This is a regular error, not a Suspense wakeable. if (getIsHydrating() && sourceFiber.mode & ConcurrentMode) { markDidThrowWhileHydratingDEV(); var _suspenseBoundary = getNearestSuspenseBoundaryToCapture(returnFiber); // If the error was thrown during hydration, we may be able to recover by // discarding the dehydrated content and switching to a client render. // Instead of surfacing the error, find the nearest Suspense boundary // and render it again without hydration. if (_suspenseBoundary !== null) { if ((_suspenseBoundary.flags & ShouldCapture) === NoFlags) { // Set a flag to indicate that we should try rendering the normal // children again, not the fallback. _suspenseBoundary.flags |= ForceClientRender; } markSuspenseBoundaryShouldCapture(_suspenseBoundary, returnFiber, sourceFiber, root, rootRenderLanes); // Even though the user may not be affected by this error, we should // still log it so it can be fixed. queueHydrationError(createCapturedValueAtFiber(value, sourceFiber)); return; } } } value = createCapturedValueAtFiber(value, sourceFiber); renderDidError(value); // We didn't find a boundary that could handle this type of exception. Start // over and traverse parent path again, this time treating the exception // as an error. var workInProgress = returnFiber; do { switch (workInProgress.tag) { case HostRoot: { var _errorInfo = value; workInProgress.flags |= ShouldCapture; var lane = pickArbitraryLane(rootRenderLanes); workInProgress.lanes = mergeLanes(workInProgress.lanes, lane); var update = createRootErrorUpdate(workInProgress, _errorInfo, lane); enqueueCapturedUpdate(workInProgress, update); return; } case ClassComponent: // Capture and retry var errorInfo = value; var ctor = workInProgress.type; var instance = workInProgress.stateNode; if ((workInProgress.flags & DidCapture) === NoFlags && (typeof ctor.getDerivedStateFromError === 'function' || instance !== null && typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance))) { workInProgress.flags |= ShouldCapture; var _lane = pickArbitraryLane(rootRenderLanes); workInProgress.lanes = mergeLanes(workInProgress.lanes, _lane); // Schedule the error boundary to re-render using updated state var _update = createClassErrorUpdate(workInProgress, errorInfo, _lane); enqueueCapturedUpdate(workInProgress, _update); return; } break; } workInProgress = workInProgress.return; } while (workInProgress !== null); } function getSuspendedCache() { { return null; } // This function is called when a Suspense boundary suspends. It returns the } var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner; var didReceiveUpdate = false; var didWarnAboutBadClass; var didWarnAboutModulePatternComponent; var didWarnAboutContextTypeOnFunctionComponent; var didWarnAboutGetDerivedStateOnFunctionComponent; var didWarnAboutFunctionRefs; var didWarnAboutReassigningProps; var didWarnAboutRevealOrder; var didWarnAboutTailOptions; { didWarnAboutBadClass = {}; didWarnAboutModulePatternComponent = {}; didWarnAboutContextTypeOnFunctionComponent = {}; didWarnAboutGetDerivedStateOnFunctionComponent = {}; didWarnAboutFunctionRefs = {}; didWarnAboutReassigningProps = false; didWarnAboutRevealOrder = {}; didWarnAboutTailOptions = {}; } function reconcileChildren(current, workInProgress, nextChildren, renderLanes) { if (current === null) { // If this is a fresh new component that hasn't been rendered yet, we // won't update its child set by applying minimal side-effects. Instead, // we will add them all to the child before it gets rendered. That means // we can optimize this reconciliation pass by not tracking side-effects. workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderLanes); } else { // If the current child is the same as the work in progress, it means that // we haven't yet started any work on these children. Therefore, we use // the clone algorithm to create a copy of all the current children. // If we had any progressed work already, that is invalid at this point so // let's throw it out. workInProgress.child = reconcileChildFibers(workInProgress, current.child, nextChildren, renderLanes); } } function forceUnmountCurrentAndReconcile(current, workInProgress, nextChildren, renderLanes) { // This function is fork of reconcileChildren. It's used in cases where we // want to reconcile without matching against the existing set. This has the // effect of all current children being unmounted; even if the type and key // are the same, the old child is unmounted and a new child is created. // // To do this, we're going to go through the reconcile algorithm twice. In // the first pass, we schedule a deletion for all the current children by // passing null. workInProgress.child = reconcileChildFibers(workInProgress, current.child, null, renderLanes); // In the second pass, we mount the new children. The trick here is that we // pass null in place of where we usually pass the current child set. This has // the effect of remounting all children regardless of whether their // identities match. workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderLanes); } function updateForwardRef(current, workInProgress, Component, nextProps, renderLanes) { // TODO: current can be non-null here even if the component // hasn't yet mounted. This happens after the first render suspends. // We'll need to figure out if this is fine or can cause issues. { if (workInProgress.type !== workInProgress.elementType) { // Lazy component props can't be validated in createElement // because they're only guaranteed to be resolved here. var innerPropTypes = Component.propTypes; if (innerPropTypes) { checkPropTypes(innerPropTypes, nextProps, // Resolved props 'prop', getComponentNameFromType(Component)); } } } var render = Component.render; var ref = workInProgress.ref; // The rest is a fork of updateFunctionComponent var nextChildren; var hasId; prepareToReadContext(workInProgress, renderLanes); { markComponentRenderStarted(workInProgress); } { ReactCurrentOwner$1.current = workInProgress; setIsRendering(true); nextChildren = renderWithHooks(current, workInProgress, render, nextProps, ref, renderLanes); hasId = checkDidRenderIdHook(); if ( workInProgress.mode & StrictLegacyMode) { setIsStrictModeForDevtools(true); try { nextChildren = renderWithHooks(current, workInProgress, render, nextProps, ref, renderLanes); hasId = checkDidRenderIdHook(); } finally { setIsStrictModeForDevtools(false); } } setIsRendering(false); } { markComponentRenderStopped(); } if (current !== null && !didReceiveUpdate) { bailoutHooks(current, workInProgress, renderLanes); return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); } if (getIsHydrating() && hasId) { pushMaterializedTreeId(workInProgress); } // React DevTools reads this flag. workInProgress.flags |= PerformedWork; reconcileChildren(current, workInProgress, nextChildren, renderLanes); return workInProgress.child; } function updateMemoComponent(current, workInProgress, Component, nextProps, renderLanes) { if (current === null) { var type = Component.type; if (isSimpleFunctionComponent(type) && Component.compare === null && // SimpleMemoComponent codepath doesn't resolve outer props either. Component.defaultProps === undefined) { var resolvedType = type; { resolvedType = resolveFunctionForHotReloading(type); } // If this is a plain function component without default props, // and with only the default shallow comparison, we upgrade it // to a SimpleMemoComponent to allow fast path updates. workInProgress.tag = SimpleMemoComponent; workInProgress.type = resolvedType; { validateFunctionComponentInDev(workInProgress, type); } return updateSimpleMemoComponent(current, workInProgress, resolvedType, nextProps, renderLanes); } { var innerPropTypes = type.propTypes; if (innerPropTypes) { // Inner memo component props aren't currently validated in createElement. // We could move it there, but we'd still need this for lazy code path. checkPropTypes(innerPropTypes, nextProps, // Resolved props 'prop', getComponentNameFromType(type)); } } var child = createFiberFromTypeAndProps(Component.type, null, nextProps, workInProgress, workInProgress.mode, renderLanes); child.ref = workInProgress.ref; child.return = workInProgress; workInProgress.child = child; return child; } { var _type = Component.type; var _innerPropTypes = _type.propTypes; if (_innerPropTypes) { // Inner memo component props aren't currently validated in createElement. // We could move it there, but we'd still need this for lazy code path. checkPropTypes(_innerPropTypes, nextProps, // Resolved props 'prop', getComponentNameFromType(_type)); } } var currentChild = current.child; // This is always exactly one child var hasScheduledUpdateOrContext = checkScheduledUpdateOrContext(current, renderLanes); if (!hasScheduledUpdateOrContext) { // This will be the props with resolved defaultProps, // unlike current.memoizedProps which will be the unresolved ones. var prevProps = currentChild.memoizedProps; // Default to shallow comparison var compare = Component.compare; compare = compare !== null ? compare : shallowEqual; if (compare(prevProps, nextProps) && current.ref === workInProgress.ref) { return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); } } // React DevTools reads this flag. workInProgress.flags |= PerformedWork; var newChild = createWorkInProgress(currentChild, nextProps); newChild.ref = workInProgress.ref; newChild.return = workInProgress; workInProgress.child = newChild; return newChild; } function updateSimpleMemoComponent(current, workInProgress, Component, nextProps, renderLanes) { // TODO: current can be non-null here even if the component // hasn't yet mounted. This happens when the inner render suspends. // We'll need to figure out if this is fine or can cause issues. { if (workInProgress.type !== workInProgress.elementType) { // Lazy component props can't be validated in createElement // because they're only guaranteed to be resolved here. var outerMemoType = workInProgress.elementType; if (outerMemoType.$$typeof === REACT_LAZY_TYPE) { // We warn when you define propTypes on lazy() // so let's just skip over it to find memo() outer wrapper. // Inner props for memo are validated later. var lazyComponent = outerMemoType; var payload = lazyComponent._payload; var init = lazyComponent._init; try { outerMemoType = init(payload); } catch (x) { outerMemoType = null; } // Inner propTypes will be validated in the function component path. var outerPropTypes = outerMemoType && outerMemoType.propTypes; if (outerPropTypes) { checkPropTypes(outerPropTypes, nextProps, // Resolved (SimpleMemoComponent has no defaultProps) 'prop', getComponentNameFromType(outerMemoType)); } } } } if (current !== null) { var prevProps = current.memoizedProps; if (shallowEqual(prevProps, nextProps) && current.ref === workInProgress.ref && ( // Prevent bailout if the implementation changed due to hot reload. workInProgress.type === current.type )) { didReceiveUpdate = false; // The props are shallowly equal. Reuse the previous props object, like we // would during a normal fiber bailout. // // We don't have strong guarantees that the props object is referentially // equal during updates where we can't bail out anyway — like if the props // are shallowly equal, but there's a local state or context update in the // same batch. // // However, as a principle, we should aim to make the behavior consistent // across different ways of memoizing a component. For example, React.memo // has a different internal Fiber layout if you pass a normal function // component (SimpleMemoComponent) versus if you pass a different type // like forwardRef (MemoComponent). But this is an implementation detail. // Wrapping a component in forwardRef (or React.lazy, etc) shouldn't // affect whether the props object is reused during a bailout. workInProgress.pendingProps = nextProps = prevProps; if (!checkScheduledUpdateOrContext(current, renderLanes)) { // The pending lanes were cleared at the beginning of beginWork. We're // about to bail out, but there might be other lanes that weren't // included in the current render. Usually, the priority level of the // remaining updates is accumulated during the evaluation of the // component (i.e. when processing the update queue). But since since // we're bailing out early *without* evaluating the component, we need // to account for it here, too. Reset to the value of the current fiber. // NOTE: This only applies to SimpleMemoComponent, not MemoComponent, // because a MemoComponent fiber does not have hooks or an update queue; // rather, it wraps around an inner component, which may or may not // contains hooks. // TODO: Move the reset at in beginWork out of the common path so that // this is no longer necessary. workInProgress.lanes = current.lanes; return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); } else if ((current.flags & ForceUpdateForLegacySuspense) !== NoFlags) { // This is a special case that only exists for legacy mode. // See https://github.com/facebook/react/pull/19216. didReceiveUpdate = true; } } } return updateFunctionComponent(current, workInProgress, Component, nextProps, renderLanes); } function updateOffscreenComponent(current, workInProgress, renderLanes) { var nextProps = workInProgress.pendingProps; var nextChildren = nextProps.children; var prevState = current !== null ? current.memoizedState : null; if (nextProps.mode === 'hidden' || enableLegacyHidden ) { // Rendering a hidden tree. if ((workInProgress.mode & ConcurrentMode) === NoMode) { // In legacy sync mode, don't defer the subtree. Render it now. // TODO: Consider how Offscreen should work with transitions in the future var nextState = { baseLanes: NoLanes, cachePool: null, transitions: null }; workInProgress.memoizedState = nextState; pushRenderLanes(workInProgress, renderLanes); } else if (!includesSomeLane(renderLanes, OffscreenLane)) { var spawnedCachePool = null; // We're hidden, and we're not rendering at Offscreen. We will bail out // and resume this tree later. var nextBaseLanes; if (prevState !== null) { var prevBaseLanes = prevState.baseLanes; nextBaseLanes = mergeLanes(prevBaseLanes, renderLanes); } else { nextBaseLanes = renderLanes; } // Schedule this fiber to re-render at offscreen priority. Then bailout. workInProgress.lanes = workInProgress.childLanes = laneToLanes(OffscreenLane); var _nextState = { baseLanes: nextBaseLanes, cachePool: spawnedCachePool, transitions: null }; workInProgress.memoizedState = _nextState; workInProgress.updateQueue = null; // to avoid a push/pop misalignment. pushRenderLanes(workInProgress, nextBaseLanes); return null; } else { // This is the second render. The surrounding visible content has already // committed. Now we resume rendering the hidden tree. // Rendering at offscreen, so we can clear the base lanes. var _nextState2 = { baseLanes: NoLanes, cachePool: null, transitions: null }; workInProgress.memoizedState = _nextState2; // Push the lanes that were skipped when we bailed out. var subtreeRenderLanes = prevState !== null ? prevState.baseLanes : renderLanes; pushRenderLanes(workInProgress, subtreeRenderLanes); } } else { // Rendering a visible tree. var _subtreeRenderLanes; if (prevState !== null) { // We're going from hidden -> visible. _subtreeRenderLanes = mergeLanes(prevState.baseLanes, renderLanes); workInProgress.memoizedState = null; } else { // We weren't previously hidden, and we still aren't, so there's nothing // special to do. Need to push to the stack regardless, though, to avoid // a push/pop misalignment. _subtreeRenderLanes = renderLanes; } pushRenderLanes(workInProgress, _subtreeRenderLanes); } reconcileChildren(current, workInProgress, nextChildren, renderLanes); return workInProgress.child; } // Note: These happen to have identical begin phases, for now. We shouldn't hold function updateFragment(current, workInProgress, renderLanes) { var nextChildren = workInProgress.pendingProps; reconcileChildren(current, workInProgress, nextChildren, renderLanes); return workInProgress.child; } function updateMode(current, workInProgress, renderLanes) { var nextChildren = workInProgress.pendingProps.children; reconcileChildren(current, workInProgress, nextChildren, renderLanes); return workInProgress.child; } function updateProfiler(current, workInProgress, renderLanes) { { workInProgress.flags |= Update; { // Reset effect durations for the next eventual effect phase. // These are reset during render to allow the DevTools commit hook a chance to read them, var stateNode = workInProgress.stateNode; stateNode.effectDuration = 0; stateNode.passiveEffectDuration = 0; } } var nextProps = workInProgress.pendingProps; var nextChildren = nextProps.children; reconcileChildren(current, workInProgress, nextChildren, renderLanes); return workInProgress.child; } function markRef(current, workInProgress) { var ref = workInProgress.ref; if (current === null && ref !== null || current !== null && current.ref !== ref) { // Schedule a Ref effect workInProgress.flags |= Ref; { workInProgress.flags |= RefStatic; } } } function updateFunctionComponent(current, workInProgress, Component, nextProps, renderLanes) { { if (workInProgress.type !== workInProgress.elementType) { // Lazy component props can't be validated in createElement // because they're only guaranteed to be resolved here. var innerPropTypes = Component.propTypes; if (innerPropTypes) { checkPropTypes(innerPropTypes, nextProps, // Resolved props 'prop', getComponentNameFromType(Component)); } } } var context; { var unmaskedContext = getUnmaskedContext(workInProgress, Component, true); context = getMaskedContext(workInProgress, unmaskedContext); } var nextChildren; var hasId; prepareToReadContext(workInProgress, renderLanes); { markComponentRenderStarted(workInProgress); } { ReactCurrentOwner$1.current = workInProgress; setIsRendering(true); nextChildren = renderWithHooks(current, workInProgress, Component, nextProps, context, renderLanes); hasId = checkDidRenderIdHook(); if ( workInProgress.mode & StrictLegacyMode) { setIsStrictModeForDevtools(true); try { nextChildren = renderWithHooks(current, workInProgress, Component, nextProps, context, renderLanes); hasId = checkDidRenderIdHook(); } finally { setIsStrictModeForDevtools(false); } } setIsRendering(false); } { markComponentRenderStopped(); } if (current !== null && !didReceiveUpdate) { bailoutHooks(current, workInProgress, renderLanes); return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); } if (getIsHydrating() && hasId) { pushMaterializedTreeId(workInProgress); } // React DevTools reads this flag. workInProgress.flags |= PerformedWork; reconcileChildren(current, workInProgress, nextChildren, renderLanes); return workInProgress.child; } function updateClassComponent(current, workInProgress, Component, nextProps, renderLanes) { { // This is used by DevTools to force a boundary to error. switch (shouldError(workInProgress)) { case false: { var _instance = workInProgress.stateNode; var ctor = workInProgress.type; // TODO This way of resetting the error boundary state is a hack. // Is there a better way to do this? var tempInstance = new ctor(workInProgress.memoizedProps, _instance.context); var state = tempInstance.state; _instance.updater.enqueueSetState(_instance, state, null); break; } case true: { workInProgress.flags |= DidCapture; workInProgress.flags |= ShouldCapture; // eslint-disable-next-line react-internal/prod-error-codes var error$1 = new Error('Simulated error coming from DevTools'); var lane = pickArbitraryLane(renderLanes); workInProgress.lanes = mergeLanes(workInProgress.lanes, lane); // Schedule the error boundary to re-render using updated state var update = createClassErrorUpdate(workInProgress, createCapturedValueAtFiber(error$1, workInProgress), lane); enqueueCapturedUpdate(workInProgress, update); break; } } if (workInProgress.type !== workInProgress.elementType) { // Lazy component props can't be validated in createElement // because they're only guaranteed to be resolved here. var innerPropTypes = Component.propTypes; if (innerPropTypes) { checkPropTypes(innerPropTypes, nextProps, // Resolved props 'prop', getComponentNameFromType(Component)); } } } // Push context providers early to prevent context stack mismatches. // During mounting we don't know the child context yet as the instance doesn't exist. // We will invalidate the child context in finishClassComponent() right after rendering. var hasContext; if (isContextProvider(Component)) { hasContext = true; pushContextProvider(workInProgress); } else { hasContext = false; } prepareToReadContext(workInProgress, renderLanes); var instance = workInProgress.stateNode; var shouldUpdate; if (instance === null) { resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress); // In the initial pass we might need to construct the instance. constructClassInstance(workInProgress, Component, nextProps); mountClassInstance(workInProgress, Component, nextProps, renderLanes); shouldUpdate = true; } else if (current === null) { // In a resume, we'll already have an instance we can reuse. shouldUpdate = resumeMountClassInstance(workInProgress, Component, nextProps, renderLanes); } else { shouldUpdate = updateClassInstance(current, workInProgress, Component, nextProps, renderLanes); } var nextUnitOfWork = finishClassComponent(current, workInProgress, Component, shouldUpdate, hasContext, renderLanes); { var inst = workInProgress.stateNode; if (shouldUpdate && inst.props !== nextProps) { if (!didWarnAboutReassigningProps) { error('It looks like %s is reassigning its own `this.props` while rendering. ' + 'This is not supported and can lead to confusing bugs.', getComponentNameFromFiber(workInProgress) || 'a component'); } didWarnAboutReassigningProps = true; } } return nextUnitOfWork; } function finishClassComponent(current, workInProgress, Component, shouldUpdate, hasContext, renderLanes) { // Refs should update even if shouldComponentUpdate returns false markRef(current, workInProgress); var didCaptureError = (workInProgress.flags & DidCapture) !== NoFlags; if (!shouldUpdate && !didCaptureError) { // Context providers should defer to sCU for rendering if (hasContext) { invalidateContextProvider(workInProgress, Component, false); } return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); } var instance = workInProgress.stateNode; // Rerender ReactCurrentOwner$1.current = workInProgress; var nextChildren; if (didCaptureError && typeof Component.getDerivedStateFromError !== 'function') { // If we captured an error, but getDerivedStateFromError is not defined, // unmount all the children. componentDidCatch will schedule an update to // re-render a fallback. This is temporary until we migrate everyone to // the new API. // TODO: Warn in a future release. nextChildren = null; { stopProfilerTimerIfRunning(); } } else { { markComponentRenderStarted(workInProgress); } { setIsRendering(true); nextChildren = instance.render(); if ( workInProgress.mode & StrictLegacyMode) { setIsStrictModeForDevtools(true); try { instance.render(); } finally { setIsStrictModeForDevtools(false); } } setIsRendering(false); } { markComponentRenderStopped(); } } // React DevTools reads this flag. workInProgress.flags |= PerformedWork; if (current !== null && didCaptureError) { // If we're recovering from an error, reconcile without reusing any of // the existing children. Conceptually, the normal children and the children // that are shown on error are two different sets, so we shouldn't reuse // normal children even if their identities match. forceUnmountCurrentAndReconcile(current, workInProgress, nextChildren, renderLanes); } else { reconcileChildren(current, workInProgress, nextChildren, renderLanes); } // Memoize state using the values we just used to render. // TODO: Restructure so we never read values from the instance. workInProgress.memoizedState = instance.state; // The context might have changed so we need to recalculate it. if (hasContext) { invalidateContextProvider(workInProgress, Component, true); } return workInProgress.child; } function pushHostRootContext(workInProgress) { var root = workInProgress.stateNode; if (root.pendingContext) { pushTopLevelContextObject(workInProgress, root.pendingContext, root.pendingContext !== root.context); } else if (root.context) { // Should always be set pushTopLevelContextObject(workInProgress, root.context, false); } pushHostContainer(workInProgress, root.containerInfo); } function updateHostRoot(current, workInProgress, renderLanes) { pushHostRootContext(workInProgress); if (current === null) { throw new Error('Should have a current fiber. This is a bug in React.'); } var nextProps = workInProgress.pendingProps; var prevState = workInProgress.memoizedState; var prevChildren = prevState.element; cloneUpdateQueue(current, workInProgress); processUpdateQueue(workInProgress, nextProps, null, renderLanes); var nextState = workInProgress.memoizedState; var root = workInProgress.stateNode; // being called "element". var nextChildren = nextState.element; if ( prevState.isDehydrated) { // This is a hydration root whose shell has not yet hydrated. We should // attempt to hydrate. // Flip isDehydrated to false to indicate that when this render // finishes, the root will no longer be dehydrated. var overrideState = { element: nextChildren, isDehydrated: false, cache: nextState.cache, pendingSuspenseBoundaries: nextState.pendingSuspenseBoundaries, transitions: nextState.transitions }; var updateQueue = workInProgress.updateQueue; // `baseState` can always be the last state because the root doesn't // have reducer functions so it doesn't need rebasing. updateQueue.baseState = overrideState; workInProgress.memoizedState = overrideState; if (workInProgress.flags & ForceClientRender) { // Something errored during a previous attempt to hydrate the shell, so we // forced a client render. var recoverableError = createCapturedValueAtFiber(new Error('There was an error while hydrating. Because the error happened outside ' + 'of a Suspense boundary, the entire root will switch to ' + 'client rendering.'), workInProgress); return mountHostRootWithoutHydrating(current, workInProgress, nextChildren, renderLanes, recoverableError); } else if (nextChildren !== prevChildren) { var _recoverableError = createCapturedValueAtFiber(new Error('This root received an early update, before anything was able ' + 'hydrate. Switched the entire root to client rendering.'), workInProgress); return mountHostRootWithoutHydrating(current, workInProgress, nextChildren, renderLanes, _recoverableError); } else { // The outermost shell has not hydrated yet. Start hydrating. enterHydrationState(workInProgress); var child = mountChildFibers(workInProgress, null, nextChildren, renderLanes); workInProgress.child = child; var node = child; while (node) { // Mark each child as hydrating. This is a fast path to know whether this // tree is part of a hydrating tree. This is used to determine if a child // node has fully mounted yet, and for scheduling event replaying. // Conceptually this is similar to Placement in that a new subtree is // inserted into the React tree here. It just happens to not need DOM // mutations because it already exists. node.flags = node.flags & ~Placement | Hydrating; node = node.sibling; } } } else { // Root is not dehydrated. Either this is a client-only root, or it // already hydrated. resetHydrationState(); if (nextChildren === prevChildren) { return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); } reconcileChildren(current, workInProgress, nextChildren, renderLanes); } return workInProgress.child; } function mountHostRootWithoutHydrating(current, workInProgress, nextChildren, renderLanes, recoverableError) { // Revert to client rendering. resetHydrationState(); queueHydrationError(recoverableError); workInProgress.flags |= ForceClientRender; reconcileChildren(current, workInProgress, nextChildren, renderLanes); return workInProgress.child; } function updateHostComponent(current, workInProgress, renderLanes) { pushHostContext(workInProgress); if (current === null) { tryToClaimNextHydratableInstance(workInProgress); } var type = workInProgress.type; var nextProps = workInProgress.pendingProps; var prevProps = current !== null ? current.memoizedProps : null; var nextChildren = nextProps.children; var isDirectTextChild = shouldSetTextContent(type, nextProps); if (isDirectTextChild) { // We special case a direct text child of a host node. This is a common // case. We won't handle it as a reified child. We will instead handle // this in the host environment that also has access to this prop. That // avoids allocating another HostText fiber and traversing it. nextChildren = null; } else if (prevProps !== null && shouldSetTextContent(type, prevProps)) { // If we're switching from a direct text child to a normal child, or to // empty, we need to schedule the text content to be reset. workInProgress.flags |= ContentReset; } markRef(current, workInProgress); reconcileChildren(current, workInProgress, nextChildren, renderLanes); return workInProgress.child; } function updateHostText(current, workInProgress) { if (current === null) { tryToClaimNextHydratableInstance(workInProgress); } // Nothing to do here. This is terminal. We'll do the completion step // immediately after. return null; } function mountLazyComponent(_current, workInProgress, elementType, renderLanes) { resetSuspendedCurrentOnMountInLegacyMode(_current, workInProgress); var props = workInProgress.pendingProps; var lazyComponent = elementType; var payload = lazyComponent._payload; var init = lazyComponent._init; var Component = init(payload); // Store the unwrapped component in the type. workInProgress.type = Component; var resolvedTag = workInProgress.tag = resolveLazyComponentTag(Component); var resolvedProps = resolveDefaultProps(Component, props); var child; switch (resolvedTag) { case FunctionComponent: { { validateFunctionComponentInDev(workInProgress, Component); workInProgress.type = Component = resolveFunctionForHotReloading(Component); } child = updateFunctionComponent(null, workInProgress, Component, resolvedProps, renderLanes); return child; } case ClassComponent: { { workInProgress.type = Component = resolveClassForHotReloading(Component); } child = updateClassComponent(null, workInProgress, Component, resolvedProps, renderLanes); return child; } case ForwardRef: { { workInProgress.type = Component = resolveForwardRefForHotReloading(Component); } child = updateForwardRef(null, workInProgress, Component, resolvedProps, renderLanes); return child; } case MemoComponent: { { if (workInProgress.type !== workInProgress.elementType) { var outerPropTypes = Component.propTypes; if (outerPropTypes) { checkPropTypes(outerPropTypes, resolvedProps, // Resolved for outer only 'prop', getComponentNameFromType(Component)); } } } child = updateMemoComponent(null, workInProgress, Component, resolveDefaultProps(Component.type, resolvedProps), // The inner type can have defaults too renderLanes); return child; } } var hint = ''; { if (Component !== null && typeof Component === 'object' && Component.$$typeof === REACT_LAZY_TYPE) { hint = ' Did you wrap a component in React.lazy() more than once?'; } } // This message intentionally doesn't mention ForwardRef or MemoComponent // because the fact that it's a separate type of work is an // implementation detail. throw new Error("Element type is invalid. Received a promise that resolves to: " + Component + ". " + ("Lazy element type must resolve to a class or function." + hint)); } function mountIncompleteClassComponent(_current, workInProgress, Component, nextProps, renderLanes) { resetSuspendedCurrentOnMountInLegacyMode(_current, workInProgress); // Promote the fiber to a class and try rendering again. workInProgress.tag = ClassComponent; // The rest of this function is a fork of `updateClassComponent` // Push context providers early to prevent context stack mismatches. // During mounting we don't know the child context yet as the instance doesn't exist. // We will invalidate the child context in finishClassComponent() right after rendering. var hasContext; if (isContextProvider(Component)) { hasContext = true; pushContextProvider(workInProgress); } else { hasContext = false; } prepareToReadContext(workInProgress, renderLanes); constructClassInstance(workInProgress, Component, nextProps); mountClassInstance(workInProgress, Component, nextProps, renderLanes); return finishClassComponent(null, workInProgress, Component, true, hasContext, renderLanes); } function mountIndeterminateComponent(_current, workInProgress, Component, renderLanes) { resetSuspendedCurrentOnMountInLegacyMode(_current, workInProgress); var props = workInProgress.pendingProps; var context; { var unmaskedContext = getUnmaskedContext(workInProgress, Component, false); context = getMaskedContext(workInProgress, unmaskedContext); } prepareToReadContext(workInProgress, renderLanes); var value; var hasId; { markComponentRenderStarted(workInProgress); } { if (Component.prototype && typeof Component.prototype.render === 'function') { var componentName = getComponentNameFromType(Component) || 'Unknown'; if (!didWarnAboutBadClass[componentName]) { error("The <%s /> component appears to have a render method, but doesn't extend React.Component. " + 'This is likely to cause errors. Change %s to extend React.Component instead.', componentName, componentName); didWarnAboutBadClass[componentName] = true; } } if (workInProgress.mode & StrictLegacyMode) { ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, null); } setIsRendering(true); ReactCurrentOwner$1.current = workInProgress; value = renderWithHooks(null, workInProgress, Component, props, context, renderLanes); hasId = checkDidRenderIdHook(); setIsRendering(false); } { markComponentRenderStopped(); } // React DevTools reads this flag. workInProgress.flags |= PerformedWork; { // Support for module components is deprecated and is removed behind a flag. // Whether or not it would crash later, we want to show a good message in DEV first. if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) { var _componentName = getComponentNameFromType(Component) || 'Unknown'; if (!didWarnAboutModulePatternComponent[_componentName]) { error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName, _componentName, _componentName); didWarnAboutModulePatternComponent[_componentName] = true; } } } if ( // Run these checks in production only if the flag is off. // Eventually we'll delete this branch altogether. typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) { { var _componentName2 = getComponentNameFromType(Component) || 'Unknown'; if (!didWarnAboutModulePatternComponent[_componentName2]) { error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName2, _componentName2, _componentName2); didWarnAboutModulePatternComponent[_componentName2] = true; } } // Proceed under the assumption that this is a class instance workInProgress.tag = ClassComponent; // Throw out any hooks that were used. workInProgress.memoizedState = null; workInProgress.updateQueue = null; // Push context providers early to prevent context stack mismatches. // During mounting we don't know the child context yet as the instance doesn't exist. // We will invalidate the child context in finishClassComponent() right after rendering. var hasContext = false; if (isContextProvider(Component)) { hasContext = true; pushContextProvider(workInProgress); } else { hasContext = false; } workInProgress.memoizedState = value.state !== null && value.state !== undefined ? value.state : null; initializeUpdateQueue(workInProgress); adoptClassInstance(workInProgress, value); mountClassInstance(workInProgress, Component, props, renderLanes); return finishClassComponent(null, workInProgress, Component, true, hasContext, renderLanes); } else { // Proceed under the assumption that this is a function component workInProgress.tag = FunctionComponent; { if ( workInProgress.mode & StrictLegacyMode) { setIsStrictModeForDevtools(true); try { value = renderWithHooks(null, workInProgress, Component, props, context, renderLanes); hasId = checkDidRenderIdHook(); } finally { setIsStrictModeForDevtools(false); } } } if (getIsHydrating() && hasId) { pushMaterializedTreeId(workInProgress); } reconcileChildren(null, workInProgress, value, renderLanes); { validateFunctionComponentInDev(workInProgress, Component); } return workInProgress.child; } } function validateFunctionComponentInDev(workInProgress, Component) { { if (Component) { if (Component.childContextTypes) { error('%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component'); } } if (workInProgress.ref !== null) { var info = ''; var ownerName = getCurrentFiberOwnerNameInDevOrNull(); if (ownerName) { info += '\n\nCheck the render method of `' + ownerName + '`.'; } var warningKey = ownerName || ''; var debugSource = workInProgress._debugSource; if (debugSource) { warningKey = debugSource.fileName + ':' + debugSource.lineNumber; } if (!didWarnAboutFunctionRefs[warningKey]) { didWarnAboutFunctionRefs[warningKey] = true; error('Function components cannot be given refs. ' + 'Attempts to access this ref will fail. ' + 'Did you mean to use React.forwardRef()?%s', info); } } if (typeof Component.getDerivedStateFromProps === 'function') { var _componentName3 = getComponentNameFromType(Component) || 'Unknown'; if (!didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3]) { error('%s: Function components do not support getDerivedStateFromProps.', _componentName3); didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3] = true; } } if (typeof Component.contextType === 'object' && Component.contextType !== null) { var _componentName4 = getComponentNameFromType(Component) || 'Unknown'; if (!didWarnAboutContextTypeOnFunctionComponent[_componentName4]) { error('%s: Function components do not support contextType.', _componentName4); didWarnAboutContextTypeOnFunctionComponent[_componentName4] = true; } } } } var SUSPENDED_MARKER = { dehydrated: null, treeContext: null, retryLane: NoLane }; function mountSuspenseOffscreenState(renderLanes) { return { baseLanes: renderLanes, cachePool: getSuspendedCache(), transitions: null }; } function updateSuspenseOffscreenState(prevOffscreenState, renderLanes) { var cachePool = null; return { baseLanes: mergeLanes(prevOffscreenState.baseLanes, renderLanes), cachePool: cachePool, transitions: prevOffscreenState.transitions }; } // TODO: Probably should inline this back function shouldRemainOnFallback(suspenseContext, current, workInProgress, renderLanes) { // If we're already showing a fallback, there are cases where we need to // remain on that fallback regardless of whether the content has resolved. // For example, SuspenseList coordinates when nested content appears. if (current !== null) { var suspenseState = current.memoizedState; if (suspenseState === null) { // Currently showing content. Don't hide it, even if ForceSuspenseFallback // is true. More precise name might be "ForceRemainSuspenseFallback". // Note: This is a factoring smell. Can't remain on a fallback if there's // no fallback to remain on. return false; } } // Not currently showing content. Consult the Suspense context. return hasSuspenseContext(suspenseContext, ForceSuspenseFallback); } function getRemainingWorkInPrimaryTree(current, renderLanes) { // TODO: Should not remove render lanes that were pinged during this render return removeLanes(current.childLanes, renderLanes); } function updateSuspenseComponent(current, workInProgress, renderLanes) { var nextProps = workInProgress.pendingProps; // This is used by DevTools to force a boundary to suspend. { if (shouldSuspend(workInProgress)) { workInProgress.flags |= DidCapture; } } var suspenseContext = suspenseStackCursor.current; var showFallback = false; var didSuspend = (workInProgress.flags & DidCapture) !== NoFlags; if (didSuspend || shouldRemainOnFallback(suspenseContext, current)) { // Something in this boundary's subtree already suspended. Switch to // rendering the fallback children. showFallback = true; workInProgress.flags &= ~DidCapture; } else { // Attempting the main content if (current === null || current.memoizedState !== null) { // This is a new mount or this boundary is already showing a fallback state. // Mark this subtree context as having at least one invisible parent that could // handle the fallback state. // Avoided boundaries are not considered since they cannot handle preferred fallback states. { suspenseContext = addSubtreeSuspenseContext(suspenseContext, InvisibleParentSuspenseContext); } } } suspenseContext = setDefaultShallowSuspenseContext(suspenseContext); pushSuspenseContext(workInProgress, suspenseContext); // OK, the next part is confusing. We're about to reconcile the Suspense // boundary's children. This involves some custom reconciliation logic. Two // main reasons this is so complicated. // // First, Legacy Mode has different semantics for backwards compatibility. The // primary tree will commit in an inconsistent state, so when we do the // second pass to render the fallback, we do some exceedingly, uh, clever // hacks to make that not totally break. Like transferring effects and // deletions from hidden tree. In Concurrent Mode, it's much simpler, // because we bailout on the primary tree completely and leave it in its old // state, no effects. Same as what we do for Offscreen (except that // Offscreen doesn't have the first render pass). // // Second is hydration. During hydration, the Suspense fiber has a slightly // different layout, where the child points to a dehydrated fragment, which // contains the DOM rendered by the server. // // Third, even if you set all that aside, Suspense is like error boundaries in // that we first we try to render one tree, and if that fails, we render again // and switch to a different tree. Like a try/catch block. So we have to track // which branch we're currently rendering. Ideally we would model this using // a stack. if (current === null) { // Initial mount // Special path for hydration // If we're currently hydrating, try to hydrate this boundary. tryToClaimNextHydratableInstance(workInProgress); // This could've been a dehydrated suspense component. var suspenseState = workInProgress.memoizedState; if (suspenseState !== null) { var dehydrated = suspenseState.dehydrated; if (dehydrated !== null) { return mountDehydratedSuspenseComponent(workInProgress, dehydrated); } } var nextPrimaryChildren = nextProps.children; var nextFallbackChildren = nextProps.fallback; if (showFallback) { var fallbackFragment = mountSuspenseFallbackChildren(workInProgress, nextPrimaryChildren, nextFallbackChildren, renderLanes); var primaryChildFragment = workInProgress.child; primaryChildFragment.memoizedState = mountSuspenseOffscreenState(renderLanes); workInProgress.memoizedState = SUSPENDED_MARKER; return fallbackFragment; } else { return mountSuspensePrimaryChildren(workInProgress, nextPrimaryChildren); } } else { // This is an update. // Special path for hydration var prevState = current.memoizedState; if (prevState !== null) { var _dehydrated = prevState.dehydrated; if (_dehydrated !== null) { return updateDehydratedSuspenseComponent(current, workInProgress, didSuspend, nextProps, _dehydrated, prevState, renderLanes); } } if (showFallback) { var _nextFallbackChildren = nextProps.fallback; var _nextPrimaryChildren = nextProps.children; var fallbackChildFragment = updateSuspenseFallbackChildren(current, workInProgress, _nextPrimaryChildren, _nextFallbackChildren, renderLanes); var _primaryChildFragment2 = workInProgress.child; var prevOffscreenState = current.child.memoizedState; _primaryChildFragment2.memoizedState = prevOffscreenState === null ? mountSuspenseOffscreenState(renderLanes) : updateSuspenseOffscreenState(prevOffscreenState, renderLanes); _primaryChildFragment2.childLanes = getRemainingWorkInPrimaryTree(current, renderLanes); workInProgress.memoizedState = SUSPENDED_MARKER; return fallbackChildFragment; } else { var _nextPrimaryChildren2 = nextProps.children; var _primaryChildFragment3 = updateSuspensePrimaryChildren(current, workInProgress, _nextPrimaryChildren2, renderLanes); workInProgress.memoizedState = null; return _primaryChildFragment3; } } } function mountSuspensePrimaryChildren(workInProgress, primaryChildren, renderLanes) { var mode = workInProgress.mode; var primaryChildProps = { mode: 'visible', children: primaryChildren }; var primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, mode); primaryChildFragment.return = workInProgress; workInProgress.child = primaryChildFragment; return primaryChildFragment; } function mountSuspenseFallbackChildren(workInProgress, primaryChildren, fallbackChildren, renderLanes) { var mode = workInProgress.mode; var progressedPrimaryFragment = workInProgress.child; var primaryChildProps = { mode: 'hidden', children: primaryChildren }; var primaryChildFragment; var fallbackChildFragment; if ((mode & ConcurrentMode) === NoMode && progressedPrimaryFragment !== null) { // In legacy mode, we commit the primary tree as if it successfully // completed, even though it's in an inconsistent state. primaryChildFragment = progressedPrimaryFragment; primaryChildFragment.childLanes = NoLanes; primaryChildFragment.pendingProps = primaryChildProps; if ( workInProgress.mode & ProfileMode) { // Reset the durations from the first pass so they aren't included in the // final amounts. This seems counterintuitive, since we're intentionally // not measuring part of the render phase, but this makes it match what we // do in Concurrent Mode. primaryChildFragment.actualDuration = 0; primaryChildFragment.actualStartTime = -1; primaryChildFragment.selfBaseDuration = 0; primaryChildFragment.treeBaseDuration = 0; } fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes, null); } else { primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, mode); fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes, null); } primaryChildFragment.return = workInProgress; fallbackChildFragment.return = workInProgress; primaryChildFragment.sibling = fallbackChildFragment; workInProgress.child = primaryChildFragment; return fallbackChildFragment; } function mountWorkInProgressOffscreenFiber(offscreenProps, mode, renderLanes) { // The props argument to `createFiberFromOffscreen` is `any` typed, so we use // this wrapper function to constrain it. return createFiberFromOffscreen(offscreenProps, mode, NoLanes, null); } function updateWorkInProgressOffscreenFiber(current, offscreenProps) { // The props argument to `createWorkInProgress` is `any` typed, so we use this // wrapper function to constrain it. return createWorkInProgress(current, offscreenProps); } function updateSuspensePrimaryChildren(current, workInProgress, primaryChildren, renderLanes) { var currentPrimaryChildFragment = current.child; var currentFallbackChildFragment = currentPrimaryChildFragment.sibling; var primaryChildFragment = updateWorkInProgressOffscreenFiber(currentPrimaryChildFragment, { mode: 'visible', children: primaryChildren }); if ((workInProgress.mode & ConcurrentMode) === NoMode) { primaryChildFragment.lanes = renderLanes; } primaryChildFragment.return = workInProgress; primaryChildFragment.sibling = null; if (currentFallbackChildFragment !== null) { // Delete the fallback child fragment var deletions = workInProgress.deletions; if (deletions === null) { workInProgress.deletions = [currentFallbackChildFragment]; workInProgress.flags |= ChildDeletion; } else { deletions.push(currentFallbackChildFragment); } } workInProgress.child = primaryChildFragment; return primaryChildFragment; } function updateSuspenseFallbackChildren(current, workInProgress, primaryChildren, fallbackChildren, renderLanes) { var mode = workInProgress.mode; var currentPrimaryChildFragment = current.child; var currentFallbackChildFragment = currentPrimaryChildFragment.sibling; var primaryChildProps = { mode: 'hidden', children: primaryChildren }; var primaryChildFragment; if ( // In legacy mode, we commit the primary tree as if it successfully // completed, even though it's in an inconsistent state. (mode & ConcurrentMode) === NoMode && // Make sure we're on the second pass, i.e. the primary child fragment was // already cloned. In legacy mode, the only case where this isn't true is // when DevTools forces us to display a fallback; we skip the first render // pass entirely and go straight to rendering the fallback. (In Concurrent // Mode, SuspenseList can also trigger this scenario, but this is a legacy- // only codepath.) workInProgress.child !== currentPrimaryChildFragment) { var progressedPrimaryFragment = workInProgress.child; primaryChildFragment = progressedPrimaryFragment; primaryChildFragment.childLanes = NoLanes; primaryChildFragment.pendingProps = primaryChildProps; if ( workInProgress.mode & ProfileMode) { // Reset the durations from the first pass so they aren't included in the // final amounts. This seems counterintuitive, since we're intentionally // not measuring part of the render phase, but this makes it match what we // do in Concurrent Mode. primaryChildFragment.actualDuration = 0; primaryChildFragment.actualStartTime = -1; primaryChildFragment.selfBaseDuration = currentPrimaryChildFragment.selfBaseDuration; primaryChildFragment.treeBaseDuration = currentPrimaryChildFragment.treeBaseDuration; } // The fallback fiber was added as a deletion during the first pass. // However, since we're going to remain on the fallback, we no longer want // to delete it. workInProgress.deletions = null; } else { primaryChildFragment = updateWorkInProgressOffscreenFiber(currentPrimaryChildFragment, primaryChildProps); // Since we're reusing a current tree, we need to reuse the flags, too. // (We don't do this in legacy mode, because in legacy mode we don't re-use // the current tree; see previous branch.) primaryChildFragment.subtreeFlags = currentPrimaryChildFragment.subtreeFlags & StaticMask; } var fallbackChildFragment; if (currentFallbackChildFragment !== null) { fallbackChildFragment = createWorkInProgress(currentFallbackChildFragment, fallbackChildren); } else { fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes, null); // Needs a placement effect because the parent (the Suspense boundary) already // mounted but this is a new fiber. fallbackChildFragment.flags |= Placement; } fallbackChildFragment.return = workInProgress; primaryChildFragment.return = workInProgress; primaryChildFragment.sibling = fallbackChildFragment; workInProgress.child = primaryChildFragment; return fallbackChildFragment; } function retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, recoverableError) { // Falling back to client rendering. Because this has performance // implications, it's considered a recoverable error, even though the user // likely won't observe anything wrong with the UI. // // The error is passed in as an argument to enforce that every caller provide // a custom message, or explicitly opt out (currently the only path that opts // out is legacy mode; every concurrent path provides an error). if (recoverableError !== null) { queueHydrationError(recoverableError); } // This will add the old fiber to the deletion list reconcileChildFibers(workInProgress, current.child, null, renderLanes); // We're now not suspended nor dehydrated. var nextProps = workInProgress.pendingProps; var primaryChildren = nextProps.children; var primaryChildFragment = mountSuspensePrimaryChildren(workInProgress, primaryChildren); // Needs a placement effect because the parent (the Suspense boundary) already // mounted but this is a new fiber. primaryChildFragment.flags |= Placement; workInProgress.memoizedState = null; return primaryChildFragment; } function mountSuspenseFallbackAfterRetryWithoutHydrating(current, workInProgress, primaryChildren, fallbackChildren, renderLanes) { var fiberMode = workInProgress.mode; var primaryChildProps = { mode: 'visible', children: primaryChildren }; var primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, fiberMode); var fallbackChildFragment = createFiberFromFragment(fallbackChildren, fiberMode, renderLanes, null); // Needs a placement effect because the parent (the Suspense // boundary) already mounted but this is a new fiber. fallbackChildFragment.flags |= Placement; primaryChildFragment.return = workInProgress; fallbackChildFragment.return = workInProgress; primaryChildFragment.sibling = fallbackChildFragment; workInProgress.child = primaryChildFragment; if ((workInProgress.mode & ConcurrentMode) !== NoMode) { // We will have dropped the effect list which contains the // deletion. We need to reconcile to delete the current child. reconcileChildFibers(workInProgress, current.child, null, renderLanes); } return fallbackChildFragment; } function mountDehydratedSuspenseComponent(workInProgress, suspenseInstance, renderLanes) { // During the first pass, we'll bail out and not drill into the children. // Instead, we'll leave the content in place and try to hydrate it later. if ((workInProgress.mode & ConcurrentMode) === NoMode) { { error('Cannot hydrate Suspense in legacy mode. Switch from ' + 'ReactDOM.hydrate(element, container) to ' + 'ReactDOMClient.hydrateRoot(container, <App />)' + '.render(element) or remove the Suspense components from ' + 'the server rendered components.'); } workInProgress.lanes = laneToLanes(SyncLane); } else if (isSuspenseInstanceFallback(suspenseInstance)) { // This is a client-only boundary. Since we won't get any content from the server // for this, we need to schedule that at a higher priority based on when it would // have timed out. In theory we could render it in this pass but it would have the // wrong priority associated with it and will prevent hydration of parent path. // Instead, we'll leave work left on it to render it in a separate commit. // TODO This time should be the time at which the server rendered response that is // a parent to this boundary was displayed. However, since we currently don't have // a protocol to transfer that time, we'll just estimate it by using the current // time. This will mean that Suspense timeouts are slightly shifted to later than // they should be. // Schedule a normal pri update to render this content. workInProgress.lanes = laneToLanes(DefaultHydrationLane); } else { // We'll continue hydrating the rest at offscreen priority since we'll already // be showing the right content coming from the server, it is no rush. workInProgress.lanes = laneToLanes(OffscreenLane); } return null; } function updateDehydratedSuspenseComponent(current, workInProgress, didSuspend, nextProps, suspenseInstance, suspenseState, renderLanes) { if (!didSuspend) { // This is the first render pass. Attempt to hydrate. // We should never be hydrating at this point because it is the first pass, // but after we've already committed once. warnIfHydrating(); if ((workInProgress.mode & ConcurrentMode) === NoMode) { return retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, // TODO: When we delete legacy mode, we should make this error argument // required — every concurrent mode path that causes hydration to // de-opt to client rendering should have an error message. null); } if (isSuspenseInstanceFallback(suspenseInstance)) { // This boundary is in a permanent fallback state. In this case, we'll never // get an update and we'll never be able to hydrate the final content. Let's just try the // client side render instead. var digest, message, stack; { var _getSuspenseInstanceF = getSuspenseInstanceFallbackErrorDetails(suspenseInstance); digest = _getSuspenseInstanceF.digest; message = _getSuspenseInstanceF.message; stack = _getSuspenseInstanceF.stack; } var error; if (message) { // eslint-disable-next-line react-internal/prod-error-codes error = new Error(message); } else { error = new Error('The server could not finish this Suspense boundary, likely ' + 'due to an error during server rendering. Switched to ' + 'client rendering.'); } var capturedValue = createCapturedValue(error, digest, stack); return retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, capturedValue); } // any context has changed, we need to treat is as if the input might have changed. var hasContextChanged = includesSomeLane(renderLanes, current.childLanes); if (didReceiveUpdate || hasContextChanged) { // This boundary has changed since the first render. This means that we are now unable to // hydrate it. We might still be able to hydrate it using a higher priority lane. var root = getWorkInProgressRoot(); if (root !== null) { var attemptHydrationAtLane = getBumpedLaneForHydration(root, renderLanes); if (attemptHydrationAtLane !== NoLane && attemptHydrationAtLane !== suspenseState.retryLane) { // Intentionally mutating since this render will get interrupted. This // is one of the very rare times where we mutate the current tree // during the render phase. suspenseState.retryLane = attemptHydrationAtLane; // TODO: Ideally this would inherit the event time of the current render var eventTime = NoTimestamp; enqueueConcurrentRenderForLane(current, attemptHydrationAtLane); scheduleUpdateOnFiber(root, current, attemptHydrationAtLane, eventTime); } } // If we have scheduled higher pri work above, this will probably just abort the render // since we now have higher priority work, but in case it doesn't, we need to prepare to // render something, if we time out. Even if that requires us to delete everything and // skip hydration. // Delay having to do this as long as the suspense timeout allows us. renderDidSuspendDelayIfPossible(); var _capturedValue = createCapturedValue(new Error('This Suspense boundary received an update before it finished ' + 'hydrating. This caused the boundary to switch to client rendering. ' + 'The usual way to fix this is to wrap the original update ' + 'in startTransition.')); return retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, _capturedValue); } else if (isSuspenseInstancePending(suspenseInstance)) { // This component is still pending more data from the server, so we can't hydrate its // content. We treat it as if this component suspended itself. It might seem as if // we could just try to render it client-side instead. However, this will perform a // lot of unnecessary work and is unlikely to complete since it often will suspend // on missing data anyway. Additionally, the server might be able to render more // than we can on the client yet. In that case we'd end up with more fallback states // on the client than if we just leave it alone. If the server times out or errors // these should update this boundary to the permanent Fallback state instead. // Mark it as having captured (i.e. suspended). workInProgress.flags |= DidCapture; // Leave the child in place. I.e. the dehydrated fragment. workInProgress.child = current.child; // Register a callback to retry this boundary once the server has sent the result. var retry = retryDehydratedSuspenseBoundary.bind(null, current); registerSuspenseInstanceRetry(suspenseInstance, retry); return null; } else { // This is the first attempt. reenterHydrationStateFromDehydratedSuspenseInstance(workInProgress, suspenseInstance, suspenseState.treeContext); var primaryChildren = nextProps.children; var primaryChildFragment = mountSuspensePrimaryChildren(workInProgress, primaryChildren); // Mark the children as hydrating. This is a fast path to know whether this // tree is part of a hydrating tree. This is used to determine if a child // node has fully mounted yet, and for scheduling event replaying. // Conceptually this is similar to Placement in that a new subtree is // inserted into the React tree here. It just happens to not need DOM // mutations because it already exists. primaryChildFragment.flags |= Hydrating; return primaryChildFragment; } } else { // This is the second render pass. We already attempted to hydrated, but // something either suspended or errored. if (workInProgress.flags & ForceClientRender) { // Something errored during hydration. Try again without hydrating. workInProgress.flags &= ~ForceClientRender; var _capturedValue2 = createCapturedValue(new Error('There was an error while hydrating this Suspense boundary. ' + 'Switched to client rendering.')); return retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, _capturedValue2); } else if (workInProgress.memoizedState !== null) { // Something suspended and we should still be in dehydrated mode. // Leave the existing child in place. workInProgress.child = current.child; // The dehydrated completion pass expects this flag to be there // but the normal suspense pass doesn't. workInProgress.flags |= DidCapture; return null; } else { // Suspended but we should no longer be in dehydrated mode. // Therefore we now have to render the fallback. var nextPrimaryChildren = nextProps.children; var nextFallbackChildren = nextProps.fallback; var fallbackChildFragment = mountSuspenseFallbackAfterRetryWithoutHydrating(current, workInProgress, nextPrimaryChildren, nextFallbackChildren, renderLanes); var _primaryChildFragment4 = workInProgress.child; _primaryChildFragment4.memoizedState = mountSuspenseOffscreenState(renderLanes); workInProgress.memoizedState = SUSPENDED_MARKER; return fallbackChildFragment; } } } function scheduleSuspenseWorkOnFiber(fiber, renderLanes, propagationRoot) { fiber.lanes = mergeLanes(fiber.lanes, renderLanes); var alternate = fiber.alternate; if (alternate !== null) { alternate.lanes = mergeLanes(alternate.lanes, renderLanes); } scheduleContextWorkOnParentPath(fiber.return, renderLanes, propagationRoot); } function propagateSuspenseContextChange(workInProgress, firstChild, renderLanes) { // Mark any Suspense boundaries with fallbacks as having work to do. // If they were previously forced into fallbacks, they may now be able // to unblock. var node = firstChild; while (node !== null) { if (node.tag === SuspenseComponent) { var state = node.memoizedState; if (state !== null) { scheduleSuspenseWorkOnFiber(node, renderLanes, workInProgress); } } else if (node.tag === SuspenseListComponent) { // If the tail is hidden there might not be an Suspense boundaries // to schedule work on. In this case we have to schedule it on the // list itself. // We don't have to traverse to the children of the list since // the list will propagate the change when it rerenders. scheduleSuspenseWorkOnFiber(node, renderLanes, workInProgress); } else if (node.child !== null) { node.child.return = node; node = node.child; continue; } if (node === workInProgress) { return; } while (node.sibling === null) { if (node.return === null || node.return === workInProgress) { return; } node = node.return; } node.sibling.return = node.return; node = node.sibling; } } function findLastContentRow(firstChild) { // This is going to find the last row among these children that is already // showing content on the screen, as opposed to being in fallback state or // new. If a row has multiple Suspense boundaries, any of them being in the // fallback state, counts as the whole row being in a fallback state. // Note that the "rows" will be workInProgress, but any nested children // will still be current since we haven't rendered them yet. The mounted // order may not be the same as the new order. We use the new order. var row = firstChild; var lastContentRow = null; while (row !== null) { var currentRow = row.alternate; // New rows can't be content rows. if (currentRow !== null && findFirstSuspended(currentRow) === null) { lastContentRow = row; } row = row.sibling; } return lastContentRow; } function validateRevealOrder(revealOrder) { { if (revealOrder !== undefined && revealOrder !== 'forwards' && revealOrder !== 'backwards' && revealOrder !== 'together' && !didWarnAboutRevealOrder[revealOrder]) { didWarnAboutRevealOrder[revealOrder] = true; if (typeof revealOrder === 'string') { switch (revealOrder.toLowerCase()) { case 'together': case 'forwards': case 'backwards': { error('"%s" is not a valid value for revealOrder on <SuspenseList />. ' + 'Use lowercase "%s" instead.', revealOrder, revealOrder.toLowerCase()); break; } case 'forward': case 'backward': { error('"%s" is not a valid value for revealOrder on <SuspenseList />. ' + 'React uses the -s suffix in the spelling. Use "%ss" instead.', revealOrder, revealOrder.toLowerCase()); break; } default: error('"%s" is not a supported revealOrder on <SuspenseList />. ' + 'Did you mean "together", "forwards" or "backwards"?', revealOrder); break; } } else { error('%s is not a supported value for revealOrder on <SuspenseList />. ' + 'Did you mean "together", "forwards" or "backwards"?', revealOrder); } } } } function validateTailOptions(tailMode, revealOrder) { { if (tailMode !== undefined && !didWarnAboutTailOptions[tailMode]) { if (tailMode !== 'collapsed' && tailMode !== 'hidden') { didWarnAboutTailOptions[tailMode] = true; error('"%s" is not a supported value for tail on <SuspenseList />. ' + 'Did you mean "collapsed" or "hidden"?', tailMode); } else if (revealOrder !== 'forwards' && revealOrder !== 'backwards') { didWarnAboutTailOptions[tailMode] = true; error('<SuspenseList tail="%s" /> is only valid if revealOrder is ' + '"forwards" or "backwards". ' + 'Did you mean to specify revealOrder="forwards"?', tailMode); } } } } function validateSuspenseListNestedChild(childSlot, index) { { var isAnArray = isArray(childSlot); var isIterable = !isAnArray && typeof getIteratorFn(childSlot) === 'function'; if (isAnArray || isIterable) { var type = isAnArray ? 'array' : 'iterable'; error('A nested %s was passed to row #%s in <SuspenseList />. Wrap it in ' + 'an additional SuspenseList to configure its revealOrder: ' + '<SuspenseList revealOrder=...> ... ' + '<SuspenseList revealOrder=...>{%s}</SuspenseList> ... ' + '</SuspenseList>', type, index, type); return false; } } return true; } function validateSuspenseListChildren(children, revealOrder) { { if ((revealOrder === 'forwards' || revealOrder === 'backwards') && children !== undefined && children !== null && children !== false) { if (isArray(children)) { for (var i = 0; i < children.length; i++) { if (!validateSuspenseListNestedChild(children[i], i)) { return; } } } else { var iteratorFn = getIteratorFn(children); if (typeof iteratorFn === 'function') { var childrenIterator = iteratorFn.call(children); if (childrenIterator) { var step = childrenIterator.next(); var _i = 0; for (; !step.done; step = childrenIterator.next()) { if (!validateSuspenseListNestedChild(step.value, _i)) { return; } _i++; } } } else { error('A single row was passed to a <SuspenseList revealOrder="%s" />. ' + 'This is not useful since it needs multiple rows. ' + 'Did you mean to pass multiple children or an array?', revealOrder); } } } } } function initSuspenseListRenderState(workInProgress, isBackwards, tail, lastContentRow, tailMode) { var renderState = workInProgress.memoizedState; if (renderState === null) { workInProgress.memoizedState = { isBackwards: isBackwards, rendering: null, renderingStartTime: 0, last: lastContentRow, tail: tail, tailMode: tailMode }; } else { // We can reuse the existing object from previous renders. renderState.isBackwards = isBackwards; renderState.rendering = null; renderState.renderingStartTime = 0; renderState.last = lastContentRow; renderState.tail = tail; renderState.tailMode = tailMode; } } // This can end up rendering this component multiple passes. // The first pass splits the children fibers into two sets. A head and tail. // We first render the head. If anything is in fallback state, we do another // pass through beginWork to rerender all children (including the tail) with // the force suspend context. If the first render didn't have anything in // in fallback state. Then we render each row in the tail one-by-one. // That happens in the completeWork phase without going back to beginWork. function updateSuspenseListComponent(current, workInProgress, renderLanes) { var nextProps = workInProgress.pendingProps; var revealOrder = nextProps.revealOrder; var tailMode = nextProps.tail; var newChildren = nextProps.children; validateRevealOrder(revealOrder); validateTailOptions(tailMode, revealOrder); validateSuspenseListChildren(newChildren, revealOrder); reconcileChildren(current, workInProgress, newChildren, renderLanes); var suspenseContext = suspenseStackCursor.current; var shouldForceFallback = hasSuspenseContext(suspenseContext, ForceSuspenseFallback); if (shouldForceFallback) { suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback); workInProgress.flags |= DidCapture; } else { var didSuspendBefore = current !== null && (current.flags & DidCapture) !== NoFlags; if (didSuspendBefore) { // If we previously forced a fallback, we need to schedule work // on any nested boundaries to let them know to try to render // again. This is the same as context updating. propagateSuspenseContextChange(workInProgress, workInProgress.child, renderLanes); } suspenseContext = setDefaultShallowSuspenseContext(suspenseContext); } pushSuspenseContext(workInProgress, suspenseContext); if ((workInProgress.mode & ConcurrentMode) === NoMode) { // In legacy mode, SuspenseList doesn't work so we just // use make it a noop by treating it as the default revealOrder. workInProgress.memoizedState = null; } else { switch (revealOrder) { case 'forwards': { var lastContentRow = findLastContentRow(workInProgress.child); var tail; if (lastContentRow === null) { // The whole list is part of the tail. // TODO: We could fast path by just rendering the tail now. tail = workInProgress.child; workInProgress.child = null; } else { // Disconnect the tail rows after the content row. // We're going to render them separately later. tail = lastContentRow.sibling; lastContentRow.sibling = null; } initSuspenseListRenderState(workInProgress, false, // isBackwards tail, lastContentRow, tailMode); break; } case 'backwards': { // We're going to find the first row that has existing content. // At the same time we're going to reverse the list of everything // we pass in the meantime. That's going to be our tail in reverse // order. var _tail = null; var row = workInProgress.child; workInProgress.child = null; while (row !== null) { var currentRow = row.alternate; // New rows can't be content rows. if (currentRow !== null && findFirstSuspended(currentRow) === null) { // This is the beginning of the main content. workInProgress.child = row; break; } var nextRow = row.sibling; row.sibling = _tail; _tail = row; row = nextRow; } // TODO: If workInProgress.child is null, we can continue on the tail immediately. initSuspenseListRenderState(workInProgress, true, // isBackwards _tail, null, // last tailMode); break; } case 'together': { initSuspenseListRenderState(workInProgress, false, // isBackwards null, // tail null, // last undefined); break; } default: { // The default reveal order is the same as not having // a boundary. workInProgress.memoizedState = null; } } } return workInProgress.child; } function updatePortalComponent(current, workInProgress, renderLanes) { pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo); var nextChildren = workInProgress.pendingProps; if (current === null) { // Portals are special because we don't append the children during mount // but at commit. Therefore we need to track insertions which the normal // flow doesn't do during mount. This doesn't happen at the root because // the root always starts with a "current" with a null child. // TODO: Consider unifying this with how the root works. workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderLanes); } else { reconcileChildren(current, workInProgress, nextChildren, renderLanes); } return workInProgress.child; } var hasWarnedAboutUsingNoValuePropOnContextProvider = false; function updateContextProvider(current, workInProgress, renderLanes) { var providerType = workInProgress.type; var context = providerType._context; var newProps = workInProgress.pendingProps; var oldProps = workInProgress.memoizedProps; var newValue = newProps.value; { if (!('value' in newProps)) { if (!hasWarnedAboutUsingNoValuePropOnContextProvider) { hasWarnedAboutUsingNoValuePropOnContextProvider = true; error('The `value` prop is required for the `<Context.Provider>`. Did you misspell it or forget to pass it?'); } } var providerPropTypes = workInProgress.type.propTypes; if (providerPropTypes) { checkPropTypes(providerPropTypes, newProps, 'prop', 'Context.Provider'); } } pushProvider(workInProgress, context, newValue); { if (oldProps !== null) { var oldValue = oldProps.value; if (objectIs(oldValue, newValue)) { // No change. Bailout early if children are the same. if (oldProps.children === newProps.children && !hasContextChanged()) { return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); } } else { // The context value changed. Search for matching consumers and schedule // them to update. propagateContextChange(workInProgress, context, renderLanes); } } } var newChildren = newProps.children; reconcileChildren(current, workInProgress, newChildren, renderLanes); return workInProgress.child; } var hasWarnedAboutUsingContextAsConsumer = false; function updateContextConsumer(current, workInProgress, renderLanes) { var context = workInProgress.type; // The logic below for Context differs depending on PROD or DEV mode. In // DEV mode, we create a separate object for Context.Consumer that acts // like a proxy to Context. This proxy object adds unnecessary code in PROD // so we use the old behaviour (Context.Consumer references Context) to // reduce size and overhead. The separate object references context via // a property called "_context", which also gives us the ability to check // in DEV mode if this property exists or not and warn if it does not. { if (context._context === undefined) { // This may be because it's a Context (rather than a Consumer). // Or it may be because it's older React where they're the same thing. // We only want to warn if we're sure it's a new React. if (context !== context.Consumer) { if (!hasWarnedAboutUsingContextAsConsumer) { hasWarnedAboutUsingContextAsConsumer = true; error('Rendering <Context> directly is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?'); } } } else { context = context._context; } } var newProps = workInProgress.pendingProps; var render = newProps.children; { if (typeof render !== 'function') { error('A context consumer was rendered with multiple children, or a child ' + "that isn't a function. A context consumer expects a single child " + 'that is a function. If you did pass a function, make sure there ' + 'is no trailing or leading whitespace around it.'); } } prepareToReadContext(workInProgress, renderLanes); var newValue = readContext(context); { markComponentRenderStarted(workInProgress); } var newChildren; { ReactCurrentOwner$1.current = workInProgress; setIsRendering(true); newChildren = render(newValue); setIsRendering(false); } { markComponentRenderStopped(); } // React DevTools reads this flag. workInProgress.flags |= PerformedWork; reconcileChildren(current, workInProgress, newChildren, renderLanes); return workInProgress.child; } function markWorkInProgressReceivedUpdate() { didReceiveUpdate = true; } function resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress) { if ((workInProgress.mode & ConcurrentMode) === NoMode) { if (current !== null) { // A lazy component only mounts if it suspended inside a non- // concurrent tree, in an inconsistent state. We want to treat it like // a new mount, even though an empty version of it already committed. // Disconnect the alternate pointers. current.alternate = null; workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect workInProgress.flags |= Placement; } } } function bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes) { if (current !== null) { // Reuse previous dependencies workInProgress.dependencies = current.dependencies; } { // Don't update "base" render times for bailouts. stopProfilerTimerIfRunning(); } markSkippedUpdateLanes(workInProgress.lanes); // Check if the children have any pending work. if (!includesSomeLane(renderLanes, workInProgress.childLanes)) { // The children don't have any work either. We can skip them. // TODO: Once we add back resuming, we should check if the children are // a work-in-progress set. If so, we need to transfer their effects. { return null; } } // This fiber doesn't have work, but its subtree does. Clone the child // fibers and continue. cloneChildFibers(current, workInProgress); return workInProgress.child; } function remountFiber(current, oldWorkInProgress, newWorkInProgress) { { var returnFiber = oldWorkInProgress.return; if (returnFiber === null) { // eslint-disable-next-line react-internal/prod-error-codes throw new Error('Cannot swap the root fiber.'); } // Disconnect from the old current. // It will get deleted. current.alternate = null; oldWorkInProgress.alternate = null; // Connect to the new tree. newWorkInProgress.index = oldWorkInProgress.index; newWorkInProgress.sibling = oldWorkInProgress.sibling; newWorkInProgress.return = oldWorkInProgress.return; newWorkInProgress.ref = oldWorkInProgress.ref; // Replace the child/sibling pointers above it. if (oldWorkInProgress === returnFiber.child) { returnFiber.child = newWorkInProgress; } else { var prevSibling = returnFiber.child; if (prevSibling === null) { // eslint-disable-next-line react-internal/prod-error-codes throw new Error('Expected parent to have a child.'); } while (prevSibling.sibling !== oldWorkInProgress) { prevSibling = prevSibling.sibling; if (prevSibling === null) { // eslint-disable-next-line react-internal/prod-error-codes throw new Error('Expected to find the previous sibling.'); } } prevSibling.sibling = newWorkInProgress; } // Delete the old fiber and place the new one. // Since the old fiber is disconnected, we have to schedule it manually. var deletions = returnFiber.deletions; if (deletions === null) { returnFiber.deletions = [current]; returnFiber.flags |= ChildDeletion; } else { deletions.push(current); } newWorkInProgress.flags |= Placement; // Restart work from the new fiber. return newWorkInProgress; } } function checkScheduledUpdateOrContext(current, renderLanes) { // Before performing an early bailout, we must check if there are pending // updates or context. var updateLanes = current.lanes; if (includesSomeLane(updateLanes, renderLanes)) { return true; } // No pending update, but because context is propagated lazily, we need return false; } function attemptEarlyBailoutIfNoScheduledUpdate(current, workInProgress, renderLanes) { // This fiber does not have any pending work. Bailout without entering // the begin phase. There's still some bookkeeping we that needs to be done // in this optimized path, mostly pushing stuff onto the stack. switch (workInProgress.tag) { case HostRoot: pushHostRootContext(workInProgress); var root = workInProgress.stateNode; resetHydrationState(); break; case HostComponent: pushHostContext(workInProgress); break; case ClassComponent: { var Component = workInProgress.type; if (isContextProvider(Component)) { pushContextProvider(workInProgress); } break; } case HostPortal: pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo); break; case ContextProvider: { var newValue = workInProgress.memoizedProps.value; var context = workInProgress.type._context; pushProvider(workInProgress, context, newValue); break; } case Profiler: { // Profiler should only call onRender when one of its descendants actually rendered. var hasChildWork = includesSomeLane(renderLanes, workInProgress.childLanes); if (hasChildWork) { workInProgress.flags |= Update; } { // Reset effect durations for the next eventual effect phase. // These are reset during render to allow the DevTools commit hook a chance to read them, var stateNode = workInProgress.stateNode; stateNode.effectDuration = 0; stateNode.passiveEffectDuration = 0; } } break; case SuspenseComponent: { var state = workInProgress.memoizedState; if (state !== null) { if (state.dehydrated !== null) { pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); // We know that this component will suspend again because if it has // been unsuspended it has committed as a resolved Suspense component. // If it needs to be retried, it should have work scheduled on it. workInProgress.flags |= DidCapture; // We should never render the children of a dehydrated boundary until we // upgrade it. We return null instead of bailoutOnAlreadyFinishedWork. return null; } // If this boundary is currently timed out, we need to decide // whether to retry the primary children, or to skip over it and // go straight to the fallback. Check the priority of the primary // child fragment. var primaryChildFragment = workInProgress.child; var primaryChildLanes = primaryChildFragment.childLanes; if (includesSomeLane(renderLanes, primaryChildLanes)) { // The primary children have pending work. Use the normal path // to attempt to render the primary children again. return updateSuspenseComponent(current, workInProgress, renderLanes); } else { // The primary child fragment does not have pending work marked // on it pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); // The primary children do not have pending work with sufficient // priority. Bailout. var child = bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); if (child !== null) { // The fallback children have pending work. Skip over the // primary children and work on the fallback. return child.sibling; } else { // Note: We can return `null` here because we already checked // whether there were nested context consumers, via the call to // `bailoutOnAlreadyFinishedWork` above. return null; } } } else { pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); } break; } case SuspenseListComponent: { var didSuspendBefore = (current.flags & DidCapture) !== NoFlags; var _hasChildWork = includesSomeLane(renderLanes, workInProgress.childLanes); if (didSuspendBefore) { if (_hasChildWork) { // If something was in fallback state last time, and we have all the // same children then we're still in progressive loading state. // Something might get unblocked by state updates or retries in the // tree which will affect the tail. So we need to use the normal // path to compute the correct tail. return updateSuspenseListComponent(current, workInProgress, renderLanes); } // If none of the children had any work, that means that none of // them got retried so they'll still be blocked in the same way // as before. We can fast bail out. workInProgress.flags |= DidCapture; } // If nothing suspended before and we're rendering the same children, // then the tail doesn't matter. Anything new that suspends will work // in the "together" mode, so we can continue from the state we had. var renderState = workInProgress.memoizedState; if (renderState !== null) { // Reset to the "together" mode in case we've started a different // update in the past but didn't complete it. renderState.rendering = null; renderState.tail = null; renderState.lastEffect = null; } pushSuspenseContext(workInProgress, suspenseStackCursor.current); if (_hasChildWork) { break; } else { // If none of the children had any work, that means that none of // them got retried so they'll still be blocked in the same way // as before. We can fast bail out. return null; } } case OffscreenComponent: case LegacyHiddenComponent: { // Need to check if the tree still needs to be deferred. This is // almost identical to the logic used in the normal update path, // so we'll just enter that. The only difference is we'll bail out // at the next level instead of this one, because the child props // have not changed. Which is fine. // TODO: Probably should refactor `beginWork` to split the bailout // path from the normal path. I'm tempted to do a labeled break here // but I won't :) workInProgress.lanes = NoLanes; return updateOffscreenComponent(current, workInProgress, renderLanes); } } return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); } function beginWork(current, workInProgress, renderLanes) { { if (workInProgress._debugNeedsRemount && current !== null) { // This will restart the begin phase with a new fiber. return remountFiber(current, workInProgress, createFiberFromTypeAndProps(workInProgress.type, workInProgress.key, workInProgress.pendingProps, workInProgress._debugOwner || null, workInProgress.mode, workInProgress.lanes)); } } if (current !== null) { var oldProps = current.memoizedProps; var newProps = workInProgress.pendingProps; if (oldProps !== newProps || hasContextChanged() || ( // Force a re-render if the implementation changed due to hot reload: workInProgress.type !== current.type )) { // If props or context changed, mark the fiber as having performed work. // This may be unset if the props are determined to be equal later (memo). didReceiveUpdate = true; } else { // Neither props nor legacy context changes. Check if there's a pending // update or context change. var hasScheduledUpdateOrContext = checkScheduledUpdateOrContext(current, renderLanes); if (!hasScheduledUpdateOrContext && // If this is the second pass of an error or suspense boundary, there // may not be work scheduled on `current`, so we check for this flag. (workInProgress.flags & DidCapture) === NoFlags) { // No pending updates or context. Bail out now. didReceiveUpdate = false; return attemptEarlyBailoutIfNoScheduledUpdate(current, workInProgress, renderLanes); } if ((current.flags & ForceUpdateForLegacySuspense) !== NoFlags) { // This is a special case that only exists for legacy mode. // See https://github.com/facebook/react/pull/19216. didReceiveUpdate = true; } else { // An update was scheduled on this fiber, but there are no new props // nor legacy context. Set this to false. If an update queue or context // consumer produces a changed value, it will set this to true. Otherwise, // the component will assume the children have not changed and bail out. didReceiveUpdate = false; } } } else { didReceiveUpdate = false; if (getIsHydrating() && isForkedChild(workInProgress)) { // Check if this child belongs to a list of muliple children in // its parent. // // In a true multi-threaded implementation, we would render children on // parallel threads. This would represent the beginning of a new render // thread for this subtree. // // We only use this for id generation during hydration, which is why the // logic is located in this special branch. var slotIndex = workInProgress.index; var numberOfForks = getForksAtLevel(); pushTreeId(workInProgress, numberOfForks, slotIndex); } } // Before entering the begin phase, clear pending update priority. // TODO: This assumes that we're about to evaluate the component and process // the update queue. However, there's an exception: SimpleMemoComponent // sometimes bails out later in the begin phase. This indicates that we should // move this assignment out of the common path and into each branch. workInProgress.lanes = NoLanes; switch (workInProgress.tag) { case IndeterminateComponent: { return mountIndeterminateComponent(current, workInProgress, workInProgress.type, renderLanes); } case LazyComponent: { var elementType = workInProgress.elementType; return mountLazyComponent(current, workInProgress, elementType, renderLanes); } case FunctionComponent: { var Component = workInProgress.type; var unresolvedProps = workInProgress.pendingProps; var resolvedProps = workInProgress.elementType === Component ? unresolvedProps : resolveDefaultProps(Component, unresolvedProps); return updateFunctionComponent(current, workInProgress, Component, resolvedProps, renderLanes); } case ClassComponent: { var _Component = workInProgress.type; var _unresolvedProps = workInProgress.pendingProps; var _resolvedProps = workInProgress.elementType === _Component ? _unresolvedProps : resolveDefaultProps(_Component, _unresolvedProps); return updateClassComponent(current, workInProgress, _Component, _resolvedProps, renderLanes); } case HostRoot: return updateHostRoot(current, workInProgress, renderLanes); case HostComponent: return updateHostComponent(current, workInProgress, renderLanes); case HostText: return updateHostText(current, workInProgress); case SuspenseComponent: return updateSuspenseComponent(current, workInProgress, renderLanes); case HostPortal: return updatePortalComponent(current, workInProgress, renderLanes); case ForwardRef: { var type = workInProgress.type; var _unresolvedProps2 = workInProgress.pendingProps; var _resolvedProps2 = workInProgress.elementType === type ? _unresolvedProps2 : resolveDefaultProps(type, _unresolvedProps2); return updateForwardRef(current, workInProgress, type, _resolvedProps2, renderLanes); } case Fragment: return updateFragment(current, workInProgress, renderLanes); case Mode: return updateMode(current, workInProgress, renderLanes); case Profiler: return updateProfiler(current, workInProgress, renderLanes); case ContextProvider: return updateContextProvider(current, workInProgress, renderLanes); case ContextConsumer: return updateContextConsumer(current, workInProgress, renderLanes); case MemoComponent: { var _type2 = workInProgress.type; var _unresolvedProps3 = workInProgress.pendingProps; // Resolve outer props first, then resolve inner props. var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3); { if (workInProgress.type !== workInProgress.elementType) { var outerPropTypes = _type2.propTypes; if (outerPropTypes) { checkPropTypes(outerPropTypes, _resolvedProps3, // Resolved for outer only 'prop', getComponentNameFromType(_type2)); } } } _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3); return updateMemoComponent(current, workInProgress, _type2, _resolvedProps3, renderLanes); } case SimpleMemoComponent: { return updateSimpleMemoComponent(current, workInProgress, workInProgress.type, workInProgress.pendingProps, renderLanes); } case IncompleteClassComponent: { var _Component2 = workInProgress.type; var _unresolvedProps4 = workInProgress.pendingProps; var _resolvedProps4 = workInProgress.elementType === _Component2 ? _unresolvedProps4 : resolveDefaultProps(_Component2, _unresolvedProps4); return mountIncompleteClassComponent(current, workInProgress, _Component2, _resolvedProps4, renderLanes); } case SuspenseListComponent: { return updateSuspenseListComponent(current, workInProgress, renderLanes); } case ScopeComponent: { break; } case OffscreenComponent: { return updateOffscreenComponent(current, workInProgress, renderLanes); } } throw new Error("Unknown unit of work tag (" + workInProgress.tag + "). This error is likely caused by a bug in " + 'React. Please file an issue.'); } function markUpdate(workInProgress) { // Tag the fiber with an update effect. This turns a Placement into // a PlacementAndUpdate. workInProgress.flags |= Update; } function markRef$1(workInProgress) { workInProgress.flags |= Ref; { workInProgress.flags |= RefStatic; } } var appendAllChildren; var updateHostContainer; var updateHostComponent$1; var updateHostText$1; { // Mutation mode appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) { // We only have the top Fiber that was created but we need recurse down its // children to find all the terminal nodes. var node = workInProgress.child; while (node !== null) { if (node.tag === HostComponent || node.tag === HostText) { appendInitialChild(parent, node.stateNode); } else if (node.tag === HostPortal) ; else if (node.child !== null) { node.child.return = node; node = node.child; continue; } if (node === workInProgress) { return; } while (node.sibling === null) { if (node.return === null || node.return === workInProgress) { return; } node = node.return; } node.sibling.return = node.return; node = node.sibling; } }; updateHostContainer = function (current, workInProgress) {// Noop }; updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) { // If we have an alternate, that means this is an update and we need to // schedule a side-effect to do the updates. var oldProps = current.memoizedProps; if (oldProps === newProps) { // In mutation mode, this is sufficient for a bailout because // we won't touch this node even if children changed. return; } // If we get updated because one of our children updated, we don't // have newProps so we'll have to reuse them. // TODO: Split the update API as separate for the props vs. children. // Even better would be if children weren't special cased at all tho. var instance = workInProgress.stateNode; var currentHostContext = getHostContext(); // TODO: Experiencing an error where oldProps is null. Suggests a host // component is hitting the resume path. Figure out why. Possibly // related to `hidden`. var updatePayload = prepareUpdate(instance, type, oldProps, newProps, rootContainerInstance, currentHostContext); // TODO: Type this specific to this type of component. workInProgress.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there // is a new ref we mark this as an update. All the work is done in commitWork. if (updatePayload) { markUpdate(workInProgress); } }; updateHostText$1 = function (current, workInProgress, oldText, newText) { // If the text differs, mark it as an update. All the work in done in commitWork. if (oldText !== newText) { markUpdate(workInProgress); } }; } function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) { if (getIsHydrating()) { // If we're hydrating, we should consume as many items as we can // so we don't leave any behind. return; } switch (renderState.tailMode) { case 'hidden': { // Any insertions at the end of the tail list after this point // should be invisible. If there are already mounted boundaries // anything before them are not considered for collapsing. // Therefore we need to go through the whole tail to find if // there are any. var tailNode = renderState.tail; var lastTailNode = null; while (tailNode !== null) { if (tailNode.alternate !== null) { lastTailNode = tailNode; } tailNode = tailNode.sibling; } // Next we're simply going to delete all insertions after the // last rendered item. if (lastTailNode === null) { // All remaining items in the tail are insertions. renderState.tail = null; } else { // Detach the insertion after the last node that was already // inserted. lastTailNode.sibling = null; } break; } case 'collapsed': { // Any insertions at the end of the tail list after this point // should be invisible. If there are already mounted boundaries // anything before them are not considered for collapsing. // Therefore we need to go through the whole tail to find if // there are any. var _tailNode = renderState.tail; var _lastTailNode = null; while (_tailNode !== null) { if (_tailNode.alternate !== null) { _lastTailNode = _tailNode; } _tailNode = _tailNode.sibling; } // Next we're simply going to delete all insertions after the // last rendered item. if (_lastTailNode === null) { // All remaining items in the tail are insertions. if (!hasRenderedATailFallback && renderState.tail !== null) { // We suspended during the head. We want to show at least one // row at the tail. So we'll keep on and cut off the rest. renderState.tail.sibling = null; } else { renderState.tail = null; } } else { // Detach the insertion after the last node that was already // inserted. _lastTailNode.sibling = null; } break; } } } function bubbleProperties(completedWork) { var didBailout = completedWork.alternate !== null && completedWork.alternate.child === completedWork.child; var newChildLanes = NoLanes; var subtreeFlags = NoFlags; if (!didBailout) { // Bubble up the earliest expiration time. if ( (completedWork.mode & ProfileMode) !== NoMode) { // In profiling mode, resetChildExpirationTime is also used to reset // profiler durations. var actualDuration = completedWork.actualDuration; var treeBaseDuration = completedWork.selfBaseDuration; var child = completedWork.child; while (child !== null) { newChildLanes = mergeLanes(newChildLanes, mergeLanes(child.lanes, child.childLanes)); subtreeFlags |= child.subtreeFlags; subtreeFlags |= child.flags; // When a fiber is cloned, its actualDuration is reset to 0. This value will // only be updated if work is done on the fiber (i.e. it doesn't bailout). // When work is done, it should bubble to the parent's actualDuration. If // the fiber has not been cloned though, (meaning no work was done), then // this value will reflect the amount of time spent working on a previous // render. In that case it should not bubble. We determine whether it was // cloned by comparing the child pointer. actualDuration += child.actualDuration; treeBaseDuration += child.treeBaseDuration; child = child.sibling; } completedWork.actualDuration = actualDuration; completedWork.treeBaseDuration = treeBaseDuration; } else { var _child = completedWork.child; while (_child !== null) { newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child.lanes, _child.childLanes)); subtreeFlags |= _child.subtreeFlags; subtreeFlags |= _child.flags; // Update the return pointer so the tree is consistent. This is a code // smell because it assumes the commit phase is never concurrent with // the render phase. Will address during refactor to alternate model. _child.return = completedWork; _child = _child.sibling; } } completedWork.subtreeFlags |= subtreeFlags; } else { // Bubble up the earliest expiration time. if ( (completedWork.mode & ProfileMode) !== NoMode) { // In profiling mode, resetChildExpirationTime is also used to reset // profiler durations. var _treeBaseDuration = completedWork.selfBaseDuration; var _child2 = completedWork.child; while (_child2 !== null) { newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child2.lanes, _child2.childLanes)); // "Static" flags share the lifetime of the fiber/hook they belong to, // so we should bubble those up even during a bailout. All the other // flags have a lifetime only of a single render + commit, so we should // ignore them. subtreeFlags |= _child2.subtreeFlags & StaticMask; subtreeFlags |= _child2.flags & StaticMask; _treeBaseDuration += _child2.treeBaseDuration; _child2 = _child2.sibling; } completedWork.treeBaseDuration = _treeBaseDuration; } else { var _child3 = completedWork.child; while (_child3 !== null) { newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child3.lanes, _child3.childLanes)); // "Static" flags share the lifetime of the fiber/hook they belong to, // so we should bubble those up even during a bailout. All the other // flags have a lifetime only of a single render + commit, so we should // ignore them. subtreeFlags |= _child3.subtreeFlags & StaticMask; subtreeFlags |= _child3.flags & StaticMask; // Update the return pointer so the tree is consistent. This is a code // smell because it assumes the commit phase is never concurrent with // the render phase. Will address during refactor to alternate model. _child3.return = completedWork; _child3 = _child3.sibling; } } completedWork.subtreeFlags |= subtreeFlags; } completedWork.childLanes = newChildLanes; return didBailout; } function completeDehydratedSuspenseBoundary(current, workInProgress, nextState) { if (hasUnhydratedTailNodes() && (workInProgress.mode & ConcurrentMode) !== NoMode && (workInProgress.flags & DidCapture) === NoFlags) { warnIfUnhydratedTailNodes(workInProgress); resetHydrationState(); workInProgress.flags |= ForceClientRender | Incomplete | ShouldCapture; return false; } var wasHydrated = popHydrationState(workInProgress); if (nextState !== null && nextState.dehydrated !== null) { // We might be inside a hydration state the first time we're picking up this // Suspense boundary, and also after we've reentered it for further hydration. if (current === null) { if (!wasHydrated) { throw new Error('A dehydrated suspense component was completed without a hydrated node. ' + 'This is probably a bug in React.'); } prepareToHydrateHostSuspenseInstance(workInProgress); bubbleProperties(workInProgress); { if ((workInProgress.mode & ProfileMode) !== NoMode) { var isTimedOutSuspense = nextState !== null; if (isTimedOutSuspense) { // Don't count time spent in a timed out Suspense subtree as part of the base duration. var primaryChildFragment = workInProgress.child; if (primaryChildFragment !== null) { // $FlowFixMe Flow doesn't support type casting in combination with the -= operator workInProgress.treeBaseDuration -= primaryChildFragment.treeBaseDuration; } } } } return false; } else { // We might have reentered this boundary to hydrate it. If so, we need to reset the hydration // state since we're now exiting out of it. popHydrationState doesn't do that for us. resetHydrationState(); if ((workInProgress.flags & DidCapture) === NoFlags) { // This boundary did not suspend so it's now hydrated and unsuspended. workInProgress.memoizedState = null; } // If nothing suspended, we need to schedule an effect to mark this boundary // as having hydrated so events know that they're free to be invoked. // It's also a signal to replay events and the suspense callback. // If something suspended, schedule an effect to attach retry listeners. // So we might as well always mark this. workInProgress.flags |= Update; bubbleProperties(workInProgress); { if ((workInProgress.mode & ProfileMode) !== NoMode) { var _isTimedOutSuspense = nextState !== null; if (_isTimedOutSuspense) { // Don't count time spent in a timed out Suspense subtree as part of the base duration. var _primaryChildFragment = workInProgress.child; if (_primaryChildFragment !== null) { // $FlowFixMe Flow doesn't support type casting in combination with the -= operator workInProgress.treeBaseDuration -= _primaryChildFragment.treeBaseDuration; } } } } return false; } } else { // Successfully completed this tree. If this was a forced client render, // there may have been recoverable errors during first hydration // attempt. If so, add them to a queue so we can log them in the // commit phase. upgradeHydrationErrorsToRecoverable(); // Fall through to normal Suspense path return true; } } function completeWork(current, workInProgress, renderLanes) { var newProps = workInProgress.pendingProps; // Note: This intentionally doesn't check if we're hydrating because comparing // to the current tree provider fiber is just as fast and less error-prone. // Ideally we would have a special version of the work loop only // for hydration. popTreeContext(workInProgress); switch (workInProgress.tag) { case IndeterminateComponent: case LazyComponent: case SimpleMemoComponent: case FunctionComponent: case ForwardRef: case Fragment: case Mode: case Profiler: case ContextConsumer: case MemoComponent: bubbleProperties(workInProgress); return null; case ClassComponent: { var Component = workInProgress.type; if (isContextProvider(Component)) { popContext(workInProgress); } bubbleProperties(workInProgress); return null; } case HostRoot: { var fiberRoot = workInProgress.stateNode; popHostContainer(workInProgress); popTopLevelContextObject(workInProgress); resetWorkInProgressVersions(); if (fiberRoot.pendingContext) { fiberRoot.context = fiberRoot.pendingContext; fiberRoot.pendingContext = null; } if (current === null || current.child === null) { // If we hydrated, pop so that we can delete any remaining children // that weren't hydrated. var wasHydrated = popHydrationState(workInProgress); if (wasHydrated) { // If we hydrated, then we'll need to schedule an update for // the commit side-effects on the root. markUpdate(workInProgress); } else { if (current !== null) { var prevState = current.memoizedState; if ( // Check if this is a client root !prevState.isDehydrated || // Check if we reverted to client rendering (e.g. due to an error) (workInProgress.flags & ForceClientRender) !== NoFlags) { // Schedule an effect to clear this container at the start of the // next commit. This handles the case of React rendering into a // container with previous children. It's also safe to do for // updates too, because current.child would only be null if the // previous render was null (so the container would already // be empty). workInProgress.flags |= Snapshot; // If this was a forced client render, there may have been // recoverable errors during first hydration attempt. If so, add // them to a queue so we can log them in the commit phase. upgradeHydrationErrorsToRecoverable(); } } } } updateHostContainer(current, workInProgress); bubbleProperties(workInProgress); return null; } case HostComponent: { popHostContext(workInProgress); var rootContainerInstance = getRootHostContainer(); var type = workInProgress.type; if (current !== null && workInProgress.stateNode != null) { updateHostComponent$1(current, workInProgress, type, newProps, rootContainerInstance); if (current.ref !== workInProgress.ref) { markRef$1(workInProgress); } } else { if (!newProps) { if (workInProgress.stateNode === null) { throw new Error('We must have new props for new mounts. This error is likely ' + 'caused by a bug in React. Please file an issue.'); } // This can happen when we abort work. bubbleProperties(workInProgress); return null; } var currentHostContext = getHostContext(); // TODO: Move createInstance to beginWork and keep it on a context // "stack" as the parent. Then append children as we go in beginWork // or completeWork depending on whether we want to add them top->down or // bottom->up. Top->down is faster in IE11. var _wasHydrated = popHydrationState(workInProgress); if (_wasHydrated) { // TODO: Move this and createInstance step into the beginPhase // to consolidate. if (prepareToHydrateHostInstance(workInProgress, rootContainerInstance, currentHostContext)) { // If changes to the hydrated node need to be applied at the // commit-phase we mark this as such. markUpdate(workInProgress); } } else { var instance = createInstance(type, newProps, rootContainerInstance, currentHostContext, workInProgress); appendAllChildren(instance, workInProgress, false, false); workInProgress.stateNode = instance; // Certain renderers require commit-time effects for initial mount. // (eg DOM renderer supports auto-focus for certain elements). // Make sure such renderers get scheduled for later work. if (finalizeInitialChildren(instance, type, newProps, rootContainerInstance)) { markUpdate(workInProgress); } } if (workInProgress.ref !== null) { // If there is a ref on a host node we need to schedule a callback markRef$1(workInProgress); } } bubbleProperties(workInProgress); return null; } case HostText: { var newText = newProps; if (current && workInProgress.stateNode != null) { var oldText = current.memoizedProps; // If we have an alternate, that means this is an update and we need // to schedule a side-effect to do the updates. updateHostText$1(current, workInProgress, oldText, newText); } else { if (typeof newText !== 'string') { if (workInProgress.stateNode === null) { throw new Error('We must have new props for new mounts. This error is likely ' + 'caused by a bug in React. Please file an issue.'); } // This can happen when we abort work. } var _rootContainerInstance = getRootHostContainer(); var _currentHostContext = getHostContext(); var _wasHydrated2 = popHydrationState(workInProgress); if (_wasHydrated2) { if (prepareToHydrateHostTextInstance(workInProgress)) { markUpdate(workInProgress); } } else { workInProgress.stateNode = createTextInstance(newText, _rootContainerInstance, _currentHostContext, workInProgress); } } bubbleProperties(workInProgress); return null; } case SuspenseComponent: { popSuspenseContext(workInProgress); var nextState = workInProgress.memoizedState; // Special path for dehydrated boundaries. We may eventually move this // to its own fiber type so that we can add other kinds of hydration // boundaries that aren't associated with a Suspense tree. In anticipation // of such a refactor, all the hydration logic is contained in // this branch. if (current === null || current.memoizedState !== null && current.memoizedState.dehydrated !== null) { var fallthroughToNormalSuspensePath = completeDehydratedSuspenseBoundary(current, workInProgress, nextState); if (!fallthroughToNormalSuspensePath) { if (workInProgress.flags & ShouldCapture) { // Special case. There were remaining unhydrated nodes. We treat // this as a mismatch. Revert to client rendering. return workInProgress; } else { // Did not finish hydrating, either because this is the initial // render or because something suspended. return null; } } // Continue with the normal Suspense path. } if ((workInProgress.flags & DidCapture) !== NoFlags) { // Something suspended. Re-render with the fallback children. workInProgress.lanes = renderLanes; // Do not reset the effect list. if ( (workInProgress.mode & ProfileMode) !== NoMode) { transferActualDuration(workInProgress); } // Don't bubble properties in this case. return workInProgress; } var nextDidTimeout = nextState !== null; var prevDidTimeout = current !== null && current.memoizedState !== null; // a passive effect, which is when we process the transitions if (nextDidTimeout !== prevDidTimeout) { // an effect to toggle the subtree's visibility. When we switch from // fallback -> primary, the inner Offscreen fiber schedules this effect // as part of its normal complete phase. But when we switch from // primary -> fallback, the inner Offscreen fiber does not have a complete // phase. So we need to schedule its effect here. // // We also use this flag to connect/disconnect the effects, but the same // logic applies: when re-connecting, the Offscreen fiber's complete // phase will handle scheduling the effect. It's only when the fallback // is active that we have to do anything special. if (nextDidTimeout) { var _offscreenFiber2 = workInProgress.child; _offscreenFiber2.flags |= Visibility; // TODO: This will still suspend a synchronous tree if anything // in the concurrent tree already suspended during this render. // This is a known bug. if ((workInProgress.mode & ConcurrentMode) !== NoMode) { // TODO: Move this back to throwException because this is too late // if this is a large tree which is common for initial loads. We // don't know if we should restart a render or not until we get // this marker, and this is too late. // If this render already had a ping or lower pri updates, // and this is the first time we know we're going to suspend we // should be able to immediately restart from within throwException. var hasInvisibleChildContext = current === null && (workInProgress.memoizedProps.unstable_avoidThisFallback !== true || !enableSuspenseAvoidThisFallback); if (hasInvisibleChildContext || hasSuspenseContext(suspenseStackCursor.current, InvisibleParentSuspenseContext)) { // If this was in an invisible tree or a new render, then showing // this boundary is ok. renderDidSuspend(); } else { // Otherwise, we're going to have to hide content so we should // suspend for longer if possible. renderDidSuspendDelayIfPossible(); } } } } var wakeables = workInProgress.updateQueue; if (wakeables !== null) { // Schedule an effect to attach a retry listener to the promise. // TODO: Move to passive phase workInProgress.flags |= Update; } bubbleProperties(workInProgress); { if ((workInProgress.mode & ProfileMode) !== NoMode) { if (nextDidTimeout) { // Don't count time spent in a timed out Suspense subtree as part of the base duration. var primaryChildFragment = workInProgress.child; if (primaryChildFragment !== null) { // $FlowFixMe Flow doesn't support type casting in combination with the -= operator workInProgress.treeBaseDuration -= primaryChildFragment.treeBaseDuration; } } } } return null; } case HostPortal: popHostContainer(workInProgress); updateHostContainer(current, workInProgress); if (current === null) { preparePortalMount(workInProgress.stateNode.containerInfo); } bubbleProperties(workInProgress); return null; case ContextProvider: // Pop provider fiber var context = workInProgress.type._context; popProvider(context, workInProgress); bubbleProperties(workInProgress); return null; case IncompleteClassComponent: { // Same as class component case. I put it down here so that the tags are // sequential to ensure this switch is compiled to a jump table. var _Component = workInProgress.type; if (isContextProvider(_Component)) { popContext(workInProgress); } bubbleProperties(workInProgress); return null; } case SuspenseListComponent: { popSuspenseContext(workInProgress); var renderState = workInProgress.memoizedState; if (renderState === null) { // We're running in the default, "independent" mode. // We don't do anything in this mode. bubbleProperties(workInProgress); return null; } var didSuspendAlready = (workInProgress.flags & DidCapture) !== NoFlags; var renderedTail = renderState.rendering; if (renderedTail === null) { // We just rendered the head. if (!didSuspendAlready) { // This is the first pass. We need to figure out if anything is still // suspended in the rendered set. // If new content unsuspended, but there's still some content that // didn't. Then we need to do a second pass that forces everything // to keep showing their fallbacks. // We might be suspended if something in this render pass suspended, or // something in the previous committed pass suspended. Otherwise, // there's no chance so we can skip the expensive call to // findFirstSuspended. var cannotBeSuspended = renderHasNotSuspendedYet() && (current === null || (current.flags & DidCapture) === NoFlags); if (!cannotBeSuspended) { var row = workInProgress.child; while (row !== null) { var suspended = findFirstSuspended(row); if (suspended !== null) { didSuspendAlready = true; workInProgress.flags |= DidCapture; cutOffTailIfNeeded(renderState, false); // If this is a newly suspended tree, it might not get committed as // part of the second pass. In that case nothing will subscribe to // its thenables. Instead, we'll transfer its thenables to the // SuspenseList so that it can retry if they resolve. // There might be multiple of these in the list but since we're // going to wait for all of them anyway, it doesn't really matter // which ones gets to ping. In theory we could get clever and keep // track of how many dependencies remain but it gets tricky because // in the meantime, we can add/remove/change items and dependencies. // We might bail out of the loop before finding any but that // doesn't matter since that means that the other boundaries that // we did find already has their listeners attached. var newThenables = suspended.updateQueue; if (newThenables !== null) { workInProgress.updateQueue = newThenables; workInProgress.flags |= Update; } // Rerender the whole list, but this time, we'll force fallbacks // to stay in place. // Reset the effect flags before doing the second pass since that's now invalid. // Reset the child fibers to their original state. workInProgress.subtreeFlags = NoFlags; resetChildFibers(workInProgress, renderLanes); // Set up the Suspense Context to force suspense and immediately // rerender the children. pushSuspenseContext(workInProgress, setShallowSuspenseContext(suspenseStackCursor.current, ForceSuspenseFallback)); // Don't bubble properties in this case. return workInProgress.child; } row = row.sibling; } } if (renderState.tail !== null && now() > getRenderTargetTime()) { // We have already passed our CPU deadline but we still have rows // left in the tail. We'll just give up further attempts to render // the main content and only render fallbacks. workInProgress.flags |= DidCapture; didSuspendAlready = true; cutOffTailIfNeeded(renderState, false); // Since nothing actually suspended, there will nothing to ping this // to get it started back up to attempt the next item. While in terms // of priority this work has the same priority as this current render, // it's not part of the same transition once the transition has // committed. If it's sync, we still want to yield so that it can be // painted. Conceptually, this is really the same as pinging. // We can use any RetryLane even if it's the one currently rendering // since we're leaving it behind on this node. workInProgress.lanes = SomeRetryLane; } } else { cutOffTailIfNeeded(renderState, false); } // Next we're going to render the tail. } else { // Append the rendered row to the child list. if (!didSuspendAlready) { var _suspended = findFirstSuspended(renderedTail); if (_suspended !== null) { workInProgress.flags |= DidCapture; didSuspendAlready = true; // Ensure we transfer the update queue to the parent so that it doesn't // get lost if this row ends up dropped during a second pass. var _newThenables = _suspended.updateQueue; if (_newThenables !== null) { workInProgress.updateQueue = _newThenables; workInProgress.flags |= Update; } cutOffTailIfNeeded(renderState, true); // This might have been modified. if (renderState.tail === null && renderState.tailMode === 'hidden' && !renderedTail.alternate && !getIsHydrating() // We don't cut it if we're hydrating. ) { // We're done. bubbleProperties(workInProgress); return null; } } else if ( // The time it took to render last row is greater than the remaining // time we have to render. So rendering one more row would likely // exceed it. now() * 2 - renderState.renderingStartTime > getRenderTargetTime() && renderLanes !== OffscreenLane) { // We have now passed our CPU deadline and we'll just give up further // attempts to render the main content and only render fallbacks. // The assumption is that this is usually faster. workInProgress.flags |= DidCapture; didSuspendAlready = true; cutOffTailIfNeeded(renderState, false); // Since nothing actually suspended, there will nothing to ping this // to get it started back up to attempt the next item. While in terms // of priority this work has the same priority as this current render, // it's not part of the same transition once the transition has // committed. If it's sync, we still want to yield so that it can be // painted. Conceptually, this is really the same as pinging. // We can use any RetryLane even if it's the one currently rendering // since we're leaving it behind on this node. workInProgress.lanes = SomeRetryLane; } } if (renderState.isBackwards) { // The effect list of the backwards tail will have been added // to the end. This breaks the guarantee that life-cycles fire in // sibling order but that isn't a strong guarantee promised by React. // Especially since these might also just pop in during future commits. // Append to the beginning of the list. renderedTail.sibling = workInProgress.child; workInProgress.child = renderedTail; } else { var previousSibling = renderState.last; if (previousSibling !== null) { previousSibling.sibling = renderedTail; } else { workInProgress.child = renderedTail; } renderState.last = renderedTail; } } if (renderState.tail !== null) { // We still have tail rows to render. // Pop a row. var next = renderState.tail; renderState.rendering = next; renderState.tail = next.sibling; renderState.renderingStartTime = now(); next.sibling = null; // Restore the context. // TODO: We can probably just avoid popping it instead and only // setting it the first time we go from not suspended to suspended. var suspenseContext = suspenseStackCursor.current; if (didSuspendAlready) { suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback); } else { suspenseContext = setDefaultShallowSuspenseContext(suspenseContext); } pushSuspenseContext(workInProgress, suspenseContext); // Do a pass over the next row. // Don't bubble properties in this case. return next; } bubbleProperties(workInProgress); return null; } case ScopeComponent: { break; } case OffscreenComponent: case LegacyHiddenComponent: { popRenderLanes(workInProgress); var _nextState = workInProgress.memoizedState; var nextIsHidden = _nextState !== null; if (current !== null) { var _prevState = current.memoizedState; var prevIsHidden = _prevState !== null; if (prevIsHidden !== nextIsHidden && ( // LegacyHidden doesn't do any hiding — it only pre-renders. !enableLegacyHidden )) { workInProgress.flags |= Visibility; } } if (!nextIsHidden || (workInProgress.mode & ConcurrentMode) === NoMode) { bubbleProperties(workInProgress); } else { // Don't bubble properties for hidden children unless we're rendering // at offscreen priority. if (includesSomeLane(subtreeRenderLanes, OffscreenLane)) { bubbleProperties(workInProgress); { // Check if there was an insertion or update in the hidden subtree. // If so, we need to hide those nodes in the commit phase, so // schedule a visibility effect. if ( workInProgress.subtreeFlags & (Placement | Update)) { workInProgress.flags |= Visibility; } } } } return null; } case CacheComponent: { return null; } case TracingMarkerComponent: { return null; } } throw new Error("Unknown unit of work tag (" + workInProgress.tag + "). This error is likely caused by a bug in " + 'React. Please file an issue.'); } function unwindWork(current, workInProgress, renderLanes) { // Note: This intentionally doesn't check if we're hydrating because comparing // to the current tree provider fiber is just as fast and less error-prone. // Ideally we would have a special version of the work loop only // for hydration. popTreeContext(workInProgress); switch (workInProgress.tag) { case ClassComponent: { var Component = workInProgress.type; if (isContextProvider(Component)) { popContext(workInProgress); } var flags = workInProgress.flags; if (flags & ShouldCapture) { workInProgress.flags = flags & ~ShouldCapture | DidCapture; if ( (workInProgress.mode & ProfileMode) !== NoMode) { transferActualDuration(workInProgress); } return workInProgress; } return null; } case HostRoot: { var root = workInProgress.stateNode; popHostContainer(workInProgress); popTopLevelContextObject(workInProgress); resetWorkInProgressVersions(); var _flags = workInProgress.flags; if ((_flags & ShouldCapture) !== NoFlags && (_flags & DidCapture) === NoFlags) { // There was an error during render that wasn't captured by a suspense // boundary. Do a second pass on the root to unmount the children. workInProgress.flags = _flags & ~ShouldCapture | DidCapture; return workInProgress; } // We unwound to the root without completing it. Exit. return null; } case HostComponent: { // TODO: popHydrationState popHostContext(workInProgress); return null; } case SuspenseComponent: { popSuspenseContext(workInProgress); var suspenseState = workInProgress.memoizedState; if (suspenseState !== null && suspenseState.dehydrated !== null) { if (workInProgress.alternate === null) { throw new Error('Threw in newly mounted dehydrated component. This is likely a bug in ' + 'React. Please file an issue.'); } resetHydrationState(); } var _flags2 = workInProgress.flags; if (_flags2 & ShouldCapture) { workInProgress.flags = _flags2 & ~ShouldCapture | DidCapture; // Captured a suspense effect. Re-render the boundary. if ( (workInProgress.mode & ProfileMode) !== NoMode) { transferActualDuration(workInProgress); } return workInProgress; } return null; } case SuspenseListComponent: { popSuspenseContext(workInProgress); // SuspenseList doesn't actually catch anything. It should've been // caught by a nested boundary. If not, it should bubble through. return null; } case HostPortal: popHostContainer(workInProgress); return null; case ContextProvider: var context = workInProgress.type._context; popProvider(context, workInProgress); return null; case OffscreenComponent: case LegacyHiddenComponent: popRenderLanes(workInProgress); return null; case CacheComponent: return null; default: return null; } } function unwindInterruptedWork(current, interruptedWork, renderLanes) { // Note: This intentionally doesn't check if we're hydrating because comparing // to the current tree provider fiber is just as fast and less error-prone. // Ideally we would have a special version of the work loop only // for hydration. popTreeContext(interruptedWork); switch (interruptedWork.tag) { case ClassComponent: { var childContextTypes = interruptedWork.type.childContextTypes; if (childContextTypes !== null && childContextTypes !== undefined) { popContext(interruptedWork); } break; } case HostRoot: { var root = interruptedWork.stateNode; popHostContainer(interruptedWork); popTopLevelContextObject(interruptedWork); resetWorkInProgressVersions(); break; } case HostComponent: { popHostContext(interruptedWork); break; } case HostPortal: popHostContainer(interruptedWork); break; case SuspenseComponent: popSuspenseContext(interruptedWork); break; case SuspenseListComponent: popSuspenseContext(interruptedWork); break; case ContextProvider: var context = interruptedWork.type._context; popProvider(context, interruptedWork); break; case OffscreenComponent: case LegacyHiddenComponent: popRenderLanes(interruptedWork); break; } } var didWarnAboutUndefinedSnapshotBeforeUpdate = null; { didWarnAboutUndefinedSnapshotBeforeUpdate = new Set(); } // Used during the commit phase to track the state of the Offscreen component stack. // Allows us to avoid traversing the return path to find the nearest Offscreen ancestor. // Only used when enableSuspenseLayoutEffectSemantics is enabled. var offscreenSubtreeIsHidden = false; var offscreenSubtreeWasHidden = false; var PossiblyWeakSet = typeof WeakSet === 'function' ? WeakSet : Set; var nextEffect = null; // Used for Profiling builds to track updaters. var inProgressLanes = null; var inProgressRoot = null; function reportUncaughtErrorInDEV(error) { // Wrapping each small part of the commit phase into a guarded // callback is a bit too slow (https://github.com/facebook/react/pull/21666). // But we rely on it to surface errors to DEV tools like overlays // (https://github.com/facebook/react/issues/21712). // As a compromise, rethrow only caught errors in a guard. { invokeGuardedCallback(null, function () { throw error; }); clearCaughtError(); } } var callComponentWillUnmountWithTimer = function (current, instance) { instance.props = current.memoizedProps; instance.state = current.memoizedState; if ( current.mode & ProfileMode) { try { startLayoutEffectTimer(); instance.componentWillUnmount(); } finally { recordLayoutEffectDuration(current); } } else { instance.componentWillUnmount(); } }; // Capture errors so they don't interrupt mounting. function safelyCallCommitHookLayoutEffectListMount(current, nearestMountedAncestor) { try { commitHookEffectListMount(Layout, current); } catch (error) { captureCommitPhaseError(current, nearestMountedAncestor, error); } } // Capture errors so they don't interrupt unmounting. function safelyCallComponentWillUnmount(current, nearestMountedAncestor, instance) { try { callComponentWillUnmountWithTimer(current, instance); } catch (error) { captureCommitPhaseError(current, nearestMountedAncestor, error); } } // Capture errors so they don't interrupt mounting. function safelyCallComponentDidMount(current, nearestMountedAncestor, instance) { try { instance.componentDidMount(); } catch (error) { captureCommitPhaseError(current, nearestMountedAncestor, error); } } // Capture errors so they don't interrupt mounting. function safelyAttachRef(current, nearestMountedAncestor) { try { commitAttachRef(current); } catch (error) { captureCommitPhaseError(current, nearestMountedAncestor, error); } } function safelyDetachRef(current, nearestMountedAncestor) { var ref = current.ref; if (ref !== null) { if (typeof ref === 'function') { var retVal; try { if (enableProfilerTimer && enableProfilerCommitHooks && current.mode & ProfileMode) { try { startLayoutEffectTimer(); retVal = ref(null); } finally { recordLayoutEffectDuration(current); } } else { retVal = ref(null); } } catch (error) { captureCommitPhaseError(current, nearestMountedAncestor, error); } { if (typeof retVal === 'function') { error('Unexpected return value from a callback ref in %s. ' + 'A callback ref should not return a function.', getComponentNameFromFiber(current)); } } } else { ref.current = null; } } } function safelyCallDestroy(current, nearestMountedAncestor, destroy) { try { destroy(); } catch (error) { captureCommitPhaseError(current, nearestMountedAncestor, error); } } var focusedInstanceHandle = null; var shouldFireAfterActiveInstanceBlur = false; function commitBeforeMutationEffects(root, firstChild) { focusedInstanceHandle = prepareForCommit(root.containerInfo); nextEffect = firstChild; commitBeforeMutationEffects_begin(); // We no longer need to track the active instance fiber var shouldFire = shouldFireAfterActiveInstanceBlur; shouldFireAfterActiveInstanceBlur = false; focusedInstanceHandle = null; return shouldFire; } function commitBeforeMutationEffects_begin() { while (nextEffect !== null) { var fiber = nextEffect; // This phase is only used for beforeActiveInstanceBlur. var child = fiber.child; if ((fiber.subtreeFlags & BeforeMutationMask) !== NoFlags && child !== null) { child.return = fiber; nextEffect = child; } else { commitBeforeMutationEffects_complete(); } } } function commitBeforeMutationEffects_complete() { while (nextEffect !== null) { var fiber = nextEffect; setCurrentFiber(fiber); try { commitBeforeMutationEffectsOnFiber(fiber); } catch (error) { captureCommitPhaseError(fiber, fiber.return, error); } resetCurrentFiber(); var sibling = fiber.sibling; if (sibling !== null) { sibling.return = fiber.return; nextEffect = sibling; return; } nextEffect = fiber.return; } } function commitBeforeMutationEffectsOnFiber(finishedWork) { var current = finishedWork.alternate; var flags = finishedWork.flags; if ((flags & Snapshot) !== NoFlags) { setCurrentFiber(finishedWork); switch (finishedWork.tag) { case FunctionComponent: case ForwardRef: case SimpleMemoComponent: { break; } case ClassComponent: { if (current !== null) { var prevProps = current.memoizedProps; var prevState = current.memoizedState; var instance = finishedWork.stateNode; // We could update instance props and state here, // but instead we rely on them being set during last render. // TODO: revisit this when we implement resuming. { if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) { if (instance.props !== finishedWork.memoizedProps) { error('Expected %s props to match memoized props before ' + 'getSnapshotBeforeUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); } if (instance.state !== finishedWork.memoizedState) { error('Expected %s state to match memoized state before ' + 'getSnapshotBeforeUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.state`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); } } } var snapshot = instance.getSnapshotBeforeUpdate(finishedWork.elementType === finishedWork.type ? prevProps : resolveDefaultProps(finishedWork.type, prevProps), prevState); { var didWarnSet = didWarnAboutUndefinedSnapshotBeforeUpdate; if (snapshot === undefined && !didWarnSet.has(finishedWork.type)) { didWarnSet.add(finishedWork.type); error('%s.getSnapshotBeforeUpdate(): A snapshot value (or null) ' + 'must be returned. You have returned undefined.', getComponentNameFromFiber(finishedWork)); } } instance.__reactInternalSnapshotBeforeUpdate = snapshot; } break; } case HostRoot: { { var root = finishedWork.stateNode; clearContainer(root.containerInfo); } break; } case HostComponent: case HostText: case HostPortal: case IncompleteClassComponent: // Nothing to do for these component types break; default: { throw new Error('This unit of work tag should not have side-effects. This error is ' + 'likely caused by a bug in React. Please file an issue.'); } } resetCurrentFiber(); } } function commitHookEffectListUnmount(flags, finishedWork, nearestMountedAncestor) { var updateQueue = finishedWork.updateQueue; var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null; if (lastEffect !== null) { var firstEffect = lastEffect.next; var effect = firstEffect; do { if ((effect.tag & flags) === flags) { // Unmount var destroy = effect.destroy; effect.destroy = undefined; if (destroy !== undefined) { { if ((flags & Passive$1) !== NoFlags$1) { markComponentPassiveEffectUnmountStarted(finishedWork); } else if ((flags & Layout) !== NoFlags$1) { markComponentLayoutEffectUnmountStarted(finishedWork); } } { if ((flags & Insertion) !== NoFlags$1) { setIsRunningInsertionEffect(true); } } safelyCallDestroy(finishedWork, nearestMountedAncestor, destroy); { if ((flags & Insertion) !== NoFlags$1) { setIsRunningInsertionEffect(false); } } { if ((flags & Passive$1) !== NoFlags$1) { markComponentPassiveEffectUnmountStopped(); } else if ((flags & Layout) !== NoFlags$1) { markComponentLayoutEffectUnmountStopped(); } } } } effect = effect.next; } while (effect !== firstEffect); } } function commitHookEffectListMount(flags, finishedWork) { var updateQueue = finishedWork.updateQueue; var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null; if (lastEffect !== null) { var firstEffect = lastEffect.next; var effect = firstEffect; do { if ((effect.tag & flags) === flags) { { if ((flags & Passive$1) !== NoFlags$1) { markComponentPassiveEffectMountStarted(finishedWork); } else if ((flags & Layout) !== NoFlags$1) { markComponentLayoutEffectMountStarted(finishedWork); } } // Mount var create = effect.create; { if ((flags & Insertion) !== NoFlags$1) { setIsRunningInsertionEffect(true); } } effect.destroy = create(); { if ((flags & Insertion) !== NoFlags$1) { setIsRunningInsertionEffect(false); } } { if ((flags & Passive$1) !== NoFlags$1) { markComponentPassiveEffectMountStopped(); } else if ((flags & Layout) !== NoFlags$1) { markComponentLayoutEffectMountStopped(); } } { var destroy = effect.destroy; if (destroy !== undefined && typeof destroy !== 'function') { var hookName = void 0; if ((effect.tag & Layout) !== NoFlags) { hookName = 'useLayoutEffect'; } else if ((effect.tag & Insertion) !== NoFlags) { hookName = 'useInsertionEffect'; } else { hookName = 'useEffect'; } var addendum = void 0; if (destroy === null) { addendum = ' You returned null. If your effect does not require clean ' + 'up, return undefined (or nothing).'; } else if (typeof destroy.then === 'function') { addendum = '\n\nIt looks like you wrote ' + hookName + '(async () => ...) or returned a Promise. ' + 'Instead, write the async function inside your effect ' + 'and call it immediately:\n\n' + hookName + '(() => {\n' + ' async function fetchData() {\n' + ' // You can await here\n' + ' const response = await MyAPI.getData(someId);\n' + ' // ...\n' + ' }\n' + ' fetchData();\n' + "}, [someId]); // Or [] if effect doesn't need props or state\n\n" + 'Learn more about data fetching with Hooks: https://reactjs.org/link/hooks-data-fetching'; } else { addendum = ' You returned: ' + destroy; } error('%s must not return anything besides a function, ' + 'which is used for clean-up.%s', hookName, addendum); } } } effect = effect.next; } while (effect !== firstEffect); } } function commitPassiveEffectDurations(finishedRoot, finishedWork) { { // Only Profilers with work in their subtree will have an Update effect scheduled. if ((finishedWork.flags & Update) !== NoFlags) { switch (finishedWork.tag) { case Profiler: { var passiveEffectDuration = finishedWork.stateNode.passiveEffectDuration; var _finishedWork$memoize = finishedWork.memoizedProps, id = _finishedWork$memoize.id, onPostCommit = _finishedWork$memoize.onPostCommit; // This value will still reflect the previous commit phase. // It does not get reset until the start of the next commit phase. var commitTime = getCommitTime(); var phase = finishedWork.alternate === null ? 'mount' : 'update'; { if (isCurrentUpdateNested()) { phase = 'nested-update'; } } if (typeof onPostCommit === 'function') { onPostCommit(id, phase, passiveEffectDuration, commitTime); } // Bubble times to the next nearest ancestor Profiler. // After we process that Profiler, we'll bubble further up. var parentFiber = finishedWork.return; outer: while (parentFiber !== null) { switch (parentFiber.tag) { case HostRoot: var root = parentFiber.stateNode; root.passiveEffectDuration += passiveEffectDuration; break outer; case Profiler: var parentStateNode = parentFiber.stateNode; parentStateNode.passiveEffectDuration += passiveEffectDuration; break outer; } parentFiber = parentFiber.return; } break; } } } } } function commitLayoutEffectOnFiber(finishedRoot, current, finishedWork, committedLanes) { if ((finishedWork.flags & LayoutMask) !== NoFlags) { switch (finishedWork.tag) { case FunctionComponent: case ForwardRef: case SimpleMemoComponent: { if ( !offscreenSubtreeWasHidden) { // At this point layout effects have already been destroyed (during mutation phase). // This is done to prevent sibling component effects from interfering with each other, // e.g. a destroy function in one component should never override a ref set // by a create function in another component during the same commit. if ( finishedWork.mode & ProfileMode) { try { startLayoutEffectTimer(); commitHookEffectListMount(Layout | HasEffect, finishedWork); } finally { recordLayoutEffectDuration(finishedWork); } } else { commitHookEffectListMount(Layout | HasEffect, finishedWork); } } break; } case ClassComponent: { var instance = finishedWork.stateNode; if (finishedWork.flags & Update) { if (!offscreenSubtreeWasHidden) { if (current === null) { // We could update instance props and state here, // but instead we rely on them being set during last render. // TODO: revisit this when we implement resuming. { if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) { if (instance.props !== finishedWork.memoizedProps) { error('Expected %s props to match memoized props before ' + 'componentDidMount. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); } if (instance.state !== finishedWork.memoizedState) { error('Expected %s state to match memoized state before ' + 'componentDidMount. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.state`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); } } } if ( finishedWork.mode & ProfileMode) { try { startLayoutEffectTimer(); instance.componentDidMount(); } finally { recordLayoutEffectDuration(finishedWork); } } else { instance.componentDidMount(); } } else { var prevProps = finishedWork.elementType === finishedWork.type ? current.memoizedProps : resolveDefaultProps(finishedWork.type, current.memoizedProps); var prevState = current.memoizedState; // We could update instance props and state here, // but instead we rely on them being set during last render. // TODO: revisit this when we implement resuming. { if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) { if (instance.props !== finishedWork.memoizedProps) { error('Expected %s props to match memoized props before ' + 'componentDidUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); } if (instance.state !== finishedWork.memoizedState) { error('Expected %s state to match memoized state before ' + 'componentDidUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.state`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); } } } if ( finishedWork.mode & ProfileMode) { try { startLayoutEffectTimer(); instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate); } finally { recordLayoutEffectDuration(finishedWork); } } else { instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate); } } } } // TODO: I think this is now always non-null by the time it reaches the // commit phase. Consider removing the type check. var updateQueue = finishedWork.updateQueue; if (updateQueue !== null) { { if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) { if (instance.props !== finishedWork.memoizedProps) { error('Expected %s props to match memoized props before ' + 'processing the update queue. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); } if (instance.state !== finishedWork.memoizedState) { error('Expected %s state to match memoized state before ' + 'processing the update queue. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.state`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); } } } // We could update instance props and state here, // but instead we rely on them being set during last render. // TODO: revisit this when we implement resuming. commitUpdateQueue(finishedWork, updateQueue, instance); } break; } case HostRoot: { // TODO: I think this is now always non-null by the time it reaches the // commit phase. Consider removing the type check. var _updateQueue = finishedWork.updateQueue; if (_updateQueue !== null) { var _instance = null; if (finishedWork.child !== null) { switch (finishedWork.child.tag) { case HostComponent: _instance = getPublicInstance(finishedWork.child.stateNode); break; case ClassComponent: _instance = finishedWork.child.stateNode; break; } } commitUpdateQueue(finishedWork, _updateQueue, _instance); } break; } case HostComponent: { var _instance2 = finishedWork.stateNode; // Renderers may schedule work to be done after host components are mounted // (eg DOM renderer may schedule auto-focus for inputs and form controls). // These effects should only be committed when components are first mounted, // aka when there is no current/alternate. if (current === null && finishedWork.flags & Update) { var type = finishedWork.type; var props = finishedWork.memoizedProps; commitMount(_instance2, type, props); } break; } case HostText: { // We have no life-cycles associated with text. break; } case HostPortal: { // We have no life-cycles associated with portals. break; } case Profiler: { { var _finishedWork$memoize2 = finishedWork.memoizedProps, onCommit = _finishedWork$memoize2.onCommit, onRender = _finishedWork$memoize2.onRender; var effectDuration = finishedWork.stateNode.effectDuration; var commitTime = getCommitTime(); var phase = current === null ? 'mount' : 'update'; { if (isCurrentUpdateNested()) { phase = 'nested-update'; } } if (typeof onRender === 'function') { onRender(finishedWork.memoizedProps.id, phase, finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, commitTime); } { if (typeof onCommit === 'function') { onCommit(finishedWork.memoizedProps.id, phase, effectDuration, commitTime); } // Schedule a passive effect for this Profiler to call onPostCommit hooks. // This effect should be scheduled even if there is no onPostCommit callback for this Profiler, // because the effect is also where times bubble to parent Profilers. enqueuePendingPassiveProfilerEffect(finishedWork); // Propagate layout effect durations to the next nearest Profiler ancestor. // Do not reset these values until the next render so DevTools has a chance to read them first. var parentFiber = finishedWork.return; outer: while (parentFiber !== null) { switch (parentFiber.tag) { case HostRoot: var root = parentFiber.stateNode; root.effectDuration += effectDuration; break outer; case Profiler: var parentStateNode = parentFiber.stateNode; parentStateNode.effectDuration += effectDuration; break outer; } parentFiber = parentFiber.return; } } } break; } case SuspenseComponent: { commitSuspenseHydrationCallbacks(finishedRoot, finishedWork); break; } case SuspenseListComponent: case IncompleteClassComponent: case ScopeComponent: case OffscreenComponent: case LegacyHiddenComponent: case TracingMarkerComponent: { break; } default: throw new Error('This unit of work tag should not have side-effects. This error is ' + 'likely caused by a bug in React. Please file an issue.'); } } if ( !offscreenSubtreeWasHidden) { { if (finishedWork.flags & Ref) { commitAttachRef(finishedWork); } } } } function reappearLayoutEffectsOnFiber(node) { // Turn on layout effects in a tree that previously disappeared. // TODO (Offscreen) Check: flags & LayoutStatic switch (node.tag) { case FunctionComponent: case ForwardRef: case SimpleMemoComponent: { if ( node.mode & ProfileMode) { try { startLayoutEffectTimer(); safelyCallCommitHookLayoutEffectListMount(node, node.return); } finally { recordLayoutEffectDuration(node); } } else { safelyCallCommitHookLayoutEffectListMount(node, node.return); } break; } case ClassComponent: { var instance = node.stateNode; if (typeof instance.componentDidMount === 'function') { safelyCallComponentDidMount(node, node.return, instance); } safelyAttachRef(node, node.return); break; } case HostComponent: { safelyAttachRef(node, node.return); break; } } } function hideOrUnhideAllChildren(finishedWork, isHidden) { // Only hide or unhide the top-most host nodes. var hostSubtreeRoot = null; { // We only have the top Fiber that was inserted but we need to recurse down its // children to find all the terminal nodes. var node = finishedWork; while (true) { if (node.tag === HostComponent) { if (hostSubtreeRoot === null) { hostSubtreeRoot = node; try { var instance = node.stateNode; if (isHidden) { hideInstance(instance); } else { unhideInstance(node.stateNode, node.memoizedProps); } } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } } } else if (node.tag === HostText) { if (hostSubtreeRoot === null) { try { var _instance3 = node.stateNode; if (isHidden) { hideTextInstance(_instance3); } else { unhideTextInstance(_instance3, node.memoizedProps); } } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } } } else if ((node.tag === OffscreenComponent || node.tag === LegacyHiddenComponent) && node.memoizedState !== null && node !== finishedWork) ; else if (node.child !== null) { node.child.return = node; node = node.child; continue; } if (node === finishedWork) { return; } while (node.sibling === null) { if (node.return === null || node.return === finishedWork) { return; } if (hostSubtreeRoot === node) { hostSubtreeRoot = null; } node = node.return; } if (hostSubtreeRoot === node) { hostSubtreeRoot = null; } node.sibling.return = node.return; node = node.sibling; } } } function commitAttachRef(finishedWork) { var ref = finishedWork.ref; if (ref !== null) { var instance = finishedWork.stateNode; var instanceToUse; switch (finishedWork.tag) { case HostComponent: instanceToUse = getPublicInstance(instance); break; default: instanceToUse = instance; } // Moved outside to ensure DCE works with this flag if (typeof ref === 'function') { var retVal; if ( finishedWork.mode & ProfileMode) { try { startLayoutEffectTimer(); retVal = ref(instanceToUse); } finally { recordLayoutEffectDuration(finishedWork); } } else { retVal = ref(instanceToUse); } { if (typeof retVal === 'function') { error('Unexpected return value from a callback ref in %s. ' + 'A callback ref should not return a function.', getComponentNameFromFiber(finishedWork)); } } } else { { if (!ref.hasOwnProperty('current')) { error('Unexpected ref object provided for %s. ' + 'Use either a ref-setter function or React.createRef().', getComponentNameFromFiber(finishedWork)); } } ref.current = instanceToUse; } } } function detachFiberMutation(fiber) { // Cut off the return pointer to disconnect it from the tree. // This enables us to detect and warn against state updates on an unmounted component. // It also prevents events from bubbling from within disconnected components. // // Ideally, we should also clear the child pointer of the parent alternate to let this // get GC:ed but we don't know which for sure which parent is the current // one so we'll settle for GC:ing the subtree of this child. // This child itself will be GC:ed when the parent updates the next time. // // Note that we can't clear child or sibling pointers yet. // They're needed for passive effects and for findDOMNode. // We defer those fields, and all other cleanup, to the passive phase (see detachFiberAfterEffects). // // Don't reset the alternate yet, either. We need that so we can detach the // alternate's fields in the passive phase. Clearing the return pointer is // sufficient for findDOMNode semantics. var alternate = fiber.alternate; if (alternate !== null) { alternate.return = null; } fiber.return = null; } function detachFiberAfterEffects(fiber) { var alternate = fiber.alternate; if (alternate !== null) { fiber.alternate = null; detachFiberAfterEffects(alternate); } // Note: Defensively using negation instead of < in case // `deletedTreeCleanUpLevel` is undefined. { // Clear cyclical Fiber fields. This level alone is designed to roughly // approximate the planned Fiber refactor. In that world, `setState` will be // bound to a special "instance" object instead of a Fiber. The Instance // object will not have any of these fields. It will only be connected to // the fiber tree via a single link at the root. So if this level alone is // sufficient to fix memory issues, that bodes well for our plans. fiber.child = null; fiber.deletions = null; fiber.sibling = null; // The `stateNode` is cyclical because on host nodes it points to the host // tree, which has its own pointers to children, parents, and siblings. // The other host nodes also point back to fibers, so we should detach that // one, too. if (fiber.tag === HostComponent) { var hostInstance = fiber.stateNode; if (hostInstance !== null) { detachDeletedInstance(hostInstance); } } fiber.stateNode = null; // I'm intentionally not clearing the `return` field in this level. We // already disconnect the `return` pointer at the root of the deleted // subtree (in `detachFiberMutation`). Besides, `return` by itself is not // cyclical — it's only cyclical when combined with `child`, `sibling`, and // `alternate`. But we'll clear it in the next level anyway, just in case. { fiber._debugOwner = null; } { // Theoretically, nothing in here should be necessary, because we already // disconnected the fiber from the tree. So even if something leaks this // particular fiber, it won't leak anything else // // The purpose of this branch is to be super aggressive so we can measure // if there's any difference in memory impact. If there is, that could // indicate a React leak we don't know about. fiber.return = null; fiber.dependencies = null; fiber.memoizedProps = null; fiber.memoizedState = null; fiber.pendingProps = null; fiber.stateNode = null; // TODO: Move to `commitPassiveUnmountInsideDeletedTreeOnFiber` instead. fiber.updateQueue = null; } } } function getHostParentFiber(fiber) { var parent = fiber.return; while (parent !== null) { if (isHostParent(parent)) { return parent; } parent = parent.return; } throw new Error('Expected to find a host parent. This error is likely caused by a bug ' + 'in React. Please file an issue.'); } function isHostParent(fiber) { return fiber.tag === HostComponent || fiber.tag === HostRoot || fiber.tag === HostPortal; } function getHostSibling(fiber) { // We're going to search forward into the tree until we find a sibling host // node. Unfortunately, if multiple insertions are done in a row we have to // search past them. This leads to exponential search for the next sibling. // TODO: Find a more efficient way to do this. var node = fiber; siblings: while (true) { // If we didn't find anything, let's try the next sibling. while (node.sibling === null) { if (node.return === null || isHostParent(node.return)) { // If we pop out of the root or hit the parent the fiber we are the // last sibling. return null; } node = node.return; } node.sibling.return = node.return; node = node.sibling; while (node.tag !== HostComponent && node.tag !== HostText && node.tag !== DehydratedFragment) { // If it is not host node and, we might have a host node inside it. // Try to search down until we find one. if (node.flags & Placement) { // If we don't have a child, try the siblings instead. continue siblings; } // If we don't have a child, try the siblings instead. // We also skip portals because they are not part of this host tree. if (node.child === null || node.tag === HostPortal) { continue siblings; } else { node.child.return = node; node = node.child; } } // Check if this host node is stable or about to be placed. if (!(node.flags & Placement)) { // Found it! return node.stateNode; } } } function commitPlacement(finishedWork) { var parentFiber = getHostParentFiber(finishedWork); // Note: these two variables *must* always be updated together. switch (parentFiber.tag) { case HostComponent: { var parent = parentFiber.stateNode; if (parentFiber.flags & ContentReset) { // Reset the text content of the parent before doing any insertions resetTextContent(parent); // Clear ContentReset from the effect tag parentFiber.flags &= ~ContentReset; } var before = getHostSibling(finishedWork); // We only have the top Fiber that was inserted but we need to recurse down its // children to find all the terminal nodes. insertOrAppendPlacementNode(finishedWork, before, parent); break; } case HostRoot: case HostPortal: { var _parent = parentFiber.stateNode.containerInfo; var _before = getHostSibling(finishedWork); insertOrAppendPlacementNodeIntoContainer(finishedWork, _before, _parent); break; } // eslint-disable-next-line-no-fallthrough default: throw new Error('Invalid host parent fiber. This error is likely caused by a bug ' + 'in React. Please file an issue.'); } } function insertOrAppendPlacementNodeIntoContainer(node, before, parent) { var tag = node.tag; var isHost = tag === HostComponent || tag === HostText; if (isHost) { var stateNode = node.stateNode; if (before) { insertInContainerBefore(parent, stateNode, before); } else { appendChildToContainer(parent, stateNode); } } else if (tag === HostPortal) ; else { var child = node.child; if (child !== null) { insertOrAppendPlacementNodeIntoContainer(child, before, parent); var sibling = child.sibling; while (sibling !== null) { insertOrAppendPlacementNodeIntoContainer(sibling, before, parent); sibling = sibling.sibling; } } } } function insertOrAppendPlacementNode(node, before, parent) { var tag = node.tag; var isHost = tag === HostComponent || tag === HostText; if (isHost) { var stateNode = node.stateNode; if (before) { insertBefore(parent, stateNode, before); } else { appendChild(parent, stateNode); } } else if (tag === HostPortal) ; else { var child = node.child; if (child !== null) { insertOrAppendPlacementNode(child, before, parent); var sibling = child.sibling; while (sibling !== null) { insertOrAppendPlacementNode(sibling, before, parent); sibling = sibling.sibling; } } } } // These are tracked on the stack as we recursively traverse a // deleted subtree. // TODO: Update these during the whole mutation phase, not just during // a deletion. var hostParent = null; var hostParentIsContainer = false; function commitDeletionEffects(root, returnFiber, deletedFiber) { { // We only have the top Fiber that was deleted but we need to recurse down its // children to find all the terminal nodes. // Recursively delete all host nodes from the parent, detach refs, clean // up mounted layout effects, and call componentWillUnmount. // We only need to remove the topmost host child in each branch. But then we // still need to keep traversing to unmount effects, refs, and cWU. TODO: We // could split this into two separate traversals functions, where the second // one doesn't include any removeChild logic. This is maybe the same // function as "disappearLayoutEffects" (or whatever that turns into after // the layout phase is refactored to use recursion). // Before starting, find the nearest host parent on the stack so we know // which instance/container to remove the children from. // TODO: Instead of searching up the fiber return path on every deletion, we // can track the nearest host component on the JS stack as we traverse the // tree during the commit phase. This would make insertions faster, too. var parent = returnFiber; findParent: while (parent !== null) { switch (parent.tag) { case HostComponent: { hostParent = parent.stateNode; hostParentIsContainer = false; break findParent; } case HostRoot: { hostParent = parent.stateNode.containerInfo; hostParentIsContainer = true; break findParent; } case HostPortal: { hostParent = parent.stateNode.containerInfo; hostParentIsContainer = true; break findParent; } } parent = parent.return; } if (hostParent === null) { throw new Error('Expected to find a host parent. This error is likely caused by ' + 'a bug in React. Please file an issue.'); } commitDeletionEffectsOnFiber(root, returnFiber, deletedFiber); hostParent = null; hostParentIsContainer = false; } detachFiberMutation(deletedFiber); } function recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, parent) { // TODO: Use a static flag to skip trees that don't have unmount effects var child = parent.child; while (child !== null) { commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, child); child = child.sibling; } } function commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, deletedFiber) { onCommitUnmount(deletedFiber); // The cases in this outer switch modify the stack before they traverse // into their subtree. There are simpler cases in the inner switch // that don't modify the stack. switch (deletedFiber.tag) { case HostComponent: { if (!offscreenSubtreeWasHidden) { safelyDetachRef(deletedFiber, nearestMountedAncestor); } // Intentional fallthrough to next branch } // eslint-disable-next-line-no-fallthrough case HostText: { // We only need to remove the nearest host child. Set the host parent // to `null` on the stack to indicate that nested children don't // need to be removed. { var prevHostParent = hostParent; var prevHostParentIsContainer = hostParentIsContainer; hostParent = null; recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber); hostParent = prevHostParent; hostParentIsContainer = prevHostParentIsContainer; if (hostParent !== null) { // Now that all the child effects have unmounted, we can remove the // node from the tree. if (hostParentIsContainer) { removeChildFromContainer(hostParent, deletedFiber.stateNode); } else { removeChild(hostParent, deletedFiber.stateNode); } } } return; } case DehydratedFragment: { // Delete the dehydrated suspense boundary and all of its content. { if (hostParent !== null) { if (hostParentIsContainer) { clearSuspenseBoundaryFromContainer(hostParent, deletedFiber.stateNode); } else { clearSuspenseBoundary(hostParent, deletedFiber.stateNode); } } } return; } case HostPortal: { { // When we go into a portal, it becomes the parent to remove from. var _prevHostParent = hostParent; var _prevHostParentIsContainer = hostParentIsContainer; hostParent = deletedFiber.stateNode.containerInfo; hostParentIsContainer = true; recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber); hostParent = _prevHostParent; hostParentIsContainer = _prevHostParentIsContainer; } return; } case FunctionComponent: case ForwardRef: case MemoComponent: case SimpleMemoComponent: { if (!offscreenSubtreeWasHidden) { var updateQueue = deletedFiber.updateQueue; if (updateQueue !== null) { var lastEffect = updateQueue.lastEffect; if (lastEffect !== null) { var firstEffect = lastEffect.next; var effect = firstEffect; do { var _effect = effect, destroy = _effect.destroy, tag = _effect.tag; if (destroy !== undefined) { if ((tag & Insertion) !== NoFlags$1) { safelyCallDestroy(deletedFiber, nearestMountedAncestor, destroy); } else if ((tag & Layout) !== NoFlags$1) { { markComponentLayoutEffectUnmountStarted(deletedFiber); } if ( deletedFiber.mode & ProfileMode) { startLayoutEffectTimer(); safelyCallDestroy(deletedFiber, nearestMountedAncestor, destroy); recordLayoutEffectDuration(deletedFiber); } else { safelyCallDestroy(deletedFiber, nearestMountedAncestor, destroy); } { markComponentLayoutEffectUnmountStopped(); } } } effect = effect.next; } while (effect !== firstEffect); } } } recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber); return; } case ClassComponent: { if (!offscreenSubtreeWasHidden) { safelyDetachRef(deletedFiber, nearestMountedAncestor); var instance = deletedFiber.stateNode; if (typeof instance.componentWillUnmount === 'function') { safelyCallComponentWillUnmount(deletedFiber, nearestMountedAncestor, instance); } } recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber); return; } case ScopeComponent: { recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber); return; } case OffscreenComponent: { if ( // TODO: Remove this dead flag deletedFiber.mode & ConcurrentMode) { // If this offscreen component is hidden, we already unmounted it. Before // deleting the children, track that it's already unmounted so that we // don't attempt to unmount the effects again. // TODO: If the tree is hidden, in most cases we should be able to skip // over the nested children entirely. An exception is we haven't yet found // the topmost host node to delete, which we already track on the stack. // But the other case is portals, which need to be detached no matter how // deeply they are nested. We should use a subtree flag to track whether a // subtree includes a nested portal. var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden || deletedFiber.memoizedState !== null; recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber); offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden; } else { recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber); } break; } default: { recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber); return; } } } function commitSuspenseCallback(finishedWork) { // TODO: Move this to passive phase var newState = finishedWork.memoizedState; } function commitSuspenseHydrationCallbacks(finishedRoot, finishedWork) { var newState = finishedWork.memoizedState; if (newState === null) { var current = finishedWork.alternate; if (current !== null) { var prevState = current.memoizedState; if (prevState !== null) { var suspenseInstance = prevState.dehydrated; if (suspenseInstance !== null) { commitHydratedSuspenseInstance(suspenseInstance); } } } } } function attachSuspenseRetryListeners(finishedWork) { // If this boundary just timed out, then it will have a set of wakeables. // For each wakeable, attach a listener so that when it resolves, React // attempts to re-render the boundary in the primary (pre-timeout) state. var wakeables = finishedWork.updateQueue; if (wakeables !== null) { finishedWork.updateQueue = null; var retryCache = finishedWork.stateNode; if (retryCache === null) { retryCache = finishedWork.stateNode = new PossiblyWeakSet(); } wakeables.forEach(function (wakeable) { // Memoize using the boundary fiber to prevent redundant listeners. var retry = resolveRetryWakeable.bind(null, finishedWork, wakeable); if (!retryCache.has(wakeable)) { retryCache.add(wakeable); { if (isDevToolsPresent) { if (inProgressLanes !== null && inProgressRoot !== null) { // If we have pending work still, associate the original updaters with it. restorePendingUpdaters(inProgressRoot, inProgressLanes); } else { throw Error('Expected finished root and lanes to be set. This is a bug in React.'); } } } wakeable.then(retry, retry); } }); } } // This function detects when a Suspense boundary goes from visible to hidden. function commitMutationEffects(root, finishedWork, committedLanes) { inProgressLanes = committedLanes; inProgressRoot = root; setCurrentFiber(finishedWork); commitMutationEffectsOnFiber(finishedWork, root); setCurrentFiber(finishedWork); inProgressLanes = null; inProgressRoot = null; } function recursivelyTraverseMutationEffects(root, parentFiber, lanes) { // Deletions effects can be scheduled on any fiber type. They need to happen // before the children effects hae fired. var deletions = parentFiber.deletions; if (deletions !== null) { for (var i = 0; i < deletions.length; i++) { var childToDelete = deletions[i]; try { commitDeletionEffects(root, parentFiber, childToDelete); } catch (error) { captureCommitPhaseError(childToDelete, parentFiber, error); } } } var prevDebugFiber = getCurrentFiber(); if (parentFiber.subtreeFlags & MutationMask) { var child = parentFiber.child; while (child !== null) { setCurrentFiber(child); commitMutationEffectsOnFiber(child, root); child = child.sibling; } } setCurrentFiber(prevDebugFiber); } function commitMutationEffectsOnFiber(finishedWork, root, lanes) { var current = finishedWork.alternate; var flags = finishedWork.flags; // The effect flag should be checked *after* we refine the type of fiber, // because the fiber tag is more specific. An exception is any flag related // to reconcilation, because those can be set on all fiber types. switch (finishedWork.tag) { case FunctionComponent: case ForwardRef: case MemoComponent: case SimpleMemoComponent: { recursivelyTraverseMutationEffects(root, finishedWork); commitReconciliationEffects(finishedWork); if (flags & Update) { try { commitHookEffectListUnmount(Insertion | HasEffect, finishedWork, finishedWork.return); commitHookEffectListMount(Insertion | HasEffect, finishedWork); } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } // Layout effects are destroyed during the mutation phase so that all // destroy functions for all fibers are called before any create functions. // This prevents sibling component effects from interfering with each other, // e.g. a destroy function in one component should never override a ref set // by a create function in another component during the same commit. if ( finishedWork.mode & ProfileMode) { try { startLayoutEffectTimer(); commitHookEffectListUnmount(Layout | HasEffect, finishedWork, finishedWork.return); } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } recordLayoutEffectDuration(finishedWork); } else { try { commitHookEffectListUnmount(Layout | HasEffect, finishedWork, finishedWork.return); } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } } } return; } case ClassComponent: { recursivelyTraverseMutationEffects(root, finishedWork); commitReconciliationEffects(finishedWork); if (flags & Ref) { if (current !== null) { safelyDetachRef(current, current.return); } } return; } case HostComponent: { recursivelyTraverseMutationEffects(root, finishedWork); commitReconciliationEffects(finishedWork); if (flags & Ref) { if (current !== null) { safelyDetachRef(current, current.return); } } { // TODO: ContentReset gets cleared by the children during the commit // phase. This is a refactor hazard because it means we must read // flags the flags after `commitReconciliationEffects` has already run; // the order matters. We should refactor so that ContentReset does not // rely on mutating the flag during commit. Like by setting a flag // during the render phase instead. if (finishedWork.flags & ContentReset) { var instance = finishedWork.stateNode; try { resetTextContent(instance); } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } } if (flags & Update) { var _instance4 = finishedWork.stateNode; if (_instance4 != null) { // Commit the work prepared earlier. var newProps = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps // as the newProps. The updatePayload will contain the real change in // this case. var oldProps = current !== null ? current.memoizedProps : newProps; var type = finishedWork.type; // TODO: Type the updateQueue to be specific to host components. var updatePayload = finishedWork.updateQueue; finishedWork.updateQueue = null; if (updatePayload !== null) { try { commitUpdate(_instance4, updatePayload, type, oldProps, newProps, finishedWork); } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } } } } } return; } case HostText: { recursivelyTraverseMutationEffects(root, finishedWork); commitReconciliationEffects(finishedWork); if (flags & Update) { { if (finishedWork.stateNode === null) { throw new Error('This should have a text node initialized. This error is likely ' + 'caused by a bug in React. Please file an issue.'); } var textInstance = finishedWork.stateNode; var newText = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps // as the newProps. The updatePayload will contain the real change in // this case. var oldText = current !== null ? current.memoizedProps : newText; try { commitTextUpdate(textInstance, oldText, newText); } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } } } return; } case HostRoot: { recursivelyTraverseMutationEffects(root, finishedWork); commitReconciliationEffects(finishedWork); if (flags & Update) { { if (current !== null) { var prevRootState = current.memoizedState; if (prevRootState.isDehydrated) { try { commitHydratedContainer(root.containerInfo); } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } } } } } return; } case HostPortal: { recursivelyTraverseMutationEffects(root, finishedWork); commitReconciliationEffects(finishedWork); return; } case SuspenseComponent: { recursivelyTraverseMutationEffects(root, finishedWork); commitReconciliationEffects(finishedWork); var offscreenFiber = finishedWork.child; if (offscreenFiber.flags & Visibility) { var offscreenInstance = offscreenFiber.stateNode; var newState = offscreenFiber.memoizedState; var isHidden = newState !== null; // Track the current state on the Offscreen instance so we can // read it during an event offscreenInstance.isHidden = isHidden; if (isHidden) { var wasHidden = offscreenFiber.alternate !== null && offscreenFiber.alternate.memoizedState !== null; if (!wasHidden) { // TODO: Move to passive phase markCommitTimeOfFallback(); } } } if (flags & Update) { try { commitSuspenseCallback(finishedWork); } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } attachSuspenseRetryListeners(finishedWork); } return; } case OffscreenComponent: { var _wasHidden = current !== null && current.memoizedState !== null; if ( // TODO: Remove this dead flag finishedWork.mode & ConcurrentMode) { // Before committing the children, track on the stack whether this // offscreen subtree was already hidden, so that we don't unmount the // effects again. var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden || _wasHidden; recursivelyTraverseMutationEffects(root, finishedWork); offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden; } else { recursivelyTraverseMutationEffects(root, finishedWork); } commitReconciliationEffects(finishedWork); if (flags & Visibility) { var _offscreenInstance = finishedWork.stateNode; var _newState = finishedWork.memoizedState; var _isHidden = _newState !== null; var offscreenBoundary = finishedWork; // Track the current state on the Offscreen instance so we can // read it during an event _offscreenInstance.isHidden = _isHidden; { if (_isHidden) { if (!_wasHidden) { if ((offscreenBoundary.mode & ConcurrentMode) !== NoMode) { nextEffect = offscreenBoundary; var offscreenChild = offscreenBoundary.child; while (offscreenChild !== null) { nextEffect = offscreenChild; disappearLayoutEffects_begin(offscreenChild); offscreenChild = offscreenChild.sibling; } } } } } { // TODO: This needs to run whenever there's an insertion or update // inside a hidden Offscreen tree. hideOrUnhideAllChildren(offscreenBoundary, _isHidden); } } return; } case SuspenseListComponent: { recursivelyTraverseMutationEffects(root, finishedWork); commitReconciliationEffects(finishedWork); if (flags & Update) { attachSuspenseRetryListeners(finishedWork); } return; } case ScopeComponent: { return; } default: { recursivelyTraverseMutationEffects(root, finishedWork); commitReconciliationEffects(finishedWork); return; } } } function commitReconciliationEffects(finishedWork) { // Placement effects (insertions, reorders) can be scheduled on any fiber // type. They needs to happen after the children effects have fired, but // before the effects on this fiber have fired. var flags = finishedWork.flags; if (flags & Placement) { try { commitPlacement(finishedWork); } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } // Clear the "placement" from effect tag so that we know that this is // inserted, before any life-cycles like componentDidMount gets called. // TODO: findDOMNode doesn't rely on this any more but isMounted does // and isMounted is deprecated anyway so we should be able to kill this. finishedWork.flags &= ~Placement; } if (flags & Hydrating) { finishedWork.flags &= ~Hydrating; } } function commitLayoutEffects(finishedWork, root, committedLanes) { inProgressLanes = committedLanes; inProgressRoot = root; nextEffect = finishedWork; commitLayoutEffects_begin(finishedWork, root, committedLanes); inProgressLanes = null; inProgressRoot = null; } function commitLayoutEffects_begin(subtreeRoot, root, committedLanes) { // Suspense layout effects semantics don't change for legacy roots. var isModernRoot = (subtreeRoot.mode & ConcurrentMode) !== NoMode; while (nextEffect !== null) { var fiber = nextEffect; var firstChild = fiber.child; if ( fiber.tag === OffscreenComponent && isModernRoot) { // Keep track of the current Offscreen stack's state. var isHidden = fiber.memoizedState !== null; var newOffscreenSubtreeIsHidden = isHidden || offscreenSubtreeIsHidden; if (newOffscreenSubtreeIsHidden) { // The Offscreen tree is hidden. Skip over its layout effects. commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes); continue; } else { // TODO (Offscreen) Also check: subtreeFlags & LayoutMask var current = fiber.alternate; var wasHidden = current !== null && current.memoizedState !== null; var newOffscreenSubtreeWasHidden = wasHidden || offscreenSubtreeWasHidden; var prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden; var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; // Traverse the Offscreen subtree with the current Offscreen as the root. offscreenSubtreeIsHidden = newOffscreenSubtreeIsHidden; offscreenSubtreeWasHidden = newOffscreenSubtreeWasHidden; if (offscreenSubtreeWasHidden && !prevOffscreenSubtreeWasHidden) { // This is the root of a reappearing boundary. Turn its layout effects // back on. nextEffect = fiber; reappearLayoutEffects_begin(fiber); } var child = firstChild; while (child !== null) { nextEffect = child; commitLayoutEffects_begin(child, // New root; bubble back up to here and stop. root, committedLanes); child = child.sibling; } // Restore Offscreen state and resume in our-progress traversal. nextEffect = fiber; offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden; offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden; commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes); continue; } } if ((fiber.subtreeFlags & LayoutMask) !== NoFlags && firstChild !== null) { firstChild.return = fiber; nextEffect = firstChild; } else { commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes); } } } function commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes) { while (nextEffect !== null) { var fiber = nextEffect; if ((fiber.flags & LayoutMask) !== NoFlags) { var current = fiber.alternate; setCurrentFiber(fiber); try { commitLayoutEffectOnFiber(root, current, fiber, committedLanes); } catch (error) { captureCommitPhaseError(fiber, fiber.return, error); } resetCurrentFiber(); } if (fiber === subtreeRoot) { nextEffect = null; return; } var sibling = fiber.sibling; if (sibling !== null) { sibling.return = fiber.return; nextEffect = sibling; return; } nextEffect = fiber.return; } } function disappearLayoutEffects_begin(subtreeRoot) { while (nextEffect !== null) { var fiber = nextEffect; var firstChild = fiber.child; // TODO (Offscreen) Check: flags & (RefStatic | LayoutStatic) switch (fiber.tag) { case FunctionComponent: case ForwardRef: case MemoComponent: case SimpleMemoComponent: { if ( fiber.mode & ProfileMode) { try { startLayoutEffectTimer(); commitHookEffectListUnmount(Layout, fiber, fiber.return); } finally { recordLayoutEffectDuration(fiber); } } else { commitHookEffectListUnmount(Layout, fiber, fiber.return); } break; } case ClassComponent: { // TODO (Offscreen) Check: flags & RefStatic safelyDetachRef(fiber, fiber.return); var instance = fiber.stateNode; if (typeof instance.componentWillUnmount === 'function') { safelyCallComponentWillUnmount(fiber, fiber.return, instance); } break; } case HostComponent: { safelyDetachRef(fiber, fiber.return); break; } case OffscreenComponent: { // Check if this is a var isHidden = fiber.memoizedState !== null; if (isHidden) { // Nested Offscreen tree is already hidden. Don't disappear // its effects. disappearLayoutEffects_complete(subtreeRoot); continue; } break; } } // TODO (Offscreen) Check: subtreeFlags & LayoutStatic if (firstChild !== null) { firstChild.return = fiber; nextEffect = firstChild; } else { disappearLayoutEffects_complete(subtreeRoot); } } } function disappearLayoutEffects_complete(subtreeRoot) { while (nextEffect !== null) { var fiber = nextEffect; if (fiber === subtreeRoot) { nextEffect = null; return; } var sibling = fiber.sibling; if (sibling !== null) { sibling.return = fiber.return; nextEffect = sibling; return; } nextEffect = fiber.return; } } function reappearLayoutEffects_begin(subtreeRoot) { while (nextEffect !== null) { var fiber = nextEffect; var firstChild = fiber.child; if (fiber.tag === OffscreenComponent) { var isHidden = fiber.memoizedState !== null; if (isHidden) { // Nested Offscreen tree is still hidden. Don't re-appear its effects. reappearLayoutEffects_complete(subtreeRoot); continue; } } // TODO (Offscreen) Check: subtreeFlags & LayoutStatic if (firstChild !== null) { // This node may have been reused from a previous render, so we can't // assume its return pointer is correct. firstChild.return = fiber; nextEffect = firstChild; } else { reappearLayoutEffects_complete(subtreeRoot); } } } function reappearLayoutEffects_complete(subtreeRoot) { while (nextEffect !== null) { var fiber = nextEffect; // TODO (Offscreen) Check: flags & LayoutStatic setCurrentFiber(fiber); try { reappearLayoutEffectsOnFiber(fiber); } catch (error) { captureCommitPhaseError(fiber, fiber.return, error); } resetCurrentFiber(); if (fiber === subtreeRoot) { nextEffect = null; return; } var sibling = fiber.sibling; if (sibling !== null) { // This node may have been reused from a previous render, so we can't // assume its return pointer is correct. sibling.return = fiber.return; nextEffect = sibling; return; } nextEffect = fiber.return; } } function commitPassiveMountEffects(root, finishedWork, committedLanes, committedTransitions) { nextEffect = finishedWork; commitPassiveMountEffects_begin(finishedWork, root, committedLanes, committedTransitions); } function commitPassiveMountEffects_begin(subtreeRoot, root, committedLanes, committedTransitions) { while (nextEffect !== null) { var fiber = nextEffect; var firstChild = fiber.child; if ((fiber.subtreeFlags & PassiveMask) !== NoFlags && firstChild !== null) { firstChild.return = fiber; nextEffect = firstChild; } else { commitPassiveMountEffects_complete(subtreeRoot, root, committedLanes, committedTransitions); } } } function commitPassiveMountEffects_complete(subtreeRoot, root, committedLanes, committedTransitions) { while (nextEffect !== null) { var fiber = nextEffect; if ((fiber.flags & Passive) !== NoFlags) { setCurrentFiber(fiber); try { commitPassiveMountOnFiber(root, fiber, committedLanes, committedTransitions); } catch (error) { captureCommitPhaseError(fiber, fiber.return, error); } resetCurrentFiber(); } if (fiber === subtreeRoot) { nextEffect = null; return; } var sibling = fiber.sibling; if (sibling !== null) { sibling.return = fiber.return; nextEffect = sibling; return; } nextEffect = fiber.return; } } function commitPassiveMountOnFiber(finishedRoot, finishedWork, committedLanes, committedTransitions) { switch (finishedWork.tag) { case FunctionComponent: case ForwardRef: case SimpleMemoComponent: { if ( finishedWork.mode & ProfileMode) { startPassiveEffectTimer(); try { commitHookEffectListMount(Passive$1 | HasEffect, finishedWork); } finally { recordPassiveEffectDuration(finishedWork); } } else { commitHookEffectListMount(Passive$1 | HasEffect, finishedWork); } break; } } } function commitPassiveUnmountEffects(firstChild) { nextEffect = firstChild; commitPassiveUnmountEffects_begin(); } function commitPassiveUnmountEffects_begin() { while (nextEffect !== null) { var fiber = nextEffect; var child = fiber.child; if ((nextEffect.flags & ChildDeletion) !== NoFlags) { var deletions = fiber.deletions; if (deletions !== null) { for (var i = 0; i < deletions.length; i++) { var fiberToDelete = deletions[i]; nextEffect = fiberToDelete; commitPassiveUnmountEffectsInsideOfDeletedTree_begin(fiberToDelete, fiber); } { // A fiber was deleted from this parent fiber, but it's still part of // the previous (alternate) parent fiber's list of children. Because // children are a linked list, an earlier sibling that's still alive // will be connected to the deleted fiber via its `alternate`: // // live fiber // --alternate--> previous live fiber // --sibling--> deleted fiber // // We can't disconnect `alternate` on nodes that haven't been deleted // yet, but we can disconnect the `sibling` and `child` pointers. var previousFiber = fiber.alternate; if (previousFiber !== null) { var detachedChild = previousFiber.child; if (detachedChild !== null) { previousFiber.child = null; do { var detachedSibling = detachedChild.sibling; detachedChild.sibling = null; detachedChild = detachedSibling; } while (detachedChild !== null); } } } nextEffect = fiber; } } if ((fiber.subtreeFlags & PassiveMask) !== NoFlags && child !== null) { child.return = fiber; nextEffect = child; } else { commitPassiveUnmountEffects_complete(); } } } function commitPassiveUnmountEffects_complete() { while (nextEffect !== null) { var fiber = nextEffect; if ((fiber.flags & Passive) !== NoFlags) { setCurrentFiber(fiber); commitPassiveUnmountOnFiber(fiber); resetCurrentFiber(); } var sibling = fiber.sibling; if (sibling !== null) { sibling.return = fiber.return; nextEffect = sibling; return; } nextEffect = fiber.return; } } function commitPassiveUnmountOnFiber(finishedWork) { switch (finishedWork.tag) { case FunctionComponent: case ForwardRef: case SimpleMemoComponent: { if ( finishedWork.mode & ProfileMode) { startPassiveEffectTimer(); commitHookEffectListUnmount(Passive$1 | HasEffect, finishedWork, finishedWork.return); recordPassiveEffectDuration(finishedWork); } else { commitHookEffectListUnmount(Passive$1 | HasEffect, finishedWork, finishedWork.return); } break; } } } function commitPassiveUnmountEffectsInsideOfDeletedTree_begin(deletedSubtreeRoot, nearestMountedAncestor) { while (nextEffect !== null) { var fiber = nextEffect; // Deletion effects fire in parent -> child order // TODO: Check if fiber has a PassiveStatic flag setCurrentFiber(fiber); commitPassiveUnmountInsideDeletedTreeOnFiber(fiber, nearestMountedAncestor); resetCurrentFiber(); var child = fiber.child; // TODO: Only traverse subtree if it has a PassiveStatic flag. (But, if we // do this, still need to handle `deletedTreeCleanUpLevel` correctly.) if (child !== null) { child.return = fiber; nextEffect = child; } else { commitPassiveUnmountEffectsInsideOfDeletedTree_complete(deletedSubtreeRoot); } } } function commitPassiveUnmountEffectsInsideOfDeletedTree_complete(deletedSubtreeRoot) { while (nextEffect !== null) { var fiber = nextEffect; var sibling = fiber.sibling; var returnFiber = fiber.return; { // Recursively traverse the entire deleted tree and clean up fiber fields. // This is more aggressive than ideal, and the long term goal is to only // have to detach the deleted tree at the root. detachFiberAfterEffects(fiber); if (fiber === deletedSubtreeRoot) { nextEffect = null; return; } } if (sibling !== null) { sibling.return = returnFiber; nextEffect = sibling; return; } nextEffect = returnFiber; } } function commitPassiveUnmountInsideDeletedTreeOnFiber(current, nearestMountedAncestor) { switch (current.tag) { case FunctionComponent: case ForwardRef: case SimpleMemoComponent: { if ( current.mode & ProfileMode) { startPassiveEffectTimer(); commitHookEffectListUnmount(Passive$1, current, nearestMountedAncestor); recordPassiveEffectDuration(current); } else { commitHookEffectListUnmount(Passive$1, current, nearestMountedAncestor); } break; } } } // TODO: Reuse reappearLayoutEffects traversal here? function invokeLayoutEffectMountInDEV(fiber) { { // We don't need to re-check StrictEffectsMode here. // This function is only called if that check has already passed. switch (fiber.tag) { case FunctionComponent: case ForwardRef: case SimpleMemoComponent: { try { commitHookEffectListMount(Layout | HasEffect, fiber); } catch (error) { captureCommitPhaseError(fiber, fiber.return, error); } break; } case ClassComponent: { var instance = fiber.stateNode; try { instance.componentDidMount(); } catch (error) { captureCommitPhaseError(fiber, fiber.return, error); } break; } } } } function invokePassiveEffectMountInDEV(fiber) { { // We don't need to re-check StrictEffectsMode here. // This function is only called if that check has already passed. switch (fiber.tag) { case FunctionComponent: case ForwardRef: case SimpleMemoComponent: { try { commitHookEffectListMount(Passive$1 | HasEffect, fiber); } catch (error) { captureCommitPhaseError(fiber, fiber.return, error); } break; } } } } function invokeLayoutEffectUnmountInDEV(fiber) { { // We don't need to re-check StrictEffectsMode here. // This function is only called if that check has already passed. switch (fiber.tag) { case FunctionComponent: case ForwardRef: case SimpleMemoComponent: { try { commitHookEffectListUnmount(Layout | HasEffect, fiber, fiber.return); } catch (error) { captureCommitPhaseError(fiber, fiber.return, error); } break; } case ClassComponent: { var instance = fiber.stateNode; if (typeof instance.componentWillUnmount === 'function') { safelyCallComponentWillUnmount(fiber, fiber.return, instance); } break; } } } } function invokePassiveEffectUnmountInDEV(fiber) { { // We don't need to re-check StrictEffectsMode here. // This function is only called if that check has already passed. switch (fiber.tag) { case FunctionComponent: case ForwardRef: case SimpleMemoComponent: { try { commitHookEffectListUnmount(Passive$1 | HasEffect, fiber, fiber.return); } catch (error) { captureCommitPhaseError(fiber, fiber.return, error); } } } } } var COMPONENT_TYPE = 0; var HAS_PSEUDO_CLASS_TYPE = 1; var ROLE_TYPE = 2; var TEST_NAME_TYPE = 3; var TEXT_TYPE = 4; if (typeof Symbol === 'function' && Symbol.for) { var symbolFor = Symbol.for; COMPONENT_TYPE = symbolFor('selector.component'); HAS_PSEUDO_CLASS_TYPE = symbolFor('selector.has_pseudo_class'); ROLE_TYPE = symbolFor('selector.role'); TEST_NAME_TYPE = symbolFor('selector.test_id'); TEXT_TYPE = symbolFor('selector.text'); } var commitHooks = []; function onCommitRoot$1() { { commitHooks.forEach(function (commitHook) { return commitHook(); }); } } var ReactCurrentActQueue = ReactSharedInternals.ReactCurrentActQueue; function isLegacyActEnvironment(fiber) { { // Legacy mode. We preserve the behavior of React 17's act. It assumes an // act environment whenever `jest` is defined, but you can still turn off // spurious warnings by setting IS_REACT_ACT_ENVIRONMENT explicitly // to false. var isReactActEnvironmentGlobal = // $FlowExpectedError – Flow doesn't know about IS_REACT_ACT_ENVIRONMENT global typeof IS_REACT_ACT_ENVIRONMENT !== 'undefined' ? IS_REACT_ACT_ENVIRONMENT : undefined; // $FlowExpectedError - Flow doesn't know about jest var jestIsDefined = typeof jest !== 'undefined'; return jestIsDefined && isReactActEnvironmentGlobal !== false; } } function isConcurrentActEnvironment() { { var isReactActEnvironmentGlobal = // $FlowExpectedError – Flow doesn't know about IS_REACT_ACT_ENVIRONMENT global typeof IS_REACT_ACT_ENVIRONMENT !== 'undefined' ? IS_REACT_ACT_ENVIRONMENT : undefined; if (!isReactActEnvironmentGlobal && ReactCurrentActQueue.current !== null) { // TODO: Include link to relevant documentation page. error('The current testing environment is not configured to support ' + 'act(...)'); } return isReactActEnvironmentGlobal; } } var ceil = Math.ceil; var ReactCurrentDispatcher$2 = ReactSharedInternals.ReactCurrentDispatcher, ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner, ReactCurrentBatchConfig$3 = ReactSharedInternals.ReactCurrentBatchConfig, ReactCurrentActQueue$1 = ReactSharedInternals.ReactCurrentActQueue; var NoContext = /* */ 0; var BatchedContext = /* */ 1; var RenderContext = /* */ 2; var CommitContext = /* */ 4; var RootInProgress = 0; var RootFatalErrored = 1; var RootErrored = 2; var RootSuspended = 3; var RootSuspendedWithDelay = 4; var RootCompleted = 5; var RootDidNotComplete = 6; // Describes where we are in the React execution stack var executionContext = NoContext; // The root we're working on var workInProgressRoot = null; // The fiber we're working on var workInProgress = null; // The lanes we're rendering var workInProgressRootRenderLanes = NoLanes; // Stack that allows components to change the render lanes for its subtree // This is a superset of the lanes we started working on at the root. The only // case where it's different from `workInProgressRootRenderLanes` is when we // enter a subtree that is hidden and needs to be unhidden: Suspense and // Offscreen component. // // Most things in the work loop should deal with workInProgressRootRenderLanes. // Most things in begin/complete phases should deal with subtreeRenderLanes. var subtreeRenderLanes = NoLanes; var subtreeRenderLanesCursor = createCursor(NoLanes); // Whether to root completed, errored, suspended, etc. var workInProgressRootExitStatus = RootInProgress; // A fatal error, if one is thrown var workInProgressRootFatalError = null; // "Included" lanes refer to lanes that were worked on during this render. It's // slightly different than `renderLanes` because `renderLanes` can change as you // enter and exit an Offscreen tree. This value is the combination of all render // lanes for the entire render phase. var workInProgressRootIncludedLanes = NoLanes; // The work left over by components that were visited during this render. Only // includes unprocessed updates, not work in bailed out children. var workInProgressRootSkippedLanes = NoLanes; // Lanes that were updated (in an interleaved event) during this render. var workInProgressRootInterleavedUpdatedLanes = NoLanes; // Lanes that were updated during the render phase (*not* an interleaved event). var workInProgressRootPingedLanes = NoLanes; // Errors that are thrown during the render phase. var workInProgressRootConcurrentErrors = null; // These are errors that we recovered from without surfacing them to the UI. // We will log them once the tree commits. var workInProgressRootRecoverableErrors = null; // The most recent time we committed a fallback. This lets us ensure a train // model where we don't commit new loading states in too quick succession. var globalMostRecentFallbackTime = 0; var FALLBACK_THROTTLE_MS = 500; // The absolute time for when we should start giving up on rendering // more and prefer CPU suspense heuristics instead. var workInProgressRootRenderTargetTime = Infinity; // How long a render is supposed to take before we start following CPU // suspense heuristics and opt out of rendering more content. var RENDER_TIMEOUT_MS = 500; var workInProgressTransitions = null; function resetRenderTimer() { workInProgressRootRenderTargetTime = now() + RENDER_TIMEOUT_MS; } function getRenderTargetTime() { return workInProgressRootRenderTargetTime; } var hasUncaughtError = false; var firstUncaughtError = null; var legacyErrorBoundariesThatAlreadyFailed = null; // Only used when enableProfilerNestedUpdateScheduledHook is true; var rootDoesHavePassiveEffects = false; var rootWithPendingPassiveEffects = null; var pendingPassiveEffectsLanes = NoLanes; var pendingPassiveProfilerEffects = []; var pendingPassiveTransitions = null; // Use these to prevent an infinite loop of nested updates var NESTED_UPDATE_LIMIT = 50; var nestedUpdateCount = 0; var rootWithNestedUpdates = null; var isFlushingPassiveEffects = false; var didScheduleUpdateDuringPassiveEffects = false; var NESTED_PASSIVE_UPDATE_LIMIT = 50; var nestedPassiveUpdateCount = 0; var rootWithPassiveNestedUpdates = null; // If two updates are scheduled within the same event, we should treat their // event times as simultaneous, even if the actual clock time has advanced // between the first and second call. var currentEventTime = NoTimestamp; var currentEventTransitionLane = NoLanes; var isRunningInsertionEffect = false; function getWorkInProgressRoot() { return workInProgressRoot; } function requestEventTime() { if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { // We're inside React, so it's fine to read the actual time. return now(); } // We're not inside React, so we may be in the middle of a browser event. if (currentEventTime !== NoTimestamp) { // Use the same start time for all updates until we enter React again. return currentEventTime; } // This is the first update since React yielded. Compute a new start time. currentEventTime = now(); return currentEventTime; } function requestUpdateLane(fiber) { // Special cases var mode = fiber.mode; if ((mode & ConcurrentMode) === NoMode) { return SyncLane; } else if ( (executionContext & RenderContext) !== NoContext && workInProgressRootRenderLanes !== NoLanes) { // This is a render phase update. These are not officially supported. The // old behavior is to give this the same "thread" (lanes) as // whatever is currently rendering. So if you call `setState` on a component // that happens later in the same render, it will flush. Ideally, we want to // remove the special case and treat them as if they came from an // interleaved event. Regardless, this pattern is not officially supported. // This behavior is only a fallback. The flag only exists until we can roll // out the setState warning, since existing code might accidentally rely on // the current behavior. return pickArbitraryLane(workInProgressRootRenderLanes); } var isTransition = requestCurrentTransition() !== NoTransition; if (isTransition) { if ( ReactCurrentBatchConfig$3.transition !== null) { var transition = ReactCurrentBatchConfig$3.transition; if (!transition._updatedFibers) { transition._updatedFibers = new Set(); } transition._updatedFibers.add(fiber); } // The algorithm for assigning an update to a lane should be stable for all // updates at the same priority within the same event. To do this, the // inputs to the algorithm must be the same. // // The trick we use is to cache the first of each of these inputs within an // event. Then reset the cached values once we can be sure the event is // over. Our heuristic for that is whenever we enter a concurrent work loop. if (currentEventTransitionLane === NoLane) { // All transitions within the same event are assigned the same lane. currentEventTransitionLane = claimNextTransitionLane(); } return currentEventTransitionLane; } // Updates originating inside certain React methods, like flushSync, have // their priority set by tracking it with a context variable. // // The opaque type returned by the host config is internally a lane, so we can // use that directly. // TODO: Move this type conversion to the event priority module. var updateLane = getCurrentUpdatePriority(); if (updateLane !== NoLane) { return updateLane; } // This update originated outside React. Ask the host environment for an // appropriate priority, based on the type of event. // // The opaque type returned by the host config is internally a lane, so we can // use that directly. // TODO: Move this type conversion to the event priority module. var eventLane = getCurrentEventPriority(); return eventLane; } function requestRetryLane(fiber) { // This is a fork of `requestUpdateLane` designed specifically for Suspense // "retries" — a special update that attempts to flip a Suspense boundary // from its placeholder state to its primary/resolved state. // Special cases var mode = fiber.mode; if ((mode & ConcurrentMode) === NoMode) { return SyncLane; } return claimNextRetryLane(); } function scheduleUpdateOnFiber(root, fiber, lane, eventTime) { checkForNestedUpdates(); { if (isRunningInsertionEffect) { error('useInsertionEffect must not schedule updates.'); } } { if (isFlushingPassiveEffects) { didScheduleUpdateDuringPassiveEffects = true; } } // Mark that the root has a pending update. markRootUpdated(root, lane, eventTime); if ((executionContext & RenderContext) !== NoLanes && root === workInProgressRoot) { // This update was dispatched during the render phase. This is a mistake // if the update originates from user space (with the exception of local // hook updates, which are handled differently and don't reach this // function), but there are some internal React features that use this as // an implementation detail, like selective hydration. warnAboutRenderPhaseUpdatesInDEV(fiber); // Track lanes that were updated during the render phase } else { // This is a normal update, scheduled from outside the render phase. For // example, during an input event. { if (isDevToolsPresent) { addFiberToLanesMap(root, fiber, lane); } } warnIfUpdatesNotWrappedWithActDEV(fiber); if (root === workInProgressRoot) { // Received an update to a tree that's in the middle of rendering. Mark // that there was an interleaved update work on this root. Unless the // `deferRenderPhaseUpdateToNextBatch` flag is off and this is a render // phase update. In that case, we don't treat render phase updates as if // they were interleaved, for backwards compat reasons. if ( (executionContext & RenderContext) === NoContext) { workInProgressRootInterleavedUpdatedLanes = mergeLanes(workInProgressRootInterleavedUpdatedLanes, lane); } if (workInProgressRootExitStatus === RootSuspendedWithDelay) { // The root already suspended with a delay, which means this render // definitely won't finish. Since we have a new update, let's mark it as // suspended now, right before marking the incoming update. This has the // effect of interrupting the current render and switching to the update. // TODO: Make sure this doesn't override pings that happen while we've // already started rendering. markRootSuspended$1(root, workInProgressRootRenderLanes); } } ensureRootIsScheduled(root, eventTime); if (lane === SyncLane && executionContext === NoContext && (fiber.mode & ConcurrentMode) === NoMode && // Treat `act` as if it's inside `batchedUpdates`, even in legacy mode. !( ReactCurrentActQueue$1.isBatchingLegacy)) { // Flush the synchronous work now, unless we're already working or inside // a batch. This is intentionally inside scheduleUpdateOnFiber instead of // scheduleCallbackForFiber to preserve the ability to schedule a callback // without immediately flushing it. We only do this for user-initiated // updates, to preserve historical behavior of legacy mode. resetRenderTimer(); flushSyncCallbacksOnlyInLegacyMode(); } } } function scheduleInitialHydrationOnRoot(root, lane, eventTime) { // This is a special fork of scheduleUpdateOnFiber that is only used to // schedule the initial hydration of a root that has just been created. Most // of the stuff in scheduleUpdateOnFiber can be skipped. // // The main reason for this separate path, though, is to distinguish the // initial children from subsequent updates. In fully client-rendered roots // (createRoot instead of hydrateRoot), all top-level renders are modeled as // updates, but hydration roots are special because the initial render must // match what was rendered on the server. var current = root.current; current.lanes = lane; markRootUpdated(root, lane, eventTime); ensureRootIsScheduled(root, eventTime); } function isUnsafeClassRenderPhaseUpdate(fiber) { // Check if this is a render phase update. Only called by class components, // which special (deprecated) behavior for UNSAFE_componentWillReceive props. return (// TODO: Remove outdated deferRenderPhaseUpdateToNextBatch experiment. We // decided not to enable it. (executionContext & RenderContext) !== NoContext ); } // Use this function to schedule a task for a root. There's only one task per // root; if a task was already scheduled, we'll check to make sure the priority // of the existing task is the same as the priority of the next level that the // root has work on. This function is called on every update, and right before // exiting a task. function ensureRootIsScheduled(root, currentTime) { var existingCallbackNode = root.callbackNode; // Check if any lanes are being starved by other work. If so, mark them as // expired so we know to work on those next. markStarvedLanesAsExpired(root, currentTime); // Determine the next lanes to work on, and their priority. var nextLanes = getNextLanes(root, root === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes); if (nextLanes === NoLanes) { // Special case: There's nothing to work on. if (existingCallbackNode !== null) { cancelCallback$1(existingCallbackNode); } root.callbackNode = null; root.callbackPriority = NoLane; return; } // We use the highest priority lane to represent the priority of the callback. var newCallbackPriority = getHighestPriorityLane(nextLanes); // Check if there's an existing task. We may be able to reuse it. var existingCallbackPriority = root.callbackPriority; if (existingCallbackPriority === newCallbackPriority && // Special case related to `act`. If the currently scheduled task is a // Scheduler task, rather than an `act` task, cancel it and re-scheduled // on the `act` queue. !( ReactCurrentActQueue$1.current !== null && existingCallbackNode !== fakeActCallbackNode)) { { // If we're going to re-use an existing task, it needs to exist. // Assume that discrete update microtasks are non-cancellable and null. // TODO: Temporary until we confirm this warning is not fired. if (existingCallbackNode == null && existingCallbackPriority !== SyncLane) { error('Expected scheduled callback to exist. This error is likely caused by a bug in React. Please file an issue.'); } } // The priority hasn't changed. We can reuse the existing task. Exit. return; } if (existingCallbackNode != null) { // Cancel the existing callback. We'll schedule a new one below. cancelCallback$1(existingCallbackNode); } // Schedule a new callback. var newCallbackNode; if (newCallbackPriority === SyncLane) { // Special case: Sync React callbacks are scheduled on a special // internal queue if (root.tag === LegacyRoot) { if ( ReactCurrentActQueue$1.isBatchingLegacy !== null) { ReactCurrentActQueue$1.didScheduleLegacyUpdate = true; } scheduleLegacySyncCallback(performSyncWorkOnRoot.bind(null, root)); } else { scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root)); } { // Flush the queue in a microtask. if ( ReactCurrentActQueue$1.current !== null) { // Inside `act`, use our internal `act` queue so that these get flushed // at the end of the current scope even when using the sync version // of `act`. ReactCurrentActQueue$1.current.push(flushSyncCallbacks); } else { scheduleMicrotask(function () { // In Safari, appending an iframe forces microtasks to run. // https://github.com/facebook/react/issues/22459 // We don't support running callbacks in the middle of render // or commit so we need to check against that. if ((executionContext & (RenderContext | CommitContext)) === NoContext) { // Note that this would still prematurely flush the callbacks // if this happens outside render or commit phase (e.g. in an event). flushSyncCallbacks(); } }); } } newCallbackNode = null; } else { var schedulerPriorityLevel; switch (lanesToEventPriority(nextLanes)) { case DiscreteEventPriority: schedulerPriorityLevel = ImmediatePriority; break; case ContinuousEventPriority: schedulerPriorityLevel = UserBlockingPriority; break; case DefaultEventPriority: schedulerPriorityLevel = NormalPriority; break; case IdleEventPriority: schedulerPriorityLevel = IdlePriority; break; default: schedulerPriorityLevel = NormalPriority; break; } newCallbackNode = scheduleCallback$1(schedulerPriorityLevel, performConcurrentWorkOnRoot.bind(null, root)); } root.callbackPriority = newCallbackPriority; root.callbackNode = newCallbackNode; } // This is the entry point for every concurrent task, i.e. anything that // goes through Scheduler. function performConcurrentWorkOnRoot(root, didTimeout) { { resetNestedUpdateFlag(); } // Since we know we're in a React event, we can clear the current // event time. The next update will compute a new event time. currentEventTime = NoTimestamp; currentEventTransitionLane = NoLanes; if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { throw new Error('Should not already be working.'); } // Flush any pending passive effects before deciding which lanes to work on, // in case they schedule additional work. var originalCallbackNode = root.callbackNode; var didFlushPassiveEffects = flushPassiveEffects(); if (didFlushPassiveEffects) { // Something in the passive effect phase may have canceled the current task. // Check if the task node for this root was changed. if (root.callbackNode !== originalCallbackNode) { // The current task was canceled. Exit. We don't need to call // `ensureRootIsScheduled` because the check above implies either that // there's a new task, or that there's no remaining work on this root. return null; } } // Determine the next lanes to work on, using the fields stored // on the root. var lanes = getNextLanes(root, root === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes); if (lanes === NoLanes) { // Defensive coding. This is never expected to happen. return null; } // We disable time-slicing in some cases: if the work has been CPU-bound // for too long ("expired" work, to prevent starvation), or we're in // sync-updates-by-default mode. // TODO: We only check `didTimeout` defensively, to account for a Scheduler // bug we're still investigating. Once the bug in Scheduler is fixed, // we can remove this, since we track expiration ourselves. var shouldTimeSlice = !includesBlockingLane(root, lanes) && !includesExpiredLane(root, lanes) && ( !didTimeout); var exitStatus = shouldTimeSlice ? renderRootConcurrent(root, lanes) : renderRootSync(root, lanes); if (exitStatus !== RootInProgress) { if (exitStatus === RootErrored) { // If something threw an error, try rendering one more time. We'll // render synchronously to block concurrent data mutations, and we'll // includes all pending updates are included. If it still fails after // the second attempt, we'll give up and commit the resulting tree. var errorRetryLanes = getLanesToRetrySynchronouslyOnError(root); if (errorRetryLanes !== NoLanes) { lanes = errorRetryLanes; exitStatus = recoverFromConcurrentError(root, errorRetryLanes); } } if (exitStatus === RootFatalErrored) { var fatalError = workInProgressRootFatalError; prepareFreshStack(root, NoLanes); markRootSuspended$1(root, lanes); ensureRootIsScheduled(root, now()); throw fatalError; } if (exitStatus === RootDidNotComplete) { // The render unwound without completing the tree. This happens in special // cases where need to exit the current render without producing a // consistent tree or committing. // // This should only happen during a concurrent render, not a discrete or // synchronous update. We should have already checked for this when we // unwound the stack. markRootSuspended$1(root, lanes); } else { // The render completed. // Check if this render may have yielded to a concurrent event, and if so, // confirm that any newly rendered stores are consistent. // TODO: It's possible that even a concurrent render may never have yielded // to the main thread, if it was fast enough, or if it expired. We could // skip the consistency check in that case, too. var renderWasConcurrent = !includesBlockingLane(root, lanes); var finishedWork = root.current.alternate; if (renderWasConcurrent && !isRenderConsistentWithExternalStores(finishedWork)) { // A store was mutated in an interleaved event. Render again, // synchronously, to block further mutations. exitStatus = renderRootSync(root, lanes); // We need to check again if something threw if (exitStatus === RootErrored) { var _errorRetryLanes = getLanesToRetrySynchronouslyOnError(root); if (_errorRetryLanes !== NoLanes) { lanes = _errorRetryLanes; exitStatus = recoverFromConcurrentError(root, _errorRetryLanes); // We assume the tree is now consistent because we didn't yield to any // concurrent events. } } if (exitStatus === RootFatalErrored) { var _fatalError = workInProgressRootFatalError; prepareFreshStack(root, NoLanes); markRootSuspended$1(root, lanes); ensureRootIsScheduled(root, now()); throw _fatalError; } } // We now have a consistent tree. The next step is either to commit it, // or, if something suspended, wait to commit it after a timeout. root.finishedWork = finishedWork; root.finishedLanes = lanes; finishConcurrentRender(root, exitStatus, lanes); } } ensureRootIsScheduled(root, now()); if (root.callbackNode === originalCallbackNode) { // The task node scheduled for this root is the same one that's // currently executed. Need to return a continuation. return performConcurrentWorkOnRoot.bind(null, root); } return null; } function recoverFromConcurrentError(root, errorRetryLanes) { // If an error occurred during hydration, discard server response and fall // back to client side render. // Before rendering again, save the errors from the previous attempt. var errorsFromFirstAttempt = workInProgressRootConcurrentErrors; if (isRootDehydrated(root)) { // The shell failed to hydrate. Set a flag to force a client rendering // during the next attempt. To do this, we call prepareFreshStack now // to create the root work-in-progress fiber. This is a bit weird in terms // of factoring, because it relies on renderRootSync not calling // prepareFreshStack again in the call below, which happens because the // root and lanes haven't changed. // // TODO: I think what we should do is set ForceClientRender inside // throwException, like we do for nested Suspense boundaries. The reason // it's here instead is so we can switch to the synchronous work loop, too. // Something to consider for a future refactor. var rootWorkInProgress = prepareFreshStack(root, errorRetryLanes); rootWorkInProgress.flags |= ForceClientRender; { errorHydratingContainer(root.containerInfo); } } var exitStatus = renderRootSync(root, errorRetryLanes); if (exitStatus !== RootErrored) { // Successfully finished rendering on retry // The errors from the failed first attempt have been recovered. Add // them to the collection of recoverable errors. We'll log them in the // commit phase. var errorsFromSecondAttempt = workInProgressRootRecoverableErrors; workInProgressRootRecoverableErrors = errorsFromFirstAttempt; // The errors from the second attempt should be queued after the errors // from the first attempt, to preserve the causal sequence. if (errorsFromSecondAttempt !== null) { queueRecoverableErrors(errorsFromSecondAttempt); } } return exitStatus; } function queueRecoverableErrors(errors) { if (workInProgressRootRecoverableErrors === null) { workInProgressRootRecoverableErrors = errors; } else { workInProgressRootRecoverableErrors.push.apply(workInProgressRootRecoverableErrors, errors); } } function finishConcurrentRender(root, exitStatus, lanes) { switch (exitStatus) { case RootInProgress: case RootFatalErrored: { throw new Error('Root did not complete. This is a bug in React.'); } // Flow knows about invariant, so it complains if I add a break // statement, but eslint doesn't know about invariant, so it complains // if I do. eslint-disable-next-line no-fallthrough case RootErrored: { // We should have already attempted to retry this tree. If we reached // this point, it errored again. Commit it. commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions); break; } case RootSuspended: { markRootSuspended$1(root, lanes); // We have an acceptable loading state. We need to figure out if we // should immediately commit it or wait a bit. if (includesOnlyRetries(lanes) && // do not delay if we're inside an act() scope !shouldForceFlushFallbacksInDEV()) { // This render only included retries, no updates. Throttle committing // retries so that we don't show too many loading states too quickly. var msUntilTimeout = globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now(); // Don't bother with a very short suspense time. if (msUntilTimeout > 10) { var nextLanes = getNextLanes(root, NoLanes); if (nextLanes !== NoLanes) { // There's additional work on this root. break; } var suspendedLanes = root.suspendedLanes; if (!isSubsetOfLanes(suspendedLanes, lanes)) { // We should prefer to render the fallback of at the last // suspended level. Ping the last suspended level to try // rendering it again. // FIXME: What if the suspended lanes are Idle? Should not restart. var eventTime = requestEventTime(); markRootPinged(root, suspendedLanes); break; } // The render is suspended, it hasn't timed out, and there's no // lower priority work to do. Instead of committing the fallback // immediately, wait for more data to arrive. root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root, workInProgressRootRecoverableErrors, workInProgressTransitions), msUntilTimeout); break; } } // The work expired. Commit immediately. commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions); break; } case RootSuspendedWithDelay: { markRootSuspended$1(root, lanes); if (includesOnlyTransitions(lanes)) { // This is a transition, so we should exit without committing a // placeholder and without scheduling a timeout. Delay indefinitely // until we receive more data. break; } if (!shouldForceFlushFallbacksInDEV()) { // This is not a transition, but we did trigger an avoided state. // Schedule a placeholder to display after a short delay, using the Just // Noticeable Difference. // TODO: Is the JND optimization worth the added complexity? If this is // the only reason we track the event time, then probably not. // Consider removing. var mostRecentEventTime = getMostRecentEventTime(root, lanes); var eventTimeMs = mostRecentEventTime; var timeElapsedMs = now() - eventTimeMs; var _msUntilTimeout = jnd(timeElapsedMs) - timeElapsedMs; // Don't bother with a very short suspense time. if (_msUntilTimeout > 10) { // Instead of committing the fallback immediately, wait for more data // to arrive. root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root, workInProgressRootRecoverableErrors, workInProgressTransitions), _msUntilTimeout); break; } } // Commit the placeholder. commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions); break; } case RootCompleted: { // The work completed. Ready to commit. commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions); break; } default: { throw new Error('Unknown root exit status.'); } } } function isRenderConsistentWithExternalStores(finishedWork) { // Search the rendered tree for external store reads, and check whether the // stores were mutated in a concurrent event. Intentionally using an iterative // loop instead of recursion so we can exit early. var node = finishedWork; while (true) { if (node.flags & StoreConsistency) { var updateQueue = node.updateQueue; if (updateQueue !== null) { var checks = updateQueue.stores; if (checks !== null) { for (var i = 0; i < checks.length; i++) { var check = checks[i]; var getSnapshot = check.getSnapshot; var renderedValue = check.value; try { if (!objectIs(getSnapshot(), renderedValue)) { // Found an inconsistent store. return false; } } catch (error) { // If `getSnapshot` throws, return `false`. This will schedule // a re-render, and the error will be rethrown during render. return false; } } } } } var child = node.child; if (node.subtreeFlags & StoreConsistency && child !== null) { child.return = node; node = child; continue; } if (node === finishedWork) { return true; } while (node.sibling === null) { if (node.return === null || node.return === finishedWork) { return true; } node = node.return; } node.sibling.return = node.return; node = node.sibling; } // Flow doesn't know this is unreachable, but eslint does // eslint-disable-next-line no-unreachable return true; } function markRootSuspended$1(root, suspendedLanes) { // When suspending, we should always exclude lanes that were pinged or (more // rarely, since we try to avoid it) updated during the render phase. // TODO: Lol maybe there's a better way to factor this besides this // obnoxiously named function :) suspendedLanes = removeLanes(suspendedLanes, workInProgressRootPingedLanes); suspendedLanes = removeLanes(suspendedLanes, workInProgressRootInterleavedUpdatedLanes); markRootSuspended(root, suspendedLanes); } // This is the entry point for synchronous tasks that don't go // through Scheduler function performSyncWorkOnRoot(root) { { syncNestedUpdateFlag(); } if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { throw new Error('Should not already be working.'); } flushPassiveEffects(); var lanes = getNextLanes(root, NoLanes); if (!includesSomeLane(lanes, SyncLane)) { // There's no remaining sync work left. ensureRootIsScheduled(root, now()); return null; } var exitStatus = renderRootSync(root, lanes); if (root.tag !== LegacyRoot && exitStatus === RootErrored) { // If something threw an error, try rendering one more time. We'll render // synchronously to block concurrent data mutations, and we'll includes // all pending updates are included. If it still fails after the second // attempt, we'll give up and commit the resulting tree. var errorRetryLanes = getLanesToRetrySynchronouslyOnError(root); if (errorRetryLanes !== NoLanes) { lanes = errorRetryLanes; exitStatus = recoverFromConcurrentError(root, errorRetryLanes); } } if (exitStatus === RootFatalErrored) { var fatalError = workInProgressRootFatalError; prepareFreshStack(root, NoLanes); markRootSuspended$1(root, lanes); ensureRootIsScheduled(root, now()); throw fatalError; } if (exitStatus === RootDidNotComplete) { throw new Error('Root did not complete. This is a bug in React.'); } // We now have a consistent tree. Because this is a sync render, we // will commit it even if something suspended. var finishedWork = root.current.alternate; root.finishedWork = finishedWork; root.finishedLanes = lanes; commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions); // Before exiting, make sure there's a callback scheduled for the next // pending level. ensureRootIsScheduled(root, now()); return null; } function flushRoot(root, lanes) { if (lanes !== NoLanes) { markRootEntangled(root, mergeLanes(lanes, SyncLane)); ensureRootIsScheduled(root, now()); if ((executionContext & (RenderContext | CommitContext)) === NoContext) { resetRenderTimer(); flushSyncCallbacks(); } } } function batchedUpdates$1(fn, a) { var prevExecutionContext = executionContext; executionContext |= BatchedContext; try { return fn(a); } finally { executionContext = prevExecutionContext; // If there were legacy sync updates, flush them at the end of the outer // most batchedUpdates-like method. if (executionContext === NoContext && // Treat `act` as if it's inside `batchedUpdates`, even in legacy mode. !( ReactCurrentActQueue$1.isBatchingLegacy)) { resetRenderTimer(); flushSyncCallbacksOnlyInLegacyMode(); } } } function discreteUpdates(fn, a, b, c, d) { var previousPriority = getCurrentUpdatePriority(); var prevTransition = ReactCurrentBatchConfig$3.transition; try { ReactCurrentBatchConfig$3.transition = null; setCurrentUpdatePriority(DiscreteEventPriority); return fn(a, b, c, d); } finally { setCurrentUpdatePriority(previousPriority); ReactCurrentBatchConfig$3.transition = prevTransition; if (executionContext === NoContext) { resetRenderTimer(); } } } // Overload the definition to the two valid signatures. // Warning, this opts-out of checking the function body. // eslint-disable-next-line no-redeclare function flushSync(fn) { // In legacy mode, we flush pending passive effects at the beginning of the // next event, not at the end of the previous one. if (rootWithPendingPassiveEffects !== null && rootWithPendingPassiveEffects.tag === LegacyRoot && (executionContext & (RenderContext | CommitContext)) === NoContext) { flushPassiveEffects(); } var prevExecutionContext = executionContext; executionContext |= BatchedContext; var prevTransition = ReactCurrentBatchConfig$3.transition; var previousPriority = getCurrentUpdatePriority(); try { ReactCurrentBatchConfig$3.transition = null; setCurrentUpdatePriority(DiscreteEventPriority); if (fn) { return fn(); } else { return undefined; } } finally { setCurrentUpdatePriority(previousPriority); ReactCurrentBatchConfig$3.transition = prevTransition; executionContext = prevExecutionContext; // Flush the immediate callbacks that were scheduled during this batch. // Note that this will happen even if batchedUpdates is higher up // the stack. if ((executionContext & (RenderContext | CommitContext)) === NoContext) { flushSyncCallbacks(); } } } function isAlreadyRendering() { // Used by the renderer to print a warning if certain APIs are called from // the wrong context. return (executionContext & (RenderContext | CommitContext)) !== NoContext; } function pushRenderLanes(fiber, lanes) { push(subtreeRenderLanesCursor, subtreeRenderLanes, fiber); subtreeRenderLanes = mergeLanes(subtreeRenderLanes, lanes); workInProgressRootIncludedLanes = mergeLanes(workInProgressRootIncludedLanes, lanes); } function popRenderLanes(fiber) { subtreeRenderLanes = subtreeRenderLanesCursor.current; pop(subtreeRenderLanesCursor, fiber); } function prepareFreshStack(root, lanes) { root.finishedWork = null; root.finishedLanes = NoLanes; var timeoutHandle = root.timeoutHandle; if (timeoutHandle !== noTimeout) { // The root previous suspended and scheduled a timeout to commit a fallback // state. Now that we have additional work, cancel the timeout. root.timeoutHandle = noTimeout; // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above cancelTimeout(timeoutHandle); } if (workInProgress !== null) { var interruptedWork = workInProgress.return; while (interruptedWork !== null) { var current = interruptedWork.alternate; unwindInterruptedWork(current, interruptedWork); interruptedWork = interruptedWork.return; } } workInProgressRoot = root; var rootWorkInProgress = createWorkInProgress(root.current, null); workInProgress = rootWorkInProgress; workInProgressRootRenderLanes = subtreeRenderLanes = workInProgressRootIncludedLanes = lanes; workInProgressRootExitStatus = RootInProgress; workInProgressRootFatalError = null; workInProgressRootSkippedLanes = NoLanes; workInProgressRootInterleavedUpdatedLanes = NoLanes; workInProgressRootPingedLanes = NoLanes; workInProgressRootConcurrentErrors = null; workInProgressRootRecoverableErrors = null; finishQueueingConcurrentUpdates(); { ReactStrictModeWarnings.discardPendingWarnings(); } return rootWorkInProgress; } function handleError(root, thrownValue) { do { var erroredWork = workInProgress; try { // Reset module-level state that was set during the render phase. resetContextDependencies(); resetHooksAfterThrow(); resetCurrentFiber(); // TODO: I found and added this missing line while investigating a // separate issue. Write a regression test using string refs. ReactCurrentOwner$2.current = null; if (erroredWork === null || erroredWork.return === null) { // Expected to be working on a non-root fiber. This is a fatal error // because there's no ancestor that can handle it; the root is // supposed to capture all errors that weren't caught by an error // boundary. workInProgressRootExitStatus = RootFatalErrored; workInProgressRootFatalError = thrownValue; // Set `workInProgress` to null. This represents advancing to the next // sibling, or the parent if there are no siblings. But since the root // has no siblings nor a parent, we set it to null. Usually this is // handled by `completeUnitOfWork` or `unwindWork`, but since we're // intentionally not calling those, we need set it here. // TODO: Consider calling `unwindWork` to pop the contexts. workInProgress = null; return; } if (enableProfilerTimer && erroredWork.mode & ProfileMode) { // Record the time spent rendering before an error was thrown. This // avoids inaccurate Profiler durations in the case of a // suspended render. stopProfilerTimerIfRunningAndRecordDelta(erroredWork, true); } if (enableSchedulingProfiler) { markComponentRenderStopped(); if (thrownValue !== null && typeof thrownValue === 'object' && typeof thrownValue.then === 'function') { var wakeable = thrownValue; markComponentSuspended(erroredWork, wakeable, workInProgressRootRenderLanes); } else { markComponentErrored(erroredWork, thrownValue, workInProgressRootRenderLanes); } } throwException(root, erroredWork.return, erroredWork, thrownValue, workInProgressRootRenderLanes); completeUnitOfWork(erroredWork); } catch (yetAnotherThrownValue) { // Something in the return path also threw. thrownValue = yetAnotherThrownValue; if (workInProgress === erroredWork && erroredWork !== null) { // If this boundary has already errored, then we had trouble processing // the error. Bubble it to the next boundary. erroredWork = erroredWork.return; workInProgress = erroredWork; } else { erroredWork = workInProgress; } continue; } // Return to the normal work loop. return; } while (true); } function pushDispatcher() { var prevDispatcher = ReactCurrentDispatcher$2.current; ReactCurrentDispatcher$2.current = ContextOnlyDispatcher; if (prevDispatcher === null) { // The React isomorphic package does not include a default dispatcher. // Instead the first renderer will lazily attach one, in order to give // nicer error messages. return ContextOnlyDispatcher; } else { return prevDispatcher; } } function popDispatcher(prevDispatcher) { ReactCurrentDispatcher$2.current = prevDispatcher; } function markCommitTimeOfFallback() { globalMostRecentFallbackTime = now(); } function markSkippedUpdateLanes(lane) { workInProgressRootSkippedLanes = mergeLanes(lane, workInProgressRootSkippedLanes); } function renderDidSuspend() { if (workInProgressRootExitStatus === RootInProgress) { workInProgressRootExitStatus = RootSuspended; } } function renderDidSuspendDelayIfPossible() { if (workInProgressRootExitStatus === RootInProgress || workInProgressRootExitStatus === RootSuspended || workInProgressRootExitStatus === RootErrored) { workInProgressRootExitStatus = RootSuspendedWithDelay; } // Check if there are updates that we skipped tree that might have unblocked // this render. if (workInProgressRoot !== null && (includesNonIdleWork(workInProgressRootSkippedLanes) || includesNonIdleWork(workInProgressRootInterleavedUpdatedLanes))) { // Mark the current render as suspended so that we switch to working on // the updates that were skipped. Usually we only suspend at the end of // the render phase. // TODO: We should probably always mark the root as suspended immediately // (inside this function), since by suspending at the end of the render // phase introduces a potential mistake where we suspend lanes that were // pinged or updated while we were rendering. markRootSuspended$1(workInProgressRoot, workInProgressRootRenderLanes); } } function renderDidError(error) { if (workInProgressRootExitStatus !== RootSuspendedWithDelay) { workInProgressRootExitStatus = RootErrored; } if (workInProgressRootConcurrentErrors === null) { workInProgressRootConcurrentErrors = [error]; } else { workInProgressRootConcurrentErrors.push(error); } } // Called during render to determine if anything has suspended. // Returns false if we're not sure. function renderHasNotSuspendedYet() { // If something errored or completed, we can't really be sure, // so those are false. return workInProgressRootExitStatus === RootInProgress; } function renderRootSync(root, lanes) { var prevExecutionContext = executionContext; executionContext |= RenderContext; var prevDispatcher = pushDispatcher(); // If the root or lanes have changed, throw out the existing stack // and prepare a fresh one. Otherwise we'll continue where we left off. if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) { { if (isDevToolsPresent) { var memoizedUpdaters = root.memoizedUpdaters; if (memoizedUpdaters.size > 0) { restorePendingUpdaters(root, workInProgressRootRenderLanes); memoizedUpdaters.clear(); } // At this point, move Fibers that scheduled the upcoming work from the Map to the Set. // If we bailout on this work, we'll move them back (like above). // It's important to move them now in case the work spawns more work at the same priority with different updaters. // That way we can keep the current update and future updates separate. movePendingFibersToMemoized(root, lanes); } } workInProgressTransitions = getTransitionsForLanes(); prepareFreshStack(root, lanes); } { markRenderStarted(lanes); } do { try { workLoopSync(); break; } catch (thrownValue) { handleError(root, thrownValue); } } while (true); resetContextDependencies(); executionContext = prevExecutionContext; popDispatcher(prevDispatcher); if (workInProgress !== null) { // This is a sync render, so we should have finished the whole tree. throw new Error('Cannot commit an incomplete root. This error is likely caused by a ' + 'bug in React. Please file an issue.'); } { markRenderStopped(); } // Set this to null to indicate there's no in-progress render. workInProgressRoot = null; workInProgressRootRenderLanes = NoLanes; return workInProgressRootExitStatus; } // The work loop is an extremely hot path. Tell Closure not to inline it. /** @noinline */ function workLoopSync() { // Already timed out, so perform work without checking if we need to yield. while (workInProgress !== null) { performUnitOfWork(workInProgress); } } function renderRootConcurrent(root, lanes) { var prevExecutionContext = executionContext; executionContext |= RenderContext; var prevDispatcher = pushDispatcher(); // If the root or lanes have changed, throw out the existing stack // and prepare a fresh one. Otherwise we'll continue where we left off. if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) { { if (isDevToolsPresent) { var memoizedUpdaters = root.memoizedUpdaters; if (memoizedUpdaters.size > 0) { restorePendingUpdaters(root, workInProgressRootRenderLanes); memoizedUpdaters.clear(); } // At this point, move Fibers that scheduled the upcoming work from the Map to the Set. // If we bailout on this work, we'll move them back (like above). // It's important to move them now in case the work spawns more work at the same priority with different updaters. // That way we can keep the current update and future updates separate. movePendingFibersToMemoized(root, lanes); } } workInProgressTransitions = getTransitionsForLanes(); resetRenderTimer(); prepareFreshStack(root, lanes); } { markRenderStarted(lanes); } do { try { workLoopConcurrent(); break; } catch (thrownValue) { handleError(root, thrownValue); } } while (true); resetContextDependencies(); popDispatcher(prevDispatcher); executionContext = prevExecutionContext; if (workInProgress !== null) { // Still work remaining. { markRenderYielded(); } return RootInProgress; } else { // Completed the tree. { markRenderStopped(); } // Set this to null to indicate there's no in-progress render. workInProgressRoot = null; workInProgressRootRenderLanes = NoLanes; // Return the final exit status. return workInProgressRootExitStatus; } } /** @noinline */ function workLoopConcurrent() { // Perform work until Scheduler asks us to yield while (workInProgress !== null && !shouldYield()) { performUnitOfWork(workInProgress); } } function performUnitOfWork(unitOfWork) { // The current, flushed, state of this fiber is the alternate. Ideally // nothing should rely on this, but relying on it here means that we don't // need an additional field on the work in progress. var current = unitOfWork.alternate; setCurrentFiber(unitOfWork); var next; if ( (unitOfWork.mode & ProfileMode) !== NoMode) { startProfilerTimer(unitOfWork); next = beginWork$1(current, unitOfWork, subtreeRenderLanes); stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true); } else { next = beginWork$1(current, unitOfWork, subtreeRenderLanes); } resetCurrentFiber(); unitOfWork.memoizedProps = unitOfWork.pendingProps; if (next === null) { // If this doesn't spawn new work, complete the current work. completeUnitOfWork(unitOfWork); } else { workInProgress = next; } ReactCurrentOwner$2.current = null; } function completeUnitOfWork(unitOfWork) { // Attempt to complete the current unit of work, then move to the next // sibling. If there are no more siblings, return to the parent fiber. var completedWork = unitOfWork; do { // The current, flushed, state of this fiber is the alternate. Ideally // nothing should rely on this, but relying on it here means that we don't // need an additional field on the work in progress. var current = completedWork.alternate; var returnFiber = completedWork.return; // Check if the work completed or if something threw. if ((completedWork.flags & Incomplete) === NoFlags) { setCurrentFiber(completedWork); var next = void 0; if ( (completedWork.mode & ProfileMode) === NoMode) { next = completeWork(current, completedWork, subtreeRenderLanes); } else { startProfilerTimer(completedWork); next = completeWork(current, completedWork, subtreeRenderLanes); // Update render duration assuming we didn't error. stopProfilerTimerIfRunningAndRecordDelta(completedWork, false); } resetCurrentFiber(); if (next !== null) { // Completing this fiber spawned new work. Work on that next. workInProgress = next; return; } } else { // This fiber did not complete because something threw. Pop values off // the stack without entering the complete phase. If this is a boundary, // capture values if possible. var _next = unwindWork(current, completedWork); // Because this fiber did not complete, don't reset its lanes. if (_next !== null) { // If completing this work spawned new work, do that next. We'll come // back here again. // Since we're restarting, remove anything that is not a host effect // from the effect tag. _next.flags &= HostEffectMask; workInProgress = _next; return; } if ( (completedWork.mode & ProfileMode) !== NoMode) { // Record the render duration for the fiber that errored. stopProfilerTimerIfRunningAndRecordDelta(completedWork, false); // Include the time spent working on failed children before continuing. var actualDuration = completedWork.actualDuration; var child = completedWork.child; while (child !== null) { actualDuration += child.actualDuration; child = child.sibling; } completedWork.actualDuration = actualDuration; } if (returnFiber !== null) { // Mark the parent fiber as incomplete and clear its subtree flags. returnFiber.flags |= Incomplete; returnFiber.subtreeFlags = NoFlags; returnFiber.deletions = null; } else { // We've unwound all the way to the root. workInProgressRootExitStatus = RootDidNotComplete; workInProgress = null; return; } } var siblingFiber = completedWork.sibling; if (siblingFiber !== null) { // If there is more work to do in this returnFiber, do that next. workInProgress = siblingFiber; return; } // Otherwise, return to the parent completedWork = returnFiber; // Update the next thing we're working on in case something throws. workInProgress = completedWork; } while (completedWork !== null); // We've reached the root. if (workInProgressRootExitStatus === RootInProgress) { workInProgressRootExitStatus = RootCompleted; } } function commitRoot(root, recoverableErrors, transitions) { // TODO: This no longer makes any sense. We already wrap the mutation and // layout phases. Should be able to remove. var previousUpdateLanePriority = getCurrentUpdatePriority(); var prevTransition = ReactCurrentBatchConfig$3.transition; try { ReactCurrentBatchConfig$3.transition = null; setCurrentUpdatePriority(DiscreteEventPriority); commitRootImpl(root, recoverableErrors, transitions, previousUpdateLanePriority); } finally { ReactCurrentBatchConfig$3.transition = prevTransition; setCurrentUpdatePriority(previousUpdateLanePriority); } return null; } function commitRootImpl(root, recoverableErrors, transitions, renderPriorityLevel) { do { // `flushPassiveEffects` will call `flushSyncUpdateQueue` at the end, which // means `flushPassiveEffects` will sometimes result in additional // passive effects. So we need to keep flushing in a loop until there are // no more pending effects. // TODO: Might be better if `flushPassiveEffects` did not automatically // flush synchronous work at the end, to avoid factoring hazards like this. flushPassiveEffects(); } while (rootWithPendingPassiveEffects !== null); flushRenderPhaseStrictModeWarningsInDEV(); if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { throw new Error('Should not already be working.'); } var finishedWork = root.finishedWork; var lanes = root.finishedLanes; { markCommitStarted(lanes); } if (finishedWork === null) { { markCommitStopped(); } return null; } else { { if (lanes === NoLanes) { error('root.finishedLanes should not be empty during a commit. This is a ' + 'bug in React.'); } } } root.finishedWork = null; root.finishedLanes = NoLanes; if (finishedWork === root.current) { throw new Error('Cannot commit the same tree as before. This error is likely caused by ' + 'a bug in React. Please file an issue.'); } // commitRoot never returns a continuation; it always finishes synchronously. // So we can clear these now to allow a new callback to be scheduled. root.callbackNode = null; root.callbackPriority = NoLane; // Update the first and last pending times on this root. The new first // pending time is whatever is left on the root fiber. var remainingLanes = mergeLanes(finishedWork.lanes, finishedWork.childLanes); markRootFinished(root, remainingLanes); if (root === workInProgressRoot) { // We can reset these now that they are finished. workInProgressRoot = null; workInProgress = null; workInProgressRootRenderLanes = NoLanes; } // If there are pending passive effects, schedule a callback to process them. // Do this as early as possible, so it is queued before anything else that // might get scheduled in the commit phase. (See #16714.) // TODO: Delete all other places that schedule the passive effect callback // They're redundant. if ((finishedWork.subtreeFlags & PassiveMask) !== NoFlags || (finishedWork.flags & PassiveMask) !== NoFlags) { if (!rootDoesHavePassiveEffects) { rootDoesHavePassiveEffects = true; // to store it in pendingPassiveTransitions until they get processed // We need to pass this through as an argument to commitRoot // because workInProgressTransitions might have changed between // the previous render and commit if we throttle the commit // with setTimeout pendingPassiveTransitions = transitions; scheduleCallback$1(NormalPriority, function () { flushPassiveEffects(); // This render triggered passive effects: release the root cache pool // *after* passive effects fire to avoid freeing a cache pool that may // be referenced by a node in the tree (HostRoot, Cache boundary etc) return null; }); } } // Check if there are any effects in the whole tree. // TODO: This is left over from the effect list implementation, where we had // to check for the existence of `firstEffect` to satisfy Flow. I think the // only other reason this optimization exists is because it affects profiling. // Reconsider whether this is necessary. var subtreeHasEffects = (finishedWork.subtreeFlags & (BeforeMutationMask | MutationMask | LayoutMask | PassiveMask)) !== NoFlags; var rootHasEffect = (finishedWork.flags & (BeforeMutationMask | MutationMask | LayoutMask | PassiveMask)) !== NoFlags; if (subtreeHasEffects || rootHasEffect) { var prevTransition = ReactCurrentBatchConfig$3.transition; ReactCurrentBatchConfig$3.transition = null; var previousPriority = getCurrentUpdatePriority(); setCurrentUpdatePriority(DiscreteEventPriority); var prevExecutionContext = executionContext; executionContext |= CommitContext; // Reset this to null before calling lifecycles ReactCurrentOwner$2.current = null; // The commit phase is broken into several sub-phases. We do a separate pass // of the effect list for each phase: all mutation effects come before all // layout effects, and so on. // The first phase a "before mutation" phase. We use this phase to read the // state of the host tree right before we mutate it. This is where // getSnapshotBeforeUpdate is called. var shouldFireAfterActiveInstanceBlur = commitBeforeMutationEffects(root, finishedWork); { // Mark the current commit time to be shared by all Profilers in this // batch. This enables them to be grouped later. recordCommitTime(); } commitMutationEffects(root, finishedWork, lanes); resetAfterCommit(root.containerInfo); // The work-in-progress tree is now the current tree. This must come after // the mutation phase, so that the previous tree is still current during // componentWillUnmount, but before the layout phase, so that the finished // work is current during componentDidMount/Update. root.current = finishedWork; // The next phase is the layout phase, where we call effects that read { markLayoutEffectsStarted(lanes); } commitLayoutEffects(finishedWork, root, lanes); { markLayoutEffectsStopped(); } // opportunity to paint. requestPaint(); executionContext = prevExecutionContext; // Reset the priority to the previous non-sync value. setCurrentUpdatePriority(previousPriority); ReactCurrentBatchConfig$3.transition = prevTransition; } else { // No effects. root.current = finishedWork; // Measure these anyway so the flamegraph explicitly shows that there were // no effects. // TODO: Maybe there's a better way to report this. { recordCommitTime(); } } var rootDidHavePassiveEffects = rootDoesHavePassiveEffects; if (rootDoesHavePassiveEffects) { // This commit has passive effects. Stash a reference to them. But don't // schedule a callback until after flushing layout work. rootDoesHavePassiveEffects = false; rootWithPendingPassiveEffects = root; pendingPassiveEffectsLanes = lanes; } else { { nestedPassiveUpdateCount = 0; rootWithPassiveNestedUpdates = null; } } // Read this again, since an effect might have updated it remainingLanes = root.pendingLanes; // Check if there's remaining work on this root // TODO: This is part of the `componentDidCatch` implementation. Its purpose // is to detect whether something might have called setState inside // `componentDidCatch`. The mechanism is known to be flawed because `setState` // inside `componentDidCatch` is itself flawed — that's why we recommend // `getDerivedStateFromError` instead. However, it could be improved by // checking if remainingLanes includes Sync work, instead of whether there's // any work remaining at all (which would also include stuff like Suspense // retries or transitions). It's been like this for a while, though, so fixing // it probably isn't that urgent. if (remainingLanes === NoLanes) { // If there's no remaining work, we can clear the set of already failed // error boundaries. legacyErrorBoundariesThatAlreadyFailed = null; } { if (!rootDidHavePassiveEffects) { commitDoubleInvokeEffectsInDEV(root.current, false); } } onCommitRoot(finishedWork.stateNode, renderPriorityLevel); { if (isDevToolsPresent) { root.memoizedUpdaters.clear(); } } { onCommitRoot$1(); } // Always call this before exiting `commitRoot`, to ensure that any // additional work on this root is scheduled. ensureRootIsScheduled(root, now()); if (recoverableErrors !== null) { // There were errors during this render, but recovered from them without // needing to surface it to the UI. We log them here. var onRecoverableError = root.onRecoverableError; for (var i = 0; i < recoverableErrors.length; i++) { var recoverableError = recoverableErrors[i]; var componentStack = recoverableError.stack; var digest = recoverableError.digest; onRecoverableError(recoverableError.value, { componentStack: componentStack, digest: digest }); } } if (hasUncaughtError) { hasUncaughtError = false; var error$1 = firstUncaughtError; firstUncaughtError = null; throw error$1; } // If the passive effects are the result of a discrete render, flush them // synchronously at the end of the current task so that the result is // immediately observable. Otherwise, we assume that they are not // order-dependent and do not need to be observed by external systems, so we // can wait until after paint. // TODO: We can optimize this by not scheduling the callback earlier. Since we // currently schedule the callback in multiple places, will wait until those // are consolidated. if (includesSomeLane(pendingPassiveEffectsLanes, SyncLane) && root.tag !== LegacyRoot) { flushPassiveEffects(); } // Read this again, since a passive effect might have updated it remainingLanes = root.pendingLanes; if (includesSomeLane(remainingLanes, SyncLane)) { { markNestedUpdateScheduled(); } // Count the number of times the root synchronously re-renders without // finishing. If there are too many, it indicates an infinite update loop. if (root === rootWithNestedUpdates) { nestedUpdateCount++; } else { nestedUpdateCount = 0; rootWithNestedUpdates = root; } } else { nestedUpdateCount = 0; } // If layout work was scheduled, flush it now. flushSyncCallbacks(); { markCommitStopped(); } return null; } function flushPassiveEffects() { // Returns whether passive effects were flushed. // TODO: Combine this check with the one in flushPassiveEFfectsImpl. We should // probably just combine the two functions. I believe they were only separate // in the first place because we used to wrap it with // `Scheduler.runWithPriority`, which accepts a function. But now we track the // priority within React itself, so we can mutate the variable directly. if (rootWithPendingPassiveEffects !== null) { var renderPriority = lanesToEventPriority(pendingPassiveEffectsLanes); var priority = lowerEventPriority(DefaultEventPriority, renderPriority); var prevTransition = ReactCurrentBatchConfig$3.transition; var previousPriority = getCurrentUpdatePriority(); try { ReactCurrentBatchConfig$3.transition = null; setCurrentUpdatePriority(priority); return flushPassiveEffectsImpl(); } finally { setCurrentUpdatePriority(previousPriority); ReactCurrentBatchConfig$3.transition = prevTransition; // Once passive effects have run for the tree - giving components a } } return false; } function enqueuePendingPassiveProfilerEffect(fiber) { { pendingPassiveProfilerEffects.push(fiber); if (!rootDoesHavePassiveEffects) { rootDoesHavePassiveEffects = true; scheduleCallback$1(NormalPriority, function () { flushPassiveEffects(); return null; }); } } } function flushPassiveEffectsImpl() { if (rootWithPendingPassiveEffects === null) { return false; } // Cache and clear the transitions flag var transitions = pendingPassiveTransitions; pendingPassiveTransitions = null; var root = rootWithPendingPassiveEffects; var lanes = pendingPassiveEffectsLanes; rootWithPendingPassiveEffects = null; // TODO: This is sometimes out of sync with rootWithPendingPassiveEffects. // Figure out why and fix it. It's not causing any known issues (probably // because it's only used for profiling), but it's a refactor hazard. pendingPassiveEffectsLanes = NoLanes; if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { throw new Error('Cannot flush passive effects while already rendering.'); } { isFlushingPassiveEffects = true; didScheduleUpdateDuringPassiveEffects = false; } { markPassiveEffectsStarted(lanes); } var prevExecutionContext = executionContext; executionContext |= CommitContext; commitPassiveUnmountEffects(root.current); commitPassiveMountEffects(root, root.current, lanes, transitions); // TODO: Move to commitPassiveMountEffects { var profilerEffects = pendingPassiveProfilerEffects; pendingPassiveProfilerEffects = []; for (var i = 0; i < profilerEffects.length; i++) { var _fiber = profilerEffects[i]; commitPassiveEffectDurations(root, _fiber); } } { markPassiveEffectsStopped(); } { commitDoubleInvokeEffectsInDEV(root.current, true); } executionContext = prevExecutionContext; flushSyncCallbacks(); { // If additional passive effects were scheduled, increment a counter. If this // exceeds the limit, we'll fire a warning. if (didScheduleUpdateDuringPassiveEffects) { if (root === rootWithPassiveNestedUpdates) { nestedPassiveUpdateCount++; } else { nestedPassiveUpdateCount = 0; rootWithPassiveNestedUpdates = root; } } else { nestedPassiveUpdateCount = 0; } isFlushingPassiveEffects = false; didScheduleUpdateDuringPassiveEffects = false; } // TODO: Move to commitPassiveMountEffects onPostCommitRoot(root); { var stateNode = root.current.stateNode; stateNode.effectDuration = 0; stateNode.passiveEffectDuration = 0; } return true; } function isAlreadyFailedLegacyErrorBoundary(instance) { return legacyErrorBoundariesThatAlreadyFailed !== null && legacyErrorBoundariesThatAlreadyFailed.has(instance); } function markLegacyErrorBoundaryAsFailed(instance) { if (legacyErrorBoundariesThatAlreadyFailed === null) { legacyErrorBoundariesThatAlreadyFailed = new Set([instance]); } else { legacyErrorBoundariesThatAlreadyFailed.add(instance); } } function prepareToThrowUncaughtError(error) { if (!hasUncaughtError) { hasUncaughtError = true; firstUncaughtError = error; } } var onUncaughtError = prepareToThrowUncaughtError; function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) { var errorInfo = createCapturedValueAtFiber(error, sourceFiber); var update = createRootErrorUpdate(rootFiber, errorInfo, SyncLane); var root = enqueueUpdate(rootFiber, update, SyncLane); var eventTime = requestEventTime(); if (root !== null) { markRootUpdated(root, SyncLane, eventTime); ensureRootIsScheduled(root, eventTime); } } function captureCommitPhaseError(sourceFiber, nearestMountedAncestor, error$1) { { reportUncaughtErrorInDEV(error$1); setIsRunningInsertionEffect(false); } if (sourceFiber.tag === HostRoot) { // Error was thrown at the root. There is no parent, so the root // itself should capture it. captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error$1); return; } var fiber = null; { fiber = nearestMountedAncestor; } while (fiber !== null) { if (fiber.tag === HostRoot) { captureCommitPhaseErrorOnRoot(fiber, sourceFiber, error$1); return; } else if (fiber.tag === ClassComponent) { var ctor = fiber.type; var instance = fiber.stateNode; if (typeof ctor.getDerivedStateFromError === 'function' || typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance)) { var errorInfo = createCapturedValueAtFiber(error$1, sourceFiber); var update = createClassErrorUpdate(fiber, errorInfo, SyncLane); var root = enqueueUpdate(fiber, update, SyncLane); var eventTime = requestEventTime(); if (root !== null) { markRootUpdated(root, SyncLane, eventTime); ensureRootIsScheduled(root, eventTime); } return; } } fiber = fiber.return; } { // TODO: Until we re-land skipUnmountedBoundaries (see #20147), this warning // will fire for errors that are thrown by destroy functions inside deleted // trees. What it should instead do is propagate the error to the parent of // the deleted tree. In the meantime, do not add this warning to the // allowlist; this is only for our internal use. error('Internal React error: Attempted to capture a commit phase error ' + 'inside a detached tree. This indicates a bug in React. Likely ' + 'causes include deleting the same fiber more than once, committing an ' + 'already-finished tree, or an inconsistent return pointer.\n\n' + 'Error message:\n\n%s', error$1); } } function pingSuspendedRoot(root, wakeable, pingedLanes) { var pingCache = root.pingCache; if (pingCache !== null) { // The wakeable resolved, so we no longer need to memoize, because it will // never be thrown again. pingCache.delete(wakeable); } var eventTime = requestEventTime(); markRootPinged(root, pingedLanes); warnIfSuspenseResolutionNotWrappedWithActDEV(root); if (workInProgressRoot === root && isSubsetOfLanes(workInProgressRootRenderLanes, pingedLanes)) { // Received a ping at the same priority level at which we're currently // rendering. We might want to restart this render. This should mirror // the logic of whether or not a root suspends once it completes. // TODO: If we're rendering sync either due to Sync, Batched or expired, // we should probably never restart. // If we're suspended with delay, or if it's a retry, we'll always suspend // so we can always restart. if (workInProgressRootExitStatus === RootSuspendedWithDelay || workInProgressRootExitStatus === RootSuspended && includesOnlyRetries(workInProgressRootRenderLanes) && now() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS) { // Restart from the root. prepareFreshStack(root, NoLanes); } else { // Even though we can't restart right now, we might get an // opportunity later. So we mark this render as having a ping. workInProgressRootPingedLanes = mergeLanes(workInProgressRootPingedLanes, pingedLanes); } } ensureRootIsScheduled(root, eventTime); } function retryTimedOutBoundary(boundaryFiber, retryLane) { // The boundary fiber (a Suspense component or SuspenseList component) // previously was rendered in its fallback state. One of the promises that // suspended it has resolved, which means at least part of the tree was // likely unblocked. Try rendering again, at a new lanes. if (retryLane === NoLane) { // TODO: Assign this to `suspenseState.retryLane`? to avoid // unnecessary entanglement? retryLane = requestRetryLane(boundaryFiber); } // TODO: Special case idle priority? var eventTime = requestEventTime(); var root = enqueueConcurrentRenderForLane(boundaryFiber, retryLane); if (root !== null) { markRootUpdated(root, retryLane, eventTime); ensureRootIsScheduled(root, eventTime); } } function retryDehydratedSuspenseBoundary(boundaryFiber) { var suspenseState = boundaryFiber.memoizedState; var retryLane = NoLane; if (suspenseState !== null) { retryLane = suspenseState.retryLane; } retryTimedOutBoundary(boundaryFiber, retryLane); } function resolveRetryWakeable(boundaryFiber, wakeable) { var retryLane = NoLane; // Default var retryCache; switch (boundaryFiber.tag) { case SuspenseComponent: retryCache = boundaryFiber.stateNode; var suspenseState = boundaryFiber.memoizedState; if (suspenseState !== null) { retryLane = suspenseState.retryLane; } break; case SuspenseListComponent: retryCache = boundaryFiber.stateNode; break; default: throw new Error('Pinged unknown suspense boundary type. ' + 'This is probably a bug in React.'); } if (retryCache !== null) { // The wakeable resolved, so we no longer need to memoize, because it will // never be thrown again. retryCache.delete(wakeable); } retryTimedOutBoundary(boundaryFiber, retryLane); } // Computes the next Just Noticeable Difference (JND) boundary. // The theory is that a person can't tell the difference between small differences in time. // Therefore, if we wait a bit longer than necessary that won't translate to a noticeable // difference in the experience. However, waiting for longer might mean that we can avoid // showing an intermediate loading state. The longer we have already waited, the harder it // is to tell small differences in time. Therefore, the longer we've already waited, // the longer we can wait additionally. At some point we have to give up though. // We pick a train model where the next boundary commits at a consistent schedule. // These particular numbers are vague estimates. We expect to adjust them based on research. function jnd(timeElapsed) { return timeElapsed < 120 ? 120 : timeElapsed < 480 ? 480 : timeElapsed < 1080 ? 1080 : timeElapsed < 1920 ? 1920 : timeElapsed < 3000 ? 3000 : timeElapsed < 4320 ? 4320 : ceil(timeElapsed / 1960) * 1960; } function checkForNestedUpdates() { if (nestedUpdateCount > NESTED_UPDATE_LIMIT) { nestedUpdateCount = 0; rootWithNestedUpdates = null; throw new Error('Maximum update depth exceeded. This can happen when a component ' + 'repeatedly calls setState inside componentWillUpdate or ' + 'componentDidUpdate. React limits the number of nested updates to ' + 'prevent infinite loops.'); } { if (nestedPassiveUpdateCount > NESTED_PASSIVE_UPDATE_LIMIT) { nestedPassiveUpdateCount = 0; rootWithPassiveNestedUpdates = null; error('Maximum update depth exceeded. This can happen when a component ' + "calls setState inside useEffect, but useEffect either doesn't " + 'have a dependency array, or one of the dependencies changes on ' + 'every render.'); } } } function flushRenderPhaseStrictModeWarningsInDEV() { { ReactStrictModeWarnings.flushLegacyContextWarning(); { ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings(); } } } function commitDoubleInvokeEffectsInDEV(fiber, hasPassiveEffects) { { // TODO (StrictEffects) Should we set a marker on the root if it contains strict effects // so we don't traverse unnecessarily? similar to subtreeFlags but just at the root level. // Maybe not a big deal since this is DEV only behavior. setCurrentFiber(fiber); invokeEffectsInDev(fiber, MountLayoutDev, invokeLayoutEffectUnmountInDEV); if (hasPassiveEffects) { invokeEffectsInDev(fiber, MountPassiveDev, invokePassiveEffectUnmountInDEV); } invokeEffectsInDev(fiber, MountLayoutDev, invokeLayoutEffectMountInDEV); if (hasPassiveEffects) { invokeEffectsInDev(fiber, MountPassiveDev, invokePassiveEffectMountInDEV); } resetCurrentFiber(); } } function invokeEffectsInDev(firstChild, fiberFlags, invokeEffectFn) { { // We don't need to re-check StrictEffectsMode here. // This function is only called if that check has already passed. var current = firstChild; var subtreeRoot = null; while (current !== null) { var primarySubtreeFlag = current.subtreeFlags & fiberFlags; if (current !== subtreeRoot && current.child !== null && primarySubtreeFlag !== NoFlags) { current = current.child; } else { if ((current.flags & fiberFlags) !== NoFlags) { invokeEffectFn(current); } if (current.sibling !== null) { current = current.sibling; } else { current = subtreeRoot = current.return; } } } } } var didWarnStateUpdateForNotYetMountedComponent = null; function warnAboutUpdateOnNotYetMountedFiberInDEV(fiber) { { if ((executionContext & RenderContext) !== NoContext) { // We let the other warning about render phase updates deal with this one. return; } if (!(fiber.mode & ConcurrentMode)) { return; } var tag = fiber.tag; if (tag !== IndeterminateComponent && tag !== HostRoot && tag !== ClassComponent && tag !== FunctionComponent && tag !== ForwardRef && tag !== MemoComponent && tag !== SimpleMemoComponent) { // Only warn for user-defined components, not internal ones like Suspense. return; } // We show the whole stack but dedupe on the top component's name because // the problematic code almost always lies inside that component. var componentName = getComponentNameFromFiber(fiber) || 'ReactComponent'; if (didWarnStateUpdateForNotYetMountedComponent !== null) { if (didWarnStateUpdateForNotYetMountedComponent.has(componentName)) { return; } didWarnStateUpdateForNotYetMountedComponent.add(componentName); } else { didWarnStateUpdateForNotYetMountedComponent = new Set([componentName]); } var previousFiber = current; try { setCurrentFiber(fiber); error("Can't perform a React state update on a component that hasn't mounted yet. " + 'This indicates that you have a side-effect in your render function that ' + 'asynchronously later calls tries to update the component. Move this work to ' + 'useEffect instead.'); } finally { if (previousFiber) { setCurrentFiber(fiber); } else { resetCurrentFiber(); } } } } var beginWork$1; { var dummyFiber = null; beginWork$1 = function (current, unitOfWork, lanes) { // If a component throws an error, we replay it again in a synchronously // dispatched event, so that the debugger will treat it as an uncaught // error See ReactErrorUtils for more information. // Before entering the begin phase, copy the work-in-progress onto a dummy // fiber. If beginWork throws, we'll use this to reset the state. var originalWorkInProgressCopy = assignFiberPropertiesInDEV(dummyFiber, unitOfWork); try { return beginWork(current, unitOfWork, lanes); } catch (originalError) { if (didSuspendOrErrorWhileHydratingDEV() || originalError !== null && typeof originalError === 'object' && typeof originalError.then === 'function') { // Don't replay promises. // Don't replay errors if we are hydrating and have already suspended or handled an error throw originalError; } // Keep this code in sync with handleError; any changes here must have // corresponding changes there. resetContextDependencies(); resetHooksAfterThrow(); // Don't reset current debug fiber, since we're about to work on the // same fiber again. // Unwind the failed stack frame unwindInterruptedWork(current, unitOfWork); // Restore the original properties of the fiber. assignFiberPropertiesInDEV(unitOfWork, originalWorkInProgressCopy); if ( unitOfWork.mode & ProfileMode) { // Reset the profiler timer. startProfilerTimer(unitOfWork); } // Run beginWork again. invokeGuardedCallback(null, beginWork, null, current, unitOfWork, lanes); if (hasCaughtError()) { var replayError = clearCaughtError(); if (typeof replayError === 'object' && replayError !== null && replayError._suppressLogging && typeof originalError === 'object' && originalError !== null && !originalError._suppressLogging) { // If suppressed, let the flag carry over to the original error which is the one we'll rethrow. originalError._suppressLogging = true; } } // We always throw the original error in case the second render pass is not idempotent. // This can happen if a memoized function or CommonJS module doesn't throw after first invocation. throw originalError; } }; } var didWarnAboutUpdateInRender = false; var didWarnAboutUpdateInRenderForAnotherComponent; { didWarnAboutUpdateInRenderForAnotherComponent = new Set(); } function warnAboutRenderPhaseUpdatesInDEV(fiber) { { if (isRendering && !getIsUpdatingOpaqueValueInRenderPhaseInDEV()) { switch (fiber.tag) { case FunctionComponent: case ForwardRef: case SimpleMemoComponent: { var renderingComponentName = workInProgress && getComponentNameFromFiber(workInProgress) || 'Unknown'; // Dedupe by the rendering component because it's the one that needs to be fixed. var dedupeKey = renderingComponentName; if (!didWarnAboutUpdateInRenderForAnotherComponent.has(dedupeKey)) { didWarnAboutUpdateInRenderForAnotherComponent.add(dedupeKey); var setStateComponentName = getComponentNameFromFiber(fiber) || 'Unknown'; error('Cannot update a component (`%s`) while rendering a ' + 'different component (`%s`). To locate the bad setState() call inside `%s`, ' + 'follow the stack trace as described in https://reactjs.org/link/setstate-in-render', setStateComponentName, renderingComponentName, renderingComponentName); } break; } case ClassComponent: { if (!didWarnAboutUpdateInRender) { error('Cannot update during an existing state transition (such as ' + 'within `render`). Render methods should be a pure ' + 'function of props and state.'); didWarnAboutUpdateInRender = true; } break; } } } } } function restorePendingUpdaters(root, lanes) { { if (isDevToolsPresent) { var memoizedUpdaters = root.memoizedUpdaters; memoizedUpdaters.forEach(function (schedulingFiber) { addFiberToLanesMap(root, schedulingFiber, lanes); }); // This function intentionally does not clear memoized updaters. // Those may still be relevant to the current commit // and a future one (e.g. Suspense). } } } var fakeActCallbackNode = {}; function scheduleCallback$1(priorityLevel, callback) { { // If we're currently inside an `act` scope, bypass Scheduler and push to // the `act` queue instead. var actQueue = ReactCurrentActQueue$1.current; if (actQueue !== null) { actQueue.push(callback); return fakeActCallbackNode; } else { return scheduleCallback(priorityLevel, callback); } } } function cancelCallback$1(callbackNode) { if ( callbackNode === fakeActCallbackNode) { return; } // In production, always call Scheduler. This function will be stripped out. return cancelCallback(callbackNode); } function shouldForceFlushFallbacksInDEV() { // Never force flush in production. This function should get stripped out. return ReactCurrentActQueue$1.current !== null; } function warnIfUpdatesNotWrappedWithActDEV(fiber) { { if (fiber.mode & ConcurrentMode) { if (!isConcurrentActEnvironment()) { // Not in an act environment. No need to warn. return; } } else { // Legacy mode has additional cases where we suppress a warning. if (!isLegacyActEnvironment()) { // Not in an act environment. No need to warn. return; } if (executionContext !== NoContext) { // Legacy mode doesn't warn if the update is batched, i.e. // batchedUpdates or flushSync. return; } if (fiber.tag !== FunctionComponent && fiber.tag !== ForwardRef && fiber.tag !== SimpleMemoComponent) { // For backwards compatibility with pre-hooks code, legacy mode only // warns for updates that originate from a hook. return; } } if (ReactCurrentActQueue$1.current === null) { var previousFiber = current; try { setCurrentFiber(fiber); error('An update to %s inside a test was not wrapped in act(...).\n\n' + 'When testing, code that causes React state updates should be ' + 'wrapped into act(...):\n\n' + 'act(() => {\n' + ' /* fire events that update state */\n' + '});\n' + '/* assert on the output */\n\n' + "This ensures that you're testing the behavior the user would see " + 'in the browser.' + ' Learn more at https://reactjs.org/link/wrap-tests-with-act', getComponentNameFromFiber(fiber)); } finally { if (previousFiber) { setCurrentFiber(fiber); } else { resetCurrentFiber(); } } } } } function warnIfSuspenseResolutionNotWrappedWithActDEV(root) { { if (root.tag !== LegacyRoot && isConcurrentActEnvironment() && ReactCurrentActQueue$1.current === null) { error('A suspended resource finished loading inside a test, but the event ' + 'was not wrapped in act(...).\n\n' + 'When testing, code that resolves suspended data should be wrapped ' + 'into act(...):\n\n' + 'act(() => {\n' + ' /* finish loading suspended data */\n' + '});\n' + '/* assert on the output */\n\n' + "This ensures that you're testing the behavior the user would see " + 'in the browser.' + ' Learn more at https://reactjs.org/link/wrap-tests-with-act'); } } } function setIsRunningInsertionEffect(isRunning) { { isRunningInsertionEffect = isRunning; } } /* eslint-disable react-internal/prod-error-codes */ var resolveFamily = null; // $FlowFixMe Flow gets confused by a WeakSet feature check below. var failedBoundaries = null; var setRefreshHandler = function (handler) { { resolveFamily = handler; } }; function resolveFunctionForHotReloading(type) { { if (resolveFamily === null) { // Hot reloading is disabled. return type; } var family = resolveFamily(type); if (family === undefined) { return type; } // Use the latest known implementation. return family.current; } } function resolveClassForHotReloading(type) { // No implementation differences. return resolveFunctionForHotReloading(type); } function resolveForwardRefForHotReloading(type) { { if (resolveFamily === null) { // Hot reloading is disabled. return type; } var family = resolveFamily(type); if (family === undefined) { // Check if we're dealing with a real forwardRef. Don't want to crash early. if (type !== null && type !== undefined && typeof type.render === 'function') { // ForwardRef is special because its resolved .type is an object, // but it's possible that we only have its inner render function in the map. // If that inner render function is different, we'll build a new forwardRef type. var currentRender = resolveFunctionForHotReloading(type.render); if (type.render !== currentRender) { var syntheticType = { $$typeof: REACT_FORWARD_REF_TYPE, render: currentRender }; if (type.displayName !== undefined) { syntheticType.displayName = type.displayName; } return syntheticType; } } return type; } // Use the latest known implementation. return family.current; } } function isCompatibleFamilyForHotReloading(fiber, element) { { if (resolveFamily === null) { // Hot reloading is disabled. return false; } var prevType = fiber.elementType; var nextType = element.type; // If we got here, we know types aren't === equal. var needsCompareFamilies = false; var $$typeofNextType = typeof nextType === 'object' && nextType !== null ? nextType.$$typeof : null; switch (fiber.tag) { case ClassComponent: { if (typeof nextType === 'function') { needsCompareFamilies = true; } break; } case FunctionComponent: { if (typeof nextType === 'function') { needsCompareFamilies = true; } else if ($$typeofNextType === REACT_LAZY_TYPE) { // We don't know the inner type yet. // We're going to assume that the lazy inner type is stable, // and so it is sufficient to avoid reconciling it away. // We're not going to unwrap or actually use the new lazy type. needsCompareFamilies = true; } break; } case ForwardRef: { if ($$typeofNextType === REACT_FORWARD_REF_TYPE) { needsCompareFamilies = true; } else if ($$typeofNextType === REACT_LAZY_TYPE) { needsCompareFamilies = true; } break; } case MemoComponent: case SimpleMemoComponent: { if ($$typeofNextType === REACT_MEMO_TYPE) { // TODO: if it was but can no longer be simple, // we shouldn't set this. needsCompareFamilies = true; } else if ($$typeofNextType === REACT_LAZY_TYPE) { needsCompareFamilies = true; } break; } default: return false; } // Check if both types have a family and it's the same one. if (needsCompareFamilies) { // Note: memo() and forwardRef() we'll compare outer rather than inner type. // This means both of them need to be registered to preserve state. // If we unwrapped and compared the inner types for wrappers instead, // then we would risk falsely saying two separate memo(Foo) // calls are equivalent because they wrap the same Foo function. var prevFamily = resolveFamily(prevType); if (prevFamily !== undefined && prevFamily === resolveFamily(nextType)) { return true; } } return false; } } function markFailedErrorBoundaryForHotReloading(fiber) { { if (resolveFamily === null) { // Hot reloading is disabled. return; } if (typeof WeakSet !== 'function') { return; } if (failedBoundaries === null) { failedBoundaries = new WeakSet(); } failedBoundaries.add(fiber); } } var scheduleRefresh = function (root, update) { { if (resolveFamily === null) { // Hot reloading is disabled. return; } var staleFamilies = update.staleFamilies, updatedFamilies = update.updatedFamilies; flushPassiveEffects(); flushSync(function () { scheduleFibersWithFamiliesRecursively(root.current, updatedFamilies, staleFamilies); }); } }; var scheduleRoot = function (root, element) { { if (root.context !== emptyContextObject) { // Super edge case: root has a legacy _renderSubtree context // but we don't know the parentComponent so we can't pass it. // Just ignore. We'll delete this with _renderSubtree code path later. return; } flushPassiveEffects(); flushSync(function () { updateContainer(element, root, null, null); }); } }; function scheduleFibersWithFamiliesRecursively(fiber, updatedFamilies, staleFamilies) { { var alternate = fiber.alternate, child = fiber.child, sibling = fiber.sibling, tag = fiber.tag, type = fiber.type; var candidateType = null; switch (tag) { case FunctionComponent: case SimpleMemoComponent: case ClassComponent: candidateType = type; break; case ForwardRef: candidateType = type.render; break; } if (resolveFamily === null) { throw new Error('Expected resolveFamily to be set during hot reload.'); } var needsRender = false; var needsRemount = false; if (candidateType !== null) { var family = resolveFamily(candidateType); if (family !== undefined) { if (staleFamilies.has(family)) { needsRemount = true; } else if (updatedFamilies.has(family)) { if (tag === ClassComponent) { needsRemount = true; } else { needsRender = true; } } } } if (failedBoundaries !== null) { if (failedBoundaries.has(fiber) || alternate !== null && failedBoundaries.has(alternate)) { needsRemount = true; } } if (needsRemount) { fiber._debugNeedsRemount = true; } if (needsRemount || needsRender) { var _root = enqueueConcurrentRenderForLane(fiber, SyncLane); if (_root !== null) { scheduleUpdateOnFiber(_root, fiber, SyncLane, NoTimestamp); } } if (child !== null && !needsRemount) { scheduleFibersWithFamiliesRecursively(child, updatedFamilies, staleFamilies); } if (sibling !== null) { scheduleFibersWithFamiliesRecursively(sibling, updatedFamilies, staleFamilies); } } } var findHostInstancesForRefresh = function (root, families) { { var hostInstances = new Set(); var types = new Set(families.map(function (family) { return family.current; })); findHostInstancesForMatchingFibersRecursively(root.current, types, hostInstances); return hostInstances; } }; function findHostInstancesForMatchingFibersRecursively(fiber, types, hostInstances) { { var child = fiber.child, sibling = fiber.sibling, tag = fiber.tag, type = fiber.type; var candidateType = null; switch (tag) { case FunctionComponent: case SimpleMemoComponent: case ClassComponent: candidateType = type; break; case ForwardRef: candidateType = type.render; break; } var didMatch = false; if (candidateType !== null) { if (types.has(candidateType)) { didMatch = true; } } if (didMatch) { // We have a match. This only drills down to the closest host components. // There's no need to search deeper because for the purpose of giving // visual feedback, "flashing" outermost parent rectangles is sufficient. findHostInstancesForFiberShallowly(fiber, hostInstances); } else { // If there's no match, maybe there will be one further down in the child tree. if (child !== null) { findHostInstancesForMatchingFibersRecursively(child, types, hostInstances); } } if (sibling !== null) { findHostInstancesForMatchingFibersRecursively(sibling, types, hostInstances); } } } function findHostInstancesForFiberShallowly(fiber, hostInstances) { { var foundHostInstances = findChildHostInstancesForFiberShallowly(fiber, hostInstances); if (foundHostInstances) { return; } // If we didn't find any host children, fallback to closest host parent. var node = fiber; while (true) { switch (node.tag) { case HostComponent: hostInstances.add(node.stateNode); return; case HostPortal: hostInstances.add(node.stateNode.containerInfo); return; case HostRoot: hostInstances.add(node.stateNode.containerInfo); return; } if (node.return === null) { throw new Error('Expected to reach root first.'); } node = node.return; } } } function findChildHostInstancesForFiberShallowly(fiber, hostInstances) { { var node = fiber; var foundHostInstances = false; while (true) { if (node.tag === HostComponent) { // We got a match. foundHostInstances = true; hostInstances.add(node.stateNode); // There may still be more, so keep searching. } else if (node.child !== null) { node.child.return = node; node = node.child; continue; } if (node === fiber) { return foundHostInstances; } while (node.sibling === null) { if (node.return === null || node.return === fiber) { return foundHostInstances; } node = node.return; } node.sibling.return = node.return; node = node.sibling; } } return false; } var hasBadMapPolyfill; { hasBadMapPolyfill = false; try { var nonExtensibleObject = Object.preventExtensions({}); /* eslint-disable no-new */ new Map([[nonExtensibleObject, null]]); new Set([nonExtensibleObject]); /* eslint-enable no-new */ } catch (e) { // TODO: Consider warning about bad polyfills hasBadMapPolyfill = true; } } function FiberNode(tag, pendingProps, key, mode) { // Instance this.tag = tag; this.key = key; this.elementType = null; this.type = null; this.stateNode = null; // Fiber this.return = null; this.child = null; this.sibling = null; this.index = 0; this.ref = null; this.pendingProps = pendingProps; this.memoizedProps = null; this.updateQueue = null; this.memoizedState = null; this.dependencies = null; this.mode = mode; // Effects this.flags = NoFlags; this.subtreeFlags = NoFlags; this.deletions = null; this.lanes = NoLanes; this.childLanes = NoLanes; this.alternate = null; { // Note: The following is done to avoid a v8 performance cliff. // // Initializing the fields below to smis and later updating them with // double values will cause Fibers to end up having separate shapes. // This behavior/bug has something to do with Object.preventExtension(). // Fortunately this only impacts DEV builds. // Unfortunately it makes React unusably slow for some applications. // To work around this, initialize the fields below with doubles. // // Learn more about this here: // https://github.com/facebook/react/issues/14365 // https://bugs.chromium.org/p/v8/issues/detail?id=8538 this.actualDuration = Number.NaN; this.actualStartTime = Number.NaN; this.selfBaseDuration = Number.NaN; this.treeBaseDuration = Number.NaN; // It's okay to replace the initial doubles with smis after initialization. // This won't trigger the performance cliff mentioned above, // and it simplifies other profiler code (including DevTools). this.actualDuration = 0; this.actualStartTime = -1; this.selfBaseDuration = 0; this.treeBaseDuration = 0; } { // This isn't directly used but is handy for debugging internals: this._debugSource = null; this._debugOwner = null; this._debugNeedsRemount = false; this._debugHookTypes = null; if (!hasBadMapPolyfill && typeof Object.preventExtensions === 'function') { Object.preventExtensions(this); } } } // This is a constructor function, rather than a POJO constructor, still // please ensure we do the following: // 1) Nobody should add any instance methods on this. Instance methods can be // more difficult to predict when they get optimized and they are almost // never inlined properly in static compilers. // 2) Nobody should rely on `instanceof Fiber` for type testing. We should // always know when it is a fiber. // 3) We might want to experiment with using numeric keys since they are easier // to optimize in a non-JIT environment. // 4) We can easily go from a constructor to a createFiber object literal if that // is faster. // 5) It should be easy to port this to a C struct and keep a C implementation // compatible. var createFiber = function (tag, pendingProps, key, mode) { // $FlowFixMe: the shapes are exact here but Flow doesn't like constructors return new FiberNode(tag, pendingProps, key, mode); }; function shouldConstruct$1(Component) { var prototype = Component.prototype; return !!(prototype && prototype.isReactComponent); } function isSimpleFunctionComponent(type) { return typeof type === 'function' && !shouldConstruct$1(type) && type.defaultProps === undefined; } function resolveLazyComponentTag(Component) { if (typeof Component === 'function') { return shouldConstruct$1(Component) ? ClassComponent : FunctionComponent; } else if (Component !== undefined && Component !== null) { var $$typeof = Component.$$typeof; if ($$typeof === REACT_FORWARD_REF_TYPE) { return ForwardRef; } if ($$typeof === REACT_MEMO_TYPE) { return MemoComponent; } } return IndeterminateComponent; } // This is used to create an alternate fiber to do work on. function createWorkInProgress(current, pendingProps) { var workInProgress = current.alternate; if (workInProgress === null) { // We use a double buffering pooling technique because we know that we'll // only ever need at most two versions of a tree. We pool the "other" unused // node that we're free to reuse. This is lazily created to avoid allocating // extra objects for things that are never updated. It also allow us to // reclaim the extra memory if needed. workInProgress = createFiber(current.tag, pendingProps, current.key, current.mode); workInProgress.elementType = current.elementType; workInProgress.type = current.type; workInProgress.stateNode = current.stateNode; { // DEV-only fields workInProgress._debugSource = current._debugSource; workInProgress._debugOwner = current._debugOwner; workInProgress._debugHookTypes = current._debugHookTypes; } workInProgress.alternate = current; current.alternate = workInProgress; } else { workInProgress.pendingProps = pendingProps; // Needed because Blocks store data on type. workInProgress.type = current.type; // We already have an alternate. // Reset the effect tag. workInProgress.flags = NoFlags; // The effects are no longer valid. workInProgress.subtreeFlags = NoFlags; workInProgress.deletions = null; { // We intentionally reset, rather than copy, actualDuration & actualStartTime. // This prevents time from endlessly accumulating in new commits. // This has the downside of resetting values for different priority renders, // But works for yielding (the common case) and should support resuming. workInProgress.actualDuration = 0; workInProgress.actualStartTime = -1; } } // Reset all effects except static ones. // Static effects are not specific to a render. workInProgress.flags = current.flags & StaticMask; workInProgress.childLanes = current.childLanes; workInProgress.lanes = current.lanes; workInProgress.child = current.child; workInProgress.memoizedProps = current.memoizedProps; workInProgress.memoizedState = current.memoizedState; workInProgress.updateQueue = current.updateQueue; // Clone the dependencies object. This is mutated during the render phase, so // it cannot be shared with the current fiber. var currentDependencies = current.dependencies; workInProgress.dependencies = currentDependencies === null ? null : { lanes: currentDependencies.lanes, firstContext: currentDependencies.firstContext }; // These will be overridden during the parent's reconciliation workInProgress.sibling = current.sibling; workInProgress.index = current.index; workInProgress.ref = current.ref; { workInProgress.selfBaseDuration = current.selfBaseDuration; workInProgress.treeBaseDuration = current.treeBaseDuration; } { workInProgress._debugNeedsRemount = current._debugNeedsRemount; switch (workInProgress.tag) { case IndeterminateComponent: case FunctionComponent: case SimpleMemoComponent: workInProgress.type = resolveFunctionForHotReloading(current.type); break; case ClassComponent: workInProgress.type = resolveClassForHotReloading(current.type); break; case ForwardRef: workInProgress.type = resolveForwardRefForHotReloading(current.type); break; } } return workInProgress; } // Used to reuse a Fiber for a second pass. function resetWorkInProgress(workInProgress, renderLanes) { // This resets the Fiber to what createFiber or createWorkInProgress would // have set the values to before during the first pass. Ideally this wouldn't // be necessary but unfortunately many code paths reads from the workInProgress // when they should be reading from current and writing to workInProgress. // We assume pendingProps, index, key, ref, return are still untouched to // avoid doing another reconciliation. // Reset the effect flags but keep any Placement tags, since that's something // that child fiber is setting, not the reconciliation. workInProgress.flags &= StaticMask | Placement; // The effects are no longer valid. var current = workInProgress.alternate; if (current === null) { // Reset to createFiber's initial values. workInProgress.childLanes = NoLanes; workInProgress.lanes = renderLanes; workInProgress.child = null; workInProgress.subtreeFlags = NoFlags; workInProgress.memoizedProps = null; workInProgress.memoizedState = null; workInProgress.updateQueue = null; workInProgress.dependencies = null; workInProgress.stateNode = null; { // Note: We don't reset the actualTime counts. It's useful to accumulate // actual time across multiple render passes. workInProgress.selfBaseDuration = 0; workInProgress.treeBaseDuration = 0; } } else { // Reset to the cloned values that createWorkInProgress would've. workInProgress.childLanes = current.childLanes; workInProgress.lanes = current.lanes; workInProgress.child = current.child; workInProgress.subtreeFlags = NoFlags; workInProgress.deletions = null; workInProgress.memoizedProps = current.memoizedProps; workInProgress.memoizedState = current.memoizedState; workInProgress.updateQueue = current.updateQueue; // Needed because Blocks store data on type. workInProgress.type = current.type; // Clone the dependencies object. This is mutated during the render phase, so // it cannot be shared with the current fiber. var currentDependencies = current.dependencies; workInProgress.dependencies = currentDependencies === null ? null : { lanes: currentDependencies.lanes, firstContext: currentDependencies.firstContext }; { // Note: We don't reset the actualTime counts. It's useful to accumulate // actual time across multiple render passes. workInProgress.selfBaseDuration = current.selfBaseDuration; workInProgress.treeBaseDuration = current.treeBaseDuration; } } return workInProgress; } function createHostRootFiber(tag, isStrictMode, concurrentUpdatesByDefaultOverride) { var mode; if (tag === ConcurrentRoot) { mode = ConcurrentMode; if (isStrictMode === true) { mode |= StrictLegacyMode; { mode |= StrictEffectsMode; } } } else { mode = NoMode; } if ( isDevToolsPresent) { // Always collect profile timings when DevTools are present. // This enables DevTools to start capturing timing at any point– // Without some nodes in the tree having empty base times. mode |= ProfileMode; } return createFiber(HostRoot, null, null, mode); } function createFiberFromTypeAndProps(type, // React$ElementType key, pendingProps, owner, mode, lanes) { var fiberTag = IndeterminateComponent; // The resolved type is set if we know what the final type will be. I.e. it's not lazy. var resolvedType = type; if (typeof type === 'function') { if (shouldConstruct$1(type)) { fiberTag = ClassComponent; { resolvedType = resolveClassForHotReloading(resolvedType); } } else { { resolvedType = resolveFunctionForHotReloading(resolvedType); } } } else if (typeof type === 'string') { fiberTag = HostComponent; } else { getTag: switch (type) { case REACT_FRAGMENT_TYPE: return createFiberFromFragment(pendingProps.children, mode, lanes, key); case REACT_STRICT_MODE_TYPE: fiberTag = Mode; mode |= StrictLegacyMode; if ( (mode & ConcurrentMode) !== NoMode) { // Strict effects should never run on legacy roots mode |= StrictEffectsMode; } break; case REACT_PROFILER_TYPE: return createFiberFromProfiler(pendingProps, mode, lanes, key); case REACT_SUSPENSE_TYPE: return createFiberFromSuspense(pendingProps, mode, lanes, key); case REACT_SUSPENSE_LIST_TYPE: return createFiberFromSuspenseList(pendingProps, mode, lanes, key); case REACT_OFFSCREEN_TYPE: return createFiberFromOffscreen(pendingProps, mode, lanes, key); case REACT_LEGACY_HIDDEN_TYPE: // eslint-disable-next-line no-fallthrough case REACT_SCOPE_TYPE: // eslint-disable-next-line no-fallthrough case REACT_CACHE_TYPE: // eslint-disable-next-line no-fallthrough case REACT_TRACING_MARKER_TYPE: // eslint-disable-next-line no-fallthrough case REACT_DEBUG_TRACING_MODE_TYPE: // eslint-disable-next-line no-fallthrough default: { if (typeof type === 'object' && type !== null) { switch (type.$$typeof) { case REACT_PROVIDER_TYPE: fiberTag = ContextProvider; break getTag; case REACT_CONTEXT_TYPE: // This is a consumer fiberTag = ContextConsumer; break getTag; case REACT_FORWARD_REF_TYPE: fiberTag = ForwardRef; { resolvedType = resolveForwardRefForHotReloading(resolvedType); } break getTag; case REACT_MEMO_TYPE: fiberTag = MemoComponent; break getTag; case REACT_LAZY_TYPE: fiberTag = LazyComponent; resolvedType = null; break getTag; } } var info = ''; { if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) { info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and " + 'named imports.'; } var ownerName = owner ? getComponentNameFromFiber(owner) : null; if (ownerName) { info += '\n\nCheck the render method of `' + ownerName + '`.'; } } throw new Error('Element type is invalid: expected a string (for built-in ' + 'components) or a class/function (for composite components) ' + ("but got: " + (type == null ? type : typeof type) + "." + info)); } } } var fiber = createFiber(fiberTag, pendingProps, key, mode); fiber.elementType = type; fiber.type = resolvedType; fiber.lanes = lanes; { fiber._debugOwner = owner; } return fiber; } function createFiberFromElement(element, mode, lanes) { var owner = null; { owner = element._owner; } var type = element.type; var key = element.key; var pendingProps = element.props; var fiber = createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, lanes); { fiber._debugSource = element._source; fiber._debugOwner = element._owner; } return fiber; } function createFiberFromFragment(elements, mode, lanes, key) { var fiber = createFiber(Fragment, elements, key, mode); fiber.lanes = lanes; return fiber; } function createFiberFromProfiler(pendingProps, mode, lanes, key) { { if (typeof pendingProps.id !== 'string') { error('Profiler must specify an "id" of type `string` as a prop. Received the type `%s` instead.', typeof pendingProps.id); } } var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode); fiber.elementType = REACT_PROFILER_TYPE; fiber.lanes = lanes; { fiber.stateNode = { effectDuration: 0, passiveEffectDuration: 0 }; } return fiber; } function createFiberFromSuspense(pendingProps, mode, lanes, key) { var fiber = createFiber(SuspenseComponent, pendingProps, key, mode); fiber.elementType = REACT_SUSPENSE_TYPE; fiber.lanes = lanes; return fiber; } function createFiberFromSuspenseList(pendingProps, mode, lanes, key) { var fiber = createFiber(SuspenseListComponent, pendingProps, key, mode); fiber.elementType = REACT_SUSPENSE_LIST_TYPE; fiber.lanes = lanes; return fiber; } function createFiberFromOffscreen(pendingProps, mode, lanes, key) { var fiber = createFiber(OffscreenComponent, pendingProps, key, mode); fiber.elementType = REACT_OFFSCREEN_TYPE; fiber.lanes = lanes; var primaryChildInstance = { isHidden: false }; fiber.stateNode = primaryChildInstance; return fiber; } function createFiberFromText(content, mode, lanes) { var fiber = createFiber(HostText, content, null, mode); fiber.lanes = lanes; return fiber; } function createFiberFromHostInstanceForDeletion() { var fiber = createFiber(HostComponent, null, null, NoMode); fiber.elementType = 'DELETED'; return fiber; } function createFiberFromDehydratedFragment(dehydratedNode) { var fiber = createFiber(DehydratedFragment, null, null, NoMode); fiber.stateNode = dehydratedNode; return fiber; } function createFiberFromPortal(portal, mode, lanes) { var pendingProps = portal.children !== null ? portal.children : []; var fiber = createFiber(HostPortal, pendingProps, portal.key, mode); fiber.lanes = lanes; fiber.stateNode = { containerInfo: portal.containerInfo, pendingChildren: null, // Used by persistent updates implementation: portal.implementation }; return fiber; } // Used for stashing WIP properties to replay failed work in DEV. function assignFiberPropertiesInDEV(target, source) { if (target === null) { // This Fiber's initial properties will always be overwritten. // We only use a Fiber to ensure the same hidden class so DEV isn't slow. target = createFiber(IndeterminateComponent, null, null, NoMode); } // This is intentionally written as a list of all properties. // We tried to use Object.assign() instead but this is called in // the hottest path, and Object.assign() was too slow: // https://github.com/facebook/react/issues/12502 // This code is DEV-only so size is not a concern. target.tag = source.tag; target.key = source.key; target.elementType = source.elementType; target.type = source.type; target.stateNode = source.stateNode; target.return = source.return; target.child = source.child; target.sibling = source.sibling; target.index = source.index; target.ref = source.ref; target.pendingProps = source.pendingProps; target.memoizedProps = source.memoizedProps; target.updateQueue = source.updateQueue; target.memoizedState = source.memoizedState; target.dependencies = source.dependencies; target.mode = source.mode; target.flags = source.flags; target.subtreeFlags = source.subtreeFlags; target.deletions = source.deletions; target.lanes = source.lanes; target.childLanes = source.childLanes; target.alternate = source.alternate; { target.actualDuration = source.actualDuration; target.actualStartTime = source.actualStartTime; target.selfBaseDuration = source.selfBaseDuration; target.treeBaseDuration = source.treeBaseDuration; } target._debugSource = source._debugSource; target._debugOwner = source._debugOwner; target._debugNeedsRemount = source._debugNeedsRemount; target._debugHookTypes = source._debugHookTypes; return target; } function FiberRootNode(containerInfo, tag, hydrate, identifierPrefix, onRecoverableError) { this.tag = tag; this.containerInfo = containerInfo; this.pendingChildren = null; this.current = null; this.pingCache = null; this.finishedWork = null; this.timeoutHandle = noTimeout; this.context = null; this.pendingContext = null; this.callbackNode = null; this.callbackPriority = NoLane; this.eventTimes = createLaneMap(NoLanes); this.expirationTimes = createLaneMap(NoTimestamp); this.pendingLanes = NoLanes; this.suspendedLanes = NoLanes; this.pingedLanes = NoLanes; this.expiredLanes = NoLanes; this.mutableReadLanes = NoLanes; this.finishedLanes = NoLanes; this.entangledLanes = NoLanes; this.entanglements = createLaneMap(NoLanes); this.identifierPrefix = identifierPrefix; this.onRecoverableError = onRecoverableError; { this.mutableSourceEagerHydrationData = null; } { this.effectDuration = 0; this.passiveEffectDuration = 0; } { this.memoizedUpdaters = new Set(); var pendingUpdatersLaneMap = this.pendingUpdatersLaneMap = []; for (var _i = 0; _i < TotalLanes; _i++) { pendingUpdatersLaneMap.push(new Set()); } } { switch (tag) { case ConcurrentRoot: this._debugRootType = hydrate ? 'hydrateRoot()' : 'createRoot()'; break; case LegacyRoot: this._debugRootType = hydrate ? 'hydrate()' : 'render()'; break; } } } function createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, // TODO: We have several of these arguments that are conceptually part of the // host config, but because they are passed in at runtime, we have to thread // them through the root constructor. Perhaps we should put them all into a // single type, like a DynamicHostConfig that is defined by the renderer. identifierPrefix, onRecoverableError, transitionCallbacks) { var root = new FiberRootNode(containerInfo, tag, hydrate, identifierPrefix, onRecoverableError); // stateNode is any. var uninitializedFiber = createHostRootFiber(tag, isStrictMode); root.current = uninitializedFiber; uninitializedFiber.stateNode = root; { var _initialState = { element: initialChildren, isDehydrated: hydrate, cache: null, // not enabled yet transitions: null, pendingSuspenseBoundaries: null }; uninitializedFiber.memoizedState = _initialState; } initializeUpdateQueue(uninitializedFiber); return root; } var ReactVersion = '18.2.0'; function createPortal(children, containerInfo, // TODO: figure out the API for cross-renderer implementation. implementation) { var key = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; { checkKeyStringCoercion(key); } return { // This tag allow us to uniquely identify this as a React Portal $$typeof: REACT_PORTAL_TYPE, key: key == null ? null : '' + key, children: children, containerInfo: containerInfo, implementation: implementation }; } var didWarnAboutNestedUpdates; var didWarnAboutFindNodeInStrictMode; { didWarnAboutNestedUpdates = false; didWarnAboutFindNodeInStrictMode = {}; } function getContextForSubtree(parentComponent) { if (!parentComponent) { return emptyContextObject; } var fiber = get(parentComponent); var parentContext = findCurrentUnmaskedContext(fiber); if (fiber.tag === ClassComponent) { var Component = fiber.type; if (isContextProvider(Component)) { return processChildContext(fiber, Component, parentContext); } } return parentContext; } function findHostInstanceWithWarning(component, methodName) { { var fiber = get(component); if (fiber === undefined) { if (typeof component.render === 'function') { throw new Error('Unable to find node on an unmounted component.'); } else { var keys = Object.keys(component).join(','); throw new Error("Argument appears to not be a ReactComponent. Keys: " + keys); } } var hostFiber = findCurrentHostFiber(fiber); if (hostFiber === null) { return null; } if (hostFiber.mode & StrictLegacyMode) { var componentName = getComponentNameFromFiber(fiber) || 'Component'; if (!didWarnAboutFindNodeInStrictMode[componentName]) { didWarnAboutFindNodeInStrictMode[componentName] = true; var previousFiber = current; try { setCurrentFiber(hostFiber); if (fiber.mode & StrictLegacyMode) { error('%s is deprecated in StrictMode. ' + '%s was passed an instance of %s which is inside StrictMode. ' + 'Instead, add a ref directly to the element you want to reference. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-find-node', methodName, methodName, componentName); } else { error('%s is deprecated in StrictMode. ' + '%s was passed an instance of %s which renders StrictMode children. ' + 'Instead, add a ref directly to the element you want to reference. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-find-node', methodName, methodName, componentName); } } finally { // Ideally this should reset to previous but this shouldn't be called in // render and there's another warning for that anyway. if (previousFiber) { setCurrentFiber(previousFiber); } else { resetCurrentFiber(); } } } } return hostFiber.stateNode; } } function createContainer(containerInfo, tag, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError, transitionCallbacks) { var hydrate = false; var initialChildren = null; return createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError); } function createHydrationContainer(initialChildren, // TODO: Remove `callback` when we delete legacy mode. callback, containerInfo, tag, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError, transitionCallbacks) { var hydrate = true; var root = createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError); // TODO: Move this to FiberRoot constructor root.context = getContextForSubtree(null); // Schedule the initial render. In a hydration root, this is different from // a regular update because the initial render must match was was rendered // on the server. // NOTE: This update intentionally doesn't have a payload. We're only using // the update to schedule work on the root fiber (and, for legacy roots, to // enqueue the callback if one is provided). var current = root.current; var eventTime = requestEventTime(); var lane = requestUpdateLane(current); var update = createUpdate(eventTime, lane); update.callback = callback !== undefined && callback !== null ? callback : null; enqueueUpdate(current, update, lane); scheduleInitialHydrationOnRoot(root, lane, eventTime); return root; } function updateContainer(element, container, parentComponent, callback) { { onScheduleRoot(container, element); } var current$1 = container.current; var eventTime = requestEventTime(); var lane = requestUpdateLane(current$1); { markRenderScheduled(lane); } var context = getContextForSubtree(parentComponent); if (container.context === null) { container.context = context; } else { container.pendingContext = context; } { if (isRendering && current !== null && !didWarnAboutNestedUpdates) { didWarnAboutNestedUpdates = true; error('Render methods should be a pure function of props and state; ' + 'triggering nested component updates from render is not allowed. ' + 'If necessary, trigger nested updates in componentDidUpdate.\n\n' + 'Check the render method of %s.', getComponentNameFromFiber(current) || 'Unknown'); } } var update = createUpdate(eventTime, lane); // Caution: React DevTools currently depends on this property // being called "element". update.payload = { element: element }; callback = callback === undefined ? null : callback; if (callback !== null) { { if (typeof callback !== 'function') { error('render(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callback); } } update.callback = callback; } var root = enqueueUpdate(current$1, update, lane); if (root !== null) { scheduleUpdateOnFiber(root, current$1, lane, eventTime); entangleTransitions(root, current$1, lane); } return lane; } function getPublicRootInstance(container) { var containerFiber = container.current; if (!containerFiber.child) { return null; } switch (containerFiber.child.tag) { case HostComponent: return getPublicInstance(containerFiber.child.stateNode); default: return containerFiber.child.stateNode; } } function attemptSynchronousHydration$1(fiber) { switch (fiber.tag) { case HostRoot: { var root = fiber.stateNode; if (isRootDehydrated(root)) { // Flush the first scheduled "update". var lanes = getHighestPriorityPendingLanes(root); flushRoot(root, lanes); } break; } case SuspenseComponent: { flushSync(function () { var root = enqueueConcurrentRenderForLane(fiber, SyncLane); if (root !== null) { var eventTime = requestEventTime(); scheduleUpdateOnFiber(root, fiber, SyncLane, eventTime); } }); // If we're still blocked after this, we need to increase // the priority of any promises resolving within this // boundary so that they next attempt also has higher pri. var retryLane = SyncLane; markRetryLaneIfNotHydrated(fiber, retryLane); break; } } } function markRetryLaneImpl(fiber, retryLane) { var suspenseState = fiber.memoizedState; if (suspenseState !== null && suspenseState.dehydrated !== null) { suspenseState.retryLane = higherPriorityLane(suspenseState.retryLane, retryLane); } } // Increases the priority of thenables when they resolve within this boundary. function markRetryLaneIfNotHydrated(fiber, retryLane) { markRetryLaneImpl(fiber, retryLane); var alternate = fiber.alternate; if (alternate) { markRetryLaneImpl(alternate, retryLane); } } function attemptContinuousHydration$1(fiber) { if (fiber.tag !== SuspenseComponent) { // We ignore HostRoots here because we can't increase // their priority and they should not suspend on I/O, // since you have to wrap anything that might suspend in // Suspense. return; } var lane = SelectiveHydrationLane; var root = enqueueConcurrentRenderForLane(fiber, lane); if (root !== null) { var eventTime = requestEventTime(); scheduleUpdateOnFiber(root, fiber, lane, eventTime); } markRetryLaneIfNotHydrated(fiber, lane); } function attemptHydrationAtCurrentPriority$1(fiber) { if (fiber.tag !== SuspenseComponent) { // We ignore HostRoots here because we can't increase // their priority other than synchronously flush it. return; } var lane = requestUpdateLane(fiber); var root = enqueueConcurrentRenderForLane(fiber, lane); if (root !== null) { var eventTime = requestEventTime(); scheduleUpdateOnFiber(root, fiber, lane, eventTime); } markRetryLaneIfNotHydrated(fiber, lane); } function findHostInstanceWithNoPortals(fiber) { var hostFiber = findCurrentHostFiberWithNoPortals(fiber); if (hostFiber === null) { return null; } return hostFiber.stateNode; } var shouldErrorImpl = function (fiber) { return null; }; function shouldError(fiber) { return shouldErrorImpl(fiber); } var shouldSuspendImpl = function (fiber) { return false; }; function shouldSuspend(fiber) { return shouldSuspendImpl(fiber); } var overrideHookState = null; var overrideHookStateDeletePath = null; var overrideHookStateRenamePath = null; var overrideProps = null; var overridePropsDeletePath = null; var overridePropsRenamePath = null; var scheduleUpdate = null; var setErrorHandler = null; var setSuspenseHandler = null; { var copyWithDeleteImpl = function (obj, path, index) { var key = path[index]; var updated = isArray(obj) ? obj.slice() : assign({}, obj); if (index + 1 === path.length) { if (isArray(updated)) { updated.splice(key, 1); } else { delete updated[key]; } return updated; } // $FlowFixMe number or string is fine here updated[key] = copyWithDeleteImpl(obj[key], path, index + 1); return updated; }; var copyWithDelete = function (obj, path) { return copyWithDeleteImpl(obj, path, 0); }; var copyWithRenameImpl = function (obj, oldPath, newPath, index) { var oldKey = oldPath[index]; var updated = isArray(obj) ? obj.slice() : assign({}, obj); if (index + 1 === oldPath.length) { var newKey = newPath[index]; // $FlowFixMe number or string is fine here updated[newKey] = updated[oldKey]; if (isArray(updated)) { updated.splice(oldKey, 1); } else { delete updated[oldKey]; } } else { // $FlowFixMe number or string is fine here updated[oldKey] = copyWithRenameImpl( // $FlowFixMe number or string is fine here obj[oldKey], oldPath, newPath, index + 1); } return updated; }; var copyWithRename = function (obj, oldPath, newPath) { if (oldPath.length !== newPath.length) { warn('copyWithRename() expects paths of the same length'); return; } else { for (var i = 0; i < newPath.length - 1; i++) { if (oldPath[i] !== newPath[i]) { warn('copyWithRename() expects paths to be the same except for the deepest key'); return; } } } return copyWithRenameImpl(obj, oldPath, newPath, 0); }; var copyWithSetImpl = function (obj, path, index, value) { if (index >= path.length) { return value; } var key = path[index]; var updated = isArray(obj) ? obj.slice() : assign({}, obj); // $FlowFixMe number or string is fine here updated[key] = copyWithSetImpl(obj[key], path, index + 1, value); return updated; }; var copyWithSet = function (obj, path, value) { return copyWithSetImpl(obj, path, 0, value); }; var findHook = function (fiber, id) { // For now, the "id" of stateful hooks is just the stateful hook index. // This may change in the future with e.g. nested hooks. var currentHook = fiber.memoizedState; while (currentHook !== null && id > 0) { currentHook = currentHook.next; id--; } return currentHook; }; // Support DevTools editable values for useState and useReducer. overrideHookState = function (fiber, id, path, value) { var hook = findHook(fiber, id); if (hook !== null) { var newState = copyWithSet(hook.memoizedState, path, value); hook.memoizedState = newState; hook.baseState = newState; // We aren't actually adding an update to the queue, // because there is no update we can add for useReducer hooks that won't trigger an error. // (There's no appropriate action type for DevTools overrides.) // As a result though, React will see the scheduled update as a noop and bailout. // Shallow cloning props works as a workaround for now to bypass the bailout check. fiber.memoizedProps = assign({}, fiber.memoizedProps); var root = enqueueConcurrentRenderForLane(fiber, SyncLane); if (root !== null) { scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); } } }; overrideHookStateDeletePath = function (fiber, id, path) { var hook = findHook(fiber, id); if (hook !== null) { var newState = copyWithDelete(hook.memoizedState, path); hook.memoizedState = newState; hook.baseState = newState; // We aren't actually adding an update to the queue, // because there is no update we can add for useReducer hooks that won't trigger an error. // (There's no appropriate action type for DevTools overrides.) // As a result though, React will see the scheduled update as a noop and bailout. // Shallow cloning props works as a workaround for now to bypass the bailout check. fiber.memoizedProps = assign({}, fiber.memoizedProps); var root = enqueueConcurrentRenderForLane(fiber, SyncLane); if (root !== null) { scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); } } }; overrideHookStateRenamePath = function (fiber, id, oldPath, newPath) { var hook = findHook(fiber, id); if (hook !== null) { var newState = copyWithRename(hook.memoizedState, oldPath, newPath); hook.memoizedState = newState; hook.baseState = newState; // We aren't actually adding an update to the queue, // because there is no update we can add for useReducer hooks that won't trigger an error. // (There's no appropriate action type for DevTools overrides.) // As a result though, React will see the scheduled update as a noop and bailout. // Shallow cloning props works as a workaround for now to bypass the bailout check. fiber.memoizedProps = assign({}, fiber.memoizedProps); var root = enqueueConcurrentRenderForLane(fiber, SyncLane); if (root !== null) { scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); } } }; // Support DevTools props for function components, forwardRef, memo, host components, etc. overrideProps = function (fiber, path, value) { fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value); if (fiber.alternate) { fiber.alternate.pendingProps = fiber.pendingProps; } var root = enqueueConcurrentRenderForLane(fiber, SyncLane); if (root !== null) { scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); } }; overridePropsDeletePath = function (fiber, path) { fiber.pendingProps = copyWithDelete(fiber.memoizedProps, path); if (fiber.alternate) { fiber.alternate.pendingProps = fiber.pendingProps; } var root = enqueueConcurrentRenderForLane(fiber, SyncLane); if (root !== null) { scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); } }; overridePropsRenamePath = function (fiber, oldPath, newPath) { fiber.pendingProps = copyWithRename(fiber.memoizedProps, oldPath, newPath); if (fiber.alternate) { fiber.alternate.pendingProps = fiber.pendingProps; } var root = enqueueConcurrentRenderForLane(fiber, SyncLane); if (root !== null) { scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); } }; scheduleUpdate = function (fiber) { var root = enqueueConcurrentRenderForLane(fiber, SyncLane); if (root !== null) { scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); } }; setErrorHandler = function (newShouldErrorImpl) { shouldErrorImpl = newShouldErrorImpl; }; setSuspenseHandler = function (newShouldSuspendImpl) { shouldSuspendImpl = newShouldSuspendImpl; }; } function findHostInstanceByFiber(fiber) { var hostFiber = findCurrentHostFiber(fiber); if (hostFiber === null) { return null; } return hostFiber.stateNode; } function emptyFindFiberByHostInstance(instance) { return null; } function getCurrentFiberForDevTools() { return current; } function injectIntoDevTools(devToolsConfig) { var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance; var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; return injectInternals({ bundleType: devToolsConfig.bundleType, version: devToolsConfig.version, rendererPackageName: devToolsConfig.rendererPackageName, rendererConfig: devToolsConfig.rendererConfig, overrideHookState: overrideHookState, overrideHookStateDeletePath: overrideHookStateDeletePath, overrideHookStateRenamePath: overrideHookStateRenamePath, overrideProps: overrideProps, overridePropsDeletePath: overridePropsDeletePath, overridePropsRenamePath: overridePropsRenamePath, setErrorHandler: setErrorHandler, setSuspenseHandler: setSuspenseHandler, scheduleUpdate: scheduleUpdate, currentDispatcherRef: ReactCurrentDispatcher, findHostInstanceByFiber: findHostInstanceByFiber, findFiberByHostInstance: findFiberByHostInstance || emptyFindFiberByHostInstance, // React Refresh findHostInstancesForRefresh: findHostInstancesForRefresh , scheduleRefresh: scheduleRefresh , scheduleRoot: scheduleRoot , setRefreshHandler: setRefreshHandler , // Enables DevTools to append owner stacks to error messages in DEV mode. getCurrentFiber: getCurrentFiberForDevTools , // Enables DevTools to detect reconciler version rather than renderer version // which may not match for third party renderers. reconcilerVersion: ReactVersion }); } /* global reportError */ var defaultOnRecoverableError = typeof reportError === 'function' ? // In modern browsers, reportError will dispatch an error event, // emulating an uncaught JavaScript error. reportError : function (error) { // In older browsers and test environments, fallback to console.error. // eslint-disable-next-line react-internal/no-production-logging console['error'](error); }; function ReactDOMRoot(internalRoot) { this._internalRoot = internalRoot; } ReactDOMHydrationRoot.prototype.render = ReactDOMRoot.prototype.render = function (children) { var root = this._internalRoot; if (root === null) { throw new Error('Cannot update an unmounted root.'); } { if (typeof arguments[1] === 'function') { error('render(...): does not support the second callback argument. ' + 'To execute a side effect after rendering, declare it in a component body with useEffect().'); } else if (isValidContainer(arguments[1])) { error('You passed a container to the second argument of root.render(...). ' + "You don't need to pass it again since you already passed it to create the root."); } else if (typeof arguments[1] !== 'undefined') { error('You passed a second argument to root.render(...) but it only accepts ' + 'one argument.'); } var container = root.containerInfo; if (container.nodeType !== COMMENT_NODE) { var hostInstance = findHostInstanceWithNoPortals(root.current); if (hostInstance) { if (hostInstance.parentNode !== container) { error('render(...): It looks like the React-rendered content of the ' + 'root container was removed without using React. This is not ' + 'supported and will cause errors. Instead, call ' + "root.unmount() to empty a root's container."); } } } } updateContainer(children, root, null, null); }; ReactDOMHydrationRoot.prototype.unmount = ReactDOMRoot.prototype.unmount = function () { { if (typeof arguments[0] === 'function') { error('unmount(...): does not support a callback argument. ' + 'To execute a side effect after rendering, declare it in a component body with useEffect().'); } } var root = this._internalRoot; if (root !== null) { this._internalRoot = null; var container = root.containerInfo; { if (isAlreadyRendering()) { error('Attempted to synchronously unmount a root while React was already ' + 'rendering. React cannot finish unmounting the root until the ' + 'current render has completed, which may lead to a race condition.'); } } flushSync(function () { updateContainer(null, root, null, null); }); unmarkContainerAsRoot(container); } }; function createRoot(container, options) { if (!isValidContainer(container)) { throw new Error('createRoot(...): Target container is not a DOM element.'); } warnIfReactDOMContainerInDEV(container); var isStrictMode = false; var concurrentUpdatesByDefaultOverride = false; var identifierPrefix = ''; var onRecoverableError = defaultOnRecoverableError; var transitionCallbacks = null; if (options !== null && options !== undefined) { { if (options.hydrate) { warn('hydrate through createRoot is deprecated. Use ReactDOMClient.hydrateRoot(container, <App />) instead.'); } else { if (typeof options === 'object' && options !== null && options.$$typeof === REACT_ELEMENT_TYPE) { error('You passed a JSX element to createRoot. You probably meant to ' + 'call root.render instead. ' + 'Example usage:\n\n' + ' let root = createRoot(domContainer);\n' + ' root.render(<App />);'); } } } if (options.unstable_strictMode === true) { isStrictMode = true; } if (options.identifierPrefix !== undefined) { identifierPrefix = options.identifierPrefix; } if (options.onRecoverableError !== undefined) { onRecoverableError = options.onRecoverableError; } if (options.transitionCallbacks !== undefined) { transitionCallbacks = options.transitionCallbacks; } } var root = createContainer(container, ConcurrentRoot, null, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError); markContainerAsRoot(root.current, container); var rootContainerElement = container.nodeType === COMMENT_NODE ? container.parentNode : container; listenToAllSupportedEvents(rootContainerElement); return new ReactDOMRoot(root); } function ReactDOMHydrationRoot(internalRoot) { this._internalRoot = internalRoot; } function scheduleHydration(target) { if (target) { queueExplicitHydrationTarget(target); } } ReactDOMHydrationRoot.prototype.unstable_scheduleHydration = scheduleHydration; function hydrateRoot(container, initialChildren, options) { if (!isValidContainer(container)) { throw new Error('hydrateRoot(...): Target container is not a DOM element.'); } warnIfReactDOMContainerInDEV(container); { if (initialChildren === undefined) { error('Must provide initial children as second argument to hydrateRoot. ' + 'Example usage: hydrateRoot(domContainer, <App />)'); } } // For now we reuse the whole bag of options since they contain // the hydration callbacks. var hydrationCallbacks = options != null ? options : null; // TODO: Delete this option var mutableSources = options != null && options.hydratedSources || null; var isStrictMode = false; var concurrentUpdatesByDefaultOverride = false; var identifierPrefix = ''; var onRecoverableError = defaultOnRecoverableError; if (options !== null && options !== undefined) { if (options.unstable_strictMode === true) { isStrictMode = true; } if (options.identifierPrefix !== undefined) { identifierPrefix = options.identifierPrefix; } if (options.onRecoverableError !== undefined) { onRecoverableError = options.onRecoverableError; } } var root = createHydrationContainer(initialChildren, null, container, ConcurrentRoot, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError); markContainerAsRoot(root.current, container); // This can't be a comment node since hydration doesn't work on comment nodes anyway. listenToAllSupportedEvents(container); if (mutableSources) { for (var i = 0; i < mutableSources.length; i++) { var mutableSource = mutableSources[i]; registerMutableSourceForHydration(root, mutableSource); } } return new ReactDOMHydrationRoot(root); } function isValidContainer(node) { return !!(node && (node.nodeType === ELEMENT_NODE || node.nodeType === DOCUMENT_NODE || node.nodeType === DOCUMENT_FRAGMENT_NODE || !disableCommentsAsDOMContainers )); } // TODO: Remove this function which also includes comment nodes. // We only use it in places that are currently more relaxed. function isValidContainerLegacy(node) { return !!(node && (node.nodeType === ELEMENT_NODE || node.nodeType === DOCUMENT_NODE || node.nodeType === DOCUMENT_FRAGMENT_NODE || node.nodeType === COMMENT_NODE && node.nodeValue === ' react-mount-point-unstable ')); } function warnIfReactDOMContainerInDEV(container) { { if (container.nodeType === ELEMENT_NODE && container.tagName && container.tagName.toUpperCase() === 'BODY') { error('createRoot(): Creating roots directly with document.body is ' + 'discouraged, since its children are often manipulated by third-party ' + 'scripts and browser extensions. This may lead to subtle ' + 'reconciliation issues. Try using a container element created ' + 'for your app.'); } if (isContainerMarkedAsRoot(container)) { if (container._reactRootContainer) { error('You are calling ReactDOMClient.createRoot() on a container that was previously ' + 'passed to ReactDOM.render(). This is not supported.'); } else { error('You are calling ReactDOMClient.createRoot() on a container that ' + 'has already been passed to createRoot() before. Instead, call ' + 'root.render() on the existing root instead if you want to update it.'); } } } } var ReactCurrentOwner$3 = ReactSharedInternals.ReactCurrentOwner; var topLevelUpdateWarnings; { topLevelUpdateWarnings = function (container) { if (container._reactRootContainer && container.nodeType !== COMMENT_NODE) { var hostInstance = findHostInstanceWithNoPortals(container._reactRootContainer.current); if (hostInstance) { if (hostInstance.parentNode !== container) { error('render(...): It looks like the React-rendered content of this ' + 'container was removed without using React. This is not ' + 'supported and will cause errors. Instead, call ' + 'ReactDOM.unmountComponentAtNode to empty a container.'); } } } var isRootRenderedBySomeReact = !!container._reactRootContainer; var rootEl = getReactRootElementInContainer(container); var hasNonRootReactChild = !!(rootEl && getInstanceFromNode(rootEl)); if (hasNonRootReactChild && !isRootRenderedBySomeReact) { error('render(...): Replacing React-rendered children with a new root ' + 'component. If you intended to update the children of this node, ' + 'you should instead have the existing children update their state ' + 'and render the new components instead of calling ReactDOM.render.'); } if (container.nodeType === ELEMENT_NODE && container.tagName && container.tagName.toUpperCase() === 'BODY') { error('render(): Rendering components directly into document.body is ' + 'discouraged, since its children are often manipulated by third-party ' + 'scripts and browser extensions. This may lead to subtle ' + 'reconciliation issues. Try rendering into a container element created ' + 'for your app.'); } }; } function getReactRootElementInContainer(container) { if (!container) { return null; } if (container.nodeType === DOCUMENT_NODE) { return container.documentElement; } else { return container.firstChild; } } function noopOnRecoverableError() {// This isn't reachable because onRecoverableError isn't called in the // legacy API. } function legacyCreateRootFromDOMContainer(container, initialChildren, parentComponent, callback, isHydrationContainer) { if (isHydrationContainer) { if (typeof callback === 'function') { var originalCallback = callback; callback = function () { var instance = getPublicRootInstance(root); originalCallback.call(instance); }; } var root = createHydrationContainer(initialChildren, callback, container, LegacyRoot, null, // hydrationCallbacks false, // isStrictMode false, // concurrentUpdatesByDefaultOverride, '', // identifierPrefix noopOnRecoverableError); container._reactRootContainer = root; markContainerAsRoot(root.current, container); var rootContainerElement = container.nodeType === COMMENT_NODE ? container.parentNode : container; listenToAllSupportedEvents(rootContainerElement); flushSync(); return root; } else { // First clear any existing content. var rootSibling; while (rootSibling = container.lastChild) { container.removeChild(rootSibling); } if (typeof callback === 'function') { var _originalCallback = callback; callback = function () { var instance = getPublicRootInstance(_root); _originalCallback.call(instance); }; } var _root = createContainer(container, LegacyRoot, null, // hydrationCallbacks false, // isStrictMode false, // concurrentUpdatesByDefaultOverride, '', // identifierPrefix noopOnRecoverableError); container._reactRootContainer = _root; markContainerAsRoot(_root.current, container); var _rootContainerElement = container.nodeType === COMMENT_NODE ? container.parentNode : container; listenToAllSupportedEvents(_rootContainerElement); // Initial mount should not be batched. flushSync(function () { updateContainer(initialChildren, _root, parentComponent, callback); }); return _root; } } function warnOnInvalidCallback$1(callback, callerName) { { if (callback !== null && typeof callback !== 'function') { error('%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback); } } } function legacyRenderSubtreeIntoContainer(parentComponent, children, container, forceHydrate, callback) { { topLevelUpdateWarnings(container); warnOnInvalidCallback$1(callback === undefined ? null : callback, 'render'); } var maybeRoot = container._reactRootContainer; var root; if (!maybeRoot) { // Initial mount root = legacyCreateRootFromDOMContainer(container, children, parentComponent, callback, forceHydrate); } else { root = maybeRoot; if (typeof callback === 'function') { var originalCallback = callback; callback = function () { var instance = getPublicRootInstance(root); originalCallback.call(instance); }; } // Update updateContainer(children, root, parentComponent, callback); } return getPublicRootInstance(root); } function findDOMNode(componentOrElement) { { var owner = ReactCurrentOwner$3.current; if (owner !== null && owner.stateNode !== null) { var warnedAboutRefsInRender = owner.stateNode._warnedAboutRefsInRender; if (!warnedAboutRefsInRender) { error('%s is accessing findDOMNode inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', getComponentNameFromType(owner.type) || 'A component'); } owner.stateNode._warnedAboutRefsInRender = true; } } if (componentOrElement == null) { return null; } if (componentOrElement.nodeType === ELEMENT_NODE) { return componentOrElement; } { return findHostInstanceWithWarning(componentOrElement, 'findDOMNode'); } } function hydrate(element, container, callback) { { error('ReactDOM.hydrate is no longer supported in React 18. Use hydrateRoot ' + 'instead. Until you switch to the new API, your app will behave as ' + "if it's running React 17. Learn " + 'more: https://reactjs.org/link/switch-to-createroot'); } if (!isValidContainerLegacy(container)) { throw new Error('Target container is not a DOM element.'); } { var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === undefined; if (isModernRoot) { error('You are calling ReactDOM.hydrate() on a container that was previously ' + 'passed to ReactDOMClient.createRoot(). This is not supported. ' + 'Did you mean to call hydrateRoot(container, element)?'); } } // TODO: throw or warn if we couldn't hydrate? return legacyRenderSubtreeIntoContainer(null, element, container, true, callback); } function render(element, container, callback) { { error('ReactDOM.render is no longer supported in React 18. Use createRoot ' + 'instead. Until you switch to the new API, your app will behave as ' + "if it's running React 17. Learn " + 'more: https://reactjs.org/link/switch-to-createroot'); } if (!isValidContainerLegacy(container)) { throw new Error('Target container is not a DOM element.'); } { var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === undefined; if (isModernRoot) { error('You are calling ReactDOM.render() on a container that was previously ' + 'passed to ReactDOMClient.createRoot(). This is not supported. ' + 'Did you mean to call root.render(element)?'); } } return legacyRenderSubtreeIntoContainer(null, element, container, false, callback); } function unstable_renderSubtreeIntoContainer(parentComponent, element, containerNode, callback) { { error('ReactDOM.unstable_renderSubtreeIntoContainer() is no longer supported ' + 'in React 18. Consider using a portal instead. Until you switch to ' + "the createRoot API, your app will behave as if it's running React " + '17. Learn more: https://reactjs.org/link/switch-to-createroot'); } if (!isValidContainerLegacy(containerNode)) { throw new Error('Target container is not a DOM element.'); } if (parentComponent == null || !has(parentComponent)) { throw new Error('parentComponent must be a valid React Component'); } return legacyRenderSubtreeIntoContainer(parentComponent, element, containerNode, false, callback); } function unmountComponentAtNode(container) { if (!isValidContainerLegacy(container)) { throw new Error('unmountComponentAtNode(...): Target container is not a DOM element.'); } { var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === undefined; if (isModernRoot) { error('You are calling ReactDOM.unmountComponentAtNode() on a container that was previously ' + 'passed to ReactDOMClient.createRoot(). This is not supported. Did you mean to call root.unmount()?'); } } if (container._reactRootContainer) { { var rootEl = getReactRootElementInContainer(container); var renderedByDifferentReact = rootEl && !getInstanceFromNode(rootEl); if (renderedByDifferentReact) { error("unmountComponentAtNode(): The node you're attempting to unmount " + 'was rendered by another copy of React.'); } } // Unmount should not be batched. flushSync(function () { legacyRenderSubtreeIntoContainer(null, null, container, false, function () { // $FlowFixMe This should probably use `delete container._reactRootContainer` container._reactRootContainer = null; unmarkContainerAsRoot(container); }); }); // If you call unmountComponentAtNode twice in quick succession, you'll // get `true` twice. That's probably fine? return true; } else { { var _rootEl = getReactRootElementInContainer(container); var hasNonRootReactChild = !!(_rootEl && getInstanceFromNode(_rootEl)); // Check if the container itself is a React root node. var isContainerReactRoot = container.nodeType === ELEMENT_NODE && isValidContainerLegacy(container.parentNode) && !!container.parentNode._reactRootContainer; if (hasNonRootReactChild) { error("unmountComponentAtNode(): The node you're attempting to unmount " + 'was rendered by React and is not a top-level container. %s', isContainerReactRoot ? 'You may have accidentally passed in a React root node instead ' + 'of its container.' : 'Instead, have the parent component update its state and ' + 'rerender in order to remove this component.'); } } return false; } } setAttemptSynchronousHydration(attemptSynchronousHydration$1); setAttemptContinuousHydration(attemptContinuousHydration$1); setAttemptHydrationAtCurrentPriority(attemptHydrationAtCurrentPriority$1); setGetCurrentUpdatePriority(getCurrentUpdatePriority); setAttemptHydrationAtPriority(runWithPriority); { if (typeof Map !== 'function' || // $FlowIssue Flow incorrectly thinks Map has no prototype Map.prototype == null || typeof Map.prototype.forEach !== 'function' || typeof Set !== 'function' || // $FlowIssue Flow incorrectly thinks Set has no prototype Set.prototype == null || typeof Set.prototype.clear !== 'function' || typeof Set.prototype.forEach !== 'function') { error('React depends on Map and Set built-in types. Make sure that you load a ' + 'polyfill in older browsers. https://reactjs.org/link/react-polyfills'); } } setRestoreImplementation(restoreControlledState$3); setBatchingImplementation(batchedUpdates$1, discreteUpdates, flushSync); function createPortal$1(children, container) { var key = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; if (!isValidContainer(container)) { throw new Error('Target container is not a DOM element.'); } // TODO: pass ReactDOM portal implementation as third argument // $FlowFixMe The Flow type is opaque but there's no way to actually create it. return createPortal(children, container, null, key); } function renderSubtreeIntoContainer(parentComponent, element, containerNode, callback) { return unstable_renderSubtreeIntoContainer(parentComponent, element, containerNode, callback); } var Internals = { usingClientEntryPoint: false, // Keep in sync with ReactTestUtils.js. // This is an array for better minification. Events: [getInstanceFromNode, getNodeFromInstance, getFiberCurrentPropsFromNode, enqueueStateRestore, restoreStateIfNeeded, batchedUpdates$1] }; function createRoot$1(container, options) { { if (!Internals.usingClientEntryPoint && !false) { error('You are importing createRoot from "react-dom" which is not supported. ' + 'You should instead import it from "react-dom/client".'); } } return createRoot(container, options); } function hydrateRoot$1(container, initialChildren, options) { { if (!Internals.usingClientEntryPoint && !false) { error('You are importing hydrateRoot from "react-dom" which is not supported. ' + 'You should instead import it from "react-dom/client".'); } } return hydrateRoot(container, initialChildren, options); } // Overload the definition to the two valid signatures. // Warning, this opts-out of checking the function body. // eslint-disable-next-line no-redeclare function flushSync$1(fn) { { if (isAlreadyRendering()) { error('flushSync was called from inside a lifecycle method. React cannot ' + 'flush when React is already rendering. Consider moving this call to ' + 'a scheduler task or micro task.'); } } return flushSync(fn); } var foundDevTools = injectIntoDevTools({ findFiberByHostInstance: getClosestInstanceFromNode, bundleType: 1 , version: ReactVersion, rendererPackageName: 'react-dom' }); { if (!foundDevTools && canUseDOM && window.top === window.self) { // If we're in Chrome or Firefox, provide a download link if not installed. if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) { var protocol = window.location.protocol; // Don't warn in exotic cases like chrome-extension://. if (/^(https?|file):$/.test(protocol)) { // eslint-disable-next-line react-internal/no-production-logging console.info('%cDownload the React DevTools ' + 'for a better development experience: ' + 'https://reactjs.org/link/react-devtools' + (protocol === 'file:' ? '\nYou might need to use a local HTTP server (instead of file://): ' + 'https://reactjs.org/link/react-devtools-faq' : ''), 'font-weight:bold'); } } } } exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = Internals; exports.createPortal = createPortal$1; exports.createRoot = createRoot$1; exports.findDOMNode = findDOMNode; exports.flushSync = flushSync$1; exports.hydrate = hydrate; exports.hydrateRoot = hydrateRoot$1; exports.render = render; exports.unmountComponentAtNode = unmountComponentAtNode; exports.unstable_batchedUpdates = batchedUpdates$1; exports.unstable_renderSubtreeIntoContainer = renderSubtreeIntoContainer; exports.version = ReactVersion; /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */ if ( typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === 'function' ) { __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error()); } })(); } /***/ }), /***/ "./node_modules/react-dom/index.js": /*!*****************************************!*\ !*** ./node_modules/react-dom/index.js ***! \*****************************************/ /***/ ((module, __unused_webpack_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) {} else { module.exports = __webpack_require__(/*! ./cjs/react-dom.development.js */ "./node_modules/react-dom/cjs/react-dom.development.js"); } /***/ }), /***/ "./node_modules/react/cjs/react-jsx-runtime.development.js": /*!*****************************************************************!*\ !*** ./node_modules/react/cjs/react-jsx-runtime.development.js ***! \*****************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /** * @license React * react-jsx-runtime.development.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ if (true) { (function() { 'use strict'; var React = __webpack_require__(/*! react */ "./node_modules/react/index.js"); // ATTENTION // When adding new symbols to this file, // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' // The Symbol used to tag the ReactElement-like types. var REACT_ELEMENT_TYPE = Symbol.for('react.element'); var REACT_PORTAL_TYPE = Symbol.for('react.portal'); var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment'); var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode'); var REACT_PROFILER_TYPE = Symbol.for('react.profiler'); var REACT_PROVIDER_TYPE = Symbol.for('react.provider'); var REACT_CONTEXT_TYPE = Symbol.for('react.context'); var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref'); var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense'); var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list'); var REACT_MEMO_TYPE = Symbol.for('react.memo'); var REACT_LAZY_TYPE = Symbol.for('react.lazy'); var REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen'); var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; function getIteratorFn(maybeIterable) { if (maybeIterable === null || typeof maybeIterable !== 'object') { return null; } var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; if (typeof maybeIterator === 'function') { return maybeIterator; } return null; } var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; function error(format) { { { for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } printWarning('error', format, args); } } } function printWarning(level, format, args) { // When changing this logic, you might want to also // update consoleWithStackDev.www.js as well. { var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; var stack = ReactDebugCurrentFrame.getStackAddendum(); if (stack !== '') { format += '%s'; args = args.concat([stack]); } // eslint-disable-next-line react-internal/safe-string-coercion var argsWithFormat = args.map(function (item) { return String(item); }); // Careful: RN currently depends on this prefix argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it // breaks IE9: https://github.com/facebook/react/issues/13610 // eslint-disable-next-line react-internal/no-production-logging Function.prototype.apply.call(console[level], console, argsWithFormat); } } // ----------------------------------------------------------------------------- var enableScopeAPI = false; // Experimental Create Event Handle API. var enableCacheElement = false; var enableTransitionTracing = false; // No known bugs, but needs performance testing var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber // stuff. Intended to enable React core members to more easily debug scheduling // issues in DEV builds. var enableDebugTracing = false; // Track which Fiber(s) schedule render work. var REACT_MODULE_REFERENCE; { REACT_MODULE_REFERENCE = Symbol.for('react.module.reference'); } function isValidElementType(type) { if (typeof type === 'string' || typeof type === 'function') { return true; } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill). if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing ) { return true; } if (typeof type === 'object' && type !== null) { if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object // types supported by any Flight configuration anywhere since // we don't know which Flight build this will end up being used // with. type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) { return true; } } return false; } function getWrappedName(outerType, innerType, wrapperName) { var displayName = outerType.displayName; if (displayName) { return displayName; } var functionName = innerType.displayName || innerType.name || ''; return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName; } // Keep in sync with react-reconciler/getComponentNameFromFiber function getContextName(type) { return type.displayName || 'Context'; } // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead. function getComponentNameFromType(type) { if (type == null) { // Host root, text node or just invalid type. return null; } { if (typeof type.tag === 'number') { error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.'); } } if (typeof type === 'function') { return type.displayName || type.name || null; } if (typeof type === 'string') { return type; } switch (type) { case REACT_FRAGMENT_TYPE: return 'Fragment'; case REACT_PORTAL_TYPE: return 'Portal'; case REACT_PROFILER_TYPE: return 'Profiler'; case REACT_STRICT_MODE_TYPE: return 'StrictMode'; case REACT_SUSPENSE_TYPE: return 'Suspense'; case REACT_SUSPENSE_LIST_TYPE: return 'SuspenseList'; } if (typeof type === 'object') { switch (type.$$typeof) { case REACT_CONTEXT_TYPE: var context = type; return getContextName(context) + '.Consumer'; case REACT_PROVIDER_TYPE: var provider = type; return getContextName(provider._context) + '.Provider'; case REACT_FORWARD_REF_TYPE: return getWrappedName(type, type.render, 'ForwardRef'); case REACT_MEMO_TYPE: var outerName = type.displayName || null; if (outerName !== null) { return outerName; } return getComponentNameFromType(type.type) || 'Memo'; case REACT_LAZY_TYPE: { var lazyComponent = type; var payload = lazyComponent._payload; var init = lazyComponent._init; try { return getComponentNameFromType(init(payload)); } catch (x) { return null; } } // eslint-disable-next-line no-fallthrough } } return null; } var assign = Object.assign; // Helpers to patch console.logs to avoid logging during side-effect free // replaying on render function. This currently only patches the object // lazily which won't cover if the log function was extracted eagerly. // We could also eagerly patch the method. var disabledDepth = 0; var prevLog; var prevInfo; var prevWarn; var prevError; var prevGroup; var prevGroupCollapsed; var prevGroupEnd; function disabledLog() {} disabledLog.__reactDisabledLog = true; function disableLogs() { { if (disabledDepth === 0) { /* eslint-disable react-internal/no-production-logging */ prevLog = console.log; prevInfo = console.info; prevWarn = console.warn; prevError = console.error; prevGroup = console.group; prevGroupCollapsed = console.groupCollapsed; prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099 var props = { configurable: true, enumerable: true, value: disabledLog, writable: true }; // $FlowFixMe Flow thinks console is immutable. Object.defineProperties(console, { info: props, log: props, warn: props, error: props, group: props, groupCollapsed: props, groupEnd: props }); /* eslint-enable react-internal/no-production-logging */ } disabledDepth++; } } function reenableLogs() { { disabledDepth--; if (disabledDepth === 0) { /* eslint-disable react-internal/no-production-logging */ var props = { configurable: true, enumerable: true, writable: true }; // $FlowFixMe Flow thinks console is immutable. Object.defineProperties(console, { log: assign({}, props, { value: prevLog }), info: assign({}, props, { value: prevInfo }), warn: assign({}, props, { value: prevWarn }), error: assign({}, props, { value: prevError }), group: assign({}, props, { value: prevGroup }), groupCollapsed: assign({}, props, { value: prevGroupCollapsed }), groupEnd: assign({}, props, { value: prevGroupEnd }) }); /* eslint-enable react-internal/no-production-logging */ } if (disabledDepth < 0) { error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.'); } } } var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; var prefix; function describeBuiltInComponentFrame(name, source, ownerFn) { { if (prefix === undefined) { // Extract the VM specific prefix used by each line. try { throw Error(); } catch (x) { var match = x.stack.trim().match(/\n( *(at )?)/); prefix = match && match[1] || ''; } } // We use the prefix to ensure our stacks line up with native stack frames. return '\n' + prefix + name; } } var reentry = false; var componentFrameCache; { var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map; componentFrameCache = new PossiblyWeakMap(); } function describeNativeComponentFrame(fn, construct) { // If something asked for a stack inside a fake render, it should get ignored. if ( !fn || reentry) { return ''; } { var frame = componentFrameCache.get(fn); if (frame !== undefined) { return frame; } } var control; reentry = true; var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined. Error.prepareStackTrace = undefined; var previousDispatcher; { previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function // for warnings. ReactCurrentDispatcher.current = null; disableLogs(); } try { // This should throw. if (construct) { // Something should be setting the props in the constructor. var Fake = function () { throw Error(); }; // $FlowFixMe Object.defineProperty(Fake.prototype, 'props', { set: function () { // We use a throwing setter instead of frozen or non-writable props // because that won't throw in a non-strict mode function. throw Error(); } }); if (typeof Reflect === 'object' && Reflect.construct) { // We construct a different control for this case to include any extra // frames added by the construct call. try { Reflect.construct(Fake, []); } catch (x) { control = x; } Reflect.construct(fn, [], Fake); } else { try { Fake.call(); } catch (x) { control = x; } fn.call(Fake.prototype); } } else { try { throw Error(); } catch (x) { control = x; } fn(); } } catch (sample) { // This is inlined manually because closure doesn't do it for us. if (sample && control && typeof sample.stack === 'string') { // This extracts the first frame from the sample that isn't also in the control. // Skipping one frame that we assume is the frame that calls the two. var sampleLines = sample.stack.split('\n'); var controlLines = control.stack.split('\n'); var s = sampleLines.length - 1; var c = controlLines.length - 1; while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { // We expect at least one stack frame to be shared. // Typically this will be the root most one. However, stack frames may be // cut off due to maximum stack limits. In this case, one maybe cut off // earlier than the other. We assume that the sample is longer or the same // and there for cut off earlier. So we should find the root most frame in // the sample somewhere in the control. c--; } for (; s >= 1 && c >= 0; s--, c--) { // Next we find the first one that isn't the same which should be the // frame that called our sample function and the control. if (sampleLines[s] !== controlLines[c]) { // In V8, the first line is describing the message but other VMs don't. // If we're about to return the first line, and the control is also on the same // line, that's a pretty good indicator that our sample threw at same line as // the control. I.e. before we entered the sample frame. So we ignore this result. // This can happen if you passed a class to function component, or non-function. if (s !== 1 || c !== 1) { do { s--; c--; // We may still have similar intermediate frames from the construct call. // The next one that isn't the same should be our match though. if (c < 0 || sampleLines[s] !== controlLines[c]) { // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier. var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "<anonymous>" // but we have a user-provided "displayName" // splice it in to make the stack more readable. if (fn.displayName && _frame.includes('<anonymous>')) { _frame = _frame.replace('<anonymous>', fn.displayName); } { if (typeof fn === 'function') { componentFrameCache.set(fn, _frame); } } // Return the line we found. return _frame; } } while (s >= 1 && c >= 0); } break; } } } } finally { reentry = false; { ReactCurrentDispatcher.current = previousDispatcher; reenableLogs(); } Error.prepareStackTrace = previousPrepareStackTrace; } // Fallback to just using the name if we couldn't make it throw. var name = fn ? fn.displayName || fn.name : ''; var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ''; { if (typeof fn === 'function') { componentFrameCache.set(fn, syntheticFrame); } } return syntheticFrame; } function describeFunctionComponentFrame(fn, source, ownerFn) { { return describeNativeComponentFrame(fn, false); } } function shouldConstruct(Component) { var prototype = Component.prototype; return !!(prototype && prototype.isReactComponent); } function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { if (type == null) { return ''; } if (typeof type === 'function') { { return describeNativeComponentFrame(type, shouldConstruct(type)); } } if (typeof type === 'string') { return describeBuiltInComponentFrame(type); } switch (type) { case REACT_SUSPENSE_TYPE: return describeBuiltInComponentFrame('Suspense'); case REACT_SUSPENSE_LIST_TYPE: return describeBuiltInComponentFrame('SuspenseList'); } if (typeof type === 'object') { switch (type.$$typeof) { case REACT_FORWARD_REF_TYPE: return describeFunctionComponentFrame(type.render); case REACT_MEMO_TYPE: // Memo may contain any component type so we recursively resolve it. return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); case REACT_LAZY_TYPE: { var lazyComponent = type; var payload = lazyComponent._payload; var init = lazyComponent._init; try { // Lazy may contain any component type so we recursively resolve it. return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); } catch (x) {} } } } return ''; } var hasOwnProperty = Object.prototype.hasOwnProperty; var loggedTypeFailures = {}; var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; function setCurrentlyValidatingElement(element) { { if (element) { var owner = element._owner; var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); ReactDebugCurrentFrame.setExtraStackFrame(stack); } else { ReactDebugCurrentFrame.setExtraStackFrame(null); } } } function checkPropTypes(typeSpecs, values, location, componentName, element) { { // $FlowFixMe This is okay but Flow doesn't know it. var has = Function.call.bind(hasOwnProperty); for (var typeSpecName in typeSpecs) { if (has(typeSpecs, typeSpecName)) { var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. if (typeof typeSpecs[typeSpecName] !== 'function') { // eslint-disable-next-line react-internal/prod-error-codes var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.'); err.name = 'Invariant Violation'; throw err; } error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'); } catch (ex) { error$1 = ex; } if (error$1 && !(error$1 instanceof Error)) { setCurrentlyValidatingElement(element); error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1); setCurrentlyValidatingElement(null); } if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error$1.message] = true; setCurrentlyValidatingElement(element); error('Failed %s type: %s', location, error$1.message); setCurrentlyValidatingElement(null); } } } } } var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare function isArray(a) { return isArrayImpl(a); } /* * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol * and Temporal.* types. See https://github.com/facebook/react/pull/22064. * * The functions in this module will throw an easier-to-understand, * easier-to-debug exception with a clear errors message message explaining the * problem. (Instead of a confusing exception thrown inside the implementation * of the `value` object). */ // $FlowFixMe only called in DEV, so void return is not possible. function typeName(value) { { // toStringTag is needed for namespaced types like Temporal.Instant var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag; var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object'; return type; } } // $FlowFixMe only called in DEV, so void return is not possible. function willCoercionThrow(value) { { try { testStringCoercion(value); return false; } catch (e) { return true; } } } function testStringCoercion(value) { // If you ended up here by following an exception call stack, here's what's // happened: you supplied an object or symbol value to React (as a prop, key, // DOM attribute, CSS property, string ref, etc.) and when React tried to // coerce it to a string using `'' + value`, an exception was thrown. // // The most common types that will cause this exception are `Symbol` instances // and Temporal objects like `Temporal.Instant`. But any object that has a // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this // exception. (Library authors do this to prevent users from using built-in // numeric operators like `+` or comparison operators like `>=` because custom // methods are needed to perform accurate arithmetic or comparison.) // // To fix the problem, coerce this object or symbol value to a string before // passing it to React. The most reliable way is usually `String(value)`. // // To find which value is throwing, check the browser or debugger console. // Before this exception was thrown, there should be `console.error` output // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the // problem and how that type was used: key, atrribute, input value prop, etc. // In most cases, this console output also shows the component and its // ancestor components where the exception happened. // // eslint-disable-next-line react-internal/safe-string-coercion return '' + value; } function checkKeyStringCoercion(value) { { if (willCoercionThrow(value)) { error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value)); return testStringCoercion(value); // throw (to help callers find troubleshooting comments) } } } var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner; var RESERVED_PROPS = { key: true, ref: true, __self: true, __source: true }; var specialPropKeyWarningShown; var specialPropRefWarningShown; var didWarnAboutStringRefs; { didWarnAboutStringRefs = {}; } function hasValidRef(config) { { if (hasOwnProperty.call(config, 'ref')) { var getter = Object.getOwnPropertyDescriptor(config, 'ref').get; if (getter && getter.isReactWarning) { return false; } } } return config.ref !== undefined; } function hasValidKey(config) { { if (hasOwnProperty.call(config, 'key')) { var getter = Object.getOwnPropertyDescriptor(config, 'key').get; if (getter && getter.isReactWarning) { return false; } } } return config.key !== undefined; } function warnIfStringRefCannotBeAutoConverted(config, self) { { if (typeof config.ref === 'string' && ReactCurrentOwner.current && self && ReactCurrentOwner.current.stateNode !== self) { var componentName = getComponentNameFromType(ReactCurrentOwner.current.type); if (!didWarnAboutStringRefs[componentName]) { error('Component "%s" contains the string ref "%s". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', getComponentNameFromType(ReactCurrentOwner.current.type), config.ref); didWarnAboutStringRefs[componentName] = true; } } } } function defineKeyPropWarningGetter(props, displayName) { { var warnAboutAccessingKey = function () { if (!specialPropKeyWarningShown) { specialPropKeyWarningShown = true; error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName); } }; warnAboutAccessingKey.isReactWarning = true; Object.defineProperty(props, 'key', { get: warnAboutAccessingKey, configurable: true }); } } function defineRefPropWarningGetter(props, displayName) { { var warnAboutAccessingRef = function () { if (!specialPropRefWarningShown) { specialPropRefWarningShown = true; error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName); } }; warnAboutAccessingRef.isReactWarning = true; Object.defineProperty(props, 'ref', { get: warnAboutAccessingRef, configurable: true }); } } /** * Factory method to create a new React element. This no longer adheres to * the class pattern, so do not use new to call it. Also, instanceof check * will not work. Instead test $$typeof field against Symbol.for('react.element') to check * if something is a React Element. * * @param {*} type * @param {*} props * @param {*} key * @param {string|object} ref * @param {*} owner * @param {*} self A *temporary* helper to detect places where `this` is * different from the `owner` when React.createElement is called, so that we * can warn. We want to get rid of owner and replace string `ref`s with arrow * functions, and as long as `this` and owner are the same, there will be no * change in behavior. * @param {*} source An annotation object (added by a transpiler or otherwise) * indicating filename, line number, and/or other information. * @internal */ var ReactElement = function (type, key, ref, self, source, owner, props) { var element = { // This tag allows us to uniquely identify this as a React Element $$typeof: REACT_ELEMENT_TYPE, // Built-in properties that belong on the element type: type, key: key, ref: ref, props: props, // Record the component responsible for creating this element. _owner: owner }; { // The validation flag is currently mutative. We put it on // an external backing store so that we can freeze the whole object. // This can be replaced with a WeakMap once they are implemented in // commonly used development environments. element._store = {}; // To make comparing ReactElements easier for testing purposes, we make // the validation flag non-enumerable (where possible, which should // include every environment we run tests in), so the test framework // ignores it. Object.defineProperty(element._store, 'validated', { configurable: false, enumerable: false, writable: true, value: false }); // self and source are DEV only properties. Object.defineProperty(element, '_self', { configurable: false, enumerable: false, writable: false, value: self }); // Two elements created in two different places should be considered // equal for testing purposes and therefore we hide it from enumeration. Object.defineProperty(element, '_source', { configurable: false, enumerable: false, writable: false, value: source }); if (Object.freeze) { Object.freeze(element.props); Object.freeze(element); } } return element; }; /** * https://github.com/reactjs/rfcs/pull/107 * @param {*} type * @param {object} props * @param {string} key */ function jsxDEV(type, config, maybeKey, source, self) { { var propName; // Reserved names are extracted var props = {}; var key = null; var ref = null; // Currently, key can be spread in as a prop. This causes a potential // issue if key is also explicitly declared (ie. <div {...props} key="Hi" /> // or <div key="Hi" {...props} /> ). We want to deprecate key spread, // but as an intermediary step, we will use jsxDEV for everything except // <div {...props} key="Hi" />, because we aren't currently able to tell if // key is explicitly declared to be undefined or not. if (maybeKey !== undefined) { { checkKeyStringCoercion(maybeKey); } key = '' + maybeKey; } if (hasValidKey(config)) { { checkKeyStringCoercion(config.key); } key = '' + config.key; } if (hasValidRef(config)) { ref = config.ref; warnIfStringRefCannotBeAutoConverted(config, self); } // Remaining properties are added to a new props object for (propName in config) { if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } // Resolve default props if (type && type.defaultProps) { var defaultProps = type.defaultProps; for (propName in defaultProps) { if (props[propName] === undefined) { props[propName] = defaultProps[propName]; } } } if (key || ref) { var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type; if (key) { defineKeyPropWarningGetter(props, displayName); } if (ref) { defineRefPropWarningGetter(props, displayName); } } return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); } } var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner; var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; function setCurrentlyValidatingElement$1(element) { { if (element) { var owner = element._owner; var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); ReactDebugCurrentFrame$1.setExtraStackFrame(stack); } else { ReactDebugCurrentFrame$1.setExtraStackFrame(null); } } } var propTypesMisspellWarningShown; { propTypesMisspellWarningShown = false; } /** * Verifies the object is a ReactElement. * See https://reactjs.org/docs/react-api.html#isvalidelement * @param {?object} object * @return {boolean} True if `object` is a ReactElement. * @final */ function isValidElement(object) { { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; } } function getDeclarationErrorAddendum() { { if (ReactCurrentOwner$1.current) { var name = getComponentNameFromType(ReactCurrentOwner$1.current.type); if (name) { return '\n\nCheck the render method of `' + name + '`.'; } } return ''; } } function getSourceInfoErrorAddendum(source) { { if (source !== undefined) { var fileName = source.fileName.replace(/^.*[\\\/]/, ''); var lineNumber = source.lineNumber; return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.'; } return ''; } } /** * Warn if there's no key explicitly set on dynamic arrays of children or * object keys are not valid. This allows us to keep track of children between * updates. */ var ownerHasKeyUseWarning = {}; function getCurrentComponentErrorInfo(parentType) { { var info = getDeclarationErrorAddendum(); if (!info) { var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name; if (parentName) { info = "\n\nCheck the top-level render call using <" + parentName + ">."; } } return info; } } /** * Warn if the element doesn't have an explicit key assigned to it. * This element is in an array. The array could grow and shrink or be * reordered. All children that haven't already been validated are required to * have a "key" property assigned to it. Error statuses are cached so a warning * will only be shown once. * * @internal * @param {ReactElement} element Element that requires a key. * @param {*} parentType element's parent's type. */ function validateExplicitKey(element, parentType) { { if (!element._store || element._store.validated || element.key != null) { return; } element._store.validated = true; var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { return; } ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a // property, it may be the creator of the child that's responsible for // assigning it a key. var childOwner = ''; if (element && element._owner && element._owner !== ReactCurrentOwner$1.current) { // Give the component that originally created this child. childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + "."; } setCurrentlyValidatingElement$1(element); error('Each child in a list should have a unique "key" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner); setCurrentlyValidatingElement$1(null); } } /** * Ensure that every element either is passed in a static location, in an * array with an explicit keys property defined, or in an object literal * with valid key property. * * @internal * @param {ReactNode} node Statically passed child of any type. * @param {*} parentType node's parent's type. */ function validateChildKeys(node, parentType) { { if (typeof node !== 'object') { return; } if (isArray(node)) { for (var i = 0; i < node.length; i++) { var child = node[i]; if (isValidElement(child)) { validateExplicitKey(child, parentType); } } } else if (isValidElement(node)) { // This element was passed in a valid location. if (node._store) { node._store.validated = true; } } else if (node) { var iteratorFn = getIteratorFn(node); if (typeof iteratorFn === 'function') { // Entry iterators used to provide implicit keys, // but now we print a separate warning for them later. if (iteratorFn !== node.entries) { var iterator = iteratorFn.call(node); var step; while (!(step = iterator.next()).done) { if (isValidElement(step.value)) { validateExplicitKey(step.value, parentType); } } } } } } } /** * Given an element, validate that its props follow the propTypes definition, * provided by the type. * * @param {ReactElement} element */ function validatePropTypes(element) { { var type = element.type; if (type === null || type === undefined || typeof type === 'string') { return; } var propTypes; if (typeof type === 'function') { propTypes = type.propTypes; } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here. // Inner props are checked in the reconciler. type.$$typeof === REACT_MEMO_TYPE)) { propTypes = type.propTypes; } else { return; } if (propTypes) { // Intentionally inside to avoid triggering lazy initializers: var name = getComponentNameFromType(type); checkPropTypes(propTypes, element.props, 'prop', name, element); } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) { propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers: var _name = getComponentNameFromType(type); error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown'); } if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) { error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.'); } } } /** * Given a fragment, validate that it can only be provided with fragment props * @param {ReactElement} fragment */ function validateFragmentProps(fragment) { { var keys = Object.keys(fragment.props); for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (key !== 'children' && key !== 'key') { setCurrentlyValidatingElement$1(fragment); error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key); setCurrentlyValidatingElement$1(null); break; } } if (fragment.ref !== null) { setCurrentlyValidatingElement$1(fragment); error('Invalid attribute `ref` supplied to `React.Fragment`.'); setCurrentlyValidatingElement$1(null); } } } function jsxWithValidation(type, props, key, isStaticChildren, source, self) { { var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to // succeed and there will likely be errors in render. if (!validType) { var info = ''; if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) { info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports."; } var sourceInfo = getSourceInfoErrorAddendum(source); if (sourceInfo) { info += sourceInfo; } else { info += getDeclarationErrorAddendum(); } var typeString; if (type === null) { typeString = 'null'; } else if (isArray(type)) { typeString = 'array'; } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) { typeString = "<" + (getComponentNameFromType(type.type) || 'Unknown') + " />"; info = ' Did you accidentally export a JSX literal instead of a component?'; } else { typeString = typeof type; } error('React.jsx: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info); } var element = jsxDEV(type, props, key, source, self); // The result can be nullish if a mock or a custom function is used. // TODO: Drop this when these are no longer allowed as the type argument. if (element == null) { return element; } // Skip key warning if the type isn't valid since our key validation logic // doesn't expect a non-string/function type and can throw confusing errors. // We don't want exception behavior to differ between dev and prod. // (Rendering will throw with a helpful message and as soon as the type is // fixed, the key warnings will appear.) if (validType) { var children = props.children; if (children !== undefined) { if (isStaticChildren) { if (isArray(children)) { for (var i = 0; i < children.length; i++) { validateChildKeys(children[i], type); } if (Object.freeze) { Object.freeze(children); } } else { error('React.jsx: Static children should always be an array. ' + 'You are likely explicitly calling React.jsxs or React.jsxDEV. ' + 'Use the Babel transform instead.'); } } else { validateChildKeys(children, type); } } } if (type === REACT_FRAGMENT_TYPE) { validateFragmentProps(element); } else { validatePropTypes(element); } return element; } } // These two functions exist to still get child warnings in dev // even with the prod transform. This means that jsxDEV is purely // opt-in behavior for better messages but that we won't stop // giving you warnings if you use production apis. function jsxWithValidationStatic(type, props, key) { { return jsxWithValidation(type, props, key, true); } } function jsxWithValidationDynamic(type, props, key) { { return jsxWithValidation(type, props, key, false); } } var jsx = jsxWithValidationDynamic ; // we may want to special case jsxs internally to take advantage of static children. // for now we can ship identical prod functions var jsxs = jsxWithValidationStatic ; exports.Fragment = REACT_FRAGMENT_TYPE; exports.jsx = jsx; exports.jsxs = jsxs; })(); } /***/ }), /***/ "./node_modules/react/cjs/react.development.js": /*!*****************************************************!*\ !*** ./node_modules/react/cjs/react.development.js ***! \*****************************************************/ /***/ ((module, exports, __webpack_require__) => { "use strict"; /* module decorator */ module = __webpack_require__.nmd(module); /** * @license React * react.development.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ if (true) { (function() { 'use strict'; /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */ if ( typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === 'function' ) { __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error()); } var ReactVersion = '18.2.0'; // ATTENTION // When adding new symbols to this file, // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' // The Symbol used to tag the ReactElement-like types. var REACT_ELEMENT_TYPE = Symbol.for('react.element'); var REACT_PORTAL_TYPE = Symbol.for('react.portal'); var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment'); var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode'); var REACT_PROFILER_TYPE = Symbol.for('react.profiler'); var REACT_PROVIDER_TYPE = Symbol.for('react.provider'); var REACT_CONTEXT_TYPE = Symbol.for('react.context'); var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref'); var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense'); var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list'); var REACT_MEMO_TYPE = Symbol.for('react.memo'); var REACT_LAZY_TYPE = Symbol.for('react.lazy'); var REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen'); var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; function getIteratorFn(maybeIterable) { if (maybeIterable === null || typeof maybeIterable !== 'object') { return null; } var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; if (typeof maybeIterator === 'function') { return maybeIterator; } return null; } /** * Keeps track of the current dispatcher. */ var ReactCurrentDispatcher = { /** * @internal * @type {ReactComponent} */ current: null }; /** * Keeps track of the current batch's configuration such as how long an update * should suspend for if it needs to. */ var ReactCurrentBatchConfig = { transition: null }; var ReactCurrentActQueue = { current: null, // Used to reproduce behavior of `batchedUpdates` in legacy mode. isBatchingLegacy: false, didScheduleLegacyUpdate: false }; /** * Keeps track of the current owner. * * The current owner is the component who should own any components that are * currently being constructed. */ var ReactCurrentOwner = { /** * @internal * @type {ReactComponent} */ current: null }; var ReactDebugCurrentFrame = {}; var currentExtraStackFrame = null; function setExtraStackFrame(stack) { { currentExtraStackFrame = stack; } } { ReactDebugCurrentFrame.setExtraStackFrame = function (stack) { { currentExtraStackFrame = stack; } }; // Stack implementation injected by the current renderer. ReactDebugCurrentFrame.getCurrentStack = null; ReactDebugCurrentFrame.getStackAddendum = function () { var stack = ''; // Add an extra top frame while an element is being validated if (currentExtraStackFrame) { stack += currentExtraStackFrame; } // Delegate to the injected renderer-specific implementation var impl = ReactDebugCurrentFrame.getCurrentStack; if (impl) { stack += impl() || ''; } return stack; }; } // ----------------------------------------------------------------------------- var enableScopeAPI = false; // Experimental Create Event Handle API. var enableCacheElement = false; var enableTransitionTracing = false; // No known bugs, but needs performance testing var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber // stuff. Intended to enable React core members to more easily debug scheduling // issues in DEV builds. var enableDebugTracing = false; // Track which Fiber(s) schedule render work. var ReactSharedInternals = { ReactCurrentDispatcher: ReactCurrentDispatcher, ReactCurrentBatchConfig: ReactCurrentBatchConfig, ReactCurrentOwner: ReactCurrentOwner }; { ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame; ReactSharedInternals.ReactCurrentActQueue = ReactCurrentActQueue; } // by calls to these methods by a Babel plugin. // // In PROD (or in packages without access to React internals), // they are left as they are instead. function warn(format) { { { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } printWarning('warn', format, args); } } } function error(format) { { { for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } printWarning('error', format, args); } } } function printWarning(level, format, args) { // When changing this logic, you might want to also // update consoleWithStackDev.www.js as well. { var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; var stack = ReactDebugCurrentFrame.getStackAddendum(); if (stack !== '') { format += '%s'; args = args.concat([stack]); } // eslint-disable-next-line react-internal/safe-string-coercion var argsWithFormat = args.map(function (item) { return String(item); }); // Careful: RN currently depends on this prefix argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it // breaks IE9: https://github.com/facebook/react/issues/13610 // eslint-disable-next-line react-internal/no-production-logging Function.prototype.apply.call(console[level], console, argsWithFormat); } } var didWarnStateUpdateForUnmountedComponent = {}; function warnNoop(publicInstance, callerName) { { var _constructor = publicInstance.constructor; var componentName = _constructor && (_constructor.displayName || _constructor.name) || 'ReactClass'; var warningKey = componentName + "." + callerName; if (didWarnStateUpdateForUnmountedComponent[warningKey]) { return; } error("Can't call %s on a component that is not yet mounted. " + 'This is a no-op, but it might indicate a bug in your application. ' + 'Instead, assign to `this.state` directly or define a `state = {};` ' + 'class property with the desired state in the %s component.', callerName, componentName); didWarnStateUpdateForUnmountedComponent[warningKey] = true; } } /** * This is the abstract API for an update queue. */ var ReactNoopUpdateQueue = { /** * Checks whether or not this composite component is mounted. * @param {ReactClass} publicInstance The instance we want to test. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function (publicInstance) { return false; }, /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {?function} callback Called after component is updated. * @param {?string} callerName name of the calling function in the public API. * @internal */ enqueueForceUpdate: function (publicInstance, callback, callerName) { warnNoop(publicInstance, 'forceUpdate'); }, /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} completeState Next state. * @param {?function} callback Called after component is updated. * @param {?string} callerName name of the calling function in the public API. * @internal */ enqueueReplaceState: function (publicInstance, completeState, callback, callerName) { warnNoop(publicInstance, 'replaceState'); }, /** * Sets a subset of the state. This only exists because _pendingState is * internal. This provides a merging strategy that is not available to deep * properties which is confusing. TODO: Expose pendingState or don't use it * during the merge. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialState Next partial state to be merged with state. * @param {?function} callback Called after component is updated. * @param {?string} Name of the calling function in the public API. * @internal */ enqueueSetState: function (publicInstance, partialState, callback, callerName) { warnNoop(publicInstance, 'setState'); } }; var assign = Object.assign; var emptyObject = {}; { Object.freeze(emptyObject); } /** * Base class helpers for the updating state of a component. */ function Component(props, context, updater) { this.props = props; this.context = context; // If a component has string refs, we will assign a different object later. this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the // renderer. this.updater = updater || ReactNoopUpdateQueue; } Component.prototype.isReactComponent = {}; /** * Sets a subset of the state. Always use this to mutate * state. You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * There is no guarantee that calls to `setState` will run synchronously, * as they may eventually be batched together. You can provide an optional * callback that will be executed when the call to setState is actually * completed. * * When a function is provided to setState, it will be called at some point in * the future (not synchronously). It will be called with the up to date * component arguments (state, props, context). These values can be different * from this.* because your function may be called after receiveProps but before * shouldComponentUpdate, and this new state, props, and context will not yet be * assigned to this. * * @param {object|function} partialState Next partial state or function to * produce next partial state to be merged with current state. * @param {?function} callback Called after state is updated. * @final * @protected */ Component.prototype.setState = function (partialState, callback) { if (typeof partialState !== 'object' && typeof partialState !== 'function' && partialState != null) { throw new Error('setState(...): takes an object of state variables to update or a ' + 'function which returns an object of state variables.'); } this.updater.enqueueSetState(this, partialState, callback, 'setState'); }; /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {?function} callback Called after update is complete. * @final * @protected */ Component.prototype.forceUpdate = function (callback) { this.updater.enqueueForceUpdate(this, callback, 'forceUpdate'); }; /** * Deprecated APIs. These APIs used to exist on classic React classes but since * we would like to deprecate them, we're not going to move them over to this * modern base class. Instead, we define a getter that warns if it's accessed. */ { var deprecatedAPIs = { isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'], replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).'] }; var defineDeprecationWarning = function (methodName, info) { Object.defineProperty(Component.prototype, methodName, { get: function () { warn('%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]); return undefined; } }); }; for (var fnName in deprecatedAPIs) { if (deprecatedAPIs.hasOwnProperty(fnName)) { defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); } } } function ComponentDummy() {} ComponentDummy.prototype = Component.prototype; /** * Convenience component with default shallow equality check for sCU. */ function PureComponent(props, context, updater) { this.props = props; this.context = context; // If a component has string refs, we will assign a different object later. this.refs = emptyObject; this.updater = updater || ReactNoopUpdateQueue; } var pureComponentPrototype = PureComponent.prototype = new ComponentDummy(); pureComponentPrototype.constructor = PureComponent; // Avoid an extra prototype jump for these methods. assign(pureComponentPrototype, Component.prototype); pureComponentPrototype.isPureReactComponent = true; // an immutable object with a single mutable value function createRef() { var refObject = { current: null }; { Object.seal(refObject); } return refObject; } var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare function isArray(a) { return isArrayImpl(a); } /* * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol * and Temporal.* types. See https://github.com/facebook/react/pull/22064. * * The functions in this module will throw an easier-to-understand, * easier-to-debug exception with a clear errors message message explaining the * problem. (Instead of a confusing exception thrown inside the implementation * of the `value` object). */ // $FlowFixMe only called in DEV, so void return is not possible. function typeName(value) { { // toStringTag is needed for namespaced types like Temporal.Instant var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag; var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object'; return type; } } // $FlowFixMe only called in DEV, so void return is not possible. function willCoercionThrow(value) { { try { testStringCoercion(value); return false; } catch (e) { return true; } } } function testStringCoercion(value) { // If you ended up here by following an exception call stack, here's what's // happened: you supplied an object or symbol value to React (as a prop, key, // DOM attribute, CSS property, string ref, etc.) and when React tried to // coerce it to a string using `'' + value`, an exception was thrown. // // The most common types that will cause this exception are `Symbol` instances // and Temporal objects like `Temporal.Instant`. But any object that has a // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this // exception. (Library authors do this to prevent users from using built-in // numeric operators like `+` or comparison operators like `>=` because custom // methods are needed to perform accurate arithmetic or comparison.) // // To fix the problem, coerce this object or symbol value to a string before // passing it to React. The most reliable way is usually `String(value)`. // // To find which value is throwing, check the browser or debugger console. // Before this exception was thrown, there should be `console.error` output // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the // problem and how that type was used: key, atrribute, input value prop, etc. // In most cases, this console output also shows the component and its // ancestor components where the exception happened. // // eslint-disable-next-line react-internal/safe-string-coercion return '' + value; } function checkKeyStringCoercion(value) { { if (willCoercionThrow(value)) { error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value)); return testStringCoercion(value); // throw (to help callers find troubleshooting comments) } } } function getWrappedName(outerType, innerType, wrapperName) { var displayName = outerType.displayName; if (displayName) { return displayName; } var functionName = innerType.displayName || innerType.name || ''; return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName; } // Keep in sync with react-reconciler/getComponentNameFromFiber function getContextName(type) { return type.displayName || 'Context'; } // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead. function getComponentNameFromType(type) { if (type == null) { // Host root, text node or just invalid type. return null; } { if (typeof type.tag === 'number') { error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.'); } } if (typeof type === 'function') { return type.displayName || type.name || null; } if (typeof type === 'string') { return type; } switch (type) { case REACT_FRAGMENT_TYPE: return 'Fragment'; case REACT_PORTAL_TYPE: return 'Portal'; case REACT_PROFILER_TYPE: return 'Profiler'; case REACT_STRICT_MODE_TYPE: return 'StrictMode'; case REACT_SUSPENSE_TYPE: return 'Suspense'; case REACT_SUSPENSE_LIST_TYPE: return 'SuspenseList'; } if (typeof type === 'object') { switch (type.$$typeof) { case REACT_CONTEXT_TYPE: var context = type; return getContextName(context) + '.Consumer'; case REACT_PROVIDER_TYPE: var provider = type; return getContextName(provider._context) + '.Provider'; case REACT_FORWARD_REF_TYPE: return getWrappedName(type, type.render, 'ForwardRef'); case REACT_MEMO_TYPE: var outerName = type.displayName || null; if (outerName !== null) { return outerName; } return getComponentNameFromType(type.type) || 'Memo'; case REACT_LAZY_TYPE: { var lazyComponent = type; var payload = lazyComponent._payload; var init = lazyComponent._init; try { return getComponentNameFromType(init(payload)); } catch (x) { return null; } } // eslint-disable-next-line no-fallthrough } } return null; } var hasOwnProperty = Object.prototype.hasOwnProperty; var RESERVED_PROPS = { key: true, ref: true, __self: true, __source: true }; var specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs; { didWarnAboutStringRefs = {}; } function hasValidRef(config) { { if (hasOwnProperty.call(config, 'ref')) { var getter = Object.getOwnPropertyDescriptor(config, 'ref').get; if (getter && getter.isReactWarning) { return false; } } } return config.ref !== undefined; } function hasValidKey(config) { { if (hasOwnProperty.call(config, 'key')) { var getter = Object.getOwnPropertyDescriptor(config, 'key').get; if (getter && getter.isReactWarning) { return false; } } } return config.key !== undefined; } function defineKeyPropWarningGetter(props, displayName) { var warnAboutAccessingKey = function () { { if (!specialPropKeyWarningShown) { specialPropKeyWarningShown = true; error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName); } } }; warnAboutAccessingKey.isReactWarning = true; Object.defineProperty(props, 'key', { get: warnAboutAccessingKey, configurable: true }); } function defineRefPropWarningGetter(props, displayName) { var warnAboutAccessingRef = function () { { if (!specialPropRefWarningShown) { specialPropRefWarningShown = true; error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName); } } }; warnAboutAccessingRef.isReactWarning = true; Object.defineProperty(props, 'ref', { get: warnAboutAccessingRef, configurable: true }); } function warnIfStringRefCannotBeAutoConverted(config) { { if (typeof config.ref === 'string' && ReactCurrentOwner.current && config.__self && ReactCurrentOwner.current.stateNode !== config.__self) { var componentName = getComponentNameFromType(ReactCurrentOwner.current.type); if (!didWarnAboutStringRefs[componentName]) { error('Component "%s" contains the string ref "%s". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', componentName, config.ref); didWarnAboutStringRefs[componentName] = true; } } } } /** * Factory method to create a new React element. This no longer adheres to * the class pattern, so do not use new to call it. Also, instanceof check * will not work. Instead test $$typeof field against Symbol.for('react.element') to check * if something is a React Element. * * @param {*} type * @param {*} props * @param {*} key * @param {string|object} ref * @param {*} owner * @param {*} self A *temporary* helper to detect places where `this` is * different from the `owner` when React.createElement is called, so that we * can warn. We want to get rid of owner and replace string `ref`s with arrow * functions, and as long as `this` and owner are the same, there will be no * change in behavior. * @param {*} source An annotation object (added by a transpiler or otherwise) * indicating filename, line number, and/or other information. * @internal */ var ReactElement = function (type, key, ref, self, source, owner, props) { var element = { // This tag allows us to uniquely identify this as a React Element $$typeof: REACT_ELEMENT_TYPE, // Built-in properties that belong on the element type: type, key: key, ref: ref, props: props, // Record the component responsible for creating this element. _owner: owner }; { // The validation flag is currently mutative. We put it on // an external backing store so that we can freeze the whole object. // This can be replaced with a WeakMap once they are implemented in // commonly used development environments. element._store = {}; // To make comparing ReactElements easier for testing purposes, we make // the validation flag non-enumerable (where possible, which should // include every environment we run tests in), so the test framework // ignores it. Object.defineProperty(element._store, 'validated', { configurable: false, enumerable: false, writable: true, value: false }); // self and source are DEV only properties. Object.defineProperty(element, '_self', { configurable: false, enumerable: false, writable: false, value: self }); // Two elements created in two different places should be considered // equal for testing purposes and therefore we hide it from enumeration. Object.defineProperty(element, '_source', { configurable: false, enumerable: false, writable: false, value: source }); if (Object.freeze) { Object.freeze(element.props); Object.freeze(element); } } return element; }; /** * Create and return a new ReactElement of the given type. * See https://reactjs.org/docs/react-api.html#createelement */ function createElement(type, config, children) { var propName; // Reserved names are extracted var props = {}; var key = null; var ref = null; var self = null; var source = null; if (config != null) { if (hasValidRef(config)) { ref = config.ref; { warnIfStringRefCannotBeAutoConverted(config); } } if (hasValidKey(config)) { { checkKeyStringCoercion(config.key); } key = '' + config.key; } self = config.__self === undefined ? null : config.__self; source = config.__source === undefined ? null : config.__source; // Remaining properties are added to a new props object for (propName in config) { if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } { if (Object.freeze) { Object.freeze(childArray); } } props.children = childArray; } // Resolve default props if (type && type.defaultProps) { var defaultProps = type.defaultProps; for (propName in defaultProps) { if (props[propName] === undefined) { props[propName] = defaultProps[propName]; } } } { if (key || ref) { var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type; if (key) { defineKeyPropWarningGetter(props, displayName); } if (ref) { defineRefPropWarningGetter(props, displayName); } } } return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); } function cloneAndReplaceKey(oldElement, newKey) { var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props); return newElement; } /** * Clone and return a new ReactElement using element as the starting point. * See https://reactjs.org/docs/react-api.html#cloneelement */ function cloneElement(element, config, children) { if (element === null || element === undefined) { throw new Error("React.cloneElement(...): The argument must be a React element, but you passed " + element + "."); } var propName; // Original props are copied var props = assign({}, element.props); // Reserved names are extracted var key = element.key; var ref = element.ref; // Self is preserved since the owner is preserved. var self = element._self; // Source is preserved since cloneElement is unlikely to be targeted by a // transpiler, and the original source is probably a better indicator of the // true owner. var source = element._source; // Owner will be preserved, unless ref is overridden var owner = element._owner; if (config != null) { if (hasValidRef(config)) { // Silently steal the ref from the parent. ref = config.ref; owner = ReactCurrentOwner.current; } if (hasValidKey(config)) { { checkKeyStringCoercion(config.key); } key = '' + config.key; } // Remaining properties override existing props var defaultProps; if (element.type && element.type.defaultProps) { defaultProps = element.type.defaultProps; } for (propName in config) { if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { if (config[propName] === undefined && defaultProps !== undefined) { // Resolve default props props[propName] = defaultProps[propName]; } else { props[propName] = config[propName]; } } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } return ReactElement(element.type, key, ref, self, source, owner, props); } /** * Verifies the object is a ReactElement. * See https://reactjs.org/docs/react-api.html#isvalidelement * @param {?object} object * @return {boolean} True if `object` is a ReactElement. * @final */ function isValidElement(object) { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; } var SEPARATOR = '.'; var SUBSEPARATOR = ':'; /** * Escape and wrap key so it is safe to use as a reactid * * @param {string} key to be escaped. * @return {string} the escaped key. */ function escape(key) { var escapeRegex = /[=:]/g; var escaperLookup = { '=': '=0', ':': '=2' }; var escapedString = key.replace(escapeRegex, function (match) { return escaperLookup[match]; }); return '$' + escapedString; } /** * TODO: Test that a single child and an array with one item have the same key * pattern. */ var didWarnAboutMaps = false; var userProvidedKeyEscapeRegex = /\/+/g; function escapeUserProvidedKey(text) { return text.replace(userProvidedKeyEscapeRegex, '$&/'); } /** * Generate a key string that identifies a element within a set. * * @param {*} element A element that could contain a manual key. * @param {number} index Index that is used if a manual key is not provided. * @return {string} */ function getElementKey(element, index) { // Do some typechecking here since we call this blindly. We want to ensure // that we don't block potential future ES APIs. if (typeof element === 'object' && element !== null && element.key != null) { // Explicit key { checkKeyStringCoercion(element.key); } return escape('' + element.key); } // Implicit key determined by the index in the set return index.toString(36); } function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) { var type = typeof children; if (type === 'undefined' || type === 'boolean') { // All of the above are perceived as null. children = null; } var invokeCallback = false; if (children === null) { invokeCallback = true; } else { switch (type) { case 'string': case 'number': invokeCallback = true; break; case 'object': switch (children.$$typeof) { case REACT_ELEMENT_TYPE: case REACT_PORTAL_TYPE: invokeCallback = true; } } } if (invokeCallback) { var _child = children; var mappedChild = callback(_child); // If it's the only child, treat the name as if it was wrapped in an array // so that it's consistent if the number of children grows: var childKey = nameSoFar === '' ? SEPARATOR + getElementKey(_child, 0) : nameSoFar; if (isArray(mappedChild)) { var escapedChildKey = ''; if (childKey != null) { escapedChildKey = escapeUserProvidedKey(childKey) + '/'; } mapIntoArray(mappedChild, array, escapedChildKey, '', function (c) { return c; }); } else if (mappedChild != null) { if (isValidElement(mappedChild)) { { // The `if` statement here prevents auto-disabling of the safe // coercion ESLint rule, so we must manually disable it below. // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key if (mappedChild.key && (!_child || _child.key !== mappedChild.key)) { checkKeyStringCoercion(mappedChild.key); } } mappedChild = cloneAndReplaceKey(mappedChild, // Keep both the (mapped) and old keys if they differ, just as // traverseAllChildren used to do for objects as children escapedPrefix + ( // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key mappedChild.key && (!_child || _child.key !== mappedChild.key) ? // $FlowFixMe Flow incorrectly thinks existing element's key can be a number // eslint-disable-next-line react-internal/safe-string-coercion escapeUserProvidedKey('' + mappedChild.key) + '/' : '') + childKey); } array.push(mappedChild); } return 1; } var child; var nextName; var subtreeCount = 0; // Count of children found in the current subtree. var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR; if (isArray(children)) { for (var i = 0; i < children.length; i++) { child = children[i]; nextName = nextNamePrefix + getElementKey(child, i); subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback); } } else { var iteratorFn = getIteratorFn(children); if (typeof iteratorFn === 'function') { var iterableChildren = children; { // Warn about using Maps as children if (iteratorFn === iterableChildren.entries) { if (!didWarnAboutMaps) { warn('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.'); } didWarnAboutMaps = true; } } var iterator = iteratorFn.call(iterableChildren); var step; var ii = 0; while (!(step = iterator.next()).done) { child = step.value; nextName = nextNamePrefix + getElementKey(child, ii++); subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback); } } else if (type === 'object') { // eslint-disable-next-line react-internal/safe-string-coercion var childrenString = String(children); throw new Error("Objects are not valid as a React child (found: " + (childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString) + "). " + 'If you meant to render a collection of children, use an array ' + 'instead.'); } } return subtreeCount; } /** * Maps children that are typically specified as `props.children`. * * See https://reactjs.org/docs/react-api.html#reactchildrenmap * * The provided mapFunction(child, index) will be called for each * leaf child. * * @param {?*} children Children tree container. * @param {function(*, int)} func The map function. * @param {*} context Context for mapFunction. * @return {object} Object containing the ordered map of results. */ function mapChildren(children, func, context) { if (children == null) { return children; } var result = []; var count = 0; mapIntoArray(children, result, '', '', function (child) { return func.call(context, child, count++); }); return result; } /** * Count the number of children that are typically specified as * `props.children`. * * See https://reactjs.org/docs/react-api.html#reactchildrencount * * @param {?*} children Children tree container. * @return {number} The number of children. */ function countChildren(children) { var n = 0; mapChildren(children, function () { n++; // Don't return anything }); return n; } /** * Iterates through children that are typically specified as `props.children`. * * See https://reactjs.org/docs/react-api.html#reactchildrenforeach * * The provided forEachFunc(child, index) will be called for each * leaf child. * * @param {?*} children Children tree container. * @param {function(*, int)} forEachFunc * @param {*} forEachContext Context for forEachContext. */ function forEachChildren(children, forEachFunc, forEachContext) { mapChildren(children, function () { forEachFunc.apply(this, arguments); // Don't return anything. }, forEachContext); } /** * Flatten a children object (typically specified as `props.children`) and * return an array with appropriately re-keyed children. * * See https://reactjs.org/docs/react-api.html#reactchildrentoarray */ function toArray(children) { return mapChildren(children, function (child) { return child; }) || []; } /** * Returns the first child in a collection of children and verifies that there * is only one child in the collection. * * See https://reactjs.org/docs/react-api.html#reactchildrenonly * * The current implementation of this function assumes that a single child gets * passed without a wrapper, but the purpose of this helper function is to * abstract away the particular structure of children. * * @param {?object} children Child collection structure. * @return {ReactElement} The first and only `ReactElement` contained in the * structure. */ function onlyChild(children) { if (!isValidElement(children)) { throw new Error('React.Children.only expected to receive a single React element child.'); } return children; } function createContext(defaultValue) { // TODO: Second argument used to be an optional `calculateChangedBits` // function. Warn to reserve for future use? var context = { $$typeof: REACT_CONTEXT_TYPE, // As a workaround to support multiple concurrent renderers, we categorize // some renderers as primary and others as secondary. We only expect // there to be two concurrent renderers at most: React Native (primary) and // Fabric (secondary); React DOM (primary) and React ART (secondary). // Secondary renderers store their context values on separate fields. _currentValue: defaultValue, _currentValue2: defaultValue, // Used to track how many concurrent renderers this context currently // supports within in a single renderer. Such as parallel server rendering. _threadCount: 0, // These are circular Provider: null, Consumer: null, // Add these to use same hidden class in VM as ServerContext _defaultValue: null, _globalName: null }; context.Provider = { $$typeof: REACT_PROVIDER_TYPE, _context: context }; var hasWarnedAboutUsingNestedContextConsumers = false; var hasWarnedAboutUsingConsumerProvider = false; var hasWarnedAboutDisplayNameOnConsumer = false; { // A separate object, but proxies back to the original context object for // backwards compatibility. It has a different $$typeof, so we can properly // warn for the incorrect usage of Context as a Consumer. var Consumer = { $$typeof: REACT_CONTEXT_TYPE, _context: context }; // $FlowFixMe: Flow complains about not setting a value, which is intentional here Object.defineProperties(Consumer, { Provider: { get: function () { if (!hasWarnedAboutUsingConsumerProvider) { hasWarnedAboutUsingConsumerProvider = true; error('Rendering <Context.Consumer.Provider> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Provider> instead?'); } return context.Provider; }, set: function (_Provider) { context.Provider = _Provider; } }, _currentValue: { get: function () { return context._currentValue; }, set: function (_currentValue) { context._currentValue = _currentValue; } }, _currentValue2: { get: function () { return context._currentValue2; }, set: function (_currentValue2) { context._currentValue2 = _currentValue2; } }, _threadCount: { get: function () { return context._threadCount; }, set: function (_threadCount) { context._threadCount = _threadCount; } }, Consumer: { get: function () { if (!hasWarnedAboutUsingNestedContextConsumers) { hasWarnedAboutUsingNestedContextConsumers = true; error('Rendering <Context.Consumer.Consumer> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?'); } return context.Consumer; } }, displayName: { get: function () { return context.displayName; }, set: function (displayName) { if (!hasWarnedAboutDisplayNameOnConsumer) { warn('Setting `displayName` on Context.Consumer has no effect. ' + "You should set it directly on the context with Context.displayName = '%s'.", displayName); hasWarnedAboutDisplayNameOnConsumer = true; } } } }); // $FlowFixMe: Flow complains about missing properties because it doesn't understand defineProperty context.Consumer = Consumer; } { context._currentRenderer = null; context._currentRenderer2 = null; } return context; } var Uninitialized = -1; var Pending = 0; var Resolved = 1; var Rejected = 2; function lazyInitializer(payload) { if (payload._status === Uninitialized) { var ctor = payload._result; var thenable = ctor(); // Transition to the next state. // This might throw either because it's missing or throws. If so, we treat it // as still uninitialized and try again next time. Which is the same as what // happens if the ctor or any wrappers processing the ctor throws. This might // end up fixing it if the resolution was a concurrency bug. thenable.then(function (moduleObject) { if (payload._status === Pending || payload._status === Uninitialized) { // Transition to the next state. var resolved = payload; resolved._status = Resolved; resolved._result = moduleObject; } }, function (error) { if (payload._status === Pending || payload._status === Uninitialized) { // Transition to the next state. var rejected = payload; rejected._status = Rejected; rejected._result = error; } }); if (payload._status === Uninitialized) { // In case, we're still uninitialized, then we're waiting for the thenable // to resolve. Set it as pending in the meantime. var pending = payload; pending._status = Pending; pending._result = thenable; } } if (payload._status === Resolved) { var moduleObject = payload._result; { if (moduleObject === undefined) { error('lazy: Expected the result of a dynamic imp' + 'ort() call. ' + 'Instead received: %s\n\nYour code should look like: \n ' + // Break up imports to avoid accidentally parsing them as dependencies. 'const MyComponent = lazy(() => imp' + "ort('./MyComponent'))\n\n" + 'Did you accidentally put curly braces around the import?', moduleObject); } } { if (!('default' in moduleObject)) { error('lazy: Expected the result of a dynamic imp' + 'ort() call. ' + 'Instead received: %s\n\nYour code should look like: \n ' + // Break up imports to avoid accidentally parsing them as dependencies. 'const MyComponent = lazy(() => imp' + "ort('./MyComponent'))", moduleObject); } } return moduleObject.default; } else { throw payload._result; } } function lazy(ctor) { var payload = { // We use these fields to store the result. _status: Uninitialized, _result: ctor }; var lazyType = { $$typeof: REACT_LAZY_TYPE, _payload: payload, _init: lazyInitializer }; { // In production, this would just set it on the object. var defaultProps; var propTypes; // $FlowFixMe Object.defineProperties(lazyType, { defaultProps: { configurable: true, get: function () { return defaultProps; }, set: function (newDefaultProps) { error('React.lazy(...): It is not supported to assign `defaultProps` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.'); defaultProps = newDefaultProps; // Match production behavior more closely: // $FlowFixMe Object.defineProperty(lazyType, 'defaultProps', { enumerable: true }); } }, propTypes: { configurable: true, get: function () { return propTypes; }, set: function (newPropTypes) { error('React.lazy(...): It is not supported to assign `propTypes` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.'); propTypes = newPropTypes; // Match production behavior more closely: // $FlowFixMe Object.defineProperty(lazyType, 'propTypes', { enumerable: true }); } } }); } return lazyType; } function forwardRef(render) { { if (render != null && render.$$typeof === REACT_MEMO_TYPE) { error('forwardRef requires a render function but received a `memo` ' + 'component. Instead of forwardRef(memo(...)), use ' + 'memo(forwardRef(...)).'); } else if (typeof render !== 'function') { error('forwardRef requires a render function but was given %s.', render === null ? 'null' : typeof render); } else { if (render.length !== 0 && render.length !== 2) { error('forwardRef render functions accept exactly two parameters: props and ref. %s', render.length === 1 ? 'Did you forget to use the ref parameter?' : 'Any additional parameter will be undefined.'); } } if (render != null) { if (render.defaultProps != null || render.propTypes != null) { error('forwardRef render functions do not support propTypes or defaultProps. ' + 'Did you accidentally pass a React component?'); } } } var elementType = { $$typeof: REACT_FORWARD_REF_TYPE, render: render }; { var ownName; Object.defineProperty(elementType, 'displayName', { enumerable: false, configurable: true, get: function () { return ownName; }, set: function (name) { ownName = name; // The inner component shouldn't inherit this display name in most cases, // because the component may be used elsewhere. // But it's nice for anonymous functions to inherit the name, // so that our component-stack generation logic will display their frames. // An anonymous function generally suggests a pattern like: // React.forwardRef((props, ref) => {...}); // This kind of inner function is not used elsewhere so the side effect is okay. if (!render.name && !render.displayName) { render.displayName = name; } } }); } return elementType; } var REACT_MODULE_REFERENCE; { REACT_MODULE_REFERENCE = Symbol.for('react.module.reference'); } function isValidElementType(type) { if (typeof type === 'string' || typeof type === 'function') { return true; } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill). if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing ) { return true; } if (typeof type === 'object' && type !== null) { if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object // types supported by any Flight configuration anywhere since // we don't know which Flight build this will end up being used // with. type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) { return true; } } return false; } function memo(type, compare) { { if (!isValidElementType(type)) { error('memo: The first argument must be a component. Instead ' + 'received: %s', type === null ? 'null' : typeof type); } } var elementType = { $$typeof: REACT_MEMO_TYPE, type: type, compare: compare === undefined ? null : compare }; { var ownName; Object.defineProperty(elementType, 'displayName', { enumerable: false, configurable: true, get: function () { return ownName; }, set: function (name) { ownName = name; // The inner component shouldn't inherit this display name in most cases, // because the component may be used elsewhere. // But it's nice for anonymous functions to inherit the name, // so that our component-stack generation logic will display their frames. // An anonymous function generally suggests a pattern like: // React.memo((props) => {...}); // This kind of inner function is not used elsewhere so the side effect is okay. if (!type.name && !type.displayName) { type.displayName = name; } } }); } return elementType; } function resolveDispatcher() { var dispatcher = ReactCurrentDispatcher.current; { if (dispatcher === null) { error('Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + ' one of the following reasons:\n' + '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' + '2. You might be breaking the Rules of Hooks\n' + '3. You might have more than one copy of React in the same app\n' + 'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.'); } } // Will result in a null access error if accessed outside render phase. We // intentionally don't throw our own error because this is in a hot path. // Also helps ensure this is inlined. return dispatcher; } function useContext(Context) { var dispatcher = resolveDispatcher(); { // TODO: add a more generic warning for invalid values. if (Context._context !== undefined) { var realContext = Context._context; // Don't deduplicate because this legitimately causes bugs // and nobody should be using this in existing code. if (realContext.Consumer === Context) { error('Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be ' + 'removed in a future major release. Did you mean to call useContext(Context) instead?'); } else if (realContext.Provider === Context) { error('Calling useContext(Context.Provider) is not supported. ' + 'Did you mean to call useContext(Context) instead?'); } } } return dispatcher.useContext(Context); } function useState(initialState) { var dispatcher = resolveDispatcher(); return dispatcher.useState(initialState); } function useReducer(reducer, initialArg, init) { var dispatcher = resolveDispatcher(); return dispatcher.useReducer(reducer, initialArg, init); } function useRef(initialValue) { var dispatcher = resolveDispatcher(); return dispatcher.useRef(initialValue); } function useEffect(create, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useEffect(create, deps); } function useInsertionEffect(create, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useInsertionEffect(create, deps); } function useLayoutEffect(create, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useLayoutEffect(create, deps); } function useCallback(callback, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useCallback(callback, deps); } function useMemo(create, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useMemo(create, deps); } function useImperativeHandle(ref, create, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useImperativeHandle(ref, create, deps); } function useDebugValue(value, formatterFn) { { var dispatcher = resolveDispatcher(); return dispatcher.useDebugValue(value, formatterFn); } } function useTransition() { var dispatcher = resolveDispatcher(); return dispatcher.useTransition(); } function useDeferredValue(value) { var dispatcher = resolveDispatcher(); return dispatcher.useDeferredValue(value); } function useId() { var dispatcher = resolveDispatcher(); return dispatcher.useId(); } function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { var dispatcher = resolveDispatcher(); return dispatcher.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); } // Helpers to patch console.logs to avoid logging during side-effect free // replaying on render function. This currently only patches the object // lazily which won't cover if the log function was extracted eagerly. // We could also eagerly patch the method. var disabledDepth = 0; var prevLog; var prevInfo; var prevWarn; var prevError; var prevGroup; var prevGroupCollapsed; var prevGroupEnd; function disabledLog() {} disabledLog.__reactDisabledLog = true; function disableLogs() { { if (disabledDepth === 0) { /* eslint-disable react-internal/no-production-logging */ prevLog = console.log; prevInfo = console.info; prevWarn = console.warn; prevError = console.error; prevGroup = console.group; prevGroupCollapsed = console.groupCollapsed; prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099 var props = { configurable: true, enumerable: true, value: disabledLog, writable: true }; // $FlowFixMe Flow thinks console is immutable. Object.defineProperties(console, { info: props, log: props, warn: props, error: props, group: props, groupCollapsed: props, groupEnd: props }); /* eslint-enable react-internal/no-production-logging */ } disabledDepth++; } } function reenableLogs() { { disabledDepth--; if (disabledDepth === 0) { /* eslint-disable react-internal/no-production-logging */ var props = { configurable: true, enumerable: true, writable: true }; // $FlowFixMe Flow thinks console is immutable. Object.defineProperties(console, { log: assign({}, props, { value: prevLog }), info: assign({}, props, { value: prevInfo }), warn: assign({}, props, { value: prevWarn }), error: assign({}, props, { value: prevError }), group: assign({}, props, { value: prevGroup }), groupCollapsed: assign({}, props, { value: prevGroupCollapsed }), groupEnd: assign({}, props, { value: prevGroupEnd }) }); /* eslint-enable react-internal/no-production-logging */ } if (disabledDepth < 0) { error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.'); } } } var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher; var prefix; function describeBuiltInComponentFrame(name, source, ownerFn) { { if (prefix === undefined) { // Extract the VM specific prefix used by each line. try { throw Error(); } catch (x) { var match = x.stack.trim().match(/\n( *(at )?)/); prefix = match && match[1] || ''; } } // We use the prefix to ensure our stacks line up with native stack frames. return '\n' + prefix + name; } } var reentry = false; var componentFrameCache; { var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map; componentFrameCache = new PossiblyWeakMap(); } function describeNativeComponentFrame(fn, construct) { // If something asked for a stack inside a fake render, it should get ignored. if ( !fn || reentry) { return ''; } { var frame = componentFrameCache.get(fn); if (frame !== undefined) { return frame; } } var control; reentry = true; var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined. Error.prepareStackTrace = undefined; var previousDispatcher; { previousDispatcher = ReactCurrentDispatcher$1.current; // Set the dispatcher in DEV because this might be call in the render function // for warnings. ReactCurrentDispatcher$1.current = null; disableLogs(); } try { // This should throw. if (construct) { // Something should be setting the props in the constructor. var Fake = function () { throw Error(); }; // $FlowFixMe Object.defineProperty(Fake.prototype, 'props', { set: function () { // We use a throwing setter instead of frozen or non-writable props // because that won't throw in a non-strict mode function. throw Error(); } }); if (typeof Reflect === 'object' && Reflect.construct) { // We construct a different control for this case to include any extra // frames added by the construct call. try { Reflect.construct(Fake, []); } catch (x) { control = x; } Reflect.construct(fn, [], Fake); } else { try { Fake.call(); } catch (x) { control = x; } fn.call(Fake.prototype); } } else { try { throw Error(); } catch (x) { control = x; } fn(); } } catch (sample) { // This is inlined manually because closure doesn't do it for us. if (sample && control && typeof sample.stack === 'string') { // This extracts the first frame from the sample that isn't also in the control. // Skipping one frame that we assume is the frame that calls the two. var sampleLines = sample.stack.split('\n'); var controlLines = control.stack.split('\n'); var s = sampleLines.length - 1; var c = controlLines.length - 1; while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { // We expect at least one stack frame to be shared. // Typically this will be the root most one. However, stack frames may be // cut off due to maximum stack limits. In this case, one maybe cut off // earlier than the other. We assume that the sample is longer or the same // and there for cut off earlier. So we should find the root most frame in // the sample somewhere in the control. c--; } for (; s >= 1 && c >= 0; s--, c--) { // Next we find the first one that isn't the same which should be the // frame that called our sample function and the control. if (sampleLines[s] !== controlLines[c]) { // In V8, the first line is describing the message but other VMs don't. // If we're about to return the first line, and the control is also on the same // line, that's a pretty good indicator that our sample threw at same line as // the control. I.e. before we entered the sample frame. So we ignore this result. // This can happen if you passed a class to function component, or non-function. if (s !== 1 || c !== 1) { do { s--; c--; // We may still have similar intermediate frames from the construct call. // The next one that isn't the same should be our match though. if (c < 0 || sampleLines[s] !== controlLines[c]) { // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier. var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "<anonymous>" // but we have a user-provided "displayName" // splice it in to make the stack more readable. if (fn.displayName && _frame.includes('<anonymous>')) { _frame = _frame.replace('<anonymous>', fn.displayName); } { if (typeof fn === 'function') { componentFrameCache.set(fn, _frame); } } // Return the line we found. return _frame; } } while (s >= 1 && c >= 0); } break; } } } } finally { reentry = false; { ReactCurrentDispatcher$1.current = previousDispatcher; reenableLogs(); } Error.prepareStackTrace = previousPrepareStackTrace; } // Fallback to just using the name if we couldn't make it throw. var name = fn ? fn.displayName || fn.name : ''; var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ''; { if (typeof fn === 'function') { componentFrameCache.set(fn, syntheticFrame); } } return syntheticFrame; } function describeFunctionComponentFrame(fn, source, ownerFn) { { return describeNativeComponentFrame(fn, false); } } function shouldConstruct(Component) { var prototype = Component.prototype; return !!(prototype && prototype.isReactComponent); } function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { if (type == null) { return ''; } if (typeof type === 'function') { { return describeNativeComponentFrame(type, shouldConstruct(type)); } } if (typeof type === 'string') { return describeBuiltInComponentFrame(type); } switch (type) { case REACT_SUSPENSE_TYPE: return describeBuiltInComponentFrame('Suspense'); case REACT_SUSPENSE_LIST_TYPE: return describeBuiltInComponentFrame('SuspenseList'); } if (typeof type === 'object') { switch (type.$$typeof) { case REACT_FORWARD_REF_TYPE: return describeFunctionComponentFrame(type.render); case REACT_MEMO_TYPE: // Memo may contain any component type so we recursively resolve it. return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); case REACT_LAZY_TYPE: { var lazyComponent = type; var payload = lazyComponent._payload; var init = lazyComponent._init; try { // Lazy may contain any component type so we recursively resolve it. return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); } catch (x) {} } } } return ''; } var loggedTypeFailures = {}; var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; function setCurrentlyValidatingElement(element) { { if (element) { var owner = element._owner; var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); ReactDebugCurrentFrame$1.setExtraStackFrame(stack); } else { ReactDebugCurrentFrame$1.setExtraStackFrame(null); } } } function checkPropTypes(typeSpecs, values, location, componentName, element) { { // $FlowFixMe This is okay but Flow doesn't know it. var has = Function.call.bind(hasOwnProperty); for (var typeSpecName in typeSpecs) { if (has(typeSpecs, typeSpecName)) { var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. if (typeof typeSpecs[typeSpecName] !== 'function') { // eslint-disable-next-line react-internal/prod-error-codes var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.'); err.name = 'Invariant Violation'; throw err; } error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'); } catch (ex) { error$1 = ex; } if (error$1 && !(error$1 instanceof Error)) { setCurrentlyValidatingElement(element); error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1); setCurrentlyValidatingElement(null); } if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error$1.message] = true; setCurrentlyValidatingElement(element); error('Failed %s type: %s', location, error$1.message); setCurrentlyValidatingElement(null); } } } } } function setCurrentlyValidatingElement$1(element) { { if (element) { var owner = element._owner; var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); setExtraStackFrame(stack); } else { setExtraStackFrame(null); } } } var propTypesMisspellWarningShown; { propTypesMisspellWarningShown = false; } function getDeclarationErrorAddendum() { if (ReactCurrentOwner.current) { var name = getComponentNameFromType(ReactCurrentOwner.current.type); if (name) { return '\n\nCheck the render method of `' + name + '`.'; } } return ''; } function getSourceInfoErrorAddendum(source) { if (source !== undefined) { var fileName = source.fileName.replace(/^.*[\\\/]/, ''); var lineNumber = source.lineNumber; return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.'; } return ''; } function getSourceInfoErrorAddendumForProps(elementProps) { if (elementProps !== null && elementProps !== undefined) { return getSourceInfoErrorAddendum(elementProps.__source); } return ''; } /** * Warn if there's no key explicitly set on dynamic arrays of children or * object keys are not valid. This allows us to keep track of children between * updates. */ var ownerHasKeyUseWarning = {}; function getCurrentComponentErrorInfo(parentType) { var info = getDeclarationErrorAddendum(); if (!info) { var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name; if (parentName) { info = "\n\nCheck the top-level render call using <" + parentName + ">."; } } return info; } /** * Warn if the element doesn't have an explicit key assigned to it. * This element is in an array. The array could grow and shrink or be * reordered. All children that haven't already been validated are required to * have a "key" property assigned to it. Error statuses are cached so a warning * will only be shown once. * * @internal * @param {ReactElement} element Element that requires a key. * @param {*} parentType element's parent's type. */ function validateExplicitKey(element, parentType) { if (!element._store || element._store.validated || element.key != null) { return; } element._store.validated = true; var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { return; } ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a // property, it may be the creator of the child that's responsible for // assigning it a key. var childOwner = ''; if (element && element._owner && element._owner !== ReactCurrentOwner.current) { // Give the component that originally created this child. childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + "."; } { setCurrentlyValidatingElement$1(element); error('Each child in a list should have a unique "key" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner); setCurrentlyValidatingElement$1(null); } } /** * Ensure that every element either is passed in a static location, in an * array with an explicit keys property defined, or in an object literal * with valid key property. * * @internal * @param {ReactNode} node Statically passed child of any type. * @param {*} parentType node's parent's type. */ function validateChildKeys(node, parentType) { if (typeof node !== 'object') { return; } if (isArray(node)) { for (var i = 0; i < node.length; i++) { var child = node[i]; if (isValidElement(child)) { validateExplicitKey(child, parentType); } } } else if (isValidElement(node)) { // This element was passed in a valid location. if (node._store) { node._store.validated = true; } } else if (node) { var iteratorFn = getIteratorFn(node); if (typeof iteratorFn === 'function') { // Entry iterators used to provide implicit keys, // but now we print a separate warning for them later. if (iteratorFn !== node.entries) { var iterator = iteratorFn.call(node); var step; while (!(step = iterator.next()).done) { if (isValidElement(step.value)) { validateExplicitKey(step.value, parentType); } } } } } } /** * Given an element, validate that its props follow the propTypes definition, * provided by the type. * * @param {ReactElement} element */ function validatePropTypes(element) { { var type = element.type; if (type === null || type === undefined || typeof type === 'string') { return; } var propTypes; if (typeof type === 'function') { propTypes = type.propTypes; } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here. // Inner props are checked in the reconciler. type.$$typeof === REACT_MEMO_TYPE)) { propTypes = type.propTypes; } else { return; } if (propTypes) { // Intentionally inside to avoid triggering lazy initializers: var name = getComponentNameFromType(type); checkPropTypes(propTypes, element.props, 'prop', name, element); } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) { propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers: var _name = getComponentNameFromType(type); error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown'); } if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) { error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.'); } } } /** * Given a fragment, validate that it can only be provided with fragment props * @param {ReactElement} fragment */ function validateFragmentProps(fragment) { { var keys = Object.keys(fragment.props); for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (key !== 'children' && key !== 'key') { setCurrentlyValidatingElement$1(fragment); error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key); setCurrentlyValidatingElement$1(null); break; } } if (fragment.ref !== null) { setCurrentlyValidatingElement$1(fragment); error('Invalid attribute `ref` supplied to `React.Fragment`.'); setCurrentlyValidatingElement$1(null); } } } function createElementWithValidation(type, props, children) { var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to // succeed and there will likely be errors in render. if (!validType) { var info = ''; if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) { info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports."; } var sourceInfo = getSourceInfoErrorAddendumForProps(props); if (sourceInfo) { info += sourceInfo; } else { info += getDeclarationErrorAddendum(); } var typeString; if (type === null) { typeString = 'null'; } else if (isArray(type)) { typeString = 'array'; } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) { typeString = "<" + (getComponentNameFromType(type.type) || 'Unknown') + " />"; info = ' Did you accidentally export a JSX literal instead of a component?'; } else { typeString = typeof type; } { error('React.createElement: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info); } } var element = createElement.apply(this, arguments); // The result can be nullish if a mock or a custom function is used. // TODO: Drop this when these are no longer allowed as the type argument. if (element == null) { return element; } // Skip key warning if the type isn't valid since our key validation logic // doesn't expect a non-string/function type and can throw confusing errors. // We don't want exception behavior to differ between dev and prod. // (Rendering will throw with a helpful message and as soon as the type is // fixed, the key warnings will appear.) if (validType) { for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], type); } } if (type === REACT_FRAGMENT_TYPE) { validateFragmentProps(element); } else { validatePropTypes(element); } return element; } var didWarnAboutDeprecatedCreateFactory = false; function createFactoryWithValidation(type) { var validatedFactory = createElementWithValidation.bind(null, type); validatedFactory.type = type; { if (!didWarnAboutDeprecatedCreateFactory) { didWarnAboutDeprecatedCreateFactory = true; warn('React.createFactory() is deprecated and will be removed in ' + 'a future major release. Consider using JSX ' + 'or use React.createElement() directly instead.'); } // Legacy hook: remove it Object.defineProperty(validatedFactory, 'type', { enumerable: false, get: function () { warn('Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.'); Object.defineProperty(this, 'type', { value: type }); return type; } }); } return validatedFactory; } function cloneElementWithValidation(element, props, children) { var newElement = cloneElement.apply(this, arguments); for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], newElement.type); } validatePropTypes(newElement); return newElement; } function startTransition(scope, options) { var prevTransition = ReactCurrentBatchConfig.transition; ReactCurrentBatchConfig.transition = {}; var currentTransition = ReactCurrentBatchConfig.transition; { ReactCurrentBatchConfig.transition._updatedFibers = new Set(); } try { scope(); } finally { ReactCurrentBatchConfig.transition = prevTransition; { if (prevTransition === null && currentTransition._updatedFibers) { var updatedFibersCount = currentTransition._updatedFibers.size; if (updatedFibersCount > 10) { warn('Detected a large number of updates inside startTransition. ' + 'If this is due to a subscription please re-write it to use React provided hooks. ' + 'Otherwise concurrent mode guarantees are off the table.'); } currentTransition._updatedFibers.clear(); } } } } var didWarnAboutMessageChannel = false; var enqueueTaskImpl = null; function enqueueTask(task) { if (enqueueTaskImpl === null) { try { // read require off the module object to get around the bundlers. // we don't want them to detect a require and bundle a Node polyfill. var requireString = ('require' + Math.random()).slice(0, 7); var nodeRequire = module && module[requireString]; // assuming we're in node, let's try to get node's // version of setImmediate, bypassing fake timers if any. enqueueTaskImpl = nodeRequire.call(module, 'timers').setImmediate; } catch (_err) { // we're in a browser // we can't use regular timers because they may still be faked // so we try MessageChannel+postMessage instead enqueueTaskImpl = function (callback) { { if (didWarnAboutMessageChannel === false) { didWarnAboutMessageChannel = true; if (typeof MessageChannel === 'undefined') { error('This browser does not have a MessageChannel implementation, ' + 'so enqueuing tasks via await act(async () => ...) will fail. ' + 'Please file an issue at https://github.com/facebook/react/issues ' + 'if you encounter this warning.'); } } } var channel = new MessageChannel(); channel.port1.onmessage = callback; channel.port2.postMessage(undefined); }; } } return enqueueTaskImpl(task); } var actScopeDepth = 0; var didWarnNoAwaitAct = false; function act(callback) { { // `act` calls can be nested, so we track the depth. This represents the // number of `act` scopes on the stack. var prevActScopeDepth = actScopeDepth; actScopeDepth++; if (ReactCurrentActQueue.current === null) { // This is the outermost `act` scope. Initialize the queue. The reconciler // will detect the queue and use it instead of Scheduler. ReactCurrentActQueue.current = []; } var prevIsBatchingLegacy = ReactCurrentActQueue.isBatchingLegacy; var result; try { // Used to reproduce behavior of `batchedUpdates` in legacy mode. Only // set to `true` while the given callback is executed, not for updates // triggered during an async event, because this is how the legacy // implementation of `act` behaved. ReactCurrentActQueue.isBatchingLegacy = true; result = callback(); // Replicate behavior of original `act` implementation in legacy mode, // which flushed updates immediately after the scope function exits, even // if it's an async function. if (!prevIsBatchingLegacy && ReactCurrentActQueue.didScheduleLegacyUpdate) { var queue = ReactCurrentActQueue.current; if (queue !== null) { ReactCurrentActQueue.didScheduleLegacyUpdate = false; flushActQueue(queue); } } } catch (error) { popActScope(prevActScopeDepth); throw error; } finally { ReactCurrentActQueue.isBatchingLegacy = prevIsBatchingLegacy; } if (result !== null && typeof result === 'object' && typeof result.then === 'function') { var thenableResult = result; // The callback is an async function (i.e. returned a promise). Wait // for it to resolve before exiting the current scope. var wasAwaited = false; var thenable = { then: function (resolve, reject) { wasAwaited = true; thenableResult.then(function (returnValue) { popActScope(prevActScopeDepth); if (actScopeDepth === 0) { // We've exited the outermost act scope. Recursively flush the // queue until there's no remaining work. recursivelyFlushAsyncActWork(returnValue, resolve, reject); } else { resolve(returnValue); } }, function (error) { // The callback threw an error. popActScope(prevActScopeDepth); reject(error); }); } }; { if (!didWarnNoAwaitAct && typeof Promise !== 'undefined') { // eslint-disable-next-line no-undef Promise.resolve().then(function () {}).then(function () { if (!wasAwaited) { didWarnNoAwaitAct = true; error('You called act(async () => ...) without await. ' + 'This could lead to unexpected testing behaviour, ' + 'interleaving multiple act calls and mixing their ' + 'scopes. ' + 'You should - await act(async () => ...);'); } }); } } return thenable; } else { var returnValue = result; // The callback is not an async function. Exit the current scope // immediately, without awaiting. popActScope(prevActScopeDepth); if (actScopeDepth === 0) { // Exiting the outermost act scope. Flush the queue. var _queue = ReactCurrentActQueue.current; if (_queue !== null) { flushActQueue(_queue); ReactCurrentActQueue.current = null; } // Return a thenable. If the user awaits it, we'll flush again in // case additional work was scheduled by a microtask. var _thenable = { then: function (resolve, reject) { // Confirm we haven't re-entered another `act` scope, in case // the user does something weird like await the thenable // multiple times. if (ReactCurrentActQueue.current === null) { // Recursively flush the queue until there's no remaining work. ReactCurrentActQueue.current = []; recursivelyFlushAsyncActWork(returnValue, resolve, reject); } else { resolve(returnValue); } } }; return _thenable; } else { // Since we're inside a nested `act` scope, the returned thenable // immediately resolves. The outer scope will flush the queue. var _thenable2 = { then: function (resolve, reject) { resolve(returnValue); } }; return _thenable2; } } } } function popActScope(prevActScopeDepth) { { if (prevActScopeDepth !== actScopeDepth - 1) { error('You seem to have overlapping act() calls, this is not supported. ' + 'Be sure to await previous act() calls before making a new one. '); } actScopeDepth = prevActScopeDepth; } } function recursivelyFlushAsyncActWork(returnValue, resolve, reject) { { var queue = ReactCurrentActQueue.current; if (queue !== null) { try { flushActQueue(queue); enqueueTask(function () { if (queue.length === 0) { // No additional work was scheduled. Finish. ReactCurrentActQueue.current = null; resolve(returnValue); } else { // Keep flushing work until there's none left. recursivelyFlushAsyncActWork(returnValue, resolve, reject); } }); } catch (error) { reject(error); } } else { resolve(returnValue); } } } var isFlushing = false; function flushActQueue(queue) { { if (!isFlushing) { // Prevent re-entrance. isFlushing = true; var i = 0; try { for (; i < queue.length; i++) { var callback = queue[i]; do { callback = callback(true); } while (callback !== null); } queue.length = 0; } catch (error) { // If something throws, leave the remaining callbacks on the queue. queue = queue.slice(i + 1); throw error; } finally { isFlushing = false; } } } } var createElement$1 = createElementWithValidation ; var cloneElement$1 = cloneElementWithValidation ; var createFactory = createFactoryWithValidation ; var Children = { map: mapChildren, forEach: forEachChildren, count: countChildren, toArray: toArray, only: onlyChild }; exports.Children = Children; exports.Component = Component; exports.Fragment = REACT_FRAGMENT_TYPE; exports.Profiler = REACT_PROFILER_TYPE; exports.PureComponent = PureComponent; exports.StrictMode = REACT_STRICT_MODE_TYPE; exports.Suspense = REACT_SUSPENSE_TYPE; exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactSharedInternals; exports.cloneElement = cloneElement$1; exports.createContext = createContext; exports.createElement = createElement$1; exports.createFactory = createFactory; exports.createRef = createRef; exports.forwardRef = forwardRef; exports.isValidElement = isValidElement; exports.lazy = lazy; exports.memo = memo; exports.startTransition = startTransition; exports.unstable_act = act; exports.useCallback = useCallback; exports.useContext = useContext; exports.useDebugValue = useDebugValue; exports.useDeferredValue = useDeferredValue; exports.useEffect = useEffect; exports.useId = useId; exports.useImperativeHandle = useImperativeHandle; exports.useInsertionEffect = useInsertionEffect; exports.useLayoutEffect = useLayoutEffect; exports.useMemo = useMemo; exports.useReducer = useReducer; exports.useRef = useRef; exports.useState = useState; exports.useSyncExternalStore = useSyncExternalStore; exports.useTransition = useTransition; exports.version = ReactVersion; /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */ if ( typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === 'function' ) { __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error()); } })(); } /***/ }), /***/ "./node_modules/react/index.js": /*!*************************************!*\ !*** ./node_modules/react/index.js ***! \*************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; if (false) {} else { module.exports = __webpack_require__(/*! ./cjs/react.development.js */ "./node_modules/react/cjs/react.development.js"); } /***/ }), /***/ "./node_modules/react/jsx-runtime.js": /*!*******************************************!*\ !*** ./node_modules/react/jsx-runtime.js ***! \*******************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; if (false) {} else { module.exports = __webpack_require__(/*! ./cjs/react-jsx-runtime.development.js */ "./node_modules/react/cjs/react-jsx-runtime.development.js"); } /***/ }), /***/ "./node_modules/scheduler/cjs/scheduler.development.js": /*!*************************************************************!*\ !*** ./node_modules/scheduler/cjs/scheduler.development.js ***! \*************************************************************/ /***/ ((__unused_webpack_module, exports) => { "use strict"; /** * @license React * scheduler.development.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ if (true) { (function() { 'use strict'; /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */ if ( typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === 'function' ) { __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error()); } var enableSchedulerDebugging = false; var enableProfiling = false; var frameYieldMs = 5; function push(heap, node) { var index = heap.length; heap.push(node); siftUp(heap, node, index); } function peek(heap) { return heap.length === 0 ? null : heap[0]; } function pop(heap) { if (heap.length === 0) { return null; } var first = heap[0]; var last = heap.pop(); if (last !== first) { heap[0] = last; siftDown(heap, last, 0); } return first; } function siftUp(heap, node, i) { var index = i; while (index > 0) { var parentIndex = index - 1 >>> 1; var parent = heap[parentIndex]; if (compare(parent, node) > 0) { // The parent is larger. Swap positions. heap[parentIndex] = node; heap[index] = parent; index = parentIndex; } else { // The parent is smaller. Exit. return; } } } function siftDown(heap, node, i) { var index = i; var length = heap.length; var halfLength = length >>> 1; while (index < halfLength) { var leftIndex = (index + 1) * 2 - 1; var left = heap[leftIndex]; var rightIndex = leftIndex + 1; var right = heap[rightIndex]; // If the left or right node is smaller, swap with the smaller of those. if (compare(left, node) < 0) { if (rightIndex < length && compare(right, left) < 0) { heap[index] = right; heap[rightIndex] = node; index = rightIndex; } else { heap[index] = left; heap[leftIndex] = node; index = leftIndex; } } else if (rightIndex < length && compare(right, node) < 0) { heap[index] = right; heap[rightIndex] = node; index = rightIndex; } else { // Neither child is smaller. Exit. return; } } } function compare(a, b) { // Compare sort index first, then task id. var diff = a.sortIndex - b.sortIndex; return diff !== 0 ? diff : a.id - b.id; } // TODO: Use symbols? var ImmediatePriority = 1; var UserBlockingPriority = 2; var NormalPriority = 3; var LowPriority = 4; var IdlePriority = 5; function markTaskErrored(task, ms) { } /* eslint-disable no-var */ var hasPerformanceNow = typeof performance === 'object' && typeof performance.now === 'function'; if (hasPerformanceNow) { var localPerformance = performance; exports.unstable_now = function () { return localPerformance.now(); }; } else { var localDate = Date; var initialTime = localDate.now(); exports.unstable_now = function () { return localDate.now() - initialTime; }; } // Max 31 bit integer. The max integer size in V8 for 32-bit systems. // Math.pow(2, 30) - 1 // 0b111111111111111111111111111111 var maxSigned31BitInt = 1073741823; // Times out immediately var IMMEDIATE_PRIORITY_TIMEOUT = -1; // Eventually times out var USER_BLOCKING_PRIORITY_TIMEOUT = 250; var NORMAL_PRIORITY_TIMEOUT = 5000; var LOW_PRIORITY_TIMEOUT = 10000; // Never times out var IDLE_PRIORITY_TIMEOUT = maxSigned31BitInt; // Tasks are stored on a min heap var taskQueue = []; var timerQueue = []; // Incrementing id counter. Used to maintain insertion order. var taskIdCounter = 1; // Pausing the scheduler is useful for debugging. var currentTask = null; var currentPriorityLevel = NormalPriority; // This is set while performing work, to prevent re-entrance. var isPerformingWork = false; var isHostCallbackScheduled = false; var isHostTimeoutScheduled = false; // Capture local references to native APIs, in case a polyfill overrides them. var localSetTimeout = typeof setTimeout === 'function' ? setTimeout : null; var localClearTimeout = typeof clearTimeout === 'function' ? clearTimeout : null; var localSetImmediate = typeof setImmediate !== 'undefined' ? setImmediate : null; // IE and Node.js + jsdom var isInputPending = typeof navigator !== 'undefined' && navigator.scheduling !== undefined && navigator.scheduling.isInputPending !== undefined ? navigator.scheduling.isInputPending.bind(navigator.scheduling) : null; function advanceTimers(currentTime) { // Check for tasks that are no longer delayed and add them to the queue. var timer = peek(timerQueue); while (timer !== null) { if (timer.callback === null) { // Timer was cancelled. pop(timerQueue); } else if (timer.startTime <= currentTime) { // Timer fired. Transfer to the task queue. pop(timerQueue); timer.sortIndex = timer.expirationTime; push(taskQueue, timer); } else { // Remaining timers are pending. return; } timer = peek(timerQueue); } } function handleTimeout(currentTime) { isHostTimeoutScheduled = false; advanceTimers(currentTime); if (!isHostCallbackScheduled) { if (peek(taskQueue) !== null) { isHostCallbackScheduled = true; requestHostCallback(flushWork); } else { var firstTimer = peek(timerQueue); if (firstTimer !== null) { requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime); } } } } function flushWork(hasTimeRemaining, initialTime) { isHostCallbackScheduled = false; if (isHostTimeoutScheduled) { // We scheduled a timeout but it's no longer needed. Cancel it. isHostTimeoutScheduled = false; cancelHostTimeout(); } isPerformingWork = true; var previousPriorityLevel = currentPriorityLevel; try { if (enableProfiling) { try { return workLoop(hasTimeRemaining, initialTime); } catch (error) { if (currentTask !== null) { var currentTime = exports.unstable_now(); markTaskErrored(currentTask, currentTime); currentTask.isQueued = false; } throw error; } } else { // No catch in prod code path. return workLoop(hasTimeRemaining, initialTime); } } finally { currentTask = null; currentPriorityLevel = previousPriorityLevel; isPerformingWork = false; } } function workLoop(hasTimeRemaining, initialTime) { var currentTime = initialTime; advanceTimers(currentTime); currentTask = peek(taskQueue); while (currentTask !== null && !(enableSchedulerDebugging )) { if (currentTask.expirationTime > currentTime && (!hasTimeRemaining || shouldYieldToHost())) { // This currentTask hasn't expired, and we've reached the deadline. break; } var callback = currentTask.callback; if (typeof callback === 'function') { currentTask.callback = null; currentPriorityLevel = currentTask.priorityLevel; var didUserCallbackTimeout = currentTask.expirationTime <= currentTime; var continuationCallback = callback(didUserCallbackTimeout); currentTime = exports.unstable_now(); if (typeof continuationCallback === 'function') { currentTask.callback = continuationCallback; } else { if (currentTask === peek(taskQueue)) { pop(taskQueue); } } advanceTimers(currentTime); } else { pop(taskQueue); } currentTask = peek(taskQueue); } // Return whether there's additional work if (currentTask !== null) { return true; } else { var firstTimer = peek(timerQueue); if (firstTimer !== null) { requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime); } return false; } } function unstable_runWithPriority(priorityLevel, eventHandler) { switch (priorityLevel) { case ImmediatePriority: case UserBlockingPriority: case NormalPriority: case LowPriority: case IdlePriority: break; default: priorityLevel = NormalPriority; } var previousPriorityLevel = currentPriorityLevel; currentPriorityLevel = priorityLevel; try { return eventHandler(); } finally { currentPriorityLevel = previousPriorityLevel; } } function unstable_next(eventHandler) { var priorityLevel; switch (currentPriorityLevel) { case ImmediatePriority: case UserBlockingPriority: case NormalPriority: // Shift down to normal priority priorityLevel = NormalPriority; break; default: // Anything lower than normal priority should remain at the current level. priorityLevel = currentPriorityLevel; break; } var previousPriorityLevel = currentPriorityLevel; currentPriorityLevel = priorityLevel; try { return eventHandler(); } finally { currentPriorityLevel = previousPriorityLevel; } } function unstable_wrapCallback(callback) { var parentPriorityLevel = currentPriorityLevel; return function () { // This is a fork of runWithPriority, inlined for performance. var previousPriorityLevel = currentPriorityLevel; currentPriorityLevel = parentPriorityLevel; try { return callback.apply(this, arguments); } finally { currentPriorityLevel = previousPriorityLevel; } }; } function unstable_scheduleCallback(priorityLevel, callback, options) { var currentTime = exports.unstable_now(); var startTime; if (typeof options === 'object' && options !== null) { var delay = options.delay; if (typeof delay === 'number' && delay > 0) { startTime = currentTime + delay; } else { startTime = currentTime; } } else { startTime = currentTime; } var timeout; switch (priorityLevel) { case ImmediatePriority: timeout = IMMEDIATE_PRIORITY_TIMEOUT; break; case UserBlockingPriority: timeout = USER_BLOCKING_PRIORITY_TIMEOUT; break; case IdlePriority: timeout = IDLE_PRIORITY_TIMEOUT; break; case LowPriority: timeout = LOW_PRIORITY_TIMEOUT; break; case NormalPriority: default: timeout = NORMAL_PRIORITY_TIMEOUT; break; } var expirationTime = startTime + timeout; var newTask = { id: taskIdCounter++, callback: callback, priorityLevel: priorityLevel, startTime: startTime, expirationTime: expirationTime, sortIndex: -1 }; if (startTime > currentTime) { // This is a delayed task. newTask.sortIndex = startTime; push(timerQueue, newTask); if (peek(taskQueue) === null && newTask === peek(timerQueue)) { // All tasks are delayed, and this is the task with the earliest delay. if (isHostTimeoutScheduled) { // Cancel an existing timeout. cancelHostTimeout(); } else { isHostTimeoutScheduled = true; } // Schedule a timeout. requestHostTimeout(handleTimeout, startTime - currentTime); } } else { newTask.sortIndex = expirationTime; push(taskQueue, newTask); // wait until the next time we yield. if (!isHostCallbackScheduled && !isPerformingWork) { isHostCallbackScheduled = true; requestHostCallback(flushWork); } } return newTask; } function unstable_pauseExecution() { } function unstable_continueExecution() { if (!isHostCallbackScheduled && !isPerformingWork) { isHostCallbackScheduled = true; requestHostCallback(flushWork); } } function unstable_getFirstCallbackNode() { return peek(taskQueue); } function unstable_cancelCallback(task) { // remove from the queue because you can't remove arbitrary nodes from an // array based heap, only the first one.) task.callback = null; } function unstable_getCurrentPriorityLevel() { return currentPriorityLevel; } var isMessageLoopRunning = false; var scheduledHostCallback = null; var taskTimeoutID = -1; // Scheduler periodically yields in case there is other work on the main // thread, like user events. By default, it yields multiple times per frame. // It does not attempt to align with frame boundaries, since most tasks don't // need to be frame aligned; for those that do, use requestAnimationFrame. var frameInterval = frameYieldMs; var startTime = -1; function shouldYieldToHost() { var timeElapsed = exports.unstable_now() - startTime; if (timeElapsed < frameInterval) { // The main thread has only been blocked for a really short amount of time; // smaller than a single frame. Don't yield yet. return false; } // The main thread has been blocked for a non-negligible amount of time. We return true; } function requestPaint() { } function forceFrameRate(fps) { if (fps < 0 || fps > 125) { // Using console['error'] to evade Babel and ESLint console['error']('forceFrameRate takes a positive int between 0 and 125, ' + 'forcing frame rates higher than 125 fps is not supported'); return; } if (fps > 0) { frameInterval = Math.floor(1000 / fps); } else { // reset the framerate frameInterval = frameYieldMs; } } var performWorkUntilDeadline = function () { if (scheduledHostCallback !== null) { var currentTime = exports.unstable_now(); // Keep track of the start time so we can measure how long the main thread // has been blocked. startTime = currentTime; var hasTimeRemaining = true; // If a scheduler task throws, exit the current browser task so the // error can be observed. // // Intentionally not using a try-catch, since that makes some debugging // techniques harder. Instead, if `scheduledHostCallback` errors, then // `hasMoreWork` will remain true, and we'll continue the work loop. var hasMoreWork = true; try { hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime); } finally { if (hasMoreWork) { // If there's more work, schedule the next message event at the end // of the preceding one. schedulePerformWorkUntilDeadline(); } else { isMessageLoopRunning = false; scheduledHostCallback = null; } } } else { isMessageLoopRunning = false; } // Yielding to the browser will give it a chance to paint, so we can }; var schedulePerformWorkUntilDeadline; if (typeof localSetImmediate === 'function') { // Node.js and old IE. // There's a few reasons for why we prefer setImmediate. // // Unlike MessageChannel, it doesn't prevent a Node.js process from exiting. // (Even though this is a DOM fork of the Scheduler, you could get here // with a mix of Node.js 15+, which has a MessageChannel, and jsdom.) // https://github.com/facebook/react/issues/20756 // // But also, it runs earlier which is the semantic we want. // If other browsers ever implement it, it's better to use it. // Although both of these would be inferior to native scheduling. schedulePerformWorkUntilDeadline = function () { localSetImmediate(performWorkUntilDeadline); }; } else if (typeof MessageChannel !== 'undefined') { // DOM and Worker environments. // We prefer MessageChannel because of the 4ms setTimeout clamping. var channel = new MessageChannel(); var port = channel.port2; channel.port1.onmessage = performWorkUntilDeadline; schedulePerformWorkUntilDeadline = function () { port.postMessage(null); }; } else { // We should only fallback here in non-browser environments. schedulePerformWorkUntilDeadline = function () { localSetTimeout(performWorkUntilDeadline, 0); }; } function requestHostCallback(callback) { scheduledHostCallback = callback; if (!isMessageLoopRunning) { isMessageLoopRunning = true; schedulePerformWorkUntilDeadline(); } } function requestHostTimeout(callback, ms) { taskTimeoutID = localSetTimeout(function () { callback(exports.unstable_now()); }, ms); } function cancelHostTimeout() { localClearTimeout(taskTimeoutID); taskTimeoutID = -1; } var unstable_requestPaint = requestPaint; var unstable_Profiling = null; exports.unstable_IdlePriority = IdlePriority; exports.unstable_ImmediatePriority = ImmediatePriority; exports.unstable_LowPriority = LowPriority; exports.unstable_NormalPriority = NormalPriority; exports.unstable_Profiling = unstable_Profiling; exports.unstable_UserBlockingPriority = UserBlockingPriority; exports.unstable_cancelCallback = unstable_cancelCallback; exports.unstable_continueExecution = unstable_continueExecution; exports.unstable_forceFrameRate = forceFrameRate; exports.unstable_getCurrentPriorityLevel = unstable_getCurrentPriorityLevel; exports.unstable_getFirstCallbackNode = unstable_getFirstCallbackNode; exports.unstable_next = unstable_next; exports.unstable_pauseExecution = unstable_pauseExecution; exports.unstable_requestPaint = unstable_requestPaint; exports.unstable_runWithPriority = unstable_runWithPriority; exports.unstable_scheduleCallback = unstable_scheduleCallback; exports.unstable_shouldYield = shouldYieldToHost; exports.unstable_wrapCallback = unstable_wrapCallback; /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */ if ( typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === 'function' ) { __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error()); } })(); } /***/ }), /***/ "./node_modules/scheduler/index.js": /*!*****************************************!*\ !*** ./node_modules/scheduler/index.js ***! \*****************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; if (false) {} else { module.exports = __webpack_require__(/*! ./cjs/scheduler.development.js */ "./node_modules/scheduler/cjs/scheduler.development.js"); } /***/ }), /***/ "./node_modules/grapesjs/dist/css/grapes.min.css": /*!*******************************************************!*\ !*** ./node_modules/grapesjs/dist/css/grapes.min.css ***! \*******************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var _style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! !../../../style-loader/dist/runtime/injectStylesIntoStyleTag.js */ "./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js"); /* harmony import */ var _style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var _css_loader_dist_cjs_js_ruleSet_1_rules_6_oneOf_1_use_1_postcss_loader_dist_cjs_js_ruleSet_1_rules_6_oneOf_1_use_2_grapes_min_css__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! !!../../../css-loader/dist/cjs.js??ruleSet[1].rules[6].oneOf[1].use[1]!../../../postcss-loader/dist/cjs.js??ruleSet[1].rules[6].oneOf[1].use[2]!./grapes.min.css */ "./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[6].oneOf[1].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[6].oneOf[1].use[2]!./node_modules/grapesjs/dist/css/grapes.min.css"); var options = {}; options.insert = "head"; options.singleton = false; var update = _style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0___default()(_css_loader_dist_cjs_js_ruleSet_1_rules_6_oneOf_1_use_1_postcss_loader_dist_cjs_js_ruleSet_1_rules_6_oneOf_1_use_2_grapes_min_css__WEBPACK_IMPORTED_MODULE_1__["default"], options); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_css_loader_dist_cjs_js_ruleSet_1_rules_6_oneOf_1_use_1_postcss_loader_dist_cjs_js_ruleSet_1_rules_6_oneOf_1_use_2_grapes_min_css__WEBPACK_IMPORTED_MODULE_1__["default"].locals || {}); /***/ }), /***/ "./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js": /*!****************************************************************************!*\ !*** ./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js ***! \****************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var isOldIE = function isOldIE() { var memo; return function memorize() { if (typeof memo === 'undefined') { // 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 memo = Boolean(window && document && document.all && !window.atob); } return memo; }; }(); var getTarget = function getTarget() { var memo = {}; return function memorize(target) { if (typeof memo[target] === 'undefined') { var styleTarget = document.querySelector(target); // Special case to return head of iframe instead of iframe itself if (window.HTMLIFrameElement && styleTarget instanceof window.HTMLIFrameElement) { try { // This will throw an exception if access to iframe is blocked // due to cross-origin restrictions styleTarget = styleTarget.contentDocument.head; } catch (e) { // istanbul ignore next styleTarget = null; } } memo[target] = styleTarget; } return memo[target]; }; }(); var stylesInDom = []; function getIndexByIdentifier(identifier) { var result = -1; for (var i = 0; i < stylesInDom.length; i++) { if (stylesInDom[i].identifier === identifier) { result = i; break; } } return result; } function modulesToDom(list, options) { var idCountMap = {}; var identifiers = []; for (var i = 0; i < list.length; i++) { var item = list[i]; var id = options.base ? item[0] + options.base : item[0]; var count = idCountMap[id] || 0; var identifier = "".concat(id, " ").concat(count); idCountMap[id] = count + 1; var index = getIndexByIdentifier(identifier); var obj = { css: item[1], media: item[2], sourceMap: item[3] }; if (index !== -1) { stylesInDom[index].references++; stylesInDom[index].updater(obj); } else { stylesInDom.push({ identifier: identifier, updater: addStyle(obj, options), references: 1 }); } identifiers.push(identifier); } return identifiers; } function insertStyleElement(options) { var style = document.createElement('style'); var attributes = options.attributes || {}; if (typeof attributes.nonce === 'undefined') { var nonce = true ? __webpack_require__.nc : 0; if (nonce) { attributes.nonce = nonce; } } Object.keys(attributes).forEach(function (key) { style.setAttribute(key, attributes[key]); }); if (typeof options.insert === 'function') { options.insert(style); } else { var target = getTarget(options.insert || 'head'); if (!target) { throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid."); } target.appendChild(style); } return style; } function removeStyleElement(style) { // istanbul ignore if if (style.parentNode === null) { return false; } style.parentNode.removeChild(style); } /* istanbul ignore next */ var replaceText = function replaceText() { var textStore = []; return function replace(index, replacement) { textStore[index] = replacement; return textStore.filter(Boolean).join('\n'); }; }(); function applyToSingletonTag(style, index, remove, obj) { var css = remove ? '' : obj.media ? "@media ".concat(obj.media, " {").concat(obj.css, "}") : obj.css; // For old IE /* istanbul ignore if */ if (style.styleSheet) { style.styleSheet.cssText = replaceText(index, css); } else { var cssNode = document.createTextNode(css); var childNodes = style.childNodes; if (childNodes[index]) { style.removeChild(childNodes[index]); } if (childNodes.length) { style.insertBefore(cssNode, childNodes[index]); } else { style.appendChild(cssNode); } } } function applyToTag(style, options, obj) { var css = obj.css; var media = obj.media; var sourceMap = obj.sourceMap; if (media) { style.setAttribute('media', media); } else { style.removeAttribute('media'); } if (sourceMap && typeof btoa !== 'undefined') { css += "\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))), " */"); } // For old IE /* istanbul ignore if */ if (style.styleSheet) { style.styleSheet.cssText = css; } else { while (style.firstChild) { style.removeChild(style.firstChild); } style.appendChild(document.createTextNode(css)); } } var singleton = null; var singletonCounter = 0; function addStyle(obj, options) { var style; var update; var remove; if (options.singleton) { var styleIndex = singletonCounter++; style = singleton || (singleton = insertStyleElement(options)); update = applyToSingletonTag.bind(null, style, styleIndex, false); remove = applyToSingletonTag.bind(null, style, styleIndex, true); } else { style = insertStyleElement(options); update = applyToTag.bind(null, style, options); remove = function remove() { removeStyleElement(style); }; } update(obj); return function updateStyle(newObj) { if (newObj) { if (newObj.css === obj.css && newObj.media === obj.media && newObj.sourceMap === obj.sourceMap) { return; } update(obj = newObj); } else { remove(); } }; } module.exports = function (list, options) { options = options || {}; // Force single-tag solution on IE6-9, which has a hard limit on the # of <style> // tags it will allow on a page if (!options.singleton && typeof options.singleton !== 'boolean') { options.singleton = isOldIE(); } list = list || []; var lastIdentifiers = modulesToDom(list, options); return function update(newList) { newList = newList || []; if (Object.prototype.toString.call(newList) !== '[object Array]') { return; } for (var i = 0; i < lastIdentifiers.length; i++) { var identifier = lastIdentifiers[i]; var index = getIndexByIdentifier(identifier); stylesInDom[index].references--; } var newLastIdentifiers = modulesToDom(newList, options); for (var _i = 0; _i < lastIdentifiers.length; _i++) { var _identifier = lastIdentifiers[_i]; var _index = getIndexByIdentifier(_identifier); if (stylesInDom[_index].references === 0) { stylesInDom[_index].updater(); stylesInDom.splice(_index, 1); } } lastIdentifiers = newLastIdentifiers; }; }; /***/ }), /***/ "./node_modules/grapesjs/dist/grapes.mjs": /*!***********************************************!*\ !*** ./node_modules/grapesjs/dist/grapes.mjs ***! \***********************************************/ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (/* binding */ __webpack_exports__default), /* harmony export */ grapesjs: () => (/* binding */ __webpack_exports__grapesjs), /* harmony export */ usePlugin: () => (/* binding */ __webpack_exports__usePlugin) /* harmony export */ }); /* provided dependency */ var Buffer = __webpack_require__(/*! buffer */ "./node_modules/buffer/index.js")["Buffer"]; /******/ var __webpack_modules__ = ({ /***/ 410: /***/ ((module, exports, __nested_webpack_require_75__) => { var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! * Backbone.Undo.js v0.2 * * Copyright (c)2013 Oliver Sartun * Released under the MIT License * * Documentation and full license available at * https://github.com/osartun/Backbone.Undo.js */ (function (factory) { if (true) { // AMD support !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__nested_webpack_require_75__(50), __nested_webpack_require_75__(316)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else {} })(function (_, Backbone) { var core_slice = Array.prototype.slice; /** * As call is faster than apply, this is a faster version of apply as it uses call. * * @param {Function} fn The function to execute * @param {Object} ctx The context the function should be called in * @param {Array} args The array of arguments that should be applied to the function * @return Forwards whatever the called function returns */ function apply (fn, ctx, args) { return args.length <= 4 ? fn.call(ctx, args[0], args[1], args[2], args[3]) : fn.apply(ctx, args); } /** * Uses slice on an array or an array-like object. * * @param {Array|Object} arr The array or array-like object. * @param {Number} [index] The index from where the array should be sliced. Default is 0. * @return {Array} The sliced array */ function slice (arr, index) { return core_slice.call(arr, index); } /** * Checks if an object has one or more specific keys. The keys * don't have to be an owned property. * You can call this function either this way: * hasKeys(obj, ["a", "b", "c"]) * or this way: * hasKeys(obj, "a", "b", "c") * * @param {Object} obj The object to check on * @param {Array} keys The keys to check for * @return {Boolean} True, if the object has all those keys */ function hasKeys (obj, keys) { if (obj == null) return false; if (!_.isArray(keys)) { keys = slice(arguments, 1); } return _.all(keys, function (key) { return key in obj; }); } /** * Returns a number that is unique per call stack. The number gets * changed after the call stack has been completely processed. * * @return {number} MagicFusionIndex */ var getMagicFusionIndex = (function () { // If you add several models to a collection or set several // attributes on a model all in sequence and yet all for // example in one function, then several Undo-Actions are // generated. // If you want to undo your last action only the last model // would be removed from the collection or the last set // attribute would be changed back to its previous value. // To prevent that we have to figure out a way to combine // all those actions that happened "at the same time". // Timestamps aren't exact enough. A complex routine could // run several milliseconds and in that time produce a lot // of actions with different timestamps. // Instead we take advantage of the single-threadedness of // JavaScript: var callstackWasIndexed = false, magicFusionIndex = -1; function indexCycle() { magicFusionIndex++; callstackWasIndexed = true; _.defer(function () { // Here comes the magic. With a Timeout of 0 // milliseconds this function gets called whenever // the current callstack is completed callstackWasIndexed = false; }) } return function () { if (!callstackWasIndexed) { indexCycle(); } return magicFusionIndex; } })(); /** * To prevent binding a listener several times to one * object, we register the objects in an ObjectRegistry * * @constructor */ function ObjectRegistry () { // This uses two different ways of storing // objects: In case the object has a cid // (which Backbone objects typically have) // it uses this cid as an index. That way // the Array's length attribute doesn't // change and the object isn't an item // in the array, but an object-property. // Otherwise it's added to the Array as an // item. // That way we can use the fast property- // lookup and only have to fall back to // iterating over the array in case // non-Backbone-objects are registered. this.registeredObjects = []; // To return a list of all registered // objects in the 'get' method we have to // store the objects that have a cid in // an additional array. this.cidIndexes = []; } ObjectRegistry.prototype = { /** * Returns whether the object is already registered in this ObjectRegistry or not. * * @this {ObjectRegistry} * @param {Object} obj The object to check * @return {Boolean} True if the object is already registered */ isRegistered: function (obj) { // This is where we get a performance boost // by using the two different ways of storing // objects. return obj && obj.cid ? this.registeredObjects[obj.cid] : _.contains(this.registeredObjects, obj); }, /** * Registers an object in this ObjectRegistry. * * @this {ObjectRegistry} * @param {Object} obj The object to register * @return {undefined} */ register: function (obj) { if (!this.isRegistered(obj)) { if (obj && obj.cid) { this.registeredObjects[obj.cid] = obj; this.cidIndexes.push(obj.cid); } else { this.registeredObjects.push(obj); } return true; } return false; }, /** * Unregisters an object from this ObjectRegistry. * * @this {ObjectRegistry} * @param {Object} obj The object to unregister * @return {undefined} */ unregister: function (obj) { if (this.isRegistered(obj)) { if (obj && obj.cid) { delete this.registeredObjects[obj.cid]; this.cidIndexes.splice(_.indexOf(this.cidIndexes, obj.cid), 1); } else { var i = _.indexOf(this.registeredObjects, obj); this.registeredObjects.splice(i, 1); } return true; } return false; }, /** * Returns an array of all objects that are currently in this ObjectRegistry. * * @return {Array} An array of all the objects which are currently in the ObjectRegistry */ get: function () { return (_.map(this.cidIndexes, function (cid) {return this.registeredObjects[cid];}, this)).concat(this.registeredObjects); } } /** * Binds or unbinds the "all"-listener for one or more objects. * * @param {String} which Either "on" or "off" * @param {Object[]} objects Array of the objects on which the "all"-listener should be bound / unbound to * @param {Function} [fn] The function that should be bound / unbound. Optional in case of "off" * @param {Object} [ctx] The context the function should be called in * @return {undefined} */ function onoff(which, objects, fn, ctx) { for (var i = 0, l = objects.length, obj; i < l; i++) { obj = objects[i]; if (!obj) continue; if (which === "on") { if (!ctx.objectRegistry.register(obj)) { // register returned false, so obj was already registered continue; } } else { if (!ctx.objectRegistry.unregister(obj)) { // unregister returned false, so obj wasn't registered continue; } } if (_.isFunction(obj[which])) { obj[which]("all", fn, ctx); } } } /** * Calls the undo/redo-function for a specific action. * * @param {String} which Either "undo" or "redo" * @param {Object} action The Action's attributes * @return {undefined} */ function actionUndoRedo (which, action) { var type = action.type, undoTypes = action.undoTypes, fn = !undoTypes[type] || undoTypes[type][which]; if (_.isFunction(fn)) { fn(action.object, action.before, action.after, action.options); } } /** * The main undo/redo function. * * @param {String} which Either "undo" or "redo" * @param {UndoManager} manager The UndoManager-instance on which an "undo"/"redo"-Event is triggered afterwards * @param {UndoStack} stack The UndoStack on which we perform * @param {Boolean} magic If true, undoes / redoes all actions with the same magicFusionIndex * @param {Boolean} everything If true, undoes / redoes every action that had been tracked * @return {undefined} */ function managerUndoRedo (which, manager, stack, magic, everything) { if (stack.isCurrentlyUndoRedoing || (which === "undo" && stack.pointer === -1) || (which === "redo" && stack.pointer === stack.length - 1)) { // We're either currently in an undo- / redo-process or // we reached the end of the stack return; } stack.isCurrentlyUndoRedoing = true; var action, actions, isUndo = which === "undo"; if (everything) { // Undo / Redo all steps until you reach the stack's beginning / end actions = isUndo && stack.pointer === stack.length - 1 || // If at the stack's end calling undo !isUndo && stack.pointer === -1 ? // or at the stack's beginning calling redo _.clone(stack.models) : // => Take all the models. Otherwise: core_slice.apply(stack.models, isUndo ? [0, stack.pointer] : [stack.pointer, stack.length - 1]); } else { // Undo / Redo only one step action = stack.at(isUndo ? stack.pointer : stack.pointer + 1); actions = magic ? stack.where({"magicFusionIndex": action.get("magicFusionIndex")}) : [action]; } stack.pointer += (isUndo ? -1 : 1) * actions.length; while (action = isUndo ? actions.pop() : actions.shift()) { // Here we're calling the Action's undo / redo method action[which](); } stack.isCurrentlyUndoRedoing = false; manager.trigger(which, manager); } /** * Checks whether an UndoAction should be created or not. Therefore it checks * whether a "condition" property is set in the undoTypes-object of the specific * event type. If not, it returns true. If it's set and a boolean, it returns it. * If it's a function, it returns its result, converting it into a boolean. * Otherwise it returns true. * * @param {Object} undoTypesType The object within the UndoTypes that holds the function for this event type (i.e. "change") * @param {Arguments} args The arguments the "condition" function is called with * @return {Boolean} True, if an UndoAction should be created */ function validateUndoActionCreation (undoTypesType, args) { var condition = undoTypesType.condition, type = typeof condition; return type === "function" ? !!apply(condition, undoTypesType, args) : type === "boolean" ? condition : true; } /** * Adds an Undo-Action to the stack. * * @param {UndoStack} stack The undostack the action should be added to. * @param {String} type The event type (i.e. "change") * @param {Arguments} args The arguments passed to the undoTypes' "on"-handler * @param {OwnedUndoTypes} undoTypes The undoTypes-object which has the "on"-handler * @return {undefined} */ function addToStack(stack, type, args, undoTypes) { if (stack.track && !stack.isCurrentlyUndoRedoing && type in undoTypes && validateUndoActionCreation(undoTypes[type], args)) { // An UndoAction should be created var res = apply(undoTypes[type]["on"], undoTypes[type], args), diff; if (hasKeys(res, "object", "before", "after")) { res.type = type; res.magicFusionIndex = getMagicFusionIndex(); res.undoTypes = undoTypes; if (stack.pointer < stack.length - 1) { // New Actions must always be added to the end of the stack. // If the pointer is not pointed to the last action in the // stack, presumably because actions were undone before, then // all following actions must be discarded var diff = stack.length - stack.pointer - 1; while (diff--) { stack.pop(); } } stack.pointer = stack.length; stack.add(res); if (stack.length > stack.maximumStackLength) { stack.shift(); stack.pointer--; } } } } /** * Predefined UndoTypes object with default handlers for the most common events. * @type {Object} */ var UndoTypes = { "add": { "undo": function (collection, ignore, model, options) { // Undo add = remove collection.remove(model, options); }, "redo": function (collection, ignore, model, options) { // Redo add = add if (options.index) { options.at = options.index; } collection.add(model, options); }, "on": function (model, collection, options) { return { object: collection, before: undefined, after: model, options: _.clone(options) }; } }, "remove": { "undo": function (collection, model, ignore, options) { if ("index" in options) { options.at = options.index; } collection.add(model, options); }, "redo": function (collection, model, ignore, options) { collection.remove(model, options); }, "on": function (model, collection, options) { return { object: collection, before: model, after: undefined, options: _.clone(options) }; } }, "change": { "undo": function (model, before, after, options) { if (_.isEmpty(before)) { _.each(_.keys(after), model.unset, model); } else { model.set(before); if (options && options.unsetData && options.unsetData.before && options.unsetData.before.length) { _.each(options.unsetData.before, model.unset, model); } } }, "redo": function (model, before, after, options) { if (_.isEmpty(after)) { _.each(_.keys(before), model.unset, model); } else { model.set(after); if (options && options.unsetData && options.unsetData.after && options.unsetData.after.length) { _.each(options.unsetData.after, model.unset, model); } } }, "on": function (model, options) { var afterAttributes = model.changedAttributes(), keysAfter = _.keys(afterAttributes), previousAttributes = _.pick(model.previousAttributes(), keysAfter), keysPrevious = _.keys(previousAttributes), unsetData = (options || (options = {})).unsetData = { after: [], before: [] }; if (keysAfter.length != keysPrevious.length) { // There are new attributes or old attributes have been unset if (keysAfter.length > keysPrevious.length) { // New attributes have been added _.each(keysAfter, function (val) { if (!(val in previousAttributes)) { unsetData.before.push(val); } }, this); } else { // Old attributes have been unset _.each(keysPrevious, function (val) { if (!(val in afterAttributes)) { unsetData.after.push(val); } }) } } return { object: model, before: previousAttributes, after: afterAttributes, options: _.clone(options) }; } }, "reset": { "undo": function (collection, before, after) { collection.reset(before); }, "redo": function (collection, before, after) { collection.reset(after); }, "on": function (collection, options) { return { object: collection, before: options.previousModels, after: _.clone(collection.models) }; } } }; /** * Every UndoManager instance has an own undoTypes object * which is an instance of OwnedUndoTypes. OwnedUndoTypes' * prototype is the global UndoTypes object. Changes to the * global UndoTypes object take effect on every instance of * UndoManager as the object is its prototype. And yet every * local UndoTypes object can be changed individually. * * @constructor */ function OwnedUndoTypes () {} OwnedUndoTypes.prototype = UndoTypes; /** * Adds, changes or removes an undo-type from an UndoTypes-object. * You can call it this way: * manipulateUndoType (1, "reset", {"on": function () {}}, undoTypes) * or this way to perform bulk actions: * manipulateUndoType (1, {"reset": {"on": function () {}}}, undoTypes) * In case of removing undo-types you can pass an Array for performing * bulk actions: * manipulateUndoType(2, ["reset", "change"], undoTypes) * * @param {Number} manipType Indicates the kind of action to execute: 0 for add, 1 for change, 2 for remove * @param {String|Object|Array} undoType The type of undoType that should be added/changed/removed. Can be an object / array to perform bulk actions * @param {Object} [fns] Object with the functions to add / change. Is optional in case you passed an object as undoType that contains these functions * @param {OwnedUndoTypes|UndoTypes} undoTypesInstance The undoTypes object to act on * @return {undefined} */ function manipulateUndoType (manipType, undoType, fns, undoTypesInstance) { // manipType, passed by the calling function // 0: add // 1: change // 2: remove if (typeof undoType === "object") { // bulk action. Iterate over this data. return _.each(undoType, function (val, key) { if (manipType === 2) { // remove // undoType is an array manipulateUndoType (manipType, val, fns, undoTypesInstance); } else { // undoType is an object manipulateUndoType (manipType, key, val, fns); } }) } switch (manipType) { case 0: // add if (hasKeys(fns, "undo", "redo", "on") && _.all(_.pick(fns, "undo", "redo", "on"), _.isFunction)) { undoTypesInstance[undoType] = fns; } break; case 1: // change if (undoTypesInstance[undoType] && _.isObject(fns)) { // undoTypeInstance[undoType] may be a prototype's property // So, if we did this _.extend(undoTypeInstance[undoType], fns) // we would extend the object on the prototype which means // that this change would have a global effect // Instead we just want to manipulate this instance. That's why // we're doing this: undoTypesInstance[undoType] = _.extend({}, undoTypesInstance[undoType], fns); } break; case 2: // remove delete undoTypesInstance[undoType]; break; } return this; } /** * Instantiating "Action" creates the UndoActions that * are collected in an UndoStack. It holds all relevant * data to undo / redo an action and has an undo / redo * method. */ var Action = Backbone.Model.extend({ defaults: { type: null, // "add", "change", "reset", etc. object: null, // The object on which the action occurred before: null, // The previous values which were changed with this action after: null, // The values after this action magicFusionIndex: null // The magicFusionIndex helps to combine // all actions that occurred "at the same time" to undo/redo them altogether }, /** * Undoes this action. * @param {OwnedUndoTypes|UndoTypes} undoTypes The undoTypes object which contains the "undo"-handler that should be used * @return {undefined} */ undo: function (undoTypes) { actionUndoRedo("undo", this.attributes); }, /** * Redoes this action. * @param {OwnedUndoTypes|UndoTypes} undoTypes The undoTypes object which contains the "redo"-handler that should be used * @return {undefined} */ redo: function (undoTypes) { actionUndoRedo("redo", this.attributes); } }), /** * An UndoStack is a collection of UndoActions in * chronological order. */ UndoStack = Backbone.Collection.extend({ model: Action, pointer: -1, // The pointer indicates the index where we are located within the stack. We start at -1 track: false, isCurrentlyUndoRedoing: false, maximumStackLength: Infinity, setMaxLength: function (val) { this.maximumStackLength = val; } }), /** * An instance of UndoManager can keep track of * changes to objects and helps to undo them. */ UndoManager = Backbone.Model.extend({ defaults: { maximumStackLength: Infinity, track: false }, /** * The constructor function. * @param {attr} [attr] Object with parameters. The available parameters are: * - maximumStackLength {number} Set the undo-stack's maximum size * - track {boolean} Start tracking changes right away * @return {undefined} */ initialize: function (attr) { this.stack = new UndoStack; this.objectRegistry = new ObjectRegistry(); this.undoTypes = new OwnedUndoTypes(); // sync the maximumStackLength attribute with our stack this.stack.setMaxLength(this.get("maximumStackLength")); this.on("change:maximumStackLength", function (model, value) { this.stack.setMaxLength(value); }, this); // Start tracking, if attr.track == true if (attr && attr.track) { this.startTracking(); } // Register objects passed in the "register" attribute if (attr && attr.register) { if (_.isArray(attr.register) || _.isArguments(attr.register)) { apply(this.register, this, attr.register); } else { this.register(attr.register); } } }, /** * Starts tracking. Changes of registered objects won't be processed until you've called this function * @return {undefined} */ startTracking: function () { this.set("track", true); this.stack.track = true; }, /** * Stops tracking. Afterwards changes of registered objects won't be processed. * @return {undefined} */ stopTracking: function () { this.set("track", false); this.stack.track = false; }, /** * Return the state of the tracking * @return {boolean} */ isTracking: function () { return this.get("track"); }, /** * This is the "all"-handler which is bound to registered * objects. It creates an UndoAction from the event and adds * it to the stack. * * @param {String} type The event type * @return {undefined} */ _addToStack: function (type) { addToStack(this.stack, type, slice(arguments, 1), this.undoTypes); }, /** * Registers one or more objects to track their changes. * @param {...Object} obj The object or objects of which changes should be tracked * @return {undefined} */ register: function () { onoff("on", arguments, this._addToStack, this); }, /** * Unregisters one or more objects. * @param {...Object} obj The object or objects of which changes shouldn't be tracked any longer * @return {undefined} */ unregister: function () { onoff("off", arguments, this._addToStack, this); }, /** * Unregisters all previously registered objects. * @return {undefined} */ unregisterAll: function () { apply(this.unregister, this, this.objectRegistry.get()); }, /** * Undoes the last action or the last set of actions in case 'magic' is true. * @param {Boolean} [magic] If true, all actions that happened basically at the same time are undone together * @return {undefined} */ undo: function (magic) { managerUndoRedo("undo", this, this.stack, magic); }, /** * Undoes all actions ever tracked by the undo manager * @return {undefined} */ undoAll: function () { managerUndoRedo("undo", this, this.stack, false, true); }, /** * Redoes a previously undone action or a set of actions. * @param {Boolean} [magic] If true, all actions that happened basically at the same time are redone together * @return {undefined} */ redo: function (magic) { managerUndoRedo("redo", this, this.stack, magic); }, /** * Redoes all actions ever tracked by the undo manager * @return {undefined} */ redoAll: function () { managerUndoRedo("redo", this, this.stack, false, true); }, /** * Checks if there's an action in the stack that can be undone / redone * @param {String} type Either "undo" or "redo" * @return {Boolean} True if there is a set of actions which can be undone / redone */ isAvailable: function (type) { var s = this.stack, l = s.length; switch (type) { case "undo": return l > 0 && s.pointer > -1; case "redo": return l > 0 && s.pointer < l - 1; default: return false; } }, /** * Sets the stack-reference to the stack of another undoManager. * @param {UndoManager} undoManager The undoManager whose stack-reference is set to this stack * @return {undefined} */ merge: function (undoManager) { // This sets the stack-reference to the stack of another // undoManager so that the stack of this other undoManager // is used by two different managers. // This enables to set up a main-undoManager and besides it // several others for special, exceptional cases (by using // instance-based custom UndoTypes). Models / collections // which need this special treatment are only registered at // those special undoManagers. Those special ones are then // merged into the main-undoManager to write on its stack. // That way it's easier to manage exceptional cases. var args = _.isArray(undoManager) ? undoManager : slice(arguments), manager; while (manager = args.pop()) { if (manager instanceof UndoManager && manager.stack instanceof UndoStack) { // set the stack reference to our stack manager.stack = this.stack; } } }, /** * Add an UndoType to this specific UndoManager-instance. * @param {String} type The event this UndoType is made for * @param {Object} fns An object of functions that are called to generate the data for an UndoAction or to process it. Must have the properties "undo", "redo" and "on". Can have the property "condition". * @return {undefined} */ addUndoType: function (type, fns) { manipulateUndoType(0, type, fns, this.undoTypes); }, /** * Overwrite properties of an existing UndoType for this specific UndoManager-instance. * @param {String} type The event the UndoType is made for * @param {Object} fns An object of functions that are called to generate the data for an UndoAction or to process it. It extends the existing object. * @return {undefined} */ changeUndoType: function (type, fns) { manipulateUndoType(1, type, fns, this.undoTypes); }, /** * Remove one or more UndoTypes of this specific UndoManager-instance to fall back to the global UndoTypes. * @param {String|Array} type The event the UndoType that should be removed is made for. You can also pass an array of events. * @return {undefined} */ removeUndoType: function (type) { manipulateUndoType(2, type, undefined, this.undoTypes); }, /** * Removes all actions from the stack. * @return {undefined} */ clear: function() { this.stack.reset(); this.stack.pointer = -1; } }); _.extend(UndoManager, { /** * Change the UndoManager's default attributes * @param {Object} defaultAttributes An object with the new default values. * @return {undefined} */ defaults: function (defaultAttributes) { _.extend(UndoManager.prototype.defaults, defaultAttributes); }, /** * Add an UndoType to the global UndoTypes-object. * @param {String} type The event this UndoType is made for * @param {Object} fns An object of functions that are called to generate the data for an UndoAction or to process it. Must have the properties "undo", "redo" and "on". Can have the property "condition". * @return {undefined} */ "addUndoType": function (type, fns) { manipulateUndoType(0, type, fns, UndoTypes); }, /** * Overwrite properties of an existing UndoType in the global UndoTypes-object. * @param {String} type The event the UndoType is made for * @param {Object} fns An object of functions that are called to generate the data for an UndoAction or to process it. It extends the existing object. * @return {undefined} */ "changeUndoType": function (type, fns) { manipulateUndoType(1, type, fns, UndoTypes) }, /** * Remove one or more UndoTypes of this specific UndoManager-instance to fall back to the global UndoTypes. * @param {String|Array} type The event the UndoType that should be removed is made for. You can also pass an array of events. * @return {undefined} */ "removeUndoType": function (type) { manipulateUndoType(2, type, undefined, UndoTypes); } }) return Backbone.UndoManager = UndoManager; }); /***/ }), /***/ 316: /***/ ((module, exports, __nested_webpack_require_28498__) => { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// Backbone.js 1.4.1 // (c) 2010-2022 Jeremy Ashkenas and DocumentCloud // Backbone may be freely distributed under the MIT license. // For all details and documentation: // http://backbonejs.org (function(factory) { // Establish the root object, `window` (`self`) in the browser, or `global` on the server. // We use `self` instead of `window` for `WebWorker` support. var root = typeof self == 'object' && self.self === self && self || typeof __nested_webpack_require_28498__.g == 'object' && __nested_webpack_require_28498__.g.global === __nested_webpack_require_28498__.g && __nested_webpack_require_28498__.g; // Set up Backbone appropriately for the environment. Start with AMD. if (true) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__nested_webpack_require_28498__(50), __nested_webpack_require_28498__(895), exports], __WEBPACK_AMD_DEFINE_RESULT__ = (function(_, $, exports) { // Export global even in AMD case in case this script is loaded with // others that may still expect a global Backbone. root.Backbone = factory(root, exports, _, $); }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); // Next for Node.js or CommonJS. jQuery may not be needed as a module. } else { var _, $; } })(function(root, Backbone, _, $) { // Initial Setup // ------------- // Save the previous value of the `Backbone` variable, so that it can be // restored later on, if `noConflict` is used. var previousBackbone = root.Backbone; // Create a local reference to a common array method we'll want to use later. var slice = Array.prototype.slice; // Current version of the library. Keep in sync with `package.json`. Backbone.VERSION = '1.4.1'; // For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns // the `$` variable. Backbone.$ = $; // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable // to its previous owner. Returns a reference to this Backbone object. Backbone.noConflict = function() { root.Backbone = previousBackbone; return this; }; // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option // will fake `"PATCH"`, `"PUT"` and `"DELETE"` requests via the `_method` parameter and // set a `X-Http-Method-Override` header. Backbone.emulateHTTP = false; // Turn on `emulateJSON` to support legacy servers that can't deal with direct // `application/json` requests ... this will encode the body as // `application/x-www-form-urlencoded` instead and will send the model in a // form param named `model`. Backbone.emulateJSON = false; // Backbone.Events // --------------- // A module that can be mixed in to *any object* in order to provide it with // a custom event channel. You may bind a callback to an event with `on` or // remove with `off`; `trigger`-ing an event fires all callbacks in // succession. // // var object = {}; // _.extend(object, Backbone.Events); // object.on('expand', function(){ alert('expanded'); }); // object.trigger('expand'); // var Events = Backbone.Events = {}; // Regular expression used to split event strings. var eventSplitter = /\s+/; // A private global variable to share between listeners and listenees. var _listening; // Iterates over the standard `event, callback` (as well as the fancy multiple // space-separated events `"change blur", callback` and jQuery-style event // maps `{event: callback}`). var eventsApi = function(iteratee, events, name, callback, opts) { var i = 0, names; if (name && typeof name === 'object') { // Handle event maps. if (callback !== void 0 && 'context' in opts && opts.context === void 0) opts.context = callback; for (names = _.keys(name); i < names.length ; i++) { events = eventsApi(iteratee, events, names[i], name[names[i]], opts); } } else if (name && eventSplitter.test(name)) { // Handle space-separated event names by delegating them individually. for (names = name.split(eventSplitter); i < names.length; i++) { events = iteratee(events, names[i], callback, opts); } } else { // Finally, standard events. events = iteratee(events, name, callback, opts); } return events; }; // Bind an event to a `callback` function. Passing `"all"` will bind // the callback to all events fired. Events.on = function(name, callback, context) { this._events = eventsApi(onApi, this._events || {}, name, callback, { context: context, ctx: this, listening: _listening }); if (_listening) { var listeners = this._listeners || (this._listeners = {}); listeners[_listening.id] = _listening; // Allow the listening to use a counter, instead of tracking // callbacks for library interop _listening.interop = false; } return this; }; // Inversion-of-control versions of `on`. Tell *this* object to listen to // an event in another object... keeping track of what it's listening to // for easier unbinding later. Events.listenTo = function(obj, name, callback) { if (!obj) return this; var id = obj._listenId || (obj._listenId = _.uniqueId('l')); var listeningTo = this._listeningTo || (this._listeningTo = {}); var listening = _listening = listeningTo[id]; // This object is not listening to any other events on `obj` yet. // Setup the necessary references to track the listening callbacks. if (!listening) { this._listenId || (this._listenId = _.uniqueId('l')); listening = _listening = listeningTo[id] = new Listening(this, obj); } // Bind callbacks on obj. var error = tryCatchOn(obj, name, callback, this); _listening = void 0; if (error) throw error; // If the target obj is not Backbone.Events, track events manually. if (listening.interop) listening.on(name, callback); return this; }; // The reducing API that adds a callback to the `events` object. var onApi = function(events, name, callback, options) { if (callback) { var handlers = events[name] || (events[name] = []); var context = options.context, ctx = options.ctx, listening = options.listening; if (listening) listening.count++; handlers.push({callback: callback, context: context, ctx: context || ctx, listening: listening}); } return events; }; // An try-catch guarded #on function, to prevent poisoning the global // `_listening` variable. var tryCatchOn = function(obj, name, callback, context) { try { obj.on(name, callback, context); } catch (e) { return e; } }; // Remove one or many callbacks. If `context` is null, removes all // callbacks with that function. If `callback` is null, removes all // callbacks for the event. If `name` is null, removes all bound // callbacks for all events. Events.off = function(name, callback, context) { if (!this._events) return this; this._events = eventsApi(offApi, this._events, name, callback, { context: context, listeners: this._listeners }); return this; }; // Tell this object to stop listening to either specific events ... or // to every object it's currently listening to. Events.stopListening = function(obj, name, callback) { var listeningTo = this._listeningTo; if (!listeningTo) return this; var ids = obj ? [obj._listenId] : _.keys(listeningTo); for (var i = 0; i < ids.length; i++) { var listening = listeningTo[ids[i]]; // If listening doesn't exist, this object is not currently // listening to obj. Break out early. if (!listening) break; listening.obj.off(name, callback, this); if (listening.interop) listening.off(name, callback); } if (_.isEmpty(listeningTo)) this._listeningTo = void 0; return this; }; // The reducing API that removes a callback from the `events` object. var offApi = function(events, name, callback, options) { if (!events) return; var context = options.context, listeners = options.listeners; var i = 0, names; // Delete all event listeners and "drop" events. if (!name && !context && !callback) { for (names = _.keys(listeners); i < names.length; i++) { listeners[names[i]].cleanup(); } return; } names = name ? [name] : _.keys(events); for (; i < names.length; i++) { name = names[i]; var handlers = events[name]; // Bail out if there are no events stored. if (!handlers) break; // Find any remaining events. var remaining = []; for (var j = 0; j < handlers.length; j++) { var handler = handlers[j]; if ( callback && callback !== handler.callback && callback !== handler.callback._callback || context && context !== handler.context ) { remaining.push(handler); } else { var listening = handler.listening; if (listening) listening.off(name, callback); } } // Replace events if there are any remaining. Otherwise, clean up. if (remaining.length) { events[name] = remaining; } else { delete events[name]; } } return events; }; // Bind an event to only be triggered a single time. After the first time // the callback is invoked, its listener will be removed. If multiple events // are passed in using the space-separated syntax, the handler will fire // once for each event, not once for a combination of all events. Events.once = function(name, callback, context) { // Map the event into a `{event: once}` object. var events = eventsApi(onceMap, {}, name, callback, this.off.bind(this)); if (typeof name === 'string' && context == null) callback = void 0; return this.on(events, callback, context); }; // Inversion-of-control versions of `once`. Events.listenToOnce = function(obj, name, callback) { // Map the event into a `{event: once}` object. var events = eventsApi(onceMap, {}, name, callback, this.stopListening.bind(this, obj)); return this.listenTo(obj, events); }; // Reduces the event callbacks into a map of `{event: onceWrapper}`. // `offer` unbinds the `onceWrapper` after it has been called. var onceMap = function(map, name, callback, offer) { if (callback) { var once = map[name] = _.once(function() { offer(name, once); callback.apply(this, arguments); }); once._callback = callback; } return map; }; // Trigger one or many events, firing all bound callbacks. Callbacks are // passed the same arguments as `trigger` is, apart from the event name // (unless you're listening on `"all"`, which will cause your callback to // receive the true name of the event as the first argument). Events.trigger = function(name) { if (!this._events) return this; var length = Math.max(0, arguments.length - 1); var args = Array(length); for (var i = 0; i < length; i++) args[i] = arguments[i + 1]; eventsApi(triggerApi, this._events, name, void 0, args); return this; }; // Handles triggering the appropriate event callbacks. var triggerApi = function(objEvents, name, callback, args) { if (objEvents) { var events = objEvents[name]; var allEvents = objEvents.all; if (events && allEvents) allEvents = allEvents.slice(); if (events) triggerEvents(events, args); if (allEvents) triggerEvents(allEvents, [name].concat(args)); } return objEvents; }; // A difficult-to-believe, but optimized internal dispatch function for // triggering events. Tries to keep the usual cases speedy (most internal // Backbone events have 3 arguments). var triggerEvents = function(events, args) { var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2]; switch (args.length) { case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return; case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return; case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return; case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return; default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args); return; } }; // A listening class that tracks and cleans up memory bindings // when all callbacks have been offed. var Listening = function(listener, obj) { this.id = listener._listenId; this.listener = listener; this.obj = obj; this.interop = true; this.count = 0; this._events = void 0; }; Listening.prototype.on = Events.on; // Offs a callback (or several). // Uses an optimized counter if the listenee uses Backbone.Events. // Otherwise, falls back to manual tracking to support events // library interop. Listening.prototype.off = function(name, callback) { var cleanup; if (this.interop) { this._events = eventsApi(offApi, this._events, name, callback, { context: void 0, listeners: void 0 }); cleanup = !this._events; } else { this.count--; cleanup = this.count === 0; } if (cleanup) this.cleanup(); }; // Cleans up memory bindings between the listener and the listenee. Listening.prototype.cleanup = function() { delete this.listener._listeningTo[this.obj._listenId]; if (!this.interop) delete this.obj._listeners[this.id]; }; // Aliases for backwards compatibility. Events.bind = Events.on; Events.unbind = Events.off; // Allow the `Backbone` object to serve as a global event bus, for folks who // want global "pubsub" in a convenient place. _.extend(Backbone, Events); // Backbone.Model // -------------- // Backbone **Models** are the basic data object in the framework -- // frequently representing a row in a table in a database on your server. // A discrete chunk of data and a bunch of useful, related methods for // performing computations and transformations on that data. // Create a new model with the specified attributes. A client id (`cid`) // is automatically generated and assigned for you. var Model = Backbone.Model = function(attributes, options) { var attrs = attributes || {}; options || (options = {}); this.preinitialize.apply(this, arguments); this.cid = _.uniqueId(this.cidPrefix); this.attributes = {}; if (options.collection) this.collection = options.collection; if (options.parse) attrs = this.parse(attrs, options) || {}; var defaults = _.result(this, 'defaults'); attrs = _.defaults(_.extend({}, defaults, attrs), defaults); this.set(attrs, options); this.changed = {}; this.initialize.apply(this, arguments); }; // Attach all inheritable methods to the Model prototype. _.extend(Model.prototype, Events, { // A hash of attributes whose current and previous value differ. changed: null, // The value returned during the last failed validation. validationError: null, // The default name for the JSON `id` attribute is `"id"`. MongoDB and // CouchDB users may want to set this to `"_id"`. idAttribute: 'id', // The prefix is used to create the client id which is used to identify models locally. // You may want to override this if you're experiencing name clashes with model ids. cidPrefix: 'c', // preinitialize is an empty function by default. You can override it with a function // or object. preinitialize will run before any instantiation logic is run in the Model. preinitialize: function(){}, // Initialize is an empty function by default. Override it with your own // initialization logic. initialize: function(){}, // Return a copy of the model's `attributes` object. toJSON: function(options) { return _.clone(this.attributes); }, // Proxy `Backbone.sync` by default -- but override this if you need // custom syncing semantics for *this* particular model. sync: function() { return Backbone.sync.apply(this, arguments); }, // Get the value of an attribute. get: function(attr) { return this.attributes[attr]; }, // Get the HTML-escaped value of an attribute. escape: function(attr) { return _.escape(this.get(attr)); }, // Returns `true` if the attribute contains a value that is not null // or undefined. has: function(attr) { return this.get(attr) != null; }, // Special-cased proxy to underscore's `_.matches` method. matches: function(attrs) { return !!_.iteratee(attrs, this)(this.attributes); }, // Set a hash of model attributes on the object, firing `"change"`. This is // the core primitive operation of a model, updating the data and notifying // anyone who needs to know about the change in state. The heart of the beast. set: function(key, val, options) { if (key == null) return this; // Handle both `"key", value` and `{key: value}` -style arguments. var attrs; if (typeof key === 'object') { attrs = key; options = val; } else { (attrs = {})[key] = val; } options || (options = {}); // Run validation. if (!this._validate(attrs, options)) return false; // Extract attributes and options. var unset = options.unset; var silent = options.silent; var changes = []; var changing = this._changing; this._changing = true; if (!changing) { this._previousAttributes = _.clone(this.attributes); this.changed = {}; } var current = this.attributes; var changed = this.changed; var prev = this._previousAttributes; // For each `set` attribute, update or delete the current value. for (var attr in attrs) { val = attrs[attr]; if (!_.isEqual(current[attr], val)) changes.push(attr); if (!_.isEqual(prev[attr], val)) { changed[attr] = val; } else { delete changed[attr]; } unset ? delete current[attr] : current[attr] = val; } // Update the `id`. if (this.idAttribute in attrs) { var prevId = this.id; this.id = this.get(this.idAttribute); this.trigger('changeId', this, prevId, options); } // Trigger all relevant attribute changes. if (!silent) { if (changes.length) this._pending = options; for (var i = 0; i < changes.length; i++) { this.trigger('change:' + changes[i], this, current[changes[i]], options); } } // You might be wondering why there's a `while` loop here. Changes can // be recursively nested within `"change"` events. if (changing) return this; if (!silent) { while (this._pending) { options = this._pending; this._pending = false; this.trigger('change', this, options); } } this._pending = false; this._changing = false; return this; }, // Remove an attribute from the model, firing `"change"`. `unset` is a noop // if the attribute doesn't exist. unset: function(attr, options) { return this.set(attr, void 0, _.extend({}, options, {unset: true})); }, // Clear all attributes on the model, firing `"change"`. clear: function(options) { var attrs = {}; for (var key in this.attributes) attrs[key] = void 0; return this.set(attrs, _.extend({}, options, {unset: true})); }, // Determine if the model has changed since the last `"change"` event. // If you specify an attribute name, determine if that attribute has changed. hasChanged: function(attr) { if (attr == null) return !_.isEmpty(this.changed); return _.has(this.changed, attr); }, // Return an object containing all the attributes that have changed, or // false if there are no changed attributes. Useful for determining what // parts of a view need to be updated and/or what attributes need to be // persisted to the server. Unset attributes will be set to undefined. // You can also pass an attributes object to diff against the model, // determining if there *would be* a change. changedAttributes: function(diff) { if (!diff) return this.hasChanged() ? _.clone(this.changed) : false; var old = this._changing ? this._previousAttributes : this.attributes; var changed = {}; var hasChanged; for (var attr in diff) { var val = diff[attr]; if (_.isEqual(old[attr], val)) continue; changed[attr] = val; hasChanged = true; } return hasChanged ? changed : false; }, // Get the previous value of an attribute, recorded at the time the last // `"change"` event was fired. previous: function(attr) { if (attr == null || !this._previousAttributes) return null; return this._previousAttributes[attr]; }, // Get all of the attributes of the model at the time of the previous // `"change"` event. previousAttributes: function() { return _.clone(this._previousAttributes); }, // Fetch the model from the server, merging the response with the model's // local attributes. Any changed attributes will trigger a "change" event. fetch: function(options) { options = _.extend({parse: true}, options); var model = this; var success = options.success; options.success = function(resp) { var serverAttrs = options.parse ? model.parse(resp, options) : resp; if (!model.set(serverAttrs, options)) return false; if (success) success.call(options.context, model, resp, options); model.trigger('sync', model, resp, options); }; wrapError(this, options); return this.sync('read', this, options); }, // Set a hash of model attributes, and sync the model to the server. // If the server returns an attributes hash that differs, the model's // state will be `set` again. save: function(key, val, options) { // Handle both `"key", value` and `{key: value}` -style arguments. var attrs; if (key == null || typeof key === 'object') { attrs = key; options = val; } else { (attrs = {})[key] = val; } options = _.extend({validate: true, parse: true}, options); var wait = options.wait; // If we're not waiting and attributes exist, save acts as // `set(attr).save(null, opts)` with validation. Otherwise, check if // the model will be valid when the attributes, if any, are set. if (attrs && !wait) { if (!this.set(attrs, options)) return false; } else if (!this._validate(attrs, options)) { return false; } // After a successful server-side save, the client is (optionally) // updated with the server-side state. var model = this; var success = options.success; var attributes = this.attributes; options.success = function(resp) { // Ensure attributes are restored during synchronous saves. model.attributes = attributes; var serverAttrs = options.parse ? model.parse(resp, options) : resp; if (wait) serverAttrs = _.extend({}, attrs, serverAttrs); if (serverAttrs && !model.set(serverAttrs, options)) return false; if (success) success.call(options.context, model, resp, options); model.trigger('sync', model, resp, options); }; wrapError(this, options); // Set temporary attributes if `{wait: true}` to properly find new ids. if (attrs && wait) this.attributes = _.extend({}, attributes, attrs); var method = this.isNew() ? 'create' : options.patch ? 'patch' : 'update'; if (method === 'patch' && !options.attrs) options.attrs = attrs; var xhr = this.sync(method, this, options); // Restore attributes. this.attributes = attributes; return xhr; }, // Destroy this model on the server if it was already persisted. // Optimistically removes the model from its collection, if it has one. // If `wait: true` is passed, waits for the server to respond before removal. destroy: function(options) { options = options ? _.clone(options) : {}; var model = this; var success = options.success; var wait = options.wait; var destroy = function() { model.stopListening(); model.trigger('destroy', model, model.collection, options); }; options.success = function(resp) { if (wait) destroy(); if (success) success.call(options.context, model, resp, options); if (!model.isNew()) model.trigger('sync', model, resp, options); }; var xhr = false; if (this.isNew()) { _.defer(options.success); } else { wrapError(this, options); xhr = this.sync('delete', this, options); } if (!wait) destroy(); return xhr; }, // Default URL for the model's representation on the server -- if you're // using Backbone's restful methods, override this to change the endpoint // that will be called. url: function() { var base = _.result(this, 'urlRoot') || _.result(this.collection, 'url') || urlError(); if (this.isNew()) return base; var id = this.get(this.idAttribute); return base.replace(/[^\/]$/, '$&/') + encodeURIComponent(id); }, // **parse** converts a response into the hash of attributes to be `set` on // the model. The default implementation is just to pass the response along. parse: function(resp, options) { return resp; }, // Create a new model with identical attributes to this one. clone: function() { return new this.constructor(this.attributes); }, // A model is new if it has never been saved to the server, and lacks an id. isNew: function() { return !this.has(this.idAttribute); }, // Check if the model is currently in a valid state. isValid: function(options) { return this._validate({}, _.extend({}, options, {validate: true})); }, // Run validation against the next complete set of model attributes, // returning `true` if all is well. Otherwise, fire an `"invalid"` event. _validate: function(attrs, options) { if (!options.validate || !this.validate) return true; attrs = _.extend({}, this.attributes, attrs); var error = this.validationError = this.validate(attrs, options) || null; if (!error) return true; this.trigger('invalid', this, error, _.extend(options, {validationError: error})); return false; } }); // Backbone.Collection // ------------------- // If models tend to represent a single row of data, a Backbone Collection is // more analogous to a table full of data ... or a small slice or page of that // table, or a collection of rows that belong together for a particular reason // -- all of the messages in this particular folder, all of the documents // belonging to this particular author, and so on. Collections maintain // indexes of their models, both in order, and for lookup by `id`. // Create a new **Collection**, perhaps to contain a specific type of `model`. // If a `comparator` is specified, the Collection will maintain // its models in sort order, as they're added and removed. var Collection = Backbone.Collection = function(models, options) { options || (options = {}); this.preinitialize.apply(this, arguments); if (options.model) this.model = options.model; if (options.comparator !== void 0) this.comparator = options.comparator; this._reset(); this.initialize.apply(this, arguments); if (models) this.reset(models, _.extend({silent: true}, options)); }; // Default options for `Collection#set`. var setOptions = {add: true, remove: true, merge: true}; var addOptions = {add: true, remove: false}; // Splices `insert` into `array` at index `at`. var splice = function(array, insert, at) { at = Math.min(Math.max(at, 0), array.length); var tail = Array(array.length - at); var length = insert.length; var i; for (i = 0; i < tail.length; i++) tail[i] = array[i + at]; for (i = 0; i < length; i++) array[i + at] = insert[i]; for (i = 0; i < tail.length; i++) array[i + length + at] = tail[i]; }; // Define the Collection's inheritable methods. _.extend(Collection.prototype, Events, { // The default model for a collection is just a **Backbone.Model**. // This should be overridden in most cases. model: Model, // preinitialize is an empty function by default. You can override it with a function // or object. preinitialize will run before any instantiation logic is run in the Collection. preinitialize: function(){}, // Initialize is an empty function by default. Override it with your own // initialization logic. initialize: function(){}, // The JSON representation of a Collection is an array of the // models' attributes. toJSON: function(options) { return this.map(function(model) { return model.toJSON(options); }); }, // Proxy `Backbone.sync` by default. sync: function() { return Backbone.sync.apply(this, arguments); }, // Add a model, or list of models to the set. `models` may be Backbone // Models or raw JavaScript objects to be converted to Models, or any // combination of the two. add: function(models, options) { return this.set(models, _.extend({merge: false}, options, addOptions)); }, // Remove a model, or a list of models from the set. remove: function(models, options) { options = _.extend({}, options); var singular = !_.isArray(models); models = singular ? [models] : models.slice(); var removed = this._removeModels(models, options); if (!options.silent && removed.length) { options.changes = {added: [], merged: [], removed: removed}; this.trigger('update', this, options); } return singular ? removed[0] : removed; }, // Update a collection by `set`-ing a new list of models, adding new ones, // removing models that are no longer present, and merging models that // already exist in the collection, as necessary. Similar to **Model#set**, // the core operation for updating the data contained by the collection. set: function(models, options) { if (models == null) return; options = _.extend({}, setOptions, options); if (options.parse && !this._isModel(models)) { models = this.parse(models, options) || []; } var singular = !_.isArray(models); models = singular ? [models] : models.slice(); var at = options.at; if (at != null) at = +at; if (at > this.length) at = this.length; if (at < 0) at += this.length + 1; var set = []; var toAdd = []; var toMerge = []; var toRemove = []; var modelMap = {}; var add = options.add; var merge = options.merge; var remove = options.remove; var sort = false; var sortable = this.comparator && at == null && options.sort !== false; var sortAttr = _.isString(this.comparator) ? this.comparator : null; // Turn bare objects into model references, and prevent invalid models // from being added. var model, i; for (i = 0; i < models.length; i++) { model = models[i]; // If a duplicate is found, prevent it from being added and // optionally merge it into the existing model. var existing = this.get(model); if (existing) { if (merge && model !== existing) { var attrs = this._isModel(model) ? model.attributes : model; if (options.parse) attrs = existing.parse(attrs, options); existing.set(attrs, options); toMerge.push(existing); if (sortable && !sort) sort = existing.hasChanged(sortAttr); } if (!modelMap[existing.cid]) { modelMap[existing.cid] = true; set.push(existing); } models[i] = existing; // If this is a new, valid model, push it to the `toAdd` list. } else if (add) { model = models[i] = this._prepareModel(model, options); if (model) { toAdd.push(model); this._addReference(model, options); modelMap[model.cid] = true; set.push(model); } } } // Remove stale models. if (remove) { for (i = 0; i < this.length; i++) { model = this.models[i]; if (!modelMap[model.cid]) toRemove.push(model); } if (toRemove.length) this._removeModels(toRemove, options); } // See if sorting is needed, update `length` and splice in new models. var orderChanged = false; var replace = !sortable && add && remove; if (set.length && replace) { orderChanged = this.length !== set.length || _.some(this.models, function(m, index) { return m !== set[index]; }); this.models.length = 0; splice(this.models, set, 0); this.length = this.models.length; } else if (toAdd.length) { if (sortable) sort = true; splice(this.models, toAdd, at == null ? this.length : at); this.length = this.models.length; } // Silently sort the collection if appropriate. if (sort) this.sort({silent: true}); // Unless silenced, it's time to fire all appropriate add/sort/update events. if (!options.silent) { for (i = 0; i < toAdd.length; i++) { if (at != null) options.index = at + i; model = toAdd[i]; model.trigger('add', model, this, options); } if (sort || orderChanged) this.trigger('sort', this, options); if (toAdd.length || toRemove.length || toMerge.length) { options.changes = { added: toAdd, removed: toRemove, merged: toMerge }; this.trigger('update', this, options); } } // Return the added (or merged) model (or models). return singular ? models[0] : models; }, // When you have more items than you want to add or remove individually, // you can reset the entire set with a new list of models, without firing // any granular `add` or `remove` events. Fires `reset` when finished. // Useful for bulk operations and optimizations. reset: function(models, options) { options = options ? _.clone(options) : {}; for (var i = 0; i < this.models.length; i++) { this._removeReference(this.models[i], options); } options.previousModels = this.models; this._reset(); models = this.add(models, _.extend({silent: true}, options)); if (!options.silent) this.trigger('reset', this, options); return models; }, // Add a model to the end of the collection. push: function(model, options) { return this.add(model, _.extend({at: this.length}, options)); }, // Remove a model from the end of the collection. pop: function(options) { var model = this.at(this.length - 1); return this.remove(model, options); }, // Add a model to the beginning of the collection. unshift: function(model, options) { return this.add(model, _.extend({at: 0}, options)); }, // Remove a model from the beginning of the collection. shift: function(options) { var model = this.at(0); return this.remove(model, options); }, // Slice out a sub-array of models from the collection. slice: function() { return slice.apply(this.models, arguments); }, // Get a model from the set by id, cid, model object with id or cid // properties, or an attributes object that is transformed through modelId. get: function(obj) { if (obj == null) return void 0; return this._byId[obj] || this._byId[this.modelId(this._isModel(obj) ? obj.attributes : obj, obj.idAttribute)] || obj.cid && this._byId[obj.cid]; }, // Returns `true` if the model is in the collection. has: function(obj) { return this.get(obj) != null; }, // Get the model at the given index. at: function(index) { if (index < 0) index += this.length; return this.models[index]; }, // Return models with matching attributes. Useful for simple cases of // `filter`. where: function(attrs, first) { return this[first ? 'find' : 'filter'](attrs); }, // Return the first model with matching attributes. Useful for simple cases // of `find`. findWhere: function(attrs) { return this.where(attrs, true); }, // Force the collection to re-sort itself. You don't need to call this under // normal circumstances, as the set will maintain sort order as each item // is added. sort: function(options) { var comparator = this.comparator; if (!comparator) throw new Error('Cannot sort a set without a comparator'); options || (options = {}); var length = comparator.length; if (_.isFunction(comparator)) comparator = comparator.bind(this); // Run sort based on type of `comparator`. if (length === 1 || _.isString(comparator)) { this.models = this.sortBy(comparator); } else { this.models.sort(comparator); } if (!options.silent) this.trigger('sort', this, options); return this; }, // Pluck an attribute from each model in the collection. pluck: function(attr) { return this.map(attr + ''); }, // Fetch the default set of models for this collection, resetting the // collection when they arrive. If `reset: true` is passed, the response // data will be passed through the `reset` method instead of `set`. fetch: function(options) { options = _.extend({parse: true}, options); var success = options.success; var collection = this; options.success = function(resp) { var method = options.reset ? 'reset' : 'set'; collection[method](resp, options); if (success) success.call(options.context, collection, resp, options); collection.trigger('sync', collection, resp, options); }; wrapError(this, options); return this.sync('read', this, options); }, // Create a new instance of a model in this collection. Add the model to the // collection immediately, unless `wait: true` is passed, in which case we // wait for the server to agree. create: function(model, options) { options = options ? _.clone(options) : {}; var wait = options.wait; model = this._prepareModel(model, options); if (!model) return false; if (!wait) this.add(model, options); var collection = this; var success = options.success; options.success = function(m, resp, callbackOpts) { if (wait) collection.add(m, callbackOpts); if (success) success.call(callbackOpts.context, m, resp, callbackOpts); }; model.save(null, options); return model; }, // **parse** converts a response into a list of models to be added to the // collection. The default implementation is just to pass it through. parse: function(resp, options) { return resp; }, // Create a new collection with an identical list of models as this one. clone: function() { return new this.constructor(this.models, { model: this.model, comparator: this.comparator }); }, // Define how to uniquely identify models in the collection. modelId: function(attrs, idAttribute) { return attrs[idAttribute || this.model.prototype.idAttribute || 'id']; }, // Get an iterator of all models in this collection. values: function() { return new CollectionIterator(this, ITERATOR_VALUES); }, // Get an iterator of all model IDs in this collection. keys: function() { return new CollectionIterator(this, ITERATOR_KEYS); }, // Get an iterator of all [ID, model] tuples in this collection. entries: function() { return new CollectionIterator(this, ITERATOR_KEYSVALUES); }, // Private method to reset all internal state. Called when the collection // is first initialized or reset. _reset: function() { this.length = 0; this.models = []; this._byId = {}; }, // Prepare a hash of attributes (or other model) to be added to this // collection. _prepareModel: function(attrs, options) { if (this._isModel(attrs)) { if (!attrs.collection) attrs.collection = this; return attrs; } options = options ? _.clone(options) : {}; options.collection = this; var model; if (this.model.prototype) { model = new this.model(attrs, options); } else { // ES class methods didn't have prototype model = this.model(attrs, options); } if (!model.validationError) return model; this.trigger('invalid', this, model.validationError, options); return false; }, // Internal method called by both remove and set. _removeModels: function(models, options) { var removed = []; for (var i = 0; i < models.length; i++) { var model = this.get(models[i]); if (!model) continue; var index = this.indexOf(model); this.models.splice(index, 1); this.length--; // Remove references before triggering 'remove' event to prevent an // infinite loop. #3693 delete this._byId[model.cid]; var id = this.modelId(model.attributes, model.idAttribute); if (id != null) delete this._byId[id]; if (!options.silent) { options.index = index; model.trigger('remove', model, this, options); } removed.push(model); this._removeReference(model, options); } return removed; }, // Method for checking whether an object should be considered a model for // the purposes of adding to the collection. _isModel: function(model) { return model instanceof Model; }, // Internal method to create a model's ties to a collection. _addReference: function(model, options) { this._byId[model.cid] = model; var id = this.modelId(model.attributes, model.idAttribute); if (id != null) this._byId[id] = model; model.on('all', this._onModelEvent, this); }, // Internal method to sever a model's ties to a collection. _removeReference: function(model, options) { delete this._byId[model.cid]; var id = this.modelId(model.attributes, model.idAttribute); if (id != null) delete this._byId[id]; if (this === model.collection) delete model.collection; model.off('all', this._onModelEvent, this); }, // Internal method called every time a model in the set fires an event. // Sets need to update their indexes when models change ids. All other // events simply proxy through. "add" and "remove" events that originate // in other collections are ignored. _onModelEvent: function(event, model, collection, options) { if (model) { if ((event === 'add' || event === 'remove') && collection !== this) return; if (event === 'destroy') this.remove(model, options); if (event === 'changeId') { var prevId = this.modelId(model.previousAttributes(), model.idAttribute); var id = this.modelId(model.attributes, model.idAttribute); if (prevId != null) delete this._byId[prevId]; if (id != null) this._byId[id] = model; } } this.trigger.apply(this, arguments); } }); // Defining an @@iterator method implements JavaScript's Iterable protocol. // In modern ES2015 browsers, this value is found at Symbol.iterator. /* global Symbol */ var $$iterator = typeof Symbol === 'function' && Symbol.iterator; if ($$iterator) { Collection.prototype[$$iterator] = Collection.prototype.values; } // CollectionIterator // ------------------ // A CollectionIterator implements JavaScript's Iterator protocol, allowing the // use of `for of` loops in modern browsers and interoperation between // Backbone.Collection and other JavaScript functions and third-party libraries // which can operate on Iterables. var CollectionIterator = function(collection, kind) { this._collection = collection; this._kind = kind; this._index = 0; }; // This "enum" defines the three possible kinds of values which can be emitted // by a CollectionIterator that correspond to the values(), keys() and entries() // methods on Collection, respectively. var ITERATOR_VALUES = 1; var ITERATOR_KEYS = 2; var ITERATOR_KEYSVALUES = 3; // All Iterators should themselves be Iterable. if ($$iterator) { CollectionIterator.prototype[$$iterator] = function() { return this; }; } CollectionIterator.prototype.next = function() { if (this._collection) { // Only continue iterating if the iterated collection is long enough. if (this._index < this._collection.length) { var model = this._collection.at(this._index); this._index++; // Construct a value depending on what kind of values should be iterated. var value; if (this._kind === ITERATOR_VALUES) { value = model; } else { var id = this._collection.modelId(model.attributes, model.idAttribute); if (this._kind === ITERATOR_KEYS) { value = id; } else { // ITERATOR_KEYSVALUES value = [id, model]; } } return {value: value, done: false}; } // Once exhausted, remove the reference to the collection so future // calls to the next method always return done. this._collection = void 0; } return {value: void 0, done: true}; }; // Backbone.View // ------------- // Backbone Views are almost more convention than they are actual code. A View // is simply a JavaScript object that represents a logical chunk of UI in the // DOM. This might be a single item, an entire list, a sidebar or panel, or // even the surrounding frame which wraps your whole app. Defining a chunk of // UI as a **View** allows you to define your DOM events declaratively, without // having to worry about render order ... and makes it easy for the view to // react to specific changes in the state of your models. // Creating a Backbone.View creates its initial element outside of the DOM, // if an existing element is not provided... var View = Backbone.View = function(options) { this.cid = _.uniqueId('view'); this.preinitialize.apply(this, arguments); _.extend(this, _.pick(options, viewOptions)); this._ensureElement(); this.initialize.apply(this, arguments); }; // Cached regex to split keys for `delegate`. var delegateEventSplitter = /^(\S+)\s*(.*)$/; // List of view options to be set as properties. var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events']; // Set up all inheritable **Backbone.View** properties and methods. _.extend(View.prototype, Events, { // The default `tagName` of a View's element is `"div"`. tagName: 'div', // jQuery delegate for element lookup, scoped to DOM elements within the // current view. This should be preferred to global lookups where possible. $: function(selector) { return this.$el.find(selector); }, // preinitialize is an empty function by default. You can override it with a function // or object. preinitialize will run before any instantiation logic is run in the View preinitialize: function(){}, // Initialize is an empty function by default. Override it with your own // initialization logic. initialize: function(){}, // **render** is the core function that your view should override, in order // to populate its element (`this.el`), with the appropriate HTML. The // convention is for **render** to always return `this`. render: function() { return this; }, // Remove this view by taking the element out of the DOM, and removing any // applicable Backbone.Events listeners. remove: function() { this._removeElement(); this.stopListening(); return this; }, // Remove this view's element from the document and all event listeners // attached to it. Exposed for subclasses using an alternative DOM // manipulation API. _removeElement: function() { this.$el.remove(); }, // Change the view's element (`this.el` property) and re-delegate the // view's events on the new element. setElement: function(element) { this.undelegateEvents(); this._setElement(element); this.delegateEvents(); return this; }, // Creates the `this.el` and `this.$el` references for this view using the // given `el`. `el` can be a CSS selector or an HTML string, a jQuery // context or an element. Subclasses can override this to utilize an // alternative DOM manipulation API and are only required to set the // `this.el` property. _setElement: function(el) { this.$el = el instanceof Backbone.$ ? el : Backbone.$(el); this.el = this.$el[0]; }, // Set callbacks, where `this.events` is a hash of // // *{"event selector": "callback"}* // // { // 'mousedown .title': 'edit', // 'click .button': 'save', // 'click .open': function(e) { ... } // } // // pairs. Callbacks will be bound to the view, with `this` set properly. // Uses event delegation for efficiency. // Omitting the selector binds the event to `this.el`. delegateEvents: function(events) { events || (events = _.result(this, 'events')); if (!events) return this; this.undelegateEvents(); for (var key in events) { var method = events[key]; if (!_.isFunction(method)) method = this[method]; if (!method) continue; var match = key.match(delegateEventSplitter); this.delegate(match[1], match[2], method.bind(this)); } return this; }, // Add a single event listener to the view's element (or a child element // using `selector`). This only works for delegate-able events: not `focus`, // `blur`, and not `change`, `submit`, and `reset` in Internet Explorer. delegate: function(eventName, selector, listener) { this.$el.on(eventName + '.delegateEvents' + this.cid, selector, listener); return this; }, // Clears all callbacks previously bound to the view by `delegateEvents`. // You usually don't need to use this, but may wish to if you have multiple // Backbone views attached to the same DOM element. undelegateEvents: function() { if (this.$el) this.$el.off('.delegateEvents' + this.cid); return this; }, // A finer-grained `undelegateEvents` for removing a single delegated event. // `selector` and `listener` are both optional. undelegate: function(eventName, selector, listener) { this.$el.off(eventName + '.delegateEvents' + this.cid, selector, listener); return this; }, // Produces a DOM element to be assigned to your view. Exposed for // subclasses using an alternative DOM manipulation API. _createElement: function(tagName) { return document.createElement(tagName); }, // Ensure that the View has a DOM element to render into. // If `this.el` is a string, pass it through `$()`, take the first // matching element, and re-assign it to `el`. Otherwise, create // an element from the `id`, `className` and `tagName` properties. _ensureElement: function() { if (!this.el) { var attrs = _.extend({}, _.result(this, 'attributes')); if (this.id) attrs.id = _.result(this, 'id'); if (this.className) attrs['class'] = _.result(this, 'className'); this.setElement(this._createElement(_.result(this, 'tagName'))); this._setAttributes(attrs); } else { this.setElement(_.result(this, 'el')); } }, // Set attributes from a hash on this view's element. Exposed for // subclasses using an alternative DOM manipulation API. _setAttributes: function(attributes) { this.$el.attr(attributes); } }); // Proxy Backbone class methods to Underscore functions, wrapping the model's // `attributes` object or collection's `models` array behind the scenes. // // collection.filter(function(model) { return model.get('age') > 10 }); // collection.each(this.addView); // // `Function#apply` can be slow so we use the method's arg count, if we know it. var addMethod = function(base, length, method, attribute) { switch (length) { case 1: return function() { return base[method](this[attribute]); }; case 2: return function(value) { return base[method](this[attribute], value); }; case 3: return function(iteratee, context) { return base[method](this[attribute], cb(iteratee, this), context); }; case 4: return function(iteratee, defaultVal, context) { return base[method](this[attribute], cb(iteratee, this), defaultVal, context); }; default: return function() { var args = slice.call(arguments); args.unshift(this[attribute]); return base[method].apply(base, args); }; } }; var addUnderscoreMethods = function(Class, base, methods, attribute) { _.each(methods, function(length, method) { if (base[method]) Class.prototype[method] = addMethod(base, length, method, attribute); }); }; // Support `collection.sortBy('attr')` and `collection.findWhere({id: 1})`. var cb = function(iteratee, instance) { if (_.isFunction(iteratee)) return iteratee; if (_.isObject(iteratee) && !instance._isModel(iteratee)) return modelMatcher(iteratee); if (_.isString(iteratee)) return function(model) { return model.get(iteratee); }; return iteratee; }; var modelMatcher = function(attrs) { var matcher = _.matches(attrs); return function(model) { return matcher(model.attributes); }; }; // Underscore methods that we want to implement on the Collection. // 90% of the core usefulness of Backbone Collections is actually implemented // right here: var collectionMethods = {forEach: 3, each: 3, map: 3, collect: 3, reduce: 0, foldl: 0, inject: 0, reduceRight: 0, foldr: 0, find: 3, detect: 3, filter: 3, select: 3, reject: 3, every: 3, all: 3, some: 3, any: 3, include: 3, includes: 3, contains: 3, invoke: 0, max: 3, min: 3, toArray: 1, size: 1, first: 3, head: 3, take: 3, initial: 3, rest: 3, tail: 3, drop: 3, last: 3, without: 0, difference: 0, indexOf: 3, shuffle: 1, lastIndexOf: 3, isEmpty: 1, chain: 1, sample: 3, partition: 3, groupBy: 3, countBy: 3, sortBy: 3, indexBy: 3, findIndex: 3, findLastIndex: 3}; // Underscore methods that we want to implement on the Model, mapped to the // number of arguments they take. var modelMethods = {keys: 1, values: 1, pairs: 1, invert: 1, pick: 0, omit: 0, chain: 1, isEmpty: 1}; // Mix in each Underscore method as a proxy to `Collection#models`. _.each([ [Collection, collectionMethods, 'models'], [Model, modelMethods, 'attributes'] ], function(config) { var Base = config[0], methods = config[1], attribute = config[2]; Base.mixin = function(obj) { var mappings = _.reduce(_.functions(obj), function(memo, name) { memo[name] = 0; return memo; }, {}); addUnderscoreMethods(Base, obj, mappings, attribute); }; addUnderscoreMethods(Base, _, methods, attribute); }); // Backbone.sync // ------------- // Override this function to change the manner in which Backbone persists // models to the server. You will be passed the type of request, and the // model in question. By default, makes a RESTful Ajax request // to the model's `url()`. Some possible customizations could be: // // * Use `setTimeout` to batch rapid-fire updates into a single request. // * Send up the models as XML instead of JSON. // * Persist models via WebSockets instead of Ajax. // // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests // as `POST`, with a `_method` parameter containing the true HTTP method, // as well as all requests with the body as `application/x-www-form-urlencoded` // instead of `application/json` with the model in a param named `model`. // Useful when interfacing with server-side languages like **PHP** that make // it difficult to read the body of `PUT` requests. Backbone.sync = function(method, model, options) { var type = methodMap[method]; // Default options, unless specified. _.defaults(options || (options = {}), { emulateHTTP: Backbone.emulateHTTP, emulateJSON: Backbone.emulateJSON }); // Default JSON-request options. var params = {type: type, dataType: 'json'}; // Ensure that we have a URL. if (!options.url) { params.url = _.result(model, 'url') || urlError(); } // Ensure that we have the appropriate request data. if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) { params.contentType = 'application/json'; params.data = JSON.stringify(options.attrs || model.toJSON(options)); } // For older servers, emulate JSON by encoding the request into an HTML-form. if (options.emulateJSON) { params.contentType = 'application/x-www-form-urlencoded'; params.data = params.data ? {model: params.data} : {}; } // For older servers, emulate HTTP by mimicking the HTTP method with `_method` // And an `X-HTTP-Method-Override` header. if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) { params.type = 'POST'; if (options.emulateJSON) params.data._method = type; var beforeSend = options.beforeSend; options.beforeSend = function(xhr) { xhr.setRequestHeader('X-HTTP-Method-Override', type); if (beforeSend) return beforeSend.apply(this, arguments); }; } // Don't process data on a non-GET request. if (params.type !== 'GET' && !options.emulateJSON) { params.processData = false; } // Pass along `textStatus` and `errorThrown` from jQuery. var error = options.error; options.error = function(xhr, textStatus, errorThrown) { options.textStatus = textStatus; options.errorThrown = errorThrown; if (error) error.call(options.context, xhr, textStatus, errorThrown); }; // Make the request, allowing the user to override any Ajax options. var xhr = options.xhr = Backbone.ajax(_.extend(params, options)); model.trigger('request', model, xhr, options); return xhr; }; // Map from CRUD to HTTP for our default `Backbone.sync` implementation. var methodMap = { 'create': 'POST', 'update': 'PUT', 'patch': 'PATCH', 'delete': 'DELETE', 'read': 'GET' }; // Set the default implementation of `Backbone.ajax` to proxy through to `$`. // Override this if you'd like to use a different library. Backbone.ajax = function() { return Backbone.$.ajax.apply(Backbone.$, arguments); }; // Backbone.Router // --------------- // Routers map faux-URLs to actions, and fire events when routes are // matched. Creating a new one sets its `routes` hash, if not set statically. var Router = Backbone.Router = function(options) { options || (options = {}); this.preinitialize.apply(this, arguments); if (options.routes) this.routes = options.routes; this._bindRoutes(); this.initialize.apply(this, arguments); }; // Cached regular expressions for matching named param parts and splatted // parts of route strings. var optionalParam = /\((.*?)\)/g; var namedParam = /(\(\?)?:\w+/g; var splatParam = /\*\w+/g; var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g; // Set up all inheritable **Backbone.Router** properties and methods. _.extend(Router.prototype, Events, { // preinitialize is an empty function by default. You can override it with a function // or object. preinitialize will run before any instantiation logic is run in the Router. preinitialize: function(){}, // Initialize is an empty function by default. Override it with your own // initialization logic. initialize: function(){}, // Manually bind a single named route to a callback. For example: // // this.route('search/:query/p:num', 'search', function(query, num) { // ... // }); // route: function(route, name, callback) { if (!_.isRegExp(route)) route = this._routeToRegExp(route); if (_.isFunction(name)) { callback = name; name = ''; } if (!callback) callback = this[name]; var router = this; Backbone.history.route(route, function(fragment) { var args = router._extractParameters(route, fragment); if (router.execute(callback, args, name) !== false) { router.trigger.apply(router, ['route:' + name].concat(args)); router.trigger('route', name, args); Backbone.history.trigger('route', router, name, args); } }); return this; }, // Execute a route handler with the provided parameters. This is an // excellent place to do pre-route setup or post-route cleanup. execute: function(callback, args, name) { if (callback) callback.apply(this, args); }, // Simple proxy to `Backbone.history` to save a fragment into the history. navigate: function(fragment, options) { Backbone.history.navigate(fragment, options); return this; }, // Bind all defined routes to `Backbone.history`. We have to reverse the // order of the routes here to support behavior where the most general // routes can be defined at the bottom of the route map. _bindRoutes: function() { if (!this.routes) return; this.routes = _.result(this, 'routes'); var route, routes = _.keys(this.routes); while ((route = routes.pop()) != null) { this.route(route, this.routes[route]); } }, // Convert a route string into a regular expression, suitable for matching // against the current location hash. _routeToRegExp: function(route) { route = route.replace(escapeRegExp, '\\$&') .replace(optionalParam, '(?:$1)?') .replace(namedParam, function(match, optional) { return optional ? match : '([^/?]+)'; }) .replace(splatParam, '([^?]*?)'); return new RegExp('^' + route + '(?:\\?([\\s\\S]*))?$'); }, // Given a route, and a URL fragment that it matches, return the array of // extracted decoded parameters. Empty or unmatched parameters will be // treated as `null` to normalize cross-browser behavior. _extractParameters: function(route, fragment) { var params = route.exec(fragment).slice(1); return _.map(params, function(param, i) { // Don't decode the search params. if (i === params.length - 1) return param || null; return param ? decodeURIComponent(param) : null; }); } }); // Backbone.History // ---------------- // Handles cross-browser history management, based on either // [pushState](http://diveintohtml5.info/history.html) and real URLs, or // [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange) // and URL fragments. If the browser supports neither (old IE, natch), // falls back to polling. var History = Backbone.History = function() { this.handlers = []; this.checkUrl = this.checkUrl.bind(this); // Ensure that `History` can be used outside of the browser. if (typeof window !== 'undefined') { this.location = window.location; this.history = window.history; } }; // Cached regex for stripping a leading hash/slash and trailing space. var routeStripper = /^[#\/]|\s+$/g; // Cached regex for stripping leading and trailing slashes. var rootStripper = /^\/+|\/+$/g; // Cached regex for stripping urls of hash. var pathStripper = /#.*$/; // Has the history handling already been started? History.started = false; // Set up all inheritable **Backbone.History** properties and methods. _.extend(History.prototype, Events, { // The default interval to poll for hash changes, if necessary, is // twenty times a second. interval: 50, // Are we at the app root? atRoot: function() { var path = this.location.pathname.replace(/[^\/]$/, '$&/'); return path === this.root && !this.getSearch(); }, // Does the pathname match the root? matchRoot: function() { var path = this.decodeFragment(this.location.pathname); var rootPath = path.slice(0, this.root.length - 1) + '/'; return rootPath === this.root; }, // Unicode characters in `location.pathname` are percent encoded so they're // decoded for comparison. `%25` should not be decoded since it may be part // of an encoded parameter. decodeFragment: function(fragment) { return decodeURI(fragment.replace(/%25/g, '%2525')); }, // In IE6, the hash fragment and search params are incorrect if the // fragment contains `?`. getSearch: function() { var match = this.location.href.replace(/#.*/, '').match(/\?.+/); return match ? match[0] : ''; }, // Gets the true hash value. Cannot use location.hash directly due to bug // in Firefox where location.hash will always be decoded. getHash: function(window) { var match = (window || this).location.href.match(/#(.*)$/); return match ? match[1] : ''; }, // Get the pathname and search params, without the root. getPath: function() { var path = this.decodeFragment( this.location.pathname + this.getSearch() ).slice(this.root.length - 1); return path.charAt(0) === '/' ? path.slice(1) : path; }, // Get the cross-browser normalized URL fragment from the path or hash. getFragment: function(fragment) { if (fragment == null) { if (this._usePushState || !this._wantsHashChange) { fragment = this.getPath(); } else { fragment = this.getHash(); } } return fragment.replace(routeStripper, ''); }, // Start the hash change handling, returning `true` if the current URL matches // an existing route, and `false` otherwise. start: function(options) { if (History.started) throw new Error('Backbone.history has already been started'); History.started = true; // Figure out the initial configuration. Do we need an iframe? // Is pushState desired ... is it available? this.options = _.extend({root: '/'}, this.options, options); this.root = this.options.root; this._wantsHashChange = this.options.hashChange !== false; this._hasHashChange = 'onhashchange' in window && (document.documentMode === void 0 || document.documentMode > 7); this._useHashChange = this._wantsHashChange && this._hasHashChange; this._wantsPushState = !!this.options.pushState; this._hasPushState = !!(this.history && this.history.pushState); this._usePushState = this._wantsPushState && this._hasPushState; this.fragment = this.getFragment(); // Normalize root to always include a leading and trailing slash. this.root = ('/' + this.root + '/').replace(rootStripper, '/'); // Transition from hashChange to pushState or vice versa if both are // requested. if (this._wantsHashChange && this._wantsPushState) { // If we've started off with a route from a `pushState`-enabled // browser, but we're currently in a browser that doesn't support it... if (!this._hasPushState && !this.atRoot()) { var rootPath = this.root.slice(0, -1) || '/'; this.location.replace(rootPath + '#' + this.getPath()); // Return immediately as browser will do redirect to new url return true; // Or if we've started out with a hash-based route, but we're currently // in a browser where it could be `pushState`-based instead... } else if (this._hasPushState && this.atRoot()) { this.navigate(this.getHash(), {replace: true}); } } // Proxy an iframe to handle location events if the browser doesn't // support the `hashchange` event, HTML5 history, or the user wants // `hashChange` but not `pushState`. if (!this._hasHashChange && this._wantsHashChange && !this._usePushState) { this.iframe = document.createElement('iframe'); this.iframe.src = 'javascript:0'; this.iframe.style.display = 'none'; this.iframe.tabIndex = -1; var body = document.body; // Using `appendChild` will throw on IE < 9 if the document is not ready. var iWindow = body.insertBefore(this.iframe, body.firstChild).contentWindow; iWindow.document.open(); iWindow.document.close(); iWindow.location.hash = '#' + this.fragment; } // Add a cross-platform `addEventListener` shim for older browsers. var addEventListener = window.addEventListener || function(eventName, listener) { return attachEvent('on' + eventName, listener); }; // Depending on whether we're using pushState or hashes, and whether // 'onhashchange' is supported, determine how we check the URL state. if (this._usePushState) { addEventListener('popstate', this.checkUrl, false); } else if (this._useHashChange && !this.iframe) { addEventListener('hashchange', this.checkUrl, false); } else if (this._wantsHashChange) { this._checkUrlInterval = setInterval(this.checkUrl, this.interval); } if (!this.options.silent) return this.loadUrl(); }, // Disable Backbone.history, perhaps temporarily. Not useful in a real app, // but possibly useful for unit testing Routers. stop: function() { // Add a cross-platform `removeEventListener` shim for older browsers. var removeEventListener = window.removeEventListener || function(eventName, listener) { return detachEvent('on' + eventName, listener); }; // Remove window listeners. if (this._usePushState) { removeEventListener('popstate', this.checkUrl, false); } else if (this._useHashChange && !this.iframe) { removeEventListener('hashchange', this.checkUrl, false); } // Clean up the iframe if necessary. if (this.iframe) { document.body.removeChild(this.iframe); this.iframe = null; } // Some environments will throw when clearing an undefined interval. if (this._checkUrlInterval) clearInterval(this._checkUrlInterval); History.started = false; }, // Add a route to be tested when the fragment changes. Routes added later // may override previous routes. route: function(route, callback) { this.handlers.unshift({route: route, callback: callback}); }, // Checks the current URL to see if it has changed, and if it has, // calls `loadUrl`, normalizing across the hidden iframe. checkUrl: function(e) { var current = this.getFragment(); // If the user pressed the back button, the iframe's hash will have // changed and we should use that for comparison. if (current === this.fragment && this.iframe) { current = this.getHash(this.iframe.contentWindow); } if (current === this.fragment) return false; if (this.iframe) this.navigate(current); this.loadUrl(); }, // Attempt to load the current URL fragment. If a route succeeds with a // match, returns `true`. If no defined routes matches the fragment, // returns `false`. loadUrl: function(fragment) { // If the root doesn't match, no routes can match either. if (!this.matchRoot()) return false; fragment = this.fragment = this.getFragment(fragment); return _.some(this.handlers, function(handler) { if (handler.route.test(fragment)) { handler.callback(fragment); return true; } }); }, // Save a fragment into the hash history, or replace the URL state if the // 'replace' option is passed. You are responsible for properly URL-encoding // the fragment in advance. // // The options object can contain `trigger: true` if you wish to have the // route callback be fired (not usually desirable), or `replace: true`, if // you wish to modify the current URL without adding an entry to the history. navigate: function(fragment, options) { if (!History.started) return false; if (!options || options === true) options = {trigger: !!options}; // Normalize the fragment. fragment = this.getFragment(fragment || ''); // Don't include a trailing slash on the root. var rootPath = this.root; if (fragment === '' || fragment.charAt(0) === '?') { rootPath = rootPath.slice(0, -1) || '/'; } var url = rootPath + fragment; // Strip the fragment of the query and hash for matching. fragment = fragment.replace(pathStripper, ''); // Decode for matching. var decodedFragment = this.decodeFragment(fragment); if (this.fragment === decodedFragment) return; this.fragment = decodedFragment; // If pushState is available, we use it to set the fragment as a real URL. if (this._usePushState) { this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url); // If hash changes haven't been explicitly disabled, update the hash // fragment to store history. } else if (this._wantsHashChange) { this._updateHash(this.location, fragment, options.replace); if (this.iframe && fragment !== this.getHash(this.iframe.contentWindow)) { var iWindow = this.iframe.contentWindow; // Opening and closing the iframe tricks IE7 and earlier to push a // history entry on hash-tag change. When replace is true, we don't // want this. if (!options.replace) { iWindow.document.open(); iWindow.document.close(); } this._updateHash(iWindow.location, fragment, options.replace); } // If you've told us that you explicitly don't want fallback hashchange- // based history, then `navigate` becomes a page refresh. } else { return this.location.assign(url); } if (options.trigger) return this.loadUrl(fragment); }, // Update the hash location, either replacing the current entry, or adding // a new one to the browser history. _updateHash: function(location, fragment, replace) { if (replace) { var href = location.href.replace(/(javascript:|#).*$/, ''); location.replace(href + '#' + fragment); } else { // Some browsers require that `hash` contains a leading #. location.hash = '#' + fragment; } } }); // Create the default Backbone.history. Backbone.history = new History; // Helpers // ------- // Helper function to correctly set up the prototype chain for subclasses. // Similar to `goog.inherits`, but uses a hash of prototype properties and // class properties to be extended. var extend = function(protoProps, staticProps) { var parent = this; var child; // The constructor function for the new subclass is either defined by you // (the "constructor" property in your `extend` definition), or defaulted // by us to simply call the parent constructor. if (protoProps && _.has(protoProps, 'constructor')) { child = protoProps.constructor; } else { child = function(){ return parent.apply(this, arguments); }; } // Add static properties to the constructor function, if supplied. _.extend(child, parent, staticProps); // Set the prototype chain to inherit from `parent`, without calling // `parent`'s constructor function and add the prototype properties. child.prototype = _.create(parent.prototype, protoProps); child.prototype.constructor = child; // Set a convenience property in case the parent's prototype is needed // later. child.__super__ = parent.prototype; return child; }; // Set up inheritance for the model, collection, router, view and history. Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend; // Throw an error when a URL is needed, and none is supplied. var urlError = function() { throw new Error('A "url" property or function must be specified'); }; // Wrap an optional error callback with a fallback error event. var wrapError = function(model, options) { var error = options.error; options.error = function(resp) { if (error) error.call(options.context, model, resp, options); model.trigger('error', model, resp, options); }; }; return Backbone; }); /***/ }), /***/ 210: /***/ ((__unused_webpack_module, __unused_webpack_exports, __nested_webpack_require_106811__) => { (function(mod) { if (true) // CommonJS mod(__nested_webpack_require_106811__(631)); else {} })(function(CodeMirror) { CodeMirror.extendMode("css", { commentStart: "/*", commentEnd: "*/", newlineAfterToken: function(_type, content) { return /^[;{}]$/.test(content); } }); CodeMirror.extendMode("javascript", { commentStart: "/*", commentEnd: "*/", // FIXME semicolons inside of for newlineAfterToken: function(_type, content, textAfter, state) { if (this.jsonMode) { return /^[\[,{]$/.test(content) || /^}/.test(textAfter); } else { if (content == ";" && state.lexical && state.lexical.type == ")") return false; return /^[;{}]$/.test(content) && !/^;/.test(textAfter); } } }); var inlineElements = /^(a|abbr|acronym|area|base|bdo|big|br|button|caption|cite|code|col|colgroup|dd|del|dfn|em|frame|hr|iframe|img|input|ins|kbd|label|legend|link|map|object|optgroup|option|param|q|samp|script|select|small|span|strong|sub|sup|textarea|tt|var)$/; CodeMirror.extendMode("xml", { commentStart: "<!--", commentEnd: "-->", newlineAfterToken: function(type, content, textAfter, state) { var inline = false; if (this.configuration == "html") inline = state.context ? inlineElements.test(state.context.tagName) : false; return !inline && ((type == "tag" && />$/.test(content) && state.context) || /^</.test(textAfter)); } }); // Comment/uncomment the specified range CodeMirror.defineExtension("commentRange", function (isComment, from, to) { var cm = this, curMode = CodeMirror.innerMode(cm.getMode(), cm.getTokenAt(from).state).mode; cm.operation(function() { if (isComment) { // Comment range cm.replaceRange(curMode.commentEnd, to); cm.replaceRange(curMode.commentStart, from); if (from.line == to.line && from.ch == to.ch) // An empty comment inserted - put cursor inside cm.setCursor(from.line, from.ch + curMode.commentStart.length); } else { // Uncomment range var selText = cm.getRange(from, to); var startIndex = selText.indexOf(curMode.commentStart); var endIndex = selText.lastIndexOf(curMode.commentEnd); if (startIndex > -1 && endIndex > -1 && endIndex > startIndex) { // Take string till comment start selText = selText.substr(0, startIndex) + // From comment start till comment end selText.substring(startIndex + curMode.commentStart.length, endIndex) + // From comment end till string end selText.substr(endIndex + curMode.commentEnd.length); } cm.replaceRange(selText, from, to); } }); }); // Applies automatic mode-aware indentation to the specified range CodeMirror.defineExtension("autoIndentRange", function (from, to) { var cmInstance = this; this.operation(function () { for (var i = from.line; i <= to.line; i++) { cmInstance.indentLine(i, "smart"); } }); }); // Applies automatic formatting to the specified range CodeMirror.defineExtension("autoFormatRange", function (from, to) { var cm = this; var outer = cm.getMode(), text = cm.getRange(from, to).split("\n"); var state = CodeMirror.copyState(outer, cm.getTokenAt(from).state); var tabSize = cm.getOption("tabSize"); var out = "", lines = 0, atSol = from.ch === 0; function newline() { out += "\n"; atSol = true; ++lines; } for (var i = 0; i < text.length; ++i) { var stream = new CodeMirror.StringStream(text[i], tabSize); while (!stream.eol()) { var inner = CodeMirror.innerMode(outer, state); var style = outer.token(stream, state), cur = stream.current(); stream.start = stream.pos; if (!atSol || /\S/.test(cur)) { out += cur; atSol = false; } if (!atSol && inner.mode.newlineAfterToken && inner.mode.newlineAfterToken(style, cur, stream.string.slice(stream.pos) || text[i+1] || "", inner.state)) newline(); } if (!stream.pos && outer.blankLine) outer.blankLine(state); if (!atSol && i < text.length - 1) newline(); } cm.operation(function () { cm.replaceRange(out, from, to); for (var cur = from.line + 1, end = from.line + lines; cur <= end; ++cur) cm.indentLine(cur, "smart"); cm.setSelection(from, cm.getCursor(false)); }); }); }); /***/ }), /***/ 631: /***/ (function(module) { // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/5/LICENSE // This is CodeMirror (https://codemirror.net/5), a code editor // implemented in JavaScript on top of the browser's DOM. // // You can find some technical background for some of the code below // at http://marijnhaverbeke.nl/blog/#cm-internals . (function (global, factory) { true ? module.exports = factory() : 0; }(this, (function () { 'use strict'; // Kludges for bugs and behavior differences that can't be feature // detected are enabled based on userAgent etc sniffing. var userAgent = navigator.userAgent; var platform = navigator.platform; var gecko = /gecko\/\d/i.test(userAgent); var ie_upto10 = /MSIE \d/.test(userAgent); var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent); var edge = /Edge\/(\d+)/.exec(userAgent); var ie = ie_upto10 || ie_11up || edge; var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]); var webkit = !edge && /WebKit\//.test(userAgent); var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent); var chrome = !edge && /Chrome\/(\d+)/.exec(userAgent); var chrome_version = chrome && +chrome[1]; var presto = /Opera\//.test(userAgent); var safari = /Apple Computer/.test(navigator.vendor); var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent); var phantom = /PhantomJS/.test(userAgent); var ios = safari && (/Mobile\/\w+/.test(userAgent) || navigator.maxTouchPoints > 2); var android = /Android/.test(userAgent); // This is woefully incomplete. Suggestions for alternative methods welcome. var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent); var mac = ios || /Mac/.test(platform); var chromeOS = /\bCrOS\b/.test(userAgent); var windows = /win/i.test(platform); var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/); if (presto_version) { presto_version = Number(presto_version[1]); } if (presto_version && presto_version >= 15) { presto = false; webkit = true; } // Some browsers use the wrong event properties to signal cmd/ctrl on OS X var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11)); var captureRightClick = gecko || (ie && ie_version >= 9); function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") } var rmClass = function(node, cls) { var current = node.className; var match = classTest(cls).exec(current); if (match) { var after = current.slice(match.index + match[0].length); node.className = current.slice(0, match.index) + (after ? match[1] + after : ""); } }; function removeChildren(e) { for (var count = e.childNodes.length; count > 0; --count) { e.removeChild(e.firstChild); } return e } function removeChildrenAndAdd(parent, e) { return removeChildren(parent).appendChild(e) } function elt(tag, content, className, style) { var e = document.createElement(tag); if (className) { e.className = className; } if (style) { e.style.cssText = style; } if (typeof content == "string") { e.appendChild(document.createTextNode(content)); } else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]); } } return e } // wrapper for elt, which removes the elt from the accessibility tree function eltP(tag, content, className, style) { var e = elt(tag, content, className, style); e.setAttribute("role", "presentation"); return e } var range; if (document.createRange) { range = function(node, start, end, endNode) { var r = document.createRange(); r.setEnd(endNode || node, end); r.setStart(node, start); return r }; } else { range = function(node, start, end) { var r = document.body.createTextRange(); try { r.moveToElementText(node.parentNode); } catch(e) { return r } r.collapse(true); r.moveEnd("character", end); r.moveStart("character", start); return r }; } function contains(parent, child) { if (child.nodeType == 3) // Android browser always returns false when child is a textnode { child = child.parentNode; } if (parent.contains) { return parent.contains(child) } do { if (child.nodeType == 11) { child = child.host; } if (child == parent) { return true } } while (child = child.parentNode) } function activeElt(doc) { // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement. // IE < 10 will throw when accessed while the page is loading or in an iframe. // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable. var activeElement; try { activeElement = doc.activeElement; } catch(e) { activeElement = doc.body || null; } while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement) { activeElement = activeElement.shadowRoot.activeElement; } return activeElement } function addClass(node, cls) { var current = node.className; if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls; } } function joinClasses(a, b) { var as = a.split(" "); for (var i = 0; i < as.length; i++) { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i]; } } return b } var selectInput = function(node) { node.select(); }; if (ios) // Mobile Safari apparently has a bug where select() is broken. { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; } else if (ie) // Suppress mysterious IE10 errors { selectInput = function(node) { try { node.select(); } catch(_e) {} }; } function doc(cm) { return cm.display.wrapper.ownerDocument } function win(cm) { return doc(cm).defaultView } function bind(f) { var args = Array.prototype.slice.call(arguments, 1); return function(){return f.apply(null, args)} } function copyObj(obj, target, overwrite) { if (!target) { target = {}; } for (var prop in obj) { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop))) { target[prop] = obj[prop]; } } return target } // Counts the column offset in a string, taking tabs into account. // Used mostly to find indentation. function countColumn(string, end, tabSize, startIndex, startValue) { if (end == null) { end = string.search(/[^\s\u00a0]/); if (end == -1) { end = string.length; } } for (var i = startIndex || 0, n = startValue || 0;;) { var nextTab = string.indexOf("\t", i); if (nextTab < 0 || nextTab >= end) { return n + (end - i) } n += nextTab - i; n += tabSize - (n % tabSize); i = nextTab + 1; } } var Delayed = function() { this.id = null; this.f = null; this.time = 0; this.handler = bind(this.onTimeout, this); }; Delayed.prototype.onTimeout = function (self) { self.id = 0; if (self.time <= +new Date) { self.f(); } else { setTimeout(self.handler, self.time - +new Date); } }; Delayed.prototype.set = function (ms, f) { this.f = f; var time = +new Date + ms; if (!this.id || time < this.time) { clearTimeout(this.id); this.id = setTimeout(this.handler, ms); this.time = time; } }; function indexOf(array, elt) { for (var i = 0; i < array.length; ++i) { if (array[i] == elt) { return i } } return -1 } // Number of pixels added to scroller and sizer to hide scrollbar var scrollerGap = 50; // Returned or thrown by various protocols to signal 'I'm not // handling this'. var Pass = {toString: function(){return "CodeMirror.Pass"}}; // Reused option objects for setSelection & friends var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"}; // The inverse of countColumn -- find the offset that corresponds to // a particular column. function findColumn(string, goal, tabSize) { for (var pos = 0, col = 0;;) { var nextTab = string.indexOf("\t", pos); if (nextTab == -1) { nextTab = string.length; } var skipped = nextTab - pos; if (nextTab == string.length || col + skipped >= goal) { return pos + Math.min(skipped, goal - col) } col += nextTab - pos; col += tabSize - (col % tabSize); pos = nextTab + 1; if (col >= goal) { return pos } } } var spaceStrs = [""]; function spaceStr(n) { while (spaceStrs.length <= n) { spaceStrs.push(lst(spaceStrs) + " "); } return spaceStrs[n] } function lst(arr) { return arr[arr.length-1] } function map(array, f) { var out = []; for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); } return out } function insertSorted(array, value, score) { var pos = 0, priority = score(value); while (pos < array.length && score(array[pos]) <= priority) { pos++; } array.splice(pos, 0, value); } function nothing() {} function createObj(base, props) { var inst; if (Object.create) { inst = Object.create(base); } else { nothing.prototype = base; inst = new nothing(); } if (props) { copyObj(props, inst); } return inst } var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; function isWordCharBasic(ch) { return /\w/.test(ch) || ch > "\x80" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)) } function isWordChar(ch, helper) { if (!helper) { return isWordCharBasic(ch) } if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true } return helper.test(ch) } function isEmpty(obj) { for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } } return true } // Extending unicode characters. A series of a non-extending char + // any number of extending chars is treated as a single unit as far // as editing and measuring is concerned. This is not fully correct, // since some scripts/fonts/browsers also treat other configurations // of code points as a group. var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/; function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) } // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range. function skipExtendingChars(str, pos, dir) { while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; } return pos } // Returns the value from the range [`from`; `to`] that satisfies // `pred` and is closest to `from`. Assumes that at least `to` // satisfies `pred`. Supports `from` being greater than `to`. function findFirst(pred, from, to) { // At any point we are certain `to` satisfies `pred`, don't know // whether `from` does. var dir = from > to ? -1 : 1; for (;;) { if (from == to) { return from } var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF); if (mid == from) { return pred(mid) ? from : to } if (pred(mid)) { to = mid; } else { from = mid + dir; } } } // BIDI HELPERS function iterateBidiSections(order, from, to, f) { if (!order) { return f(from, to, "ltr", 0) } var found = false; for (var i = 0; i < order.length; ++i) { var part = order[i]; if (part.from < to && part.to > from || from == to && part.to == from) { f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i); found = true; } } if (!found) { f(from, to, "ltr"); } } var bidiOther = null; function getBidiPartAt(order, ch, sticky) { var found; bidiOther = null; for (var i = 0; i < order.length; ++i) { var cur = order[i]; if (cur.from < ch && cur.to > ch) { return i } if (cur.to == ch) { if (cur.from != cur.to && sticky == "before") { found = i; } else { bidiOther = i; } } if (cur.from == ch) { if (cur.from != cur.to && sticky != "before") { found = i; } else { bidiOther = i; } } } return found != null ? found : bidiOther } // Bidirectional ordering algorithm // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm // that this (partially) implements. // One-char codes used for character types: // L (L): Left-to-Right // R (R): Right-to-Left // r (AL): Right-to-Left Arabic // 1 (EN): European Number // + (ES): European Number Separator // % (ET): European Number Terminator // n (AN): Arabic Number // , (CS): Common Number Separator // m (NSM): Non-Spacing Mark // b (BN): Boundary Neutral // s (B): Paragraph Separator // t (S): Segment Separator // w (WS): Whitespace // N (ON): Other Neutrals // Returns null if characters are ordered as they appear // (left-to-right), or an array of sections ({from, to, level} // objects) in the order in which they occur visually. var bidiOrdering = (function() { // Character types for codepoints 0 to 0xff var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN"; // Character types for codepoints 0x600 to 0x6f9 var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111"; function charType(code) { if (code <= 0xf7) { return lowTypes.charAt(code) } else if (0x590 <= code && code <= 0x5f4) { return "R" } else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) } else if (0x6ee <= code && code <= 0x8ac) { return "r" } else if (0x2000 <= code && code <= 0x200b) { return "w" } else if (code == 0x200c) { return "b" } else { return "L" } } var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/; function BidiSpan(level, from, to) { this.level = level; this.from = from; this.to = to; } return function(str, direction) { var outerType = direction == "ltr" ? "L" : "R"; if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false } var len = str.length, types = []; for (var i = 0; i < len; ++i) { types.push(charType(str.charCodeAt(i))); } // W1. Examine each non-spacing mark (NSM) in the level run, and // change the type of the NSM to the type of the previous // character. If the NSM is at the start of the level run, it will // get the type of sor. for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) { var type = types[i$1]; if (type == "m") { types[i$1] = prev; } else { prev = type; } } // W2. Search backwards from each instance of a European number // until the first strong type (R, L, AL, or sor) is found. If an // AL is found, change the type of the European number to Arabic // number. // W3. Change all ALs to R. for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) { var type$1 = types[i$2]; if (type$1 == "1" && cur == "r") { types[i$2] = "n"; } else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R"; } } } // W4. A single European separator between two European numbers // changes to a European number. A single common separator between // two numbers of the same type changes to that type. for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) { var type$2 = types[i$3]; if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1"; } else if (type$2 == "," && prev$1 == types[i$3+1] && (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1; } prev$1 = type$2; } // W5. A sequence of European terminators adjacent to European // numbers changes to all European numbers. // W6. Otherwise, separators and terminators change to Other // Neutral. for (var i$4 = 0; i$4 < len; ++i$4) { var type$3 = types[i$4]; if (type$3 == ",") { types[i$4] = "N"; } else if (type$3 == "%") { var end = (void 0); for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {} var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N"; for (var j = i$4; j < end; ++j) { types[j] = replace; } i$4 = end - 1; } } // W7. Search backwards from each instance of a European number // until the first strong type (R, L, or sor) is found. If an L is // found, then change the type of the European number to L. for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) { var type$4 = types[i$5]; if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L"; } else if (isStrong.test(type$4)) { cur$1 = type$4; } } // N1. A sequence of neutrals takes the direction of the // surrounding strong text if the text on both sides has the same // direction. European and Arabic numbers act as if they were R in // terms of their influence on neutrals. Start-of-level-run (sor) // and end-of-level-run (eor) are used at level run boundaries. // N2. Any remaining neutrals take the embedding direction. for (var i$6 = 0; i$6 < len; ++i$6) { if (isNeutral.test(types[i$6])) { var end$1 = (void 0); for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {} var before = (i$6 ? types[i$6-1] : outerType) == "L"; var after = (end$1 < len ? types[end$1] : outerType) == "L"; var replace$1 = before == after ? (before ? "L" : "R") : outerType; for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; } i$6 = end$1 - 1; } } // Here we depart from the documented algorithm, in order to avoid // building up an actual levels array. Since there are only three // levels (0, 1, 2) in an implementation that doesn't take // explicit embedding into account, we can build up the order on // the fly, without following the level-based algorithm. var order = [], m; for (var i$7 = 0; i$7 < len;) { if (countsAsLeft.test(types[i$7])) { var start = i$7; for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {} order.push(new BidiSpan(0, start, i$7)); } else { var pos = i$7, at = order.length, isRTL = direction == "rtl" ? 1 : 0; for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {} for (var j$2 = pos; j$2 < i$7;) { if (countsAsNum.test(types[j$2])) { if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); at += isRTL; } var nstart = j$2; for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {} order.splice(at, 0, new BidiSpan(2, nstart, j$2)); at += isRTL; pos = j$2; } else { ++j$2; } } if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); } } } if (direction == "ltr") { if (order[0].level == 1 && (m = str.match(/^\s+/))) { order[0].from = m[0].length; order.unshift(new BidiSpan(0, 0, m[0].length)); } if (lst(order).level == 1 && (m = str.match(/\s+$/))) { lst(order).to -= m[0].length; order.push(new BidiSpan(0, len - m[0].length, len)); } } return direction == "rtl" ? order.reverse() : order } })(); // Get the bidi ordering for the given line (and cache it). Returns // false for lines that are fully left-to-right, and an array of // BidiSpan objects otherwise. function getOrder(line, direction) { var order = line.order; if (order == null) { order = line.order = bidiOrdering(line.text, direction); } return order } // EVENT HANDLING // Lightweight event framework. on/off also work on DOM nodes, // registering native DOM handlers. var noHandlers = []; var on = function(emitter, type, f) { if (emitter.addEventListener) { emitter.addEventListener(type, f, false); } else if (emitter.attachEvent) { emitter.attachEvent("on" + type, f); } else { var map = emitter._handlers || (emitter._handlers = {}); map[type] = (map[type] || noHandlers).concat(f); } }; function getHandlers(emitter, type) { return emitter._handlers && emitter._handlers[type] || noHandlers } function off(emitter, type, f) { if (emitter.removeEventListener) { emitter.removeEventListener(type, f, false); } else if (emitter.detachEvent) { emitter.detachEvent("on" + type, f); } else { var map = emitter._handlers, arr = map && map[type]; if (arr) { var index = indexOf(arr, f); if (index > -1) { map[type] = arr.slice(0, index).concat(arr.slice(index + 1)); } } } } function signal(emitter, type /*, values...*/) { var handlers = getHandlers(emitter, type); if (!handlers.length) { return } var args = Array.prototype.slice.call(arguments, 2); for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); } } // The DOM events that CodeMirror handles can be overridden by // registering a (non-DOM) handler on the editor for the event name, // and preventDefault-ing the event in that handler. function signalDOMEvent(cm, e, override) { if (typeof e == "string") { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; } signal(cm, override || e.type, cm, e); return e_defaultPrevented(e) || e.codemirrorIgnore } function signalCursorActivity(cm) { var arr = cm._handlers && cm._handlers.cursorActivity; if (!arr) { return } var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []); for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1) { set.push(arr[i]); } } } function hasHandler(emitter, type) { return getHandlers(emitter, type).length > 0 } // Add on and off methods to a constructor's prototype, to make // registering events on such objects more convenient. function eventMixin(ctor) { ctor.prototype.on = function(type, f) {on(this, type, f);}; ctor.prototype.off = function(type, f) {off(this, type, f);}; } // Due to the fact that we still support jurassic IE versions, some // compatibility wrappers are needed. function e_preventDefault(e) { if (e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; } } function e_stopPropagation(e) { if (e.stopPropagation) { e.stopPropagation(); } else { e.cancelBubble = true; } } function e_defaultPrevented(e) { return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false } function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);} function e_target(e) {return e.target || e.srcElement} function e_button(e) { var b = e.which; if (b == null) { if (e.button & 1) { b = 1; } else if (e.button & 2) { b = 3; } else if (e.button & 4) { b = 2; } } if (mac && e.ctrlKey && b == 1) { b = 3; } return b } // Detect drag-and-drop var dragAndDrop = function() { // There is *some* kind of drag-and-drop support in IE6-8, but I // couldn't get it to work yet. if (ie && ie_version < 9) { return false } var div = elt('div'); return "draggable" in div || "dragDrop" in div }(); var zwspSupported; function zeroWidthElement(measure) { if (zwspSupported == null) { var test = elt("span", "\u200b"); removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")])); if (measure.firstChild.offsetHeight != 0) { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); } } var node = zwspSupported ? elt("span", "\u200b") : elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px"); node.setAttribute("cm-text", ""); return node } // Feature-detect IE's crummy client rect reporting for bidi text var badBidiRects; function hasBadBidiRects(measure) { if (badBidiRects != null) { return badBidiRects } var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA")); var r0 = range(txt, 0, 1).getBoundingClientRect(); var r1 = range(txt, 1, 2).getBoundingClientRect(); removeChildren(measure); if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780) return badBidiRects = (r1.right - r0.right < 3) } // See if "".split is the broken IE version, if so, provide an // alternative way to split lines. var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) { var pos = 0, result = [], l = string.length; while (pos <= l) { var nl = string.indexOf("\n", pos); if (nl == -1) { nl = string.length; } var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl); var rt = line.indexOf("\r"); if (rt != -1) { result.push(line.slice(0, rt)); pos += rt + 1; } else { result.push(line); pos = nl + 1; } } return result } : function (string) { return string.split(/\r\n?|\n/); }; var hasSelection = window.getSelection ? function (te) { try { return te.selectionStart != te.selectionEnd } catch(e) { return false } } : function (te) { var range; try {range = te.ownerDocument.selection.createRange();} catch(e) {} if (!range || range.parentElement() != te) { return false } return range.compareEndPoints("StartToEnd", range) != 0 }; var hasCopyEvent = (function () { var e = elt("div"); if ("oncopy" in e) { return true } e.setAttribute("oncopy", "return;"); return typeof e.oncopy == "function" })(); var badZoomedRects = null; function hasBadZoomedRects(measure) { if (badZoomedRects != null) { return badZoomedRects } var node = removeChildrenAndAdd(measure, elt("span", "x")); var normal = node.getBoundingClientRect(); var fromRange = range(node, 0, 1).getBoundingClientRect(); return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1 } // Known modes, by name and by MIME var modes = {}, mimeModes = {}; // Extra arguments are stored as the mode's dependencies, which is // used by (legacy) mechanisms like loadmode.js to automatically // load a mode. (Preferred mechanism is the require/define calls.) function defineMode(name, mode) { if (arguments.length > 2) { mode.dependencies = Array.prototype.slice.call(arguments, 2); } modes[name] = mode; } function defineMIME(mime, spec) { mimeModes[mime] = spec; } // Given a MIME type, a {name, ...options} config object, or a name // string, return a mode config object. function resolveMode(spec) { if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) { spec = mimeModes[spec]; } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) { var found = mimeModes[spec.name]; if (typeof found == "string") { found = {name: found}; } spec = createObj(found, spec); spec.name = found.name; } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) { return resolveMode("application/xml") } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) { return resolveMode("application/json") } if (typeof spec == "string") { return {name: spec} } else { return spec || {name: "null"} } } // Given a mode spec (anything that resolveMode accepts), find and // initialize an actual mode object. function getMode(options, spec) { spec = resolveMode(spec); var mfactory = modes[spec.name]; if (!mfactory) { return getMode(options, "text/plain") } var modeObj = mfactory(options, spec); if (modeExtensions.hasOwnProperty(spec.name)) { var exts = modeExtensions[spec.name]; for (var prop in exts) { if (!exts.hasOwnProperty(prop)) { continue } if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop]; } modeObj[prop] = exts[prop]; } } modeObj.name = spec.name; if (spec.helperType) { modeObj.helperType = spec.helperType; } if (spec.modeProps) { for (var prop$1 in spec.modeProps) { modeObj[prop$1] = spec.modeProps[prop$1]; } } return modeObj } // This can be used to attach properties to mode objects from // outside the actual mode definition. var modeExtensions = {}; function extendMode(mode, properties) { var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {}); copyObj(properties, exts); } function copyState(mode, state) { if (state === true) { return state } if (mode.copyState) { return mode.copyState(state) } var nstate = {}; for (var n in state) { var val = state[n]; if (val instanceof Array) { val = val.concat([]); } nstate[n] = val; } return nstate } // Given a mode and a state (for that mode), find the inner mode and // state at the position that the state refers to. function innerMode(mode, state) { var info; while (mode.innerMode) { info = mode.innerMode(state); if (!info || info.mode == mode) { break } state = info.state; mode = info.mode; } return info || {mode: mode, state: state} } function startState(mode, a1, a2) { return mode.startState ? mode.startState(a1, a2) : true } // STRING STREAM // Fed to the mode parsers, provides helper functions to make // parsers more succinct. var StringStream = function(string, tabSize, lineOracle) { this.pos = this.start = 0; this.string = string; this.tabSize = tabSize || 8; this.lastColumnPos = this.lastColumnValue = 0; this.lineStart = 0; this.lineOracle = lineOracle; }; StringStream.prototype.eol = function () {return this.pos >= this.string.length}; StringStream.prototype.sol = function () {return this.pos == this.lineStart}; StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined}; StringStream.prototype.next = function () { if (this.pos < this.string.length) { return this.string.charAt(this.pos++) } }; StringStream.prototype.eat = function (match) { var ch = this.string.charAt(this.pos); var ok; if (typeof match == "string") { ok = ch == match; } else { ok = ch && (match.test ? match.test(ch) : match(ch)); } if (ok) {++this.pos; return ch} }; StringStream.prototype.eatWhile = function (match) { var start = this.pos; while (this.eat(match)){} return this.pos > start }; StringStream.prototype.eatSpace = function () { var start = this.pos; while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this.pos; } return this.pos > start }; StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;}; StringStream.prototype.skipTo = function (ch) { var found = this.string.indexOf(ch, this.pos); if (found > -1) {this.pos = found; return true} }; StringStream.prototype.backUp = function (n) {this.pos -= n;}; StringStream.prototype.column = function () { if (this.lastColumnPos < this.start) { this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue); this.lastColumnPos = this.start; } return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0) }; StringStream.prototype.indentation = function () { return countColumn(this.string, null, this.tabSize) - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0) }; StringStream.prototype.match = function (pattern, consume, caseInsensitive) { if (typeof pattern == "string") { var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; }; var substr = this.string.substr(this.pos, pattern.length); if (cased(substr) == cased(pattern)) { if (consume !== false) { this.pos += pattern.length; } return true } } else { var match = this.string.slice(this.pos).match(pattern); if (match && match.index > 0) { return null } if (match && consume !== false) { this.pos += match[0].length; } return match } }; StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)}; StringStream.prototype.hideFirstChars = function (n, inner) { this.lineStart += n; try { return inner() } finally { this.lineStart -= n; } }; StringStream.prototype.lookAhead = function (n) { var oracle = this.lineOracle; return oracle && oracle.lookAhead(n) }; StringStream.prototype.baseToken = function () { var oracle = this.lineOracle; return oracle && oracle.baseToken(this.pos) }; // Find the line object corresponding to the given line number. function getLine(doc, n) { n -= doc.first; if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") } var chunk = doc; while (!chunk.lines) { for (var i = 0;; ++i) { var child = chunk.children[i], sz = child.chunkSize(); if (n < sz) { chunk = child; break } n -= sz; } } return chunk.lines[n] } // Get the part of a document between two positions, as an array of // strings. function getBetween(doc, start, end) { var out = [], n = start.line; doc.iter(start.line, end.line + 1, function (line) { var text = line.text; if (n == end.line) { text = text.slice(0, end.ch); } if (n == start.line) { text = text.slice(start.ch); } out.push(text); ++n; }); return out } // Get the lines between from and to, as array of strings. function getLines(doc, from, to) { var out = []; doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value return out } // Update the height of a line, propagating the height change // upwards to parent nodes. function updateLineHeight(line, height) { var diff = height - line.height; if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } } } // Given a line object, find its line number by walking up through // its parent links. function lineNo(line) { if (line.parent == null) { return null } var cur = line.parent, no = indexOf(cur.lines, line); for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { for (var i = 0;; ++i) { if (chunk.children[i] == cur) { break } no += chunk.children[i].chunkSize(); } } return no + cur.first } // Find the line at the given vertical position, using the height // information in the document tree. function lineAtHeight(chunk, h) { var n = chunk.first; outer: do { for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) { var child = chunk.children[i$1], ch = child.height; if (h < ch) { chunk = child; continue outer } h -= ch; n += child.chunkSize(); } return n } while (!chunk.lines) var i = 0; for (; i < chunk.lines.length; ++i) { var line = chunk.lines[i], lh = line.height; if (h < lh) { break } h -= lh; } return n + i } function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size} function lineNumberFor(options, i) { return String(options.lineNumberFormatter(i + options.firstLineNumber)) } // A Pos instance represents a position within the text. function Pos(line, ch, sticky) { if ( sticky === void 0 ) sticky = null; if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) } this.line = line; this.ch = ch; this.sticky = sticky; } // Compare two positions, return 0 if they are the same, a negative // number when a is less, and a positive number otherwise. function cmp(a, b) { return a.line - b.line || a.ch - b.ch } function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 } function copyPos(x) {return Pos(x.line, x.ch)} function maxPos(a, b) { return cmp(a, b) < 0 ? b : a } function minPos(a, b) { return cmp(a, b) < 0 ? a : b } // Most of the external API clips given positions to make sure they // actually exist within the document. function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))} function clipPos(doc, pos) { if (pos.line < doc.first) { return Pos(doc.first, 0) } var last = doc.first + doc.size - 1; if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) } return clipToLen(pos, getLine(doc, pos.line).text.length) } function clipToLen(pos, linelen) { var ch = pos.ch; if (ch == null || ch > linelen) { return Pos(pos.line, linelen) } else if (ch < 0) { return Pos(pos.line, 0) } else { return pos } } function clipPosArray(doc, array) { var out = []; for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); } return out } var SavedContext = function(state, lookAhead) { this.state = state; this.lookAhead = lookAhead; }; var Context = function(doc, state, line, lookAhead) { this.state = state; this.doc = doc; this.line = line; this.maxLookAhead = lookAhead || 0; this.baseTokens = null; this.baseTokenPos = 1; }; Context.prototype.lookAhead = function (n) { var line = this.doc.getLine(this.line + n); if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; } return line }; Context.prototype.baseToken = function (n) { if (!this.baseTokens) { return null } while (this.baseTokens[this.baseTokenPos] <= n) { this.baseTokenPos += 2; } var type = this.baseTokens[this.baseTokenPos + 1]; return {type: type && type.replace(/( |^)overlay .*/, ""), size: this.baseTokens[this.baseTokenPos] - n} }; Context.prototype.nextLine = function () { this.line++; if (this.maxLookAhead > 0) { this.maxLookAhead--; } }; Context.fromSaved = function (doc, saved, line) { if (saved instanceof SavedContext) { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) } else { return new Context(doc, copyState(doc.mode, saved), line) } }; Context.prototype.save = function (copy) { var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state; return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state }; // Compute a style array (an array starting with a mode generation // -- for invalidation -- followed by pairs of end positions and // style strings), which is used to highlight the tokens on the // line. function highlightLine(cm, line, context, forceToEnd) { // A styles array always starts with a number identifying the // mode/overlays that it is based on (for easy invalidation). var st = [cm.state.modeGen], lineClasses = {}; // Compute the base array of styles runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); }, lineClasses, forceToEnd); var state = context.state; // Run overlays, adjust style array. var loop = function ( o ) { context.baseTokens = st; var overlay = cm.state.overlays[o], i = 1, at = 0; context.state = true; runMode(cm, line.text, overlay.mode, context, function (end, style) { var start = i; // Ensure there's a token end at the current position, and that i points at it while (at < end) { var i_end = st[i]; if (i_end > end) { st.splice(i, 1, end, st[i+1], i_end); } i += 2; at = Math.min(end, i_end); } if (!style) { return } if (overlay.opaque) { st.splice(start, i - start, end, "overlay " + style); i = start + 2; } else { for (; start < i; start += 2) { var cur = st[start+1]; st[start+1] = (cur ? cur + " " : "") + "overlay " + style; } } }, lineClasses); context.state = state; context.baseTokens = null; context.baseTokenPos = 1; }; for (var o = 0; o < cm.state.overlays.length; ++o) loop( o ); return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null} } function getLineStyles(cm, line, updateFrontier) { if (!line.styles || line.styles[0] != cm.state.modeGen) { var context = getContextBefore(cm, lineNo(line)); var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state); var result = highlightLine(cm, line, context); if (resetState) { context.state = resetState; } line.stateAfter = context.save(!resetState); line.styles = result.styles; if (result.classes) { line.styleClasses = result.classes; } else if (line.styleClasses) { line.styleClasses = null; } if (updateFrontier === cm.doc.highlightFrontier) { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); } } return line.styles } function getContextBefore(cm, n, precise) { var doc = cm.doc, display = cm.display; if (!doc.mode.startState) { return new Context(doc, true, n) } var start = findStartLine(cm, n, precise); var saved = start > doc.first && getLine(doc, start - 1).stateAfter; var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start); doc.iter(start, n, function (line) { processLine(cm, line.text, context); var pos = context.line; line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null; context.nextLine(); }); if (precise) { doc.modeFrontier = context.line; } return context } // Lightweight form of highlight -- proceed over this line and // update state, but don't save a style array. Used for lines that // aren't currently visible. function processLine(cm, text, context, startAt) { var mode = cm.doc.mode; var stream = new StringStream(text, cm.options.tabSize, context); stream.start = stream.pos = startAt || 0; if (text == "") { callBlankLine(mode, context.state); } while (!stream.eol()) { readToken(mode, stream, context.state); stream.start = stream.pos; } } function callBlankLine(mode, state) { if (mode.blankLine) { return mode.blankLine(state) } if (!mode.innerMode) { return } var inner = innerMode(mode, state); if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) } } function readToken(mode, stream, state, inner) { for (var i = 0; i < 10; i++) { if (inner) { inner[0] = innerMode(mode, state).mode; } var style = mode.token(stream, state); if (stream.pos > stream.start) { return style } } throw new Error("Mode " + mode.name + " failed to advance stream.") } var Token = function(stream, type, state) { this.start = stream.start; this.end = stream.pos; this.string = stream.current(); this.type = type || null; this.state = state; }; // Utility for getTokenAt and getLineTokens function takeToken(cm, pos, precise, asArray) { var doc = cm.doc, mode = doc.mode, style; pos = clipPos(doc, pos); var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise); var stream = new StringStream(line.text, cm.options.tabSize, context), tokens; if (asArray) { tokens = []; } while ((asArray || stream.pos < pos.ch) && !stream.eol()) { stream.start = stream.pos; style = readToken(mode, stream, context.state); if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); } } return asArray ? tokens : new Token(stream, style, context.state) } function extractLineClasses(type, output) { if (type) { for (;;) { var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/); if (!lineClass) { break } type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length); var prop = lineClass[1] ? "bgClass" : "textClass"; if (output[prop] == null) { output[prop] = lineClass[2]; } else if (!(new RegExp("(?:^|\\s)" + lineClass[2] + "(?:$|\\s)")).test(output[prop])) { output[prop] += " " + lineClass[2]; } } } return type } // Run the given mode's parser over a line, calling f for each token. function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) { var flattenSpans = mode.flattenSpans; if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; } var curStart = 0, curStyle = null; var stream = new StringStream(text, cm.options.tabSize, context), style; var inner = cm.options.addModeClass && [null]; if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); } while (!stream.eol()) { if (stream.pos > cm.options.maxHighlightLength) { flattenSpans = false; if (forceToEnd) { processLine(cm, text, context, stream.pos); } stream.pos = text.length; style = null; } else { style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses); } if (inner) { var mName = inner[0].name; if (mName) { style = "m-" + (style ? mName + " " + style : mName); } } if (!flattenSpans || curStyle != style) { while (curStart < stream.start) { curStart = Math.min(stream.start, curStart + 5000); f(curStart, curStyle); } curStyle = style; } stream.start = stream.pos; } while (curStart < stream.pos) { // Webkit seems to refuse to render text nodes longer than 57444 // characters, and returns inaccurate measurements in nodes // starting around 5000 chars. var pos = Math.min(stream.pos, curStart + 5000); f(pos, curStyle); curStart = pos; } } // Finds the line to start with when starting a parse. Tries to // find a line with a stateAfter, so that it can start with a // valid state. If that fails, it returns the line with the // smallest indentation, which tends to need the least context to // parse correctly. function findStartLine(cm, n, precise) { var minindent, minline, doc = cm.doc; var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100); for (var search = n; search > lim; --search) { if (search <= doc.first) { return doc.first } var line = getLine(doc, search - 1), after = line.stateAfter; if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier)) { return search } var indented = countColumn(line.text, null, cm.options.tabSize); if (minline == null || minindent > indented) { minline = search - 1; minindent = indented; } } return minline } function retreatFrontier(doc, n) { doc.modeFrontier = Math.min(doc.modeFrontier, n); if (doc.highlightFrontier < n - 10) { return } var start = doc.first; for (var line = n - 1; line > start; line--) { var saved = getLine(doc, line).stateAfter; // change is on 3 // state on line 1 looked ahead 2 -- so saw 3 // test 1 + 2 < 3 should cover this if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) { start = line + 1; break } } doc.highlightFrontier = Math.min(doc.highlightFrontier, start); } // Optimize some code when these features are not used. var sawReadOnlySpans = false, sawCollapsedSpans = false; function seeReadOnlySpans() { sawReadOnlySpans = true; } function seeCollapsedSpans() { sawCollapsedSpans = true; } // TEXTMARKER SPANS function MarkedSpan(marker, from, to) { this.marker = marker; this.from = from; this.to = to; } // Search an array of spans for a span matching the given marker. function getMarkedSpanFor(spans, marker) { if (spans) { for (var i = 0; i < spans.length; ++i) { var span = spans[i]; if (span.marker == marker) { return span } } } } // Remove a span from an array, returning undefined if no spans are // left (we don't store arrays for lines without spans). function removeMarkedSpan(spans, span) { var r; for (var i = 0; i < spans.length; ++i) { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } } return r } // Add a span to a line. function addMarkedSpan(line, span, op) { var inThisOp = op && window.WeakSet && (op.markedSpans || (op.markedSpans = new WeakSet)); if (inThisOp && line.markedSpans && inThisOp.has(line.markedSpans)) { line.markedSpans.push(span); } else { line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]; if (inThisOp) { inThisOp.add(line.markedSpans); } } span.marker.attachLine(line); } // Used for the algorithm that adjusts markers for a change in the // document. These functions cut an array of spans at a given // character position, returning an array of remaining chunks (or // undefined if nothing remains). function markedSpansBefore(old, startCh, isInsert) { var nw; if (old) { for (var i = 0; i < old.length; ++i) { var span = old[i], marker = span.marker; var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh); if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) { var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh) ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to)); } } } return nw } function markedSpansAfter(old, endCh, isInsert) { var nw; if (old) { for (var i = 0; i < old.length; ++i) { var span = old[i], marker = span.marker; var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh); if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) { var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh) ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh, span.to == null ? null : span.to - endCh)); } } } return nw } // Given a change object, compute the new set of marker spans that // cover the line in which the change took place. Removes spans // entirely within the change, reconnects spans belonging to the // same marker that appear on both sides of the change, and cuts off // spans partially within the change. Returns an array of span // arrays with one element for each line in (after) the change. function stretchSpansOverChange(doc, change) { if (change.full) { return null } var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans; var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans; if (!oldFirst && !oldLast) { return null } var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0; // Get the spans that 'stick out' on both sides var first = markedSpansBefore(oldFirst, startCh, isInsert); var last = markedSpansAfter(oldLast, endCh, isInsert); // Next, merge those two ends var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0); if (first) { // Fix up .to properties of first for (var i = 0; i < first.length; ++i) { var span = first[i]; if (span.to == null) { var found = getMarkedSpanFor(last, span.marker); if (!found) { span.to = startCh; } else if (sameLine) { span.to = found.to == null ? null : found.to + offset; } } } } if (last) { // Fix up .from in last (or move them into first in case of sameLine) for (var i$1 = 0; i$1 < last.length; ++i$1) { var span$1 = last[i$1]; if (span$1.to != null) { span$1.to += offset; } if (span$1.from == null) { var found$1 = getMarkedSpanFor(first, span$1.marker); if (!found$1) { span$1.from = offset; if (sameLine) { (first || (first = [])).push(span$1); } } } else { span$1.from += offset; if (sameLine) { (first || (first = [])).push(span$1); } } } } // Make sure we didn't create any zero-length spans if (first) { first = clearEmptySpans(first); } if (last && last != first) { last = clearEmptySpans(last); } var newMarkers = [first]; if (!sameLine) { // Fill gap with whole-line-spans var gap = change.text.length - 2, gapMarkers; if (gap > 0 && first) { for (var i$2 = 0; i$2 < first.length; ++i$2) { if (first[i$2].to == null) { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } } for (var i$3 = 0; i$3 < gap; ++i$3) { newMarkers.push(gapMarkers); } newMarkers.push(last); } return newMarkers } // Remove spans that are empty and don't have a clearWhenEmpty // option of false. function clearEmptySpans(spans) { for (var i = 0; i < spans.length; ++i) { var span = spans[i]; if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false) { spans.splice(i--, 1); } } if (!spans.length) { return null } return spans } // Used to 'clip' out readOnly ranges when making a change. function removeReadOnlyRanges(doc, from, to) { var markers = null; doc.iter(from.line, to.line + 1, function (line) { if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) { var mark = line.markedSpans[i].marker; if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) { (markers || (markers = [])).push(mark); } } } }); if (!markers) { return null } var parts = [{from: from, to: to}]; for (var i = 0; i < markers.length; ++i) { var mk = markers[i], m = mk.find(0); for (var j = 0; j < parts.length; ++j) { var p = parts[j]; if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue } var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to); if (dfrom < 0 || !mk.inclusiveLeft && !dfrom) { newParts.push({from: p.from, to: m.from}); } if (dto > 0 || !mk.inclusiveRight && !dto) { newParts.push({from: m.to, to: p.to}); } parts.splice.apply(parts, newParts); j += newParts.length - 3; } } return parts } // Connect or disconnect spans from a line. function detachMarkedSpans(line) { var spans = line.markedSpans; if (!spans) { return } for (var i = 0; i < spans.length; ++i) { spans[i].marker.detachLine(line); } line.markedSpans = null; } function attachMarkedSpans(line, spans) { if (!spans) { return } for (var i = 0; i < spans.length; ++i) { spans[i].marker.attachLine(line); } line.markedSpans = spans; } // Helpers used when computing which overlapping collapsed span // counts as the larger one. function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 } function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 } // Returns a number indicating which of two overlapping collapsed // spans is larger (and thus includes the other). Falls back to // comparing ids when the spans cover exactly the same range. function compareCollapsedMarkers(a, b) { var lenDiff = a.lines.length - b.lines.length; if (lenDiff != 0) { return lenDiff } var aPos = a.find(), bPos = b.find(); var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b); if (fromCmp) { return -fromCmp } var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b); if (toCmp) { return toCmp } return b.id - a.id } // Find out whether a line ends or starts in a collapsed span. If // so, return the marker for that span. function collapsedSpanAtSide(line, start) { var sps = sawCollapsedSpans && line.markedSpans, found; if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) { sp = sps[i]; if (sp.marker.collapsed && (start ? sp.from : sp.to) == null && (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { found = sp.marker; } } } return found } function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) } function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) } function collapsedSpanAround(line, ch) { var sps = sawCollapsedSpans && line.markedSpans, found; if (sps) { for (var i = 0; i < sps.length; ++i) { var sp = sps[i]; if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) && (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { found = sp.marker; } } } return found } // Test whether there exists a collapsed span that partially // overlaps (covers the start or end, but not both) of a new span. // Such overlap is not allowed. function conflictingCollapsedRange(doc, lineNo, from, to, marker) { var line = getLine(doc, lineNo); var sps = sawCollapsedSpans && line.markedSpans; if (sps) { for (var i = 0; i < sps.length; ++i) { var sp = sps[i]; if (!sp.marker.collapsed) { continue } var found = sp.marker.find(0); var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker); var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker); if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue } if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) || fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0)) { return true } } } } // A visual line is a line as drawn on the screen. Folding, for // example, can cause multiple logical lines to appear on the same // visual line. This finds the start of the visual line that the // given line is part of (usually that is the line itself). function visualLine(line) { var merged; while (merged = collapsedSpanAtStart(line)) { line = merged.find(-1, true).line; } return line } function visualLineEnd(line) { var merged; while (merged = collapsedSpanAtEnd(line)) { line = merged.find(1, true).line; } return line } // Returns an array of logical lines that continue the visual line // started by the argument, or undefined if there are no such lines. function visualLineContinued(line) { var merged, lines; while (merged = collapsedSpanAtEnd(line)) { line = merged.find(1, true).line ;(lines || (lines = [])).push(line); } return lines } // Get the line number of the start of the visual line that the // given line number is part of. function visualLineNo(doc, lineN) { var line = getLine(doc, lineN), vis = visualLine(line); if (line == vis) { return lineN } return lineNo(vis) } // Get the line number of the start of the next visual line after // the given line. function visualLineEndNo(doc, lineN) { if (lineN > doc.lastLine()) { return lineN } var line = getLine(doc, lineN), merged; if (!lineIsHidden(doc, line)) { return lineN } while (merged = collapsedSpanAtEnd(line)) { line = merged.find(1, true).line; } return lineNo(line) + 1 } // Compute whether a line is hidden. Lines count as hidden when they // are part of a visual line that starts with another line, or when // they are entirely covered by collapsed, non-widget span. function lineIsHidden(doc, line) { var sps = sawCollapsedSpans && line.markedSpans; if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) { sp = sps[i]; if (!sp.marker.collapsed) { continue } if (sp.from == null) { return true } if (sp.marker.widgetNode) { continue } if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp)) { return true } } } } function lineIsHiddenInner(doc, line, span) { if (span.to == null) { var end = span.marker.find(1, true); return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker)) } if (span.marker.inclusiveRight && span.to == line.text.length) { return true } for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) { sp = line.markedSpans[i]; if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to && (sp.to == null || sp.to != span.from) && (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && lineIsHiddenInner(doc, line, sp)) { return true } } } // Find the height above the given line. function heightAtLine(lineObj) { lineObj = visualLine(lineObj); var h = 0, chunk = lineObj.parent; for (var i = 0; i < chunk.lines.length; ++i) { var line = chunk.lines[i]; if (line == lineObj) { break } else { h += line.height; } } for (var p = chunk.parent; p; chunk = p, p = chunk.parent) { for (var i$1 = 0; i$1 < p.children.length; ++i$1) { var cur = p.children[i$1]; if (cur == chunk) { break } else { h += cur.height; } } } return h } // Compute the character length of a line, taking into account // collapsed ranges (see markText) that might hide parts, and join // other lines onto it. function lineLength(line) { if (line.height == 0) { return 0 } var len = line.text.length, merged, cur = line; while (merged = collapsedSpanAtStart(cur)) { var found = merged.find(0, true); cur = found.from.line; len += found.from.ch - found.to.ch; } cur = line; while (merged = collapsedSpanAtEnd(cur)) { var found$1 = merged.find(0, true); len -= cur.text.length - found$1.from.ch; cur = found$1.to.line; len += cur.text.length - found$1.to.ch; } return len } // Find the longest line in the document. function findMaxLine(cm) { var d = cm.display, doc = cm.doc; d.maxLine = getLine(doc, doc.first); d.maxLineLength = lineLength(d.maxLine); d.maxLineChanged = true; doc.iter(function (line) { var len = lineLength(line); if (len > d.maxLineLength) { d.maxLineLength = len; d.maxLine = line; } }); } // LINE DATA STRUCTURE // Line objects. These hold state related to a line, including // highlighting info (the styles array). var Line = function(text, markedSpans, estimateHeight) { this.text = text; attachMarkedSpans(this, markedSpans); this.height = estimateHeight ? estimateHeight(this) : 1; }; Line.prototype.lineNo = function () { return lineNo(this) }; eventMixin(Line); // Change the content (text, markers) of a line. Automatically // invalidates cached information and tries to re-estimate the // line's height. function updateLine(line, text, markedSpans, estimateHeight) { line.text = text; if (line.stateAfter) { line.stateAfter = null; } if (line.styles) { line.styles = null; } if (line.order != null) { line.order = null; } detachMarkedSpans(line); attachMarkedSpans(line, markedSpans); var estHeight = estimateHeight ? estimateHeight(line) : 1; if (estHeight != line.height) { updateLineHeight(line, estHeight); } } // Detach a line from the document tree and its markers. function cleanUpLine(line) { line.parent = null; detachMarkedSpans(line); } // Convert a style as returned by a mode (either null, or a string // containing one or more styles) to a CSS style. This is cached, // and also looks for line-wide styles. var styleToClassCache = {}, styleToClassCacheWithMode = {}; function interpretTokenStyle(style, options) { if (!style || /^\s*$/.test(style)) { return null } var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache; return cache[style] || (cache[style] = style.replace(/\S+/g, "cm-$&")) } // Render the DOM representation of the text of a line. Also builds // up a 'line map', which points at the DOM nodes that represent // specific stretches of text, and is used by the measuring code. // The returned object contains the DOM node, this map, and // information about line-wide styles that were set by the mode. function buildLineContent(cm, lineView) { // The padding-right forces the element to have a 'border', which // is needed on Webkit to be able to get line-level bounding // rectangles for it (in measureChar). var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null); var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content, col: 0, pos: 0, cm: cm, trailingSpace: false, splitSpaces: cm.getOption("lineWrapping")}; lineView.measure = {}; // Iterate over the logical lines that make up this visual line. for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) { var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0); builder.pos = 0; builder.addToken = buildToken; // Optionally wire in some hacks into the token-rendering // algorithm, to deal with browser quirks. if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction))) { builder.addToken = buildTokenBadBidi(builder.addToken, order); } builder.map = []; var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line); insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate)); if (line.styleClasses) { if (line.styleClasses.bgClass) { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); } if (line.styleClasses.textClass) { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); } } // Ensure at least a single node is present, for measuring. if (builder.map.length == 0) { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); } // Store the map and a cache object for the current logical line if (i == 0) { lineView.measure.map = builder.map; lineView.measure.cache = {}; } else { (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map) ;(lineView.measure.caches || (lineView.measure.caches = [])).push({}); } } // See issue #2901 if (webkit) { var last = builder.content.lastChild; if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab"))) { builder.content.className = "cm-tab-wrap-hack"; } } signal(cm, "renderLine", cm, lineView.line, builder.pre); if (builder.pre.className) { builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); } return builder } function defaultSpecialCharPlaceholder(ch) { var token = elt("span", "\u2022", "cm-invalidchar"); token.title = "\\u" + ch.charCodeAt(0).toString(16); token.setAttribute("aria-label", token.title); return token } // Build up the DOM representation for a single token, and add it to // the line map. Takes care to render special characters separately. function buildToken(builder, text, style, startStyle, endStyle, css, attributes) { if (!text) { return } var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text; var special = builder.cm.state.specialChars, mustWrap = false; var content; if (!special.test(text)) { builder.col += text.length; content = document.createTextNode(displayText); builder.map.push(builder.pos, builder.pos + text.length, content); if (ie && ie_version < 9) { mustWrap = true; } builder.pos += text.length; } else { content = document.createDocumentFragment(); var pos = 0; while (true) { special.lastIndex = pos; var m = special.exec(text); var skipped = m ? m.index - pos : text.length - pos; if (skipped) { var txt = document.createTextNode(displayText.slice(pos, pos + skipped)); if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])); } else { content.appendChild(txt); } builder.map.push(builder.pos, builder.pos + skipped, txt); builder.col += skipped; builder.pos += skipped; } if (!m) { break } pos += skipped + 1; var txt$1 = (void 0); if (m[0] == "\t") { var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize; txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")); txt$1.setAttribute("role", "presentation"); txt$1.setAttribute("cm-text", "\t"); builder.col += tabWidth; } else if (m[0] == "\r" || m[0] == "\n") { txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar")); txt$1.setAttribute("cm-text", m[0]); builder.col += 1; } else { txt$1 = builder.cm.options.specialCharPlaceholder(m[0]); txt$1.setAttribute("cm-text", m[0]); if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])); } else { content.appendChild(txt$1); } builder.col += 1; } builder.map.push(builder.pos, builder.pos + 1, txt$1); builder.pos++; } } builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32; if (style || startStyle || endStyle || mustWrap || css || attributes) { var fullStyle = style || ""; if (startStyle) { fullStyle += startStyle; } if (endStyle) { fullStyle += endStyle; } var token = elt("span", [content], fullStyle, css); if (attributes) { for (var attr in attributes) { if (attributes.hasOwnProperty(attr) && attr != "style" && attr != "class") { token.setAttribute(attr, attributes[attr]); } } } return builder.content.appendChild(token) } builder.content.appendChild(content); } // Change some spaces to NBSP to prevent the browser from collapsing // trailing spaces at the end of a line when rendering text (issue #1362). function splitSpaces(text, trailingBefore) { if (text.length > 1 && !/ /.test(text)) { return text } var spaceBefore = trailingBefore, result = ""; for (var i = 0; i < text.length; i++) { var ch = text.charAt(i); if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32)) { ch = "\u00a0"; } result += ch; spaceBefore = ch == " "; } return result } // Work around nonsense dimensions being reported for stretches of // right-to-left text. function buildTokenBadBidi(inner, order) { return function (builder, text, style, startStyle, endStyle, css, attributes) { style = style ? style + " cm-force-border" : "cm-force-border"; var start = builder.pos, end = start + text.length; for (;;) { // Find the part that overlaps with the start of this text var part = (void 0); for (var i = 0; i < order.length; i++) { part = order[i]; if (part.to > start && part.from <= start) { break } } if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, css, attributes) } inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes); startStyle = null; text = text.slice(part.to - start); start = part.to; } } } function buildCollapsedSpan(builder, size, marker, ignoreWidget) { var widget = !ignoreWidget && marker.widgetNode; if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); } if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) { if (!widget) { widget = builder.content.appendChild(document.createElement("span")); } widget.setAttribute("cm-marker", marker.id); } if (widget) { builder.cm.display.input.setUneditable(widget); builder.content.appendChild(widget); } builder.pos += size; builder.trailingSpace = false; } // Outputs a number of spans to make up a line, taking highlighting // and marked text into account. function insertLineContent(line, builder, styles) { var spans = line.markedSpans, allText = line.text, at = 0; if (!spans) { for (var i$1 = 1; i$1 < styles.length; i$1+=2) { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); } return } var len = allText.length, pos = 0, i = 1, text = "", style, css; var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed, attributes; for (;;) { if (nextChange == pos) { // Update current marker set spanStyle = spanEndStyle = spanStartStyle = css = ""; attributes = null; collapsed = null; nextChange = Infinity; var foundBookmarks = [], endStyles = (void 0); for (var j = 0; j < spans.length; ++j) { var sp = spans[j], m = sp.marker; if (m.type == "bookmark" && sp.from == pos && m.widgetNode) { foundBookmarks.push(m); } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) { if (sp.to != null && sp.to != pos && nextChange > sp.to) { nextChange = sp.to; spanEndStyle = ""; } if (m.className) { spanStyle += " " + m.className; } if (m.css) { css = (css ? css + ";" : "") + m.css; } if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle; } if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); } // support for the old title property // https://github.com/codemirror/CodeMirror/pull/5673 if (m.title) { (attributes || (attributes = {})).title = m.title; } if (m.attributes) { for (var attr in m.attributes) { (attributes || (attributes = {}))[attr] = m.attributes[attr]; } } if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0)) { collapsed = sp; } } else if (sp.from > pos && nextChange > sp.from) { nextChange = sp.from; } } if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2) { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1]; } } } if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2) { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } } if (collapsed && (collapsed.from || 0) == pos) { buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos, collapsed.marker, collapsed.from == null); if (collapsed.to == null) { return } if (collapsed.to == pos) { collapsed = false; } } } if (pos >= len) { break } var upto = Math.min(len, nextChange); while (true) { if (text) { var end = pos + text.length; if (!collapsed) { var tokenText = end > upto ? text.slice(0, upto - pos) : text; builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle, spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", css, attributes); } if (end >= upto) {text = text.slice(upto - pos); pos = upto; break} pos = end; spanStartStyle = ""; } text = allText.slice(at, at = styles[i++]); style = interpretTokenStyle(styles[i++], builder.cm.options); } } } // These objects are used to represent the visible (currently drawn) // part of the document. A LineView may correspond to multiple // logical lines, if those are connected by collapsed ranges. function LineView(doc, line, lineN) { // The starting line this.line = line; // Continuing lines, if any this.rest = visualLineContinued(line); // Number of logical lines in this visual line this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1; this.node = this.text = null; this.hidden = lineIsHidden(doc, line); } // Create a range of LineView objects for the given lines. function buildViewArray(cm, from, to) { var array = [], nextPos; for (var pos = from; pos < to; pos = nextPos) { var view = new LineView(cm.doc, getLine(cm.doc, pos), pos); nextPos = pos + view.size; array.push(view); } return array } var operationGroup = null; function pushOperation(op) { if (operationGroup) { operationGroup.ops.push(op); } else { op.ownsGroup = operationGroup = { ops: [op], delayedCallbacks: [] }; } } function fireCallbacksForOps(group) { // Calls delayed callbacks and cursorActivity handlers until no // new ones appear var callbacks = group.delayedCallbacks, i = 0; do { for (; i < callbacks.length; i++) { callbacks[i].call(null); } for (var j = 0; j < group.ops.length; j++) { var op = group.ops[j]; if (op.cursorActivityHandlers) { while (op.cursorActivityCalled < op.cursorActivityHandlers.length) { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } } } } while (i < callbacks.length) } function finishOperation(op, endCb) { var group = op.ownsGroup; if (!group) { return } try { fireCallbacksForOps(group); } finally { operationGroup = null; endCb(group); } } var orphanDelayedCallbacks = null; // Often, we want to signal events at a point where we are in the // middle of some work, but don't want the handler to start calling // other methods on the editor, which might be in an inconsistent // state or simply not expect any other events to happen. // signalLater looks whether there are any handlers, and schedules // them to be executed when the last operation ends, or, if no // operation is active, when a timeout fires. function signalLater(emitter, type /*, values...*/) { var arr = getHandlers(emitter, type); if (!arr.length) { return } var args = Array.prototype.slice.call(arguments, 2), list; if (operationGroup) { list = operationGroup.delayedCallbacks; } else if (orphanDelayedCallbacks) { list = orphanDelayedCallbacks; } else { list = orphanDelayedCallbacks = []; setTimeout(fireOrphanDelayed, 0); } var loop = function ( i ) { list.push(function () { return arr[i].apply(null, args); }); }; for (var i = 0; i < arr.length; ++i) loop( i ); } function fireOrphanDelayed() { var delayed = orphanDelayedCallbacks; orphanDelayedCallbacks = null; for (var i = 0; i < delayed.length; ++i) { delayed[i](); } } // When an aspect of a line changes, a string is added to // lineView.changes. This updates the relevant part of the line's // DOM structure. function updateLineForChanges(cm, lineView, lineN, dims) { for (var j = 0; j < lineView.changes.length; j++) { var type = lineView.changes[j]; if (type == "text") { updateLineText(cm, lineView); } else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims); } else if (type == "class") { updateLineClasses(cm, lineView); } else if (type == "widget") { updateLineWidgets(cm, lineView, dims); } } lineView.changes = null; } // Lines with gutter elements, widgets or a background class need to // be wrapped, and have the extra elements added to the wrapper div function ensureLineWrapped(lineView) { if (lineView.node == lineView.text) { lineView.node = elt("div", null, null, "position: relative"); if (lineView.text.parentNode) { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); } lineView.node.appendChild(lineView.text); if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; } } return lineView.node } function updateLineBackground(cm, lineView) { var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass; if (cls) { cls += " CodeMirror-linebackground"; } if (lineView.background) { if (cls) { lineView.background.className = cls; } else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; } } else if (cls) { var wrap = ensureLineWrapped(lineView); lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild); cm.display.input.setUneditable(lineView.background); } } // Wrapper around buildLineContent which will reuse the structure // in display.externalMeasured when possible. function getLineContent(cm, lineView) { var ext = cm.display.externalMeasured; if (ext && ext.line == lineView.line) { cm.display.externalMeasured = null; lineView.measure = ext.measure; return ext.built } return buildLineContent(cm, lineView) } // Redraw the line's text. Interacts with the background and text // classes because the mode may output tokens that influence these // classes. function updateLineText(cm, lineView) { var cls = lineView.text.className; var built = getLineContent(cm, lineView); if (lineView.text == lineView.node) { lineView.node = built.pre; } lineView.text.parentNode.replaceChild(built.pre, lineView.text); lineView.text = built.pre; if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) { lineView.bgClass = built.bgClass; lineView.textClass = built.textClass; updateLineClasses(cm, lineView); } else if (cls) { lineView.text.className = cls; } } function updateLineClasses(cm, lineView) { updateLineBackground(cm, lineView); if (lineView.line.wrapClass) { ensureLineWrapped(lineView).className = lineView.line.wrapClass; } else if (lineView.node != lineView.text) { lineView.node.className = ""; } var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass; lineView.text.className = textClass || ""; } function updateLineGutter(cm, lineView, lineN, dims) { if (lineView.gutter) { lineView.node.removeChild(lineView.gutter); lineView.gutter = null; } if (lineView.gutterBackground) { lineView.node.removeChild(lineView.gutterBackground); lineView.gutterBackground = null; } if (lineView.line.gutterClass) { var wrap = ensureLineWrapped(lineView); lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass, ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px")); cm.display.input.setUneditable(lineView.gutterBackground); wrap.insertBefore(lineView.gutterBackground, lineView.text); } var markers = lineView.line.gutterMarkers; if (cm.options.lineNumbers || markers) { var wrap$1 = ensureLineWrapped(lineView); var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px")); gutterWrap.setAttribute("aria-hidden", "true"); cm.display.input.setUneditable(gutterWrap); wrap$1.insertBefore(gutterWrap, lineView.text); if (lineView.line.gutterClass) { gutterWrap.className += " " + lineView.line.gutterClass; } if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) { lineView.lineNumber = gutterWrap.appendChild( elt("div", lineNumberFor(cm.options, lineN), "CodeMirror-linenumber CodeMirror-gutter-elt", ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))); } if (markers) { for (var k = 0; k < cm.display.gutterSpecs.length; ++k) { var id = cm.display.gutterSpecs[k].className, found = markers.hasOwnProperty(id) && markers[id]; if (found) { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))); } } } } } function updateLineWidgets(cm, lineView, dims) { if (lineView.alignable) { lineView.alignable = null; } var isWidget = classTest("CodeMirror-linewidget"); for (var node = lineView.node.firstChild, next = (void 0); node; node = next) { next = node.nextSibling; if (isWidget.test(node.className)) { lineView.node.removeChild(node); } } insertLineWidgets(cm, lineView, dims); } // Build a line's DOM representation from scratch function buildLineElement(cm, lineView, lineN, dims) { var built = getLineContent(cm, lineView); lineView.text = lineView.node = built.pre; if (built.bgClass) { lineView.bgClass = built.bgClass; } if (built.textClass) { lineView.textClass = built.textClass; } updateLineClasses(cm, lineView); updateLineGutter(cm, lineView, lineN, dims); insertLineWidgets(cm, lineView, dims); return lineView.node } // A lineView may contain multiple logical lines (when merged by // collapsed spans). The widgets for all of them need to be drawn. function insertLineWidgets(cm, lineView, dims) { insertLineWidgetsFor(cm, lineView.line, lineView, dims, true); if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++) { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } } } function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) { if (!line.widgets) { return } var wrap = ensureLineWrapped(lineView); for (var i = 0, ws = line.widgets; i < ws.length; ++i) { var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget" + (widget.className ? " " + widget.className : "")); if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true"); } positionLineWidget(widget, node, lineView, dims); cm.display.input.setUneditable(node); if (allowAbove && widget.above) { wrap.insertBefore(node, lineView.gutter || lineView.text); } else { wrap.appendChild(node); } signalLater(widget, "redraw"); } } function positionLineWidget(widget, node, lineView, dims) { if (widget.noHScroll) { (lineView.alignable || (lineView.alignable = [])).push(node); var width = dims.wrapperWidth; node.style.left = dims.fixedPos + "px"; if (!widget.coverGutter) { width -= dims.gutterTotalWidth; node.style.paddingLeft = dims.gutterTotalWidth + "px"; } node.style.width = width + "px"; } if (widget.coverGutter) { node.style.zIndex = 5; node.style.position = "relative"; if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px"; } } } function widgetHeight(widget) { if (widget.height != null) { return widget.height } var cm = widget.doc.cm; if (!cm) { return 0 } if (!contains(document.body, widget.node)) { var parentStyle = "position: relative;"; if (widget.coverGutter) { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; } if (widget.noHScroll) { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; } removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle)); } return widget.height = widget.node.parentNode.offsetHeight } // Return true when the given mouse event happened in a widget function eventInWidget(display, e) { for (var n = e_target(e); n != display.wrapper; n = n.parentNode) { if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") || (n.parentNode == display.sizer && n != display.mover)) { return true } } } // POSITION MEASUREMENT function paddingTop(display) {return display.lineSpace.offsetTop} function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight} function paddingH(display) { if (display.cachedPaddingH) { return display.cachedPaddingH } var e = removeChildrenAndAdd(display.measure, elt("pre", "x", "CodeMirror-line-like")); var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle; var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)}; if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; } return data } function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth } function displayWidth(cm) { return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth } function displayHeight(cm) { return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight } // Ensure the lineView.wrapping.heights array is populated. This is // an array of bottom offsets for the lines that make up a drawn // line. When lineWrapping is on, there might be more than one // height. function ensureLineHeights(cm, lineView, rect) { var wrapping = cm.options.lineWrapping; var curWidth = wrapping && displayWidth(cm); if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) { var heights = lineView.measure.heights = []; if (wrapping) { lineView.measure.width = curWidth; var rects = lineView.text.firstChild.getClientRects(); for (var i = 0; i < rects.length - 1; i++) { var cur = rects[i], next = rects[i + 1]; if (Math.abs(cur.bottom - next.bottom) > 2) { heights.push((cur.bottom + next.top) / 2 - rect.top); } } } heights.push(rect.bottom - rect.top); } } // Find a line map (mapping character offsets to text nodes) and a // measurement cache for the given line number. (A line view might // contain multiple lines when collapsed ranges are present.) function mapFromLineView(lineView, line, lineN) { if (lineView.line == line) { return {map: lineView.measure.map, cache: lineView.measure.cache} } if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++) { if (lineView.rest[i] == line) { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } } for (var i$1 = 0; i$1 < lineView.rest.length; i$1++) { if (lineNo(lineView.rest[i$1]) > lineN) { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } } } } // Render a line into the hidden node display.externalMeasured. Used // when measurement is needed for a line that's not in the viewport. function updateExternalMeasurement(cm, line) { line = visualLine(line); var lineN = lineNo(line); var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN); view.lineN = lineN; var built = view.built = buildLineContent(cm, view); view.text = built.pre; removeChildrenAndAdd(cm.display.lineMeasure, built.pre); return view } // Get a {top, bottom, left, right} box (in line-local coordinates) // for a given character. function measureChar(cm, line, ch, bias) { return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias) } // Find a line view that corresponds to the given line number. function findViewForLine(cm, lineN) { if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo) { return cm.display.view[findViewIndex(cm, lineN)] } var ext = cm.display.externalMeasured; if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size) { return ext } } // Measurement can be split in two steps, the set-up work that // applies to the whole line, and the measurement of the actual // character. Functions like coordsChar, that need to do a lot of // measurements in a row, can thus ensure that the set-up work is // only done once. function prepareMeasureForLine(cm, line) { var lineN = lineNo(line); var view = findViewForLine(cm, lineN); if (view && !view.text) { view = null; } else if (view && view.changes) { updateLineForChanges(cm, view, lineN, getDimensions(cm)); cm.curOp.forceUpdate = true; } if (!view) { view = updateExternalMeasurement(cm, line); } var info = mapFromLineView(view, line, lineN); return { line: line, view: view, rect: null, map: info.map, cache: info.cache, before: info.before, hasHeights: false } } // Given a prepared measurement object, measures the position of an // actual character (or fetches it from the cache). function measureCharPrepared(cm, prepared, ch, bias, varHeight) { if (prepared.before) { ch = -1; } var key = ch + (bias || ""), found; if (prepared.cache.hasOwnProperty(key)) { found = prepared.cache[key]; } else { if (!prepared.rect) { prepared.rect = prepared.view.text.getBoundingClientRect(); } if (!prepared.hasHeights) { ensureLineHeights(cm, prepared.view, prepared.rect); prepared.hasHeights = true; } found = measureCharInner(cm, prepared, ch, bias); if (!found.bogus) { prepared.cache[key] = found; } } return {left: found.left, right: found.right, top: varHeight ? found.rtop : found.top, bottom: varHeight ? found.rbottom : found.bottom} } var nullRect = {left: 0, right: 0, top: 0, bottom: 0}; function nodeAndOffsetInLineMap(map, ch, bias) { var node, start, end, collapse, mStart, mEnd; // First, search the line map for the text node corresponding to, // or closest to, the target character. for (var i = 0; i < map.length; i += 3) { mStart = map[i]; mEnd = map[i + 1]; if (ch < mStart) { start = 0; end = 1; collapse = "left"; } else if (ch < mEnd) { start = ch - mStart; end = start + 1; } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) { end = mEnd - mStart; start = end - 1; if (ch >= mEnd) { collapse = "right"; } } if (start != null) { node = map[i + 2]; if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right")) { collapse = bias; } if (bias == "left" && start == 0) { while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) { node = map[(i -= 3) + 2]; collapse = "left"; } } if (bias == "right" && start == mEnd - mStart) { while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) { node = map[(i += 3) + 2]; collapse = "right"; } } break } } return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd} } function getUsefulRect(rects, bias) { var rect = nullRect; if (bias == "left") { for (var i = 0; i < rects.length; i++) { if ((rect = rects[i]).left != rect.right) { break } } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) { if ((rect = rects[i$1]).left != rect.right) { break } } } return rect } function measureCharInner(cm, prepared, ch, bias) { var place = nodeAndOffsetInLineMap(prepared.map, ch, bias); var node = place.node, start = place.start, end = place.end, collapse = place.collapse; var rect; if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates. for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; } while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; } if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) { rect = node.parentNode.getBoundingClientRect(); } else { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); } if (rect.left || rect.right || start == 0) { break } end = start; start = start - 1; collapse = "right"; } if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); } } else { // If it is a widget, simply get the box for the whole widget. if (start > 0) { collapse = bias = "right"; } var rects; if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1) { rect = rects[bias == "right" ? rects.length - 1 : 0]; } else { rect = node.getBoundingClientRect(); } } if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) { var rSpan = node.parentNode.getClientRects()[0]; if (rSpan) { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; } else { rect = nullRect; } } var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top; var mid = (rtop + rbot) / 2; var heights = prepared.view.measure.heights; var i = 0; for (; i < heights.length - 1; i++) { if (mid < heights[i]) { break } } var top = i ? heights[i - 1] : 0, bot = heights[i]; var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left, right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left, top: top, bottom: bot}; if (!rect.left && !rect.right) { result.bogus = true; } if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; } return result } // Work around problem with bounding client rects on ranges being // returned incorrectly when zoomed on IE10 and below. function maybeUpdateRectForZooming(measure, rect) { if (!window.screen || screen.logicalXDPI == null || screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure)) { return rect } var scaleX = screen.logicalXDPI / screen.deviceXDPI; var scaleY = screen.logicalYDPI / screen.deviceYDPI; return {left: rect.left * scaleX, right: rect.right * scaleX, top: rect.top * scaleY, bottom: rect.bottom * scaleY} } function clearLineMeasurementCacheFor(lineView) { if (lineView.measure) { lineView.measure.cache = {}; lineView.measure.heights = null; if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++) { lineView.measure.caches[i] = {}; } } } } function clearLineMeasurementCache(cm) { cm.display.externalMeasure = null; removeChildren(cm.display.lineMeasure); for (var i = 0; i < cm.display.view.length; i++) { clearLineMeasurementCacheFor(cm.display.view[i]); } } function clearCaches(cm) { clearLineMeasurementCache(cm); cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null; if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; } cm.display.lineNumChars = null; } function pageScrollX(doc) { // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206 // which causes page_Offset and bounding client rects to use // different reference viewports and invalidate our calculations. if (chrome && android) { return -(doc.body.getBoundingClientRect().left - parseInt(getComputedStyle(doc.body).marginLeft)) } return doc.defaultView.pageXOffset || (doc.documentElement || doc.body).scrollLeft } function pageScrollY(doc) { if (chrome && android) { return -(doc.body.getBoundingClientRect().top - parseInt(getComputedStyle(doc.body).marginTop)) } return doc.defaultView.pageYOffset || (doc.documentElement || doc.body).scrollTop } function widgetTopHeight(lineObj) { var ref = visualLine(lineObj); var widgets = ref.widgets; var height = 0; if (widgets) { for (var i = 0; i < widgets.length; ++i) { if (widgets[i].above) { height += widgetHeight(widgets[i]); } } } return height } // Converts a {top, bottom, left, right} box from line-local // coordinates into another coordinate system. Context may be one of // "line", "div" (display.lineDiv), "local"./null (editor), "window", // or "page". function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) { if (!includeWidgets) { var height = widgetTopHeight(lineObj); rect.top += height; rect.bottom += height; } if (context == "line") { return rect } if (!context) { context = "local"; } var yOff = heightAtLine(lineObj); if (context == "local") { yOff += paddingTop(cm.display); } else { yOff -= cm.display.viewOffset; } if (context == "page" || context == "window") { var lOff = cm.display.lineSpace.getBoundingClientRect(); yOff += lOff.top + (context == "window" ? 0 : pageScrollY(doc(cm))); var xOff = lOff.left + (context == "window" ? 0 : pageScrollX(doc(cm))); rect.left += xOff; rect.right += xOff; } rect.top += yOff; rect.bottom += yOff; return rect } // Coverts a box from "div" coords to another coordinate system. // Context may be "window", "page", "div", or "local"./null. function fromCoordSystem(cm, coords, context) { if (context == "div") { return coords } var left = coords.left, top = coords.top; // First move into "page" coordinate system if (context == "page") { left -= pageScrollX(doc(cm)); top -= pageScrollY(doc(cm)); } else if (context == "local" || !context) { var localBox = cm.display.sizer.getBoundingClientRect(); left += localBox.left; top += localBox.top; } var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect(); return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top} } function charCoords(cm, pos, context, lineObj, bias) { if (!lineObj) { lineObj = getLine(cm.doc, pos.line); } return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context) } // Returns a box for a given cursor position, which may have an // 'other' property containing the position of the secondary cursor // on a bidi boundary. // A cursor Pos(line, char, "before") is on the same visual line as `char - 1` // and after `char - 1` in writing order of `char - 1` // A cursor Pos(line, char, "after") is on the same visual line as `char` // and before `char` in writing order of `char` // Examples (upper-case letters are RTL, lower-case are LTR): // Pos(0, 1, ...) // before after // ab a|b a|b // aB a|B aB| // Ab |Ab A|b // AB B|A B|A // Every position after the last character on a line is considered to stick // to the last character on the line. function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) { lineObj = lineObj || getLine(cm.doc, pos.line); if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); } function get(ch, right) { var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight); if (right) { m.left = m.right; } else { m.right = m.left; } return intoCoordSystem(cm, lineObj, m, context) } var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky; if (ch >= lineObj.text.length) { ch = lineObj.text.length; sticky = "before"; } else if (ch <= 0) { ch = 0; sticky = "after"; } if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") } function getBidi(ch, partPos, invert) { var part = order[partPos], right = part.level == 1; return get(invert ? ch - 1 : ch, right != invert) } var partPos = getBidiPartAt(order, ch, sticky); var other = bidiOther; var val = getBidi(ch, partPos, sticky == "before"); if (other != null) { val.other = getBidi(ch, other, sticky != "before"); } return val } // Used to cheaply estimate the coordinates for a position. Used for // intermediate scroll updates. function estimateCoords(cm, pos) { var left = 0; pos = clipPos(cm.doc, pos); if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; } var lineObj = getLine(cm.doc, pos.line); var top = heightAtLine(lineObj) + paddingTop(cm.display); return {left: left, right: left, top: top, bottom: top + lineObj.height} } // Positions returned by coordsChar contain some extra information. // xRel is the relative x position of the input coordinates compared // to the found position (so xRel > 0 means the coordinates are to // the right of the character position, for example). When outside // is true, that means the coordinates lie outside the line's // vertical range. function PosWithInfo(line, ch, sticky, outside, xRel) { var pos = Pos(line, ch, sticky); pos.xRel = xRel; if (outside) { pos.outside = outside; } return pos } // Compute the character position closest to the given coordinates. // Input must be lineSpace-local ("div" coordinate system). function coordsChar(cm, x, y) { var doc = cm.doc; y += cm.display.viewOffset; if (y < 0) { return PosWithInfo(doc.first, 0, null, -1, -1) } var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1; if (lineN > last) { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1) } if (x < 0) { x = 0; } var lineObj = getLine(doc, lineN); for (;;) { var found = coordsCharInner(cm, lineObj, lineN, x, y); var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0)); if (!collapsed) { return found } var rangeEnd = collapsed.find(1); if (rangeEnd.line == lineN) { return rangeEnd } lineObj = getLine(doc, lineN = rangeEnd.line); } } function wrappedLineExtent(cm, lineObj, preparedMeasure, y) { y -= widgetTopHeight(lineObj); var end = lineObj.text.length; var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0); end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end); return {begin: begin, end: end} } function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) { if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); } var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top; return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop) } // Returns true if the given side of a box is after the given // coordinates, in top-to-bottom, left-to-right order. function boxIsAfter(box, x, y, left) { return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x } function coordsCharInner(cm, lineObj, lineNo, x, y) { // Move y into line-local coordinate space y -= heightAtLine(lineObj); var preparedMeasure = prepareMeasureForLine(cm, lineObj); // When directly calling `measureCharPrepared`, we have to adjust // for the widgets at this line. var widgetHeight = widgetTopHeight(lineObj); var begin = 0, end = lineObj.text.length, ltr = true; var order = getOrder(lineObj, cm.doc.direction); // If the line isn't plain left-to-right text, first figure out // which bidi section the coordinates fall into. if (order) { var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart) (cm, lineObj, lineNo, preparedMeasure, order, x, y); ltr = part.level != 1; // The awkward -1 offsets are needed because findFirst (called // on these below) will treat its first bound as inclusive, // second as exclusive, but we want to actually address the // characters in the part's range begin = ltr ? part.from : part.to - 1; end = ltr ? part.to : part.from - 1; } // A binary search to find the first character whose bounding box // starts after the coordinates. If we run across any whose box wrap // the coordinates, store that. var chAround = null, boxAround = null; var ch = findFirst(function (ch) { var box = measureCharPrepared(cm, preparedMeasure, ch); box.top += widgetHeight; box.bottom += widgetHeight; if (!boxIsAfter(box, x, y, false)) { return false } if (box.top <= y && box.left <= x) { chAround = ch; boxAround = box; } return true }, begin, end); var baseX, sticky, outside = false; // If a box around the coordinates was found, use that if (boxAround) { // Distinguish coordinates nearer to the left or right side of the box var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr; ch = chAround + (atStart ? 0 : 1); sticky = atStart ? "after" : "before"; baseX = atLeft ? boxAround.left : boxAround.right; } else { // (Adjust for extended bound, if necessary.) if (!ltr && (ch == end || ch == begin)) { ch++; } // To determine which side to associate with, get the box to the // left of the character and compare it's vertical position to the // coordinates sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" : (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight <= y) == ltr ? "after" : "before"; // Now get accurate coordinates for this place, in order to get a // base X position var coords = cursorCoords(cm, Pos(lineNo, ch, sticky), "line", lineObj, preparedMeasure); baseX = coords.left; outside = y < coords.top ? -1 : y >= coords.bottom ? 1 : 0; } ch = skipExtendingChars(lineObj.text, ch, 1); return PosWithInfo(lineNo, ch, sticky, outside, x - baseX) } function coordsBidiPart(cm, lineObj, lineNo, preparedMeasure, order, x, y) { // Bidi parts are sorted left-to-right, and in a non-line-wrapping // situation, we can take this ordering to correspond to the visual // ordering. This finds the first part whose end is after the given // coordinates. var index = findFirst(function (i) { var part = order[i], ltr = part.level != 1; return boxIsAfter(cursorCoords(cm, Pos(lineNo, ltr ? part.to : part.from, ltr ? "before" : "after"), "line", lineObj, preparedMeasure), x, y, true) }, 0, order.length - 1); var part = order[index]; // If this isn't the first part, the part's start is also after // the coordinates, and the coordinates aren't on the same line as // that start, move one part back. if (index > 0) { var ltr = part.level != 1; var start = cursorCoords(cm, Pos(lineNo, ltr ? part.from : part.to, ltr ? "after" : "before"), "line", lineObj, preparedMeasure); if (boxIsAfter(start, x, y, true) && start.top > y) { part = order[index - 1]; } } return part } function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) { // In a wrapped line, rtl text on wrapping boundaries can do things // that don't correspond to the ordering in our `order` array at // all, so a binary search doesn't work, and we want to return a // part that only spans one line so that the binary search in // coordsCharInner is safe. As such, we first find the extent of the // wrapped line, and then do a flat search in which we discard any // spans that aren't on the line. var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y); var begin = ref.begin; var end = ref.end; if (/\s/.test(lineObj.text.charAt(end - 1))) { end--; } var part = null, closestDist = null; for (var i = 0; i < order.length; i++) { var p = order[i]; if (p.from >= end || p.to <= begin) { continue } var ltr = p.level != 1; var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right; // Weigh against spans ending before this, so that they are only // picked if nothing ends after var dist = endX < x ? x - endX + 1e9 : endX - x; if (!part || closestDist > dist) { part = p; closestDist = dist; } } if (!part) { part = order[order.length - 1]; } // Clip the part to the wrapped line. if (part.from < begin) { part = {from: begin, to: part.to, level: part.level}; } if (part.to > end) { part = {from: part.from, to: end, level: part.level}; } return part } var measureText; // Compute the default text height. function textHeight(display) { if (display.cachedTextHeight != null) { return display.cachedTextHeight } if (measureText == null) { measureText = elt("pre", null, "CodeMirror-line-like"); // Measure a bunch of lines, for browsers that compute // fractional heights. for (var i = 0; i < 49; ++i) { measureText.appendChild(document.createTextNode("x")); measureText.appendChild(elt("br")); } measureText.appendChild(document.createTextNode("x")); } removeChildrenAndAdd(display.measure, measureText); var height = measureText.offsetHeight / 50; if (height > 3) { display.cachedTextHeight = height; } removeChildren(display.measure); return height || 1 } // Compute the default character width. function charWidth(display) { if (display.cachedCharWidth != null) { return display.cachedCharWidth } var anchor = elt("span", "xxxxxxxxxx"); var pre = elt("pre", [anchor], "CodeMirror-line-like"); removeChildrenAndAdd(display.measure, pre); var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10; if (width > 2) { display.cachedCharWidth = width; } return width || 10 } // Do a bulk-read of the DOM positions and sizes needed to draw the // view, so that we don't interleave reading and writing to the DOM. function getDimensions(cm) { var d = cm.display, left = {}, width = {}; var gutterLeft = d.gutters.clientLeft; for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) { var id = cm.display.gutterSpecs[i].className; left[id] = n.offsetLeft + n.clientLeft + gutterLeft; width[id] = n.clientWidth; } return {fixedPos: compensateForHScroll(d), gutterTotalWidth: d.gutters.offsetWidth, gutterLeft: left, gutterWidth: width, wrapperWidth: d.wrapper.clientWidth} } // Computes display.scroller.scrollLeft + display.gutters.offsetWidth, // but using getBoundingClientRect to get a sub-pixel-accurate // result. function compensateForHScroll(display) { return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left } // Returns a function that estimates the height of a line, to use as // first approximation until the line becomes visible (and is thus // properly measurable). function estimateHeight(cm) { var th = textHeight(cm.display), wrapping = cm.options.lineWrapping; var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3); return function (line) { if (lineIsHidden(cm.doc, line)) { return 0 } var widgetsHeight = 0; if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) { if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; } } } if (wrapping) { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th } else { return widgetsHeight + th } } } function estimateLineHeights(cm) { var doc = cm.doc, est = estimateHeight(cm); doc.iter(function (line) { var estHeight = est(line); if (estHeight != line.height) { updateLineHeight(line, estHeight); } }); } // Given a mouse event, find the corresponding position. If liberal // is false, it checks whether a gutter or scrollbar was clicked, // and returns null if it was. forRect is used by rectangular // selections, and tries to estimate a character position even for // coordinates beyond the right of the text. function posFromMouse(cm, e, liberal, forRect) { var display = cm.display; if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null } var x, y, space = display.lineSpace.getBoundingClientRect(); // Fails unpredictably on IE[67] when mouse is dragged around quickly. try { x = e.clientX - space.left; y = e.clientY - space.top; } catch (e$1) { return null } var coords = coordsChar(cm, x, y), line; if (forRect && coords.xRel > 0 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) { var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length; coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff)); } return coords } // Find the view element corresponding to a given line. Return null // when the line isn't visible. function findViewIndex(cm, n) { if (n >= cm.display.viewTo) { return null } n -= cm.display.viewFrom; if (n < 0) { return null } var view = cm.display.view; for (var i = 0; i < view.length; i++) { n -= view[i].size; if (n < 0) { return i } } } // Updates the display.view data structure for a given change to the // document. From and to are in pre-change coordinates. Lendiff is // the amount of lines added or subtracted by the change. This is // used for changes that span multiple lines, or change the way // lines are divided into visual lines. regLineChange (below) // registers single-line changes. function regChange(cm, from, to, lendiff) { if (from == null) { from = cm.doc.first; } if (to == null) { to = cm.doc.first + cm.doc.size; } if (!lendiff) { lendiff = 0; } var display = cm.display; if (lendiff && to < display.viewTo && (display.updateLineNumbers == null || display.updateLineNumbers > from)) { display.updateLineNumbers = from; } cm.curOp.viewChanged = true; if (from >= display.viewTo) { // Change after if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo) { resetView(cm); } } else if (to <= display.viewFrom) { // Change before if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) { resetView(cm); } else { display.viewFrom += lendiff; display.viewTo += lendiff; } } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap resetView(cm); } else if (from <= display.viewFrom) { // Top overlap var cut = viewCuttingPoint(cm, to, to + lendiff, 1); if (cut) { display.view = display.view.slice(cut.index); display.viewFrom = cut.lineN; display.viewTo += lendiff; } else { resetView(cm); } } else if (to >= display.viewTo) { // Bottom overlap var cut$1 = viewCuttingPoint(cm, from, from, -1); if (cut$1) { display.view = display.view.slice(0, cut$1.index); display.viewTo = cut$1.lineN; } else { resetView(cm); } } else { // Gap in the middle var cutTop = viewCuttingPoint(cm, from, from, -1); var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1); if (cutTop && cutBot) { display.view = display.view.slice(0, cutTop.index) .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN)) .concat(display.view.slice(cutBot.index)); display.viewTo += lendiff; } else { resetView(cm); } } var ext = display.externalMeasured; if (ext) { if (to < ext.lineN) { ext.lineN += lendiff; } else if (from < ext.lineN + ext.size) { display.externalMeasured = null; } } } // Register a change to a single line. Type must be one of "text", // "gutter", "class", "widget" function regLineChange(cm, line, type) { cm.curOp.viewChanged = true; var display = cm.display, ext = cm.display.externalMeasured; if (ext && line >= ext.lineN && line < ext.lineN + ext.size) { display.externalMeasured = null; } if (line < display.viewFrom || line >= display.viewTo) { return } var lineView = display.view[findViewIndex(cm, line)]; if (lineView.node == null) { return } var arr = lineView.changes || (lineView.changes = []); if (indexOf(arr, type) == -1) { arr.push(type); } } // Clear the view. function resetView(cm) { cm.display.viewFrom = cm.display.viewTo = cm.doc.first; cm.display.view = []; cm.display.viewOffset = 0; } function viewCuttingPoint(cm, oldN, newN, dir) { var index = findViewIndex(cm, oldN), diff, view = cm.display.view; if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size) { return {index: index, lineN: newN} } var n = cm.display.viewFrom; for (var i = 0; i < index; i++) { n += view[i].size; } if (n != oldN) { if (dir > 0) { if (index == view.length - 1) { return null } diff = (n + view[index].size) - oldN; index++; } else { diff = n - oldN; } oldN += diff; newN += diff; } while (visualLineNo(cm.doc, newN) != newN) { if (index == (dir < 0 ? 0 : view.length - 1)) { return null } newN += dir * view[index - (dir < 0 ? 1 : 0)].size; index += dir; } return {index: index, lineN: newN} } // Force the view to cover a given range, adding empty view element // or clipping off existing ones as needed. function adjustView(cm, from, to) { var display = cm.display, view = display.view; if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) { display.view = buildViewArray(cm, from, to); display.viewFrom = from; } else { if (display.viewFrom > from) { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); } else if (display.viewFrom < from) { display.view = display.view.slice(findViewIndex(cm, from)); } display.viewFrom = from; if (display.viewTo < to) { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); } else if (display.viewTo > to) { display.view = display.view.slice(0, findViewIndex(cm, to)); } } display.viewTo = to; } // Count the number of lines in the view whose DOM representation is // out of date (or nonexistent). function countDirtyView(cm) { var view = cm.display.view, dirty = 0; for (var i = 0; i < view.length; i++) { var lineView = view[i]; if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; } } return dirty } function updateSelection(cm) { cm.display.input.showSelection(cm.display.input.prepareSelection()); } function prepareSelection(cm, primary) { if ( primary === void 0 ) primary = true; var doc = cm.doc, result = {}; var curFragment = result.cursors = document.createDocumentFragment(); var selFragment = result.selection = document.createDocumentFragment(); var customCursor = cm.options.$customCursor; if (customCursor) { primary = true; } for (var i = 0; i < doc.sel.ranges.length; i++) { if (!primary && i == doc.sel.primIndex) { continue } var range = doc.sel.ranges[i]; if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) { continue } var collapsed = range.empty(); if (customCursor) { var head = customCursor(cm, range); if (head) { drawSelectionCursor(cm, head, curFragment); } } else if (collapsed || cm.options.showCursorWhenSelecting) { drawSelectionCursor(cm, range.head, curFragment); } if (!collapsed) { drawSelectionRange(cm, range, selFragment); } } return result } // Draws a cursor for the given range function drawSelectionCursor(cm, head, output) { var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine); var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor")); cursor.style.left = pos.left + "px"; cursor.style.top = pos.top + "px"; cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"; if (/\bcm-fat-cursor\b/.test(cm.getWrapperElement().className)) { var charPos = charCoords(cm, head, "div", null, null); var width = charPos.right - charPos.left; cursor.style.width = (width > 0 ? width : cm.defaultCharWidth()) + "px"; } if (pos.other) { // Secondary cursor, shown when on a 'jump' in bi-directional text var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor")); otherCursor.style.display = ""; otherCursor.style.left = pos.other.left + "px"; otherCursor.style.top = pos.other.top + "px"; otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"; } } function cmpCoords(a, b) { return a.top - b.top || a.left - b.left } // Draws the given range as a highlighted selection function drawSelectionRange(cm, range, output) { var display = cm.display, doc = cm.doc; var fragment = document.createDocumentFragment(); var padding = paddingH(cm.display), leftSide = padding.left; var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right; var docLTR = doc.direction == "ltr"; function add(left, top, width, bottom) { if (top < 0) { top = 0; } top = Math.round(top); bottom = Math.round(bottom); fragment.appendChild(elt("div", null, "CodeMirror-selected", ("position: absolute; left: " + left + "px;\n top: " + top + "px; width: " + (width == null ? rightSide - left : width) + "px;\n height: " + (bottom - top) + "px"))); } function drawForLine(line, fromArg, toArg) { var lineObj = getLine(doc, line); var lineLen = lineObj.text.length; var start, end; function coords(ch, bias) { return charCoords(cm, Pos(line, ch), "div", lineObj, bias) } function wrapX(pos, dir, side) { var extent = wrappedLineExtentChar(cm, lineObj, null, pos); var prop = (dir == "ltr") == (side == "after") ? "left" : "right"; var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1); return coords(ch, prop)[prop] } var order = getOrder(lineObj, doc.direction); iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) { var ltr = dir == "ltr"; var fromPos = coords(from, ltr ? "left" : "right"); var toPos = coords(to - 1, ltr ? "right" : "left"); var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen; var first = i == 0, last = !order || i == order.length - 1; if (toPos.top - fromPos.top <= 3) { // Single line var openLeft = (docLTR ? openStart : openEnd) && first; var openRight = (docLTR ? openEnd : openStart) && last; var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left; var right = openRight ? rightSide : (ltr ? toPos : fromPos).right; add(left, fromPos.top, right - left, fromPos.bottom); } else { // Multiple lines var topLeft, topRight, botLeft, botRight; if (ltr) { topLeft = docLTR && openStart && first ? leftSide : fromPos.left; topRight = docLTR ? rightSide : wrapX(from, dir, "before"); botLeft = docLTR ? leftSide : wrapX(to, dir, "after"); botRight = docLTR && openEnd && last ? rightSide : toPos.right; } else { topLeft = !docLTR ? leftSide : wrapX(from, dir, "before"); topRight = !docLTR && openStart && first ? rightSide : fromPos.right; botLeft = !docLTR && openEnd && last ? leftSide : toPos.left; botRight = !docLTR ? rightSide : wrapX(to, dir, "after"); } add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom); if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); } add(botLeft, toPos.top, botRight - botLeft, toPos.bottom); } if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; } if (cmpCoords(toPos, start) < 0) { start = toPos; } if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; } if (cmpCoords(toPos, end) < 0) { end = toPos; } }); return {start: start, end: end} } var sFrom = range.from(), sTo = range.to(); if (sFrom.line == sTo.line) { drawForLine(sFrom.line, sFrom.ch, sTo.ch); } else { var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line); var singleVLine = visualLine(fromLine) == visualLine(toLine); var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end; var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start; if (singleVLine) { if (leftEnd.top < rightStart.top - 2) { add(leftEnd.right, leftEnd.top, null, leftEnd.bottom); add(leftSide, rightStart.top, rightStart.left, rightStart.bottom); } else { add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom); } } if (leftEnd.bottom < rightStart.top) { add(leftSide, leftEnd.bottom, null, rightStart.top); } } output.appendChild(fragment); } // Cursor-blinking function restartBlink(cm) { if (!cm.state.focused) { return } var display = cm.display; clearInterval(display.blinker); var on = true; display.cursorDiv.style.visibility = ""; if (cm.options.cursorBlinkRate > 0) { display.blinker = setInterval(function () { if (!cm.hasFocus()) { onBlur(cm); } display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; }, cm.options.cursorBlinkRate); } else if (cm.options.cursorBlinkRate < 0) { display.cursorDiv.style.visibility = "hidden"; } } function ensureFocus(cm) { if (!cm.hasFocus()) { cm.display.input.focus(); if (!cm.state.focused) { onFocus(cm); } } } function delayBlurEvent(cm) { cm.state.delayingBlurEvent = true; setTimeout(function () { if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false; if (cm.state.focused) { onBlur(cm); } } }, 100); } function onFocus(cm, e) { if (cm.state.delayingBlurEvent && !cm.state.draggingText) { cm.state.delayingBlurEvent = false; } if (cm.options.readOnly == "nocursor") { return } if (!cm.state.focused) { signal(cm, "focus", cm, e); cm.state.focused = true; addClass(cm.display.wrapper, "CodeMirror-focused"); // This test prevents this from firing when a context // menu is closed (since the input reset would kill the // select-all detection hack) if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) { cm.display.input.reset(); if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730 } cm.display.input.receivedFocus(); } restartBlink(cm); } function onBlur(cm, e) { if (cm.state.delayingBlurEvent) { return } if (cm.state.focused) { signal(cm, "blur", cm, e); cm.state.focused = false; rmClass(cm.display.wrapper, "CodeMirror-focused"); } clearInterval(cm.display.blinker); setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150); } // Read the actual heights of the rendered lines, and update their // stored heights to match. function updateHeightsInViewport(cm) { var display = cm.display; var prevBottom = display.lineDiv.offsetTop; var viewTop = Math.max(0, display.scroller.getBoundingClientRect().top); var oldHeight = display.lineDiv.getBoundingClientRect().top; var mustScroll = 0; for (var i = 0; i < display.view.length; i++) { var cur = display.view[i], wrapping = cm.options.lineWrapping; var height = (void 0), width = 0; if (cur.hidden) { continue } oldHeight += cur.line.height; if (ie && ie_version < 8) { var bot = cur.node.offsetTop + cur.node.offsetHeight; height = bot - prevBottom; prevBottom = bot; } else { var box = cur.node.getBoundingClientRect(); height = box.bottom - box.top; // Check that lines don't extend past the right of the current // editor width if (!wrapping && cur.text.firstChild) { width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1; } } var diff = cur.line.height - height; if (diff > .005 || diff < -.005) { if (oldHeight < viewTop) { mustScroll -= diff; } updateLineHeight(cur.line, height); updateWidgetHeight(cur.line); if (cur.rest) { for (var j = 0; j < cur.rest.length; j++) { updateWidgetHeight(cur.rest[j]); } } } if (width > cm.display.sizerWidth) { var chWidth = Math.ceil(width / charWidth(cm.display)); if (chWidth > cm.display.maxLineLength) { cm.display.maxLineLength = chWidth; cm.display.maxLine = cur.line; cm.display.maxLineChanged = true; } } } if (Math.abs(mustScroll) > 2) { display.scroller.scrollTop += mustScroll; } } // Read and store the height of line widgets associated with the // given line. function updateWidgetHeight(line) { if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) { var w = line.widgets[i], parent = w.node.parentNode; if (parent) { w.height = parent.offsetHeight; } } } } // Compute the lines that are visible in a given viewport (defaults // the the current scroll position). viewport may contain top, // height, and ensure (see op.scrollToPos) properties. function visibleLines(display, doc, viewport) { var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop; top = Math.floor(top - paddingTop(display)); var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight; var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom); // Ensure is a {from: {line, ch}, to: {line, ch}} object, and // forces those lines into the viewport (if possible). if (viewport && viewport.ensure) { var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line; if (ensureFrom < from) { from = ensureFrom; to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight); } else if (Math.min(ensureTo, doc.lastLine()) >= to) { from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight); to = ensureTo; } } return {from: from, to: Math.max(to, from + 1)} } // SCROLLING THINGS INTO VIEW // If an editor sits on the top or bottom of the window, partially // scrolled out of view, this ensures that the cursor is visible. function maybeScrollWindow(cm, rect) { if (signalDOMEvent(cm, "scrollCursorIntoView")) { return } var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null; var doc = display.wrapper.ownerDocument; if (rect.top + box.top < 0) { doScroll = true; } else if (rect.bottom + box.top > (doc.defaultView.innerHeight || doc.documentElement.clientHeight)) { doScroll = false; } if (doScroll != null && !phantom) { var scrollNode = elt("div", "\u200b", null, ("position: absolute;\n top: " + (rect.top - display.viewOffset - paddingTop(cm.display)) + "px;\n height: " + (rect.bottom - rect.top + scrollGap(cm) + display.barHeight) + "px;\n left: " + (rect.left) + "px; width: " + (Math.max(2, rect.right - rect.left)) + "px;")); cm.display.lineSpace.appendChild(scrollNode); scrollNode.scrollIntoView(doScroll); cm.display.lineSpace.removeChild(scrollNode); } } // Scroll a given position into view (immediately), verifying that // it actually became visible (as line heights are accurately // measured, the position of something may 'drift' during drawing). function scrollPosIntoView(cm, pos, end, margin) { if (margin == null) { margin = 0; } var rect; if (!cm.options.lineWrapping && pos == end) { // Set pos and end to the cursor positions around the character pos sticks to // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch // If pos == Pos(_, 0, "before"), pos and end are unchanged end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos; pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos; } for (var limit = 0; limit < 5; limit++) { var changed = false; var coords = cursorCoords(cm, pos); var endCoords = !end || end == pos ? coords : cursorCoords(cm, end); rect = {left: Math.min(coords.left, endCoords.left), top: Math.min(coords.top, endCoords.top) - margin, right: Math.max(coords.left, endCoords.left), bottom: Math.max(coords.bottom, endCoords.bottom) + margin}; var scrollPos = calculateScrollPos(cm, rect); var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft; if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; } } if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; } } if (!changed) { break } } return rect } // Scroll a given set of coordinates into view (immediately). function scrollIntoView(cm, rect) { var scrollPos = calculateScrollPos(cm, rect); if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); } if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); } } // Calculate a new scroll position needed to scroll the given // rectangle into view. Returns an object with scrollTop and // scrollLeft properties. When these are undefined, the // vertical/horizontal position does not need to be adjusted. function calculateScrollPos(cm, rect) { var display = cm.display, snapMargin = textHeight(cm.display); if (rect.top < 0) { rect.top = 0; } var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop; var screen = displayHeight(cm), result = {}; if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; } var docBottom = cm.doc.height + paddingVert(display); var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin; if (rect.top < screentop) { result.scrollTop = atTop ? 0 : rect.top; } else if (rect.bottom > screentop + screen) { var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen); if (newTop != screentop) { result.scrollTop = newTop; } } var gutterSpace = cm.options.fixedGutter ? 0 : display.gutters.offsetWidth; var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft - gutterSpace; var screenw = displayWidth(cm) - display.gutters.offsetWidth; var tooWide = rect.right - rect.left > screenw; if (tooWide) { rect.right = rect.left + screenw; } if (rect.left < 10) { result.scrollLeft = 0; } else if (rect.left < screenleft) { result.scrollLeft = Math.max(0, rect.left + gutterSpace - (tooWide ? 0 : 10)); } else if (rect.right > screenw + screenleft - 3) { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; } return result } // Store a relative adjustment to the scroll position in the current // operation (to be applied when the operation finishes). function addToScrollTop(cm, top) { if (top == null) { return } resolveScrollToPos(cm); cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top; } // Make sure that at the end of the operation the current cursor is // shown. function ensureCursorVisible(cm) { resolveScrollToPos(cm); var cur = cm.getCursor(); cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin}; } function scrollToCoords(cm, x, y) { if (x != null || y != null) { resolveScrollToPos(cm); } if (x != null) { cm.curOp.scrollLeft = x; } if (y != null) { cm.curOp.scrollTop = y; } } function scrollToRange(cm, range) { resolveScrollToPos(cm); cm.curOp.scrollToPos = range; } // When an operation has its scrollToPos property set, and another // scroll action is applied before the end of the operation, this // 'simulates' scrolling that position into view in a cheap way, so // that the effect of intermediate scroll commands is not ignored. function resolveScrollToPos(cm) { var range = cm.curOp.scrollToPos; if (range) { cm.curOp.scrollToPos = null; var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to); scrollToCoordsRange(cm, from, to, range.margin); } } function scrollToCoordsRange(cm, from, to, margin) { var sPos = calculateScrollPos(cm, { left: Math.min(from.left, to.left), top: Math.min(from.top, to.top) - margin, right: Math.max(from.right, to.right), bottom: Math.max(from.bottom, to.bottom) + margin }); scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop); } // Sync the scrollable area and scrollbars, ensure the viewport // covers the visible area. function updateScrollTop(cm, val) { if (Math.abs(cm.doc.scrollTop - val) < 2) { return } if (!gecko) { updateDisplaySimple(cm, {top: val}); } setScrollTop(cm, val, true); if (gecko) { updateDisplaySimple(cm); } startWorker(cm, 100); } function setScrollTop(cm, val, forceScroll) { val = Math.max(0, Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val)); if (cm.display.scroller.scrollTop == val && !forceScroll) { return } cm.doc.scrollTop = val; cm.display.scrollbars.setScrollTop(val); if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; } } // Sync scroller and scrollbar, ensure the gutter elements are // aligned. function setScrollLeft(cm, val, isScroller, forceScroll) { val = Math.max(0, Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth)); if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return } cm.doc.scrollLeft = val; alignHorizontally(cm); if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; } cm.display.scrollbars.setScrollLeft(val); } // SCROLLBARS // Prepare DOM reads needed to update the scrollbars. Done in one // shot to minimize update/measure roundtrips. function measureForScrollbars(cm) { var d = cm.display, gutterW = d.gutters.offsetWidth; var docH = Math.round(cm.doc.height + paddingVert(cm.display)); return { clientHeight: d.scroller.clientHeight, viewHeight: d.wrapper.clientHeight, scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth, viewWidth: d.wrapper.clientWidth, barLeft: cm.options.fixedGutter ? gutterW : 0, docHeight: docH, scrollHeight: docH + scrollGap(cm) + d.barHeight, nativeBarWidth: d.nativeBarWidth, gutterWidth: gutterW } } var NativeScrollbars = function(place, scroll, cm) { this.cm = cm; var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar"); var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar"); vert.tabIndex = horiz.tabIndex = -1; place(vert); place(horiz); on(vert, "scroll", function () { if (vert.clientHeight) { scroll(vert.scrollTop, "vertical"); } }); on(horiz, "scroll", function () { if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal"); } }); this.checkedZeroWidth = false; // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8). if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; } }; NativeScrollbars.prototype.update = function (measure) { var needsH = measure.scrollWidth > measure.clientWidth + 1; var needsV = measure.scrollHeight > measure.clientHeight + 1; var sWidth = measure.nativeBarWidth; if (needsV) { this.vert.style.display = "block"; this.vert.style.bottom = needsH ? sWidth + "px" : "0"; var totalHeight = measure.viewHeight - (needsH ? sWidth : 0); // A bug in IE8 can cause this value to be negative, so guard it. this.vert.firstChild.style.height = Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px"; } else { this.vert.scrollTop = 0; this.vert.style.display = ""; this.vert.firstChild.style.height = "0"; } if (needsH) { this.horiz.style.display = "block"; this.horiz.style.right = needsV ? sWidth + "px" : "0"; this.horiz.style.left = measure.barLeft + "px"; var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0); this.horiz.firstChild.style.width = Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px"; } else { this.horiz.style.display = ""; this.horiz.firstChild.style.width = "0"; } if (!this.checkedZeroWidth && measure.clientHeight > 0) { if (sWidth == 0) { this.zeroWidthHack(); } this.checkedZeroWidth = true; } return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0} }; NativeScrollbars.prototype.setScrollLeft = function (pos) { if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; } if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); } }; NativeScrollbars.prototype.setScrollTop = function (pos) { if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; } if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); } }; NativeScrollbars.prototype.zeroWidthHack = function () { var w = mac && !mac_geMountainLion ? "12px" : "18px"; this.horiz.style.height = this.vert.style.width = w; this.horiz.style.visibility = this.vert.style.visibility = "hidden"; this.disableHoriz = new Delayed; this.disableVert = new Delayed; }; NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) { bar.style.visibility = ""; function maybeDisable() { // To find out whether the scrollbar is still visible, we // check whether the element under the pixel in the bottom // right corner of the scrollbar box is the scrollbar box // itself (when the bar is still visible) or its filler child // (when the bar is hidden). If it is still visible, we keep // it enabled, if it's hidden, we disable pointer events. var box = bar.getBoundingClientRect(); var elt = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2) : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1); if (elt != bar) { bar.style.visibility = "hidden"; } else { delay.set(1000, maybeDisable); } } delay.set(1000, maybeDisable); }; NativeScrollbars.prototype.clear = function () { var parent = this.horiz.parentNode; parent.removeChild(this.horiz); parent.removeChild(this.vert); }; var NullScrollbars = function () {}; NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} }; NullScrollbars.prototype.setScrollLeft = function () {}; NullScrollbars.prototype.setScrollTop = function () {}; NullScrollbars.prototype.clear = function () {}; function updateScrollbars(cm, measure) { if (!measure) { measure = measureForScrollbars(cm); } var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight; updateScrollbarsInner(cm, measure); for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) { if (startWidth != cm.display.barWidth && cm.options.lineWrapping) { updateHeightsInViewport(cm); } updateScrollbarsInner(cm, measureForScrollbars(cm)); startWidth = cm.display.barWidth; startHeight = cm.display.barHeight; } } // Re-synchronize the fake scrollbars with the actual size of the // content. function updateScrollbarsInner(cm, measure) { var d = cm.display; var sizes = d.scrollbars.update(measure); d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px"; d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px"; d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent"; if (sizes.right && sizes.bottom) { d.scrollbarFiller.style.display = "block"; d.scrollbarFiller.style.height = sizes.bottom + "px"; d.scrollbarFiller.style.width = sizes.right + "px"; } else { d.scrollbarFiller.style.display = ""; } if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) { d.gutterFiller.style.display = "block"; d.gutterFiller.style.height = sizes.bottom + "px"; d.gutterFiller.style.width = measure.gutterWidth + "px"; } else { d.gutterFiller.style.display = ""; } } var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars}; function initScrollbars(cm) { if (cm.display.scrollbars) { cm.display.scrollbars.clear(); if (cm.display.scrollbars.addClass) { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); } } cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) { cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller); // Prevent clicks in the scrollbars from killing focus on(node, "mousedown", function () { if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); } }); node.setAttribute("cm-not-content", "true"); }, function (pos, axis) { if (axis == "horizontal") { setScrollLeft(cm, pos); } else { updateScrollTop(cm, pos); } }, cm); if (cm.display.scrollbars.addClass) { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); } } // Operations are used to wrap a series of changes to the editor // state in such a way that each change won't have to update the // cursor and display (which would be awkward, slow, and // error-prone). Instead, display updates are batched and then all // combined and executed at once. var nextOpId = 0; // Start a new operation. function startOperation(cm) { cm.curOp = { cm: cm, viewChanged: false, // Flag that indicates that lines might need to be redrawn startHeight: cm.doc.height, // Used to detect need to update scrollbar forceUpdate: false, // Used to force a redraw updateInput: 0, // Whether to reset the input textarea typing: false, // Whether this reset should be careful to leave existing text (for compositing) changeObjs: null, // Accumulated changes, for firing change events cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already selectionChanged: false, // Whether the selection needs to be redrawn updateMaxLine: false, // Set when the widest line needs to be determined anew scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet scrollToPos: null, // Used to scroll to a specific position focus: false, id: ++nextOpId, // Unique ID markArrays: null // Used by addMarkedSpan }; pushOperation(cm.curOp); } // Finish an operation, updating the display and signalling delayed events function endOperation(cm) { var op = cm.curOp; if (op) { finishOperation(op, function (group) { for (var i = 0; i < group.ops.length; i++) { group.ops[i].cm.curOp = null; } endOperations(group); }); } } // The DOM updates done when an operation finishes are batched so // that the minimum number of relayouts are required. function endOperations(group) { var ops = group.ops; for (var i = 0; i < ops.length; i++) // Read DOM { endOperation_R1(ops[i]); } for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe) { endOperation_W1(ops[i$1]); } for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM { endOperation_R2(ops[i$2]); } for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe) { endOperation_W2(ops[i$3]); } for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM { endOperation_finish(ops[i$4]); } } function endOperation_R1(op) { var cm = op.cm, display = cm.display; maybeClipScrollbars(cm); if (op.updateMaxLine) { findMaxLine(cm); } op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null || op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom || op.scrollToPos.to.line >= display.viewTo) || display.maxLineChanged && cm.options.lineWrapping; op.update = op.mustUpdate && new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate); } function endOperation_W1(op) { op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update); } function endOperation_R2(op) { var cm = op.cm, display = cm.display; if (op.updatedDisplay) { updateHeightsInViewport(cm); } op.barMeasure = measureForScrollbars(cm); // If the max line changed since it was last measured, measure it, // and ensure the document's width matches it. // updateDisplay_W2 will use these properties to do the actual resizing if (display.maxLineChanged && !cm.options.lineWrapping) { op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3; cm.display.sizerWidth = op.adjustWidthTo; op.barMeasure.scrollWidth = Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth); op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm)); } if (op.updatedDisplay || op.selectionChanged) { op.preparedSelection = display.input.prepareSelection(); } } function endOperation_W2(op) { var cm = op.cm; if (op.adjustWidthTo != null) { cm.display.sizer.style.minWidth = op.adjustWidthTo + "px"; if (op.maxScrollLeft < cm.doc.scrollLeft) { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); } cm.display.maxLineChanged = false; } var takeFocus = op.focus && op.focus == activeElt(doc(cm)); if (op.preparedSelection) { cm.display.input.showSelection(op.preparedSelection, takeFocus); } if (op.updatedDisplay || op.startHeight != cm.doc.height) { updateScrollbars(cm, op.barMeasure); } if (op.updatedDisplay) { setDocumentHeight(cm, op.barMeasure); } if (op.selectionChanged) { restartBlink(cm); } if (cm.state.focused && op.updateInput) { cm.display.input.reset(op.typing); } if (takeFocus) { ensureFocus(op.cm); } } function endOperation_finish(op) { var cm = op.cm, display = cm.display, doc = cm.doc; if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); } // Abort mouse wheel delta measurement, when scrolling explicitly if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos)) { display.wheelStartX = display.wheelStartY = null; } // Propagate the scroll position to the actual DOM scroller if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); } if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); } // If we need to scroll a specific position into view, do so. if (op.scrollToPos) { var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from), clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin); maybeScrollWindow(cm, rect); } // Fire events for markers that are hidden/unidden by editing or // undoing var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers; if (hidden) { for (var i = 0; i < hidden.length; ++i) { if (!hidden[i].lines.length) { signal(hidden[i], "hide"); } } } if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1) { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide"); } } } if (display.wrapper.offsetHeight) { doc.scrollTop = cm.display.scroller.scrollTop; } // Fire change events, and delayed event handlers if (op.changeObjs) { signal(cm, "changes", cm, op.changeObjs); } if (op.update) { op.update.finish(); } } // Run the given function in an operation function runInOp(cm, f) { if (cm.curOp) { return f() } startOperation(cm); try { return f() } finally { endOperation(cm); } } // Wraps a function in an operation. Returns the wrapped function. function operation(cm, f) { return function() { if (cm.curOp) { return f.apply(cm, arguments) } startOperation(cm); try { return f.apply(cm, arguments) } finally { endOperation(cm); } } } // Used to add methods to editor and doc instances, wrapping them in // operations. function methodOp(f) { return function() { if (this.curOp) { return f.apply(this, arguments) } startOperation(this); try { return f.apply(this, arguments) } finally { endOperation(this); } } } function docMethodOp(f) { return function() { var cm = this.cm; if (!cm || cm.curOp) { return f.apply(this, arguments) } startOperation(cm); try { return f.apply(this, arguments) } finally { endOperation(cm); } } } // HIGHLIGHT WORKER function startWorker(cm, time) { if (cm.doc.highlightFrontier < cm.display.viewTo) { cm.state.highlight.set(time, bind(highlightWorker, cm)); } } function highlightWorker(cm) { var doc = cm.doc; if (doc.highlightFrontier >= cm.display.viewTo) { return } var end = +new Date + cm.options.workTime; var context = getContextBefore(cm, doc.highlightFrontier); var changedLines = []; doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) { if (context.line >= cm.display.viewFrom) { // Visible var oldStyles = line.styles; var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null; var highlighted = highlightLine(cm, line, context, true); if (resetState) { context.state = resetState; } line.styles = highlighted.styles; var oldCls = line.styleClasses, newCls = highlighted.classes; if (newCls) { line.styleClasses = newCls; } else if (oldCls) { line.styleClasses = null; } var ischange = !oldStyles || oldStyles.length != line.styles.length || oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass); for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; } if (ischange) { changedLines.push(context.line); } line.stateAfter = context.save(); context.nextLine(); } else { if (line.text.length <= cm.options.maxHighlightLength) { processLine(cm, line.text, context); } line.stateAfter = context.line % 5 == 0 ? context.save() : null; context.nextLine(); } if (+new Date > end) { startWorker(cm, cm.options.workDelay); return true } }); doc.highlightFrontier = context.line; doc.modeFrontier = Math.max(doc.modeFrontier, context.line); if (changedLines.length) { runInOp(cm, function () { for (var i = 0; i < changedLines.length; i++) { regLineChange(cm, changedLines[i], "text"); } }); } } // DISPLAY DRAWING var DisplayUpdate = function(cm, viewport, force) { var display = cm.display; this.viewport = viewport; // Store some values that we'll need later (but don't want to force a relayout for) this.visible = visibleLines(display, cm.doc, viewport); this.editorIsHidden = !display.wrapper.offsetWidth; this.wrapperHeight = display.wrapper.clientHeight; this.wrapperWidth = display.wrapper.clientWidth; this.oldDisplayWidth = displayWidth(cm); this.force = force; this.dims = getDimensions(cm); this.events = []; }; DisplayUpdate.prototype.signal = function (emitter, type) { if (hasHandler(emitter, type)) { this.events.push(arguments); } }; DisplayUpdate.prototype.finish = function () { for (var i = 0; i < this.events.length; i++) { signal.apply(null, this.events[i]); } }; function maybeClipScrollbars(cm) { var display = cm.display; if (!display.scrollbarsClipped && display.scroller.offsetWidth) { display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth; display.heightForcer.style.height = scrollGap(cm) + "px"; display.sizer.style.marginBottom = -display.nativeBarWidth + "px"; display.sizer.style.borderRightWidth = scrollGap(cm) + "px"; display.scrollbarsClipped = true; } } function selectionSnapshot(cm) { if (cm.hasFocus()) { return null } var active = activeElt(doc(cm)); if (!active || !contains(cm.display.lineDiv, active)) { return null } var result = {activeElt: active}; if (window.getSelection) { var sel = win(cm).getSelection(); if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) { result.anchorNode = sel.anchorNode; result.anchorOffset = sel.anchorOffset; result.focusNode = sel.focusNode; result.focusOffset = sel.focusOffset; } } return result } function restoreSelection(snapshot) { if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt(snapshot.activeElt.ownerDocument)) { return } snapshot.activeElt.focus(); if (!/^(INPUT|TEXTAREA)$/.test(snapshot.activeElt.nodeName) && snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) { var doc = snapshot.activeElt.ownerDocument; var sel = doc.defaultView.getSelection(), range = doc.createRange(); range.setEnd(snapshot.anchorNode, snapshot.anchorOffset); range.collapse(false); sel.removeAllRanges(); sel.addRange(range); sel.extend(snapshot.focusNode, snapshot.focusOffset); } } // Does the actual updating of the line display. Bails out // (returning false) when there is nothing to be done and forced is // false. function updateDisplayIfNeeded(cm, update) { var display = cm.display, doc = cm.doc; if (update.editorIsHidden) { resetView(cm); return false } // Bail out if the visible area is already rendered and nothing changed. if (!update.force && update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo && (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) && display.renderedView == display.view && countDirtyView(cm) == 0) { return false } if (maybeUpdateLineNumberWidth(cm)) { resetView(cm); update.dims = getDimensions(cm); } // Compute a suitable new viewport (from & to) var end = doc.first + doc.size; var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first); var to = Math.min(end, update.visible.to + cm.options.viewportMargin); if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); } if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); } if (sawCollapsedSpans) { from = visualLineNo(cm.doc, from); to = visualLineEndNo(cm.doc, to); } var different = from != display.viewFrom || to != display.viewTo || display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth; adjustView(cm, from, to); display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom)); // Position the mover div to align with the current scroll position cm.display.mover.style.top = display.viewOffset + "px"; var toUpdate = countDirtyView(cm); if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view && (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo)) { return false } // For big changes, we hide the enclosing element during the // update, since that speeds up the operations on most browsers. var selSnapshot = selectionSnapshot(cm); if (toUpdate > 4) { display.lineDiv.style.display = "none"; } patchDisplay(cm, display.updateLineNumbers, update.dims); if (toUpdate > 4) { display.lineDiv.style.display = ""; } display.renderedView = display.view; // There might have been a widget with a focused element that got // hidden or updated, if so re-focus it. restoreSelection(selSnapshot); // Prevent selection and cursors from interfering with the scroll // width and height. removeChildren(display.cursorDiv); removeChildren(display.selectionDiv); display.gutters.style.height = display.sizer.style.minHeight = 0; if (different) { display.lastWrapHeight = update.wrapperHeight; display.lastWrapWidth = update.wrapperWidth; startWorker(cm, 400); } display.updateLineNumbers = null; return true } function postUpdateDisplay(cm, update) { var viewport = update.viewport; for (var first = true;; first = false) { if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) { // Clip forced viewport to actual scrollable area. if (viewport && viewport.top != null) { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; } // Updated line heights might result in the drawn area not // actually covering the viewport. Keep looping until it does. update.visible = visibleLines(cm.display, cm.doc, viewport); if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo) { break } } else if (first) { update.visible = visibleLines(cm.display, cm.doc, viewport); } if (!updateDisplayIfNeeded(cm, update)) { break } updateHeightsInViewport(cm); var barMeasure = measureForScrollbars(cm); updateSelection(cm); updateScrollbars(cm, barMeasure); setDocumentHeight(cm, barMeasure); update.force = false; } update.signal(cm, "update", cm); if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) { update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo); cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo; } } function updateDisplaySimple(cm, viewport) { var update = new DisplayUpdate(cm, viewport); if (updateDisplayIfNeeded(cm, update)) { updateHeightsInViewport(cm); postUpdateDisplay(cm, update); var barMeasure = measureForScrollbars(cm); updateSelection(cm); updateScrollbars(cm, barMeasure); setDocumentHeight(cm, barMeasure); update.finish(); } } // Sync the actual display DOM structure with display.view, removing // nodes for lines that are no longer in view, and creating the ones // that are not there yet, and updating the ones that are out of // date. function patchDisplay(cm, updateNumbersFrom, dims) { var display = cm.display, lineNumbers = cm.options.lineNumbers; var container = display.lineDiv, cur = container.firstChild; function rm(node) { var next = node.nextSibling; // Works around a throw-scroll bug in OS X Webkit if (webkit && mac && cm.display.currentWheelTarget == node) { node.style.display = "none"; } else { node.parentNode.removeChild(node); } return next } var view = display.view, lineN = display.viewFrom; // Loop over the elements in the view, syncing cur (the DOM nodes // in display.lineDiv) with the view as we go. for (var i = 0; i < view.length; i++) { var lineView = view[i]; if (lineView.hidden) ; else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet var node = buildLineElement(cm, lineView, lineN, dims); container.insertBefore(node, cur); } else { // Already drawn while (cur != lineView.node) { cur = rm(cur); } var updateNumber = lineNumbers && updateNumbersFrom != null && updateNumbersFrom <= lineN && lineView.lineNumber; if (lineView.changes) { if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false; } updateLineForChanges(cm, lineView, lineN, dims); } if (updateNumber) { removeChildren(lineView.lineNumber); lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN))); } cur = lineView.node.nextSibling; } lineN += lineView.size; } while (cur) { cur = rm(cur); } } function updateGutterSpace(display) { var width = display.gutters.offsetWidth; display.sizer.style.marginLeft = width + "px"; // Send an event to consumers responding to changes in gutter width. signalLater(display, "gutterChanged", display); } function setDocumentHeight(cm, measure) { cm.display.sizer.style.minHeight = measure.docHeight + "px"; cm.display.heightForcer.style.top = measure.docHeight + "px"; cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px"; } // Re-align line numbers and gutter marks to compensate for // horizontal scrolling. function alignHorizontally(cm) { var display = cm.display, view = display.view; if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return } var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft; var gutterW = display.gutters.offsetWidth, left = comp + "px"; for (var i = 0; i < view.length; i++) { if (!view[i].hidden) { if (cm.options.fixedGutter) { if (view[i].gutter) { view[i].gutter.style.left = left; } if (view[i].gutterBackground) { view[i].gutterBackground.style.left = left; } } var align = view[i].alignable; if (align) { for (var j = 0; j < align.length; j++) { align[j].style.left = left; } } } } if (cm.options.fixedGutter) { display.gutters.style.left = (comp + gutterW) + "px"; } } // Used to ensure that the line number gutter is still the right // size for the current document size. Returns true when an update // is needed. function maybeUpdateLineNumberWidth(cm) { if (!cm.options.lineNumbers) { return false } var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display; if (last.length != display.lineNumChars) { var test = display.measure.appendChild(elt("div", [elt("div", last)], "CodeMirror-linenumber CodeMirror-gutter-elt")); var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW; display.lineGutter.style.width = ""; display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1; display.lineNumWidth = display.lineNumInnerWidth + padding; display.lineNumChars = display.lineNumInnerWidth ? last.length : -1; display.lineGutter.style.width = display.lineNumWidth + "px"; updateGutterSpace(cm.display); return true } return false } function getGutters(gutters, lineNumbers) { var result = [], sawLineNumbers = false; for (var i = 0; i < gutters.length; i++) { var name = gutters[i], style = null; if (typeof name != "string") { style = name.style; name = name.className; } if (name == "CodeMirror-linenumbers") { if (!lineNumbers) { continue } else { sawLineNumbers = true; } } result.push({className: name, style: style}); } if (lineNumbers && !sawLineNumbers) { result.push({className: "CodeMirror-linenumbers", style: null}); } return result } // Rebuild the gutter elements, ensure the margin to the left of the // code matches their width. function renderGutters(display) { var gutters = display.gutters, specs = display.gutterSpecs; removeChildren(gutters); display.lineGutter = null; for (var i = 0; i < specs.length; ++i) { var ref = specs[i]; var className = ref.className; var style = ref.style; var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + className)); if (style) { gElt.style.cssText = style; } if (className == "CodeMirror-linenumbers") { display.lineGutter = gElt; gElt.style.width = (display.lineNumWidth || 1) + "px"; } } gutters.style.display = specs.length ? "" : "none"; updateGutterSpace(display); } function updateGutters(cm) { renderGutters(cm.display); regChange(cm); alignHorizontally(cm); } // The display handles the DOM integration, both for input reading // and content drawing. It holds references to DOM nodes and // display-related state. function Display(place, doc, input, options) { var d = this; this.input = input; // Covers bottom-right square when both scrollbars are present. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler"); d.scrollbarFiller.setAttribute("cm-not-content", "true"); // Covers bottom of gutter when coverGutterNextToScrollbar is on // and h scrollbar is present. d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler"); d.gutterFiller.setAttribute("cm-not-content", "true"); // Will contain the actual code, positioned to cover the viewport. d.lineDiv = eltP("div", null, "CodeMirror-code"); // Elements are added to these to represent selection and cursors. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1"); d.cursorDiv = elt("div", null, "CodeMirror-cursors"); // A visibility: hidden element used to find the size of things. d.measure = elt("div", null, "CodeMirror-measure"); // When lines outside of the viewport are measured, they are drawn in this. d.lineMeasure = elt("div", null, "CodeMirror-measure"); // Wraps everything that needs to exist inside the vertically-padded coordinate system d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv], null, "position: relative; outline: none"); var lines = eltP("div", [d.lineSpace], "CodeMirror-lines"); // Moved around its parent to cover visible view. d.mover = elt("div", [lines], null, "position: relative"); // Set to the height of the document, allowing scrolling. d.sizer = elt("div", [d.mover], "CodeMirror-sizer"); d.sizerWidth = null; // Behavior of elts with overflow: auto and padding is // inconsistent across browsers. This is used to ensure the // scrollable area is big enough. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;"); // Will contain the gutters, if any. d.gutters = elt("div", null, "CodeMirror-gutters"); d.lineGutter = null; // Actual scrollable element. d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll"); d.scroller.setAttribute("tabIndex", "-1"); // The element in which the editor lives. d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror"); // See #6982. FIXME remove when this has been fixed for a while in Chrome if (chrome && chrome_version >= 105) { d.wrapper.style.clipPath = "inset(0px)"; } // This attribute is respected by automatic translation systems such as Google Translate, // and may also be respected by tools used by human translators. d.wrapper.setAttribute('translate', 'no'); // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported) if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; } if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; } if (place) { if (place.appendChild) { place.appendChild(d.wrapper); } else { place(d.wrapper); } } // Current rendered range (may be bigger than the view window). d.viewFrom = d.viewTo = doc.first; d.reportedViewFrom = d.reportedViewTo = doc.first; // Information about the rendered lines. d.view = []; d.renderedView = null; // Holds info about a single rendered line when it was rendered // for measurement, while not in view. d.externalMeasured = null; // Empty space (in pixels) above the view d.viewOffset = 0; d.lastWrapHeight = d.lastWrapWidth = 0; d.updateLineNumbers = null; d.nativeBarWidth = d.barHeight = d.barWidth = 0; d.scrollbarsClipped = false; // Used to only resize the line number gutter when necessary (when // the amount of lines crosses a boundary that makes its width change) d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null; // Set to true when a non-horizontal-scrolling line widget is // added. As an optimization, line widget aligning is skipped when // this is false. d.alignWidgets = false; d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; // Tracks the maximum line length so that the horizontal scrollbar // can be kept static when scrolling. d.maxLine = null; d.maxLineLength = 0; d.maxLineChanged = false; // Used for measuring wheel scrolling granularity d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null; // True when shift is held down. d.shift = false; // Used to track whether anything happened since the context menu // was opened. d.selForContextMenu = null; d.activeTouch = null; d.gutterSpecs = getGutters(options.gutters, options.lineNumbers); renderGutters(d); input.init(d); } // Since the delta values reported on mouse wheel events are // unstandardized between browsers and even browser versions, and // generally horribly unpredictable, this code starts by measuring // the scroll effect that the first few mouse wheel events have, // and, from that, detects the way it can convert deltas to pixel // offsets afterwards. // // The reason we want to know the amount a wheel event will scroll // is that it gives us a chance to update the display before the // actual scrolling happens, reducing flickering. var wheelSamples = 0, wheelPixelsPerUnit = null; // Fill in a browser-detected starting value on browsers where we // know one. These don't have to be accurate -- the result of them // being wrong would just be a slight flicker on the first wheel // scroll (if it is large enough). if (ie) { wheelPixelsPerUnit = -.53; } else if (gecko) { wheelPixelsPerUnit = 15; } else if (chrome) { wheelPixelsPerUnit = -.7; } else if (safari) { wheelPixelsPerUnit = -1/3; } function wheelEventDelta(e) { var dx = e.wheelDeltaX, dy = e.wheelDeltaY; if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; } if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; } else if (dy == null) { dy = e.wheelDelta; } return {x: dx, y: dy} } function wheelEventPixels(e) { var delta = wheelEventDelta(e); delta.x *= wheelPixelsPerUnit; delta.y *= wheelPixelsPerUnit; return delta } function onScrollWheel(cm, e) { // On Chrome 102, viewport updates somehow stop wheel-based // scrolling. Turning off pointer events during the scroll seems // to avoid the issue. if (chrome && chrome_version == 102) { if (cm.display.chromeScrollHack == null) { cm.display.sizer.style.pointerEvents = "none"; } else { clearTimeout(cm.display.chromeScrollHack); } cm.display.chromeScrollHack = setTimeout(function () { cm.display.chromeScrollHack = null; cm.display.sizer.style.pointerEvents = ""; }, 100); } var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y; var pixelsPerUnit = wheelPixelsPerUnit; if (e.deltaMode === 0) { dx = e.deltaX; dy = e.deltaY; pixelsPerUnit = 1; } var display = cm.display, scroll = display.scroller; // Quit if there's nothing to scroll here var canScrollX = scroll.scrollWidth > scroll.clientWidth; var canScrollY = scroll.scrollHeight > scroll.clientHeight; if (!(dx && canScrollX || dy && canScrollY)) { return } // Webkit browsers on OS X abort momentum scrolls when the target // of the scroll event is removed from the scrollable element. // This hack (see related code in patchDisplay) makes sure the // element is kept around. if (dy && mac && webkit) { outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) { for (var i = 0; i < view.length; i++) { if (view[i].node == cur) { cm.display.currentWheelTarget = cur; break outer } } } } // On some browsers, horizontal scrolling will cause redraws to // happen before the gutter has been realigned, causing it to // wriggle around in a most unseemly way. When we have an // estimated pixels/delta value, we just handle horizontal // scrolling entirely here. It'll be slightly off from native, but // better than glitching out. if (dx && !gecko && !presto && pixelsPerUnit != null) { if (dy && canScrollY) { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * pixelsPerUnit)); } setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * pixelsPerUnit)); // Only prevent default scrolling if vertical scrolling is // actually possible. Otherwise, it causes vertical scroll // jitter on OSX trackpads when deltaX is small and deltaY // is large (issue #3579) if (!dy || (dy && canScrollY)) { e_preventDefault(e); } display.wheelStartX = null; // Abort measurement, if in progress return } // 'Project' the visible viewport to cover the area that is being // scrolled into view (if we know enough to estimate it). if (dy && pixelsPerUnit != null) { var pixels = dy * pixelsPerUnit; var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight; if (pixels < 0) { top = Math.max(0, top + pixels - 50); } else { bot = Math.min(cm.doc.height, bot + pixels + 50); } updateDisplaySimple(cm, {top: top, bottom: bot}); } if (wheelSamples < 20 && e.deltaMode !== 0) { if (display.wheelStartX == null) { display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop; display.wheelDX = dx; display.wheelDY = dy; setTimeout(function () { if (display.wheelStartX == null) { return } var movedX = scroll.scrollLeft - display.wheelStartX; var movedY = scroll.scrollTop - display.wheelStartY; var sample = (movedY && display.wheelDY && movedY / display.wheelDY) || (movedX && display.wheelDX && movedX / display.wheelDX); display.wheelStartX = display.wheelStartY = null; if (!sample) { return } wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1); ++wheelSamples; }, 200); } else { display.wheelDX += dx; display.wheelDY += dy; } } } // Selection objects are immutable. A new one is created every time // the selection changes. A selection is one or more non-overlapping // (and non-touching) ranges, sorted, and an integer that indicates // which one is the primary selection (the one that's scrolled into // view, that getCursor returns, etc). var Selection = function(ranges, primIndex) { this.ranges = ranges; this.primIndex = primIndex; }; Selection.prototype.primary = function () { return this.ranges[this.primIndex] }; Selection.prototype.equals = function (other) { if (other == this) { return true } if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false } for (var i = 0; i < this.ranges.length; i++) { var here = this.ranges[i], there = other.ranges[i]; if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false } } return true }; Selection.prototype.deepCopy = function () { var out = []; for (var i = 0; i < this.ranges.length; i++) { out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head)); } return new Selection(out, this.primIndex) }; Selection.prototype.somethingSelected = function () { for (var i = 0; i < this.ranges.length; i++) { if (!this.ranges[i].empty()) { return true } } return false }; Selection.prototype.contains = function (pos, end) { if (!end) { end = pos; } for (var i = 0; i < this.ranges.length; i++) { var range = this.ranges[i]; if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0) { return i } } return -1 }; var Range = function(anchor, head) { this.anchor = anchor; this.head = head; }; Range.prototype.from = function () { return minPos(this.anchor, this.head) }; Range.prototype.to = function () { return maxPos(this.anchor, this.head) }; Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch }; // Take an unsorted, potentially overlapping set of ranges, and // build a selection out of it. 'Consumes' ranges array (modifying // it). function normalizeSelection(cm, ranges, primIndex) { var mayTouch = cm && cm.options.selectionsMayTouch; var prim = ranges[primIndex]; ranges.sort(function (a, b) { return cmp(a.from(), b.from()); }); primIndex = indexOf(ranges, prim); for (var i = 1; i < ranges.length; i++) { var cur = ranges[i], prev = ranges[i - 1]; var diff = cmp(prev.to(), cur.from()); if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) { var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to()); var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head; if (i <= primIndex) { --primIndex; } ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to)); } } return new Selection(ranges, primIndex) } function simpleSelection(anchor, head) { return new Selection([new Range(anchor, head || anchor)], 0) } // Compute the position of the end of a change (its 'to' property // refers to the pre-change end). function changeEnd(change) { if (!change.text) { return change.to } return Pos(change.from.line + change.text.length - 1, lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0)) } // Adjust a position to refer to the post-change position of the // same text, or the end of the change if the change covers it. function adjustForChange(pos, change) { if (cmp(pos, change.from) < 0) { return pos } if (cmp(pos, change.to) <= 0) { return changeEnd(change) } var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch; if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; } return Pos(line, ch) } function computeSelAfterChange(doc, change) { var out = []; for (var i = 0; i < doc.sel.ranges.length; i++) { var range = doc.sel.ranges[i]; out.push(new Range(adjustForChange(range.anchor, change), adjustForChange(range.head, change))); } return normalizeSelection(doc.cm, out, doc.sel.primIndex) } function offsetPos(pos, old, nw) { if (pos.line == old.line) { return Pos(nw.line, pos.ch - old.ch + nw.ch) } else { return Pos(nw.line + (pos.line - old.line), pos.ch) } } // Used by replaceSelections to allow moving the selection to the // start or around the replaced test. Hint may be "start" or "around". function computeReplacedSel(doc, changes, hint) { var out = []; var oldPrev = Pos(doc.first, 0), newPrev = oldPrev; for (var i = 0; i < changes.length; i++) { var change = changes[i]; var from = offsetPos(change.from, oldPrev, newPrev); var to = offsetPos(changeEnd(change), oldPrev, newPrev); oldPrev = change.to; newPrev = to; if (hint == "around") { var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0; out[i] = new Range(inv ? to : from, inv ? from : to); } else { out[i] = new Range(from, from); } } return new Selection(out, doc.sel.primIndex) } // Used to get the editor into a consistent state again when options change. function loadMode(cm) { cm.doc.mode = getMode(cm.options, cm.doc.modeOption); resetModeState(cm); } function resetModeState(cm) { cm.doc.iter(function (line) { if (line.stateAfter) { line.stateAfter = null; } if (line.styles) { line.styles = null; } }); cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first; startWorker(cm, 100); cm.state.modeGen++; if (cm.curOp) { regChange(cm); } } // DOCUMENT DATA STRUCTURE // By default, updates that start and end at the beginning of a line // are treated specially, in order to make the association of line // widgets and marker elements with the text behave more intuitive. function isWholeLineUpdate(doc, change) { return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" && (!doc.cm || doc.cm.options.wholeLineUpdateBefore) } // Perform a change on the document data structure. function updateDoc(doc, change, markedSpans, estimateHeight) { function spansFor(n) {return markedSpans ? markedSpans[n] : null} function update(line, text, spans) { updateLine(line, text, spans, estimateHeight); signalLater(line, "change", line, change); } function linesFor(start, end) { var result = []; for (var i = start; i < end; ++i) { result.push(new Line(text[i], spansFor(i), estimateHeight)); } return result } var from = change.from, to = change.to, text = change.text; var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line); var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line; // Adjust the line structure if (change.full) { doc.insert(0, linesFor(0, text.length)); doc.remove(text.length, doc.size - text.length); } else if (isWholeLineUpdate(doc, change)) { // This is a whole-line replace. Treated specially to make // sure line objects move the way they are supposed to. var added = linesFor(0, text.length - 1); update(lastLine, lastLine.text, lastSpans); if (nlines) { doc.remove(from.line, nlines); } if (added.length) { doc.insert(from.line, added); } } else if (firstLine == lastLine) { if (text.length == 1) { update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans); } else { var added$1 = linesFor(1, text.length - 1); added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight)); update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); doc.insert(from.line + 1, added$1); } } else if (text.length == 1) { update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0)); doc.remove(from.line + 1, nlines); } else { update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans); var added$2 = linesFor(1, text.length - 1); if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); } doc.insert(from.line + 1, added$2); } signalLater(doc, "change", doc, change); } // Call f for all linked documents. function linkedDocs(doc, f, sharedHistOnly) { function propagate(doc, skip, sharedHist) { if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) { var rel = doc.linked[i]; if (rel.doc == skip) { continue } var shared = sharedHist && rel.sharedHist; if (sharedHistOnly && !shared) { continue } f(rel.doc, shared); propagate(rel.doc, doc, shared); } } } propagate(doc, null, true); } // Attach a document to an editor. function attachDoc(cm, doc) { if (doc.cm) { throw new Error("This document is already in use.") } cm.doc = doc; doc.cm = cm; estimateLineHeights(cm); loadMode(cm); setDirectionClass(cm); cm.options.direction = doc.direction; if (!cm.options.lineWrapping) { findMaxLine(cm); } cm.options.mode = doc.modeOption; regChange(cm); } function setDirectionClass(cm) { (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl"); } function directionChanged(cm) { runInOp(cm, function () { setDirectionClass(cm); regChange(cm); }); } function History(prev) { // Arrays of change events and selections. Doing something adds an // event to done and clears undo. Undoing moves events from done // to undone, redoing moves them in the other direction. this.done = []; this.undone = []; this.undoDepth = prev ? prev.undoDepth : Infinity; // Used to track when changes can be merged into a single undo // event this.lastModTime = this.lastSelTime = 0; this.lastOp = this.lastSelOp = null; this.lastOrigin = this.lastSelOrigin = null; // Used by the isClean() method this.generation = this.maxGeneration = prev ? prev.maxGeneration : 1; } // Create a history change event from an updateDoc-style change // object. function historyChangeFromChange(doc, change) { var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)}; attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true); return histChange } // Pop all selection events off the end of a history array. Stop at // a change event. function clearSelectionEvents(array) { while (array.length) { var last = lst(array); if (last.ranges) { array.pop(); } else { break } } } // Find the top change event in the history. Pop off selection // events that are in the way. function lastChangeEvent(hist, force) { if (force) { clearSelectionEvents(hist.done); return lst(hist.done) } else if (hist.done.length && !lst(hist.done).ranges) { return lst(hist.done) } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) { hist.done.pop(); return lst(hist.done) } } // Register a change in the history. Merges changes that are within // a single operation, or are close together with an origin that // allows merging (starting with "+") into a single event. function addChangeToHistory(doc, change, selAfter, opId) { var hist = doc.history; hist.undone.length = 0; var time = +new Date, cur; var last; if ((hist.lastOp == opId || hist.lastOrigin == change.origin && change.origin && ((change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) || change.origin.charAt(0) == "*")) && (cur = lastChangeEvent(hist, hist.lastOp == opId))) { // Merge this change into the last event last = lst(cur.changes); if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) { // Optimized case for simple insertion -- don't want to add // new changesets for every character typed last.to = changeEnd(change); } else { // Add new sub-event cur.changes.push(historyChangeFromChange(doc, change)); } } else { // Can not be merged, start a new event. var before = lst(hist.done); if (!before || !before.ranges) { pushSelectionToHistory(doc.sel, hist.done); } cur = {changes: [historyChangeFromChange(doc, change)], generation: hist.generation}; hist.done.push(cur); while (hist.done.length > hist.undoDepth) { hist.done.shift(); if (!hist.done[0].ranges) { hist.done.shift(); } } } hist.done.push(selAfter); hist.generation = ++hist.maxGeneration; hist.lastModTime = hist.lastSelTime = time; hist.lastOp = hist.lastSelOp = opId; hist.lastOrigin = hist.lastSelOrigin = change.origin; if (!last) { signal(doc, "historyAdded"); } } function selectionEventCanBeMerged(doc, origin, prev, sel) { var ch = origin.charAt(0); return ch == "*" || ch == "+" && prev.ranges.length == sel.ranges.length && prev.somethingSelected() == sel.somethingSelected() && new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500) } // Called whenever the selection changes, sets the new selection as // the pending selection in the history, and pushes the old pending // selection into the 'done' array when it was significantly // different (in number of selected ranges, emptiness, or time). function addSelectionToHistory(doc, sel, opId, options) { var hist = doc.history, origin = options && options.origin; // A new event is started when the previous origin does not match // the current, or the origins don't allow matching. Origins // starting with * are always merged, those starting with + are // merged when similar and close together in time. if (opId == hist.lastSelOp || (origin && hist.lastSelOrigin == origin && (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin || selectionEventCanBeMerged(doc, origin, lst(hist.done), sel)))) { hist.done[hist.done.length - 1] = sel; } else { pushSelectionToHistory(sel, hist.done); } hist.lastSelTime = +new Date; hist.lastSelOrigin = origin; hist.lastSelOp = opId; if (options && options.clearRedo !== false) { clearSelectionEvents(hist.undone); } } function pushSelectionToHistory(sel, dest) { var top = lst(dest); if (!(top && top.ranges && top.equals(sel))) { dest.push(sel); } } // Used to store marked span information in the history. function attachLocalSpans(doc, change, from, to) { var existing = change["spans_" + doc.id], n = 0; doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) { if (line.markedSpans) { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; } ++n; }); } // When un/re-doing restores text containing marked spans, those // that have been explicitly cleared should not be restored. function removeClearedSpans(spans) { if (!spans) { return null } var out; for (var i = 0; i < spans.length; ++i) { if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } } else if (out) { out.push(spans[i]); } } return !out ? spans : out.length ? out : null } // Retrieve and filter the old marked spans stored in a change event. function getOldSpans(doc, change) { var found = change["spans_" + doc.id]; if (!found) { return null } var nw = []; for (var i = 0; i < change.text.length; ++i) { nw.push(removeClearedSpans(found[i])); } return nw } // Used for un/re-doing changes from the history. Combines the // result of computing the existing spans with the set of spans that // existed in the history (so that deleting around a span and then // undoing brings back the span). function mergeOldSpans(doc, change) { var old = getOldSpans(doc, change); var stretched = stretchSpansOverChange(doc, change); if (!old) { return stretched } if (!stretched) { return old } for (var i = 0; i < old.length; ++i) { var oldCur = old[i], stretchCur = stretched[i]; if (oldCur && stretchCur) { spans: for (var j = 0; j < stretchCur.length; ++j) { var span = stretchCur[j]; for (var k = 0; k < oldCur.length; ++k) { if (oldCur[k].marker == span.marker) { continue spans } } oldCur.push(span); } } else if (stretchCur) { old[i] = stretchCur; } } return old } // Used both to provide a JSON-safe object in .getHistory, and, when // detaching a document, to split the history in two function copyHistoryArray(events, newGroup, instantiateSel) { var copy = []; for (var i = 0; i < events.length; ++i) { var event = events[i]; if (event.ranges) { copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event); continue } var changes = event.changes, newChanges = []; copy.push({changes: newChanges}); for (var j = 0; j < changes.length; ++j) { var change = changes[j], m = (void 0); newChanges.push({from: change.from, to: change.to, text: change.text}); if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) { if (indexOf(newGroup, Number(m[1])) > -1) { lst(newChanges)[prop] = change[prop]; delete change[prop]; } } } } } } return copy } // The 'scroll' parameter given to many of these indicated whether // the new cursor position should be scrolled into view after // modifying the selection. // If shift is held or the extend flag is set, extends a range to // include a given position (and optionally a second position). // Otherwise, simply returns the range between the given positions. // Used for cursor motion and such. function extendRange(range, head, other, extend) { if (extend) { var anchor = range.anchor; if (other) { var posBefore = cmp(head, anchor) < 0; if (posBefore != (cmp(other, anchor) < 0)) { anchor = head; head = other; } else if (posBefore != (cmp(head, other) < 0)) { head = other; } } return new Range(anchor, head) } else { return new Range(other || head, head) } } // Extend the primary selection range, discard the rest. function extendSelection(doc, head, other, options, extend) { if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); } setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options); } // Extend all selections (pos is an array of selections with length // equal the number of selections) function extendSelections(doc, heads, options) { var out = []; var extend = doc.cm && (doc.cm.display.shift || doc.extend); for (var i = 0; i < doc.sel.ranges.length; i++) { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); } var newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex); setSelection(doc, newSel, options); } // Updates a single range in the selection. function replaceOneSelection(doc, i, range, options) { var ranges = doc.sel.ranges.slice(0); ranges[i] = range; setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options); } // Reset the selection to a single range. function setSimpleSelection(doc, anchor, head, options) { setSelection(doc, simpleSelection(anchor, head), options); } // Give beforeSelectionChange handlers a change to influence a // selection update. function filterSelectionChange(doc, sel, options) { var obj = { ranges: sel.ranges, update: function(ranges) { this.ranges = []; for (var i = 0; i < ranges.length; i++) { this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor), clipPos(doc, ranges[i].head)); } }, origin: options && options.origin }; signal(doc, "beforeSelectionChange", doc, obj); if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj); } if (obj.ranges != sel.ranges) { return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1) } else { return sel } } function setSelectionReplaceHistory(doc, sel, options) { var done = doc.history.done, last = lst(done); if (last && last.ranges) { done[done.length - 1] = sel; setSelectionNoUndo(doc, sel, options); } else { setSelection(doc, sel, options); } } // Set a new selection. function setSelection(doc, sel, options) { setSelectionNoUndo(doc, sel, options); addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options); } function setSelectionNoUndo(doc, sel, options) { if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) { sel = filterSelectionChange(doc, sel, options); } var bias = options && options.bias || (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1); setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true)); if (!(options && options.scroll === false) && doc.cm && doc.cm.getOption("readOnly") != "nocursor") { ensureCursorVisible(doc.cm); } } function setSelectionInner(doc, sel) { if (sel.equals(doc.sel)) { return } doc.sel = sel; if (doc.cm) { doc.cm.curOp.updateInput = 1; doc.cm.curOp.selectionChanged = true; signalCursorActivity(doc.cm); } signalLater(doc, "cursorActivity", doc); } // Verify that the selection does not partially select any atomic // marked ranges. function reCheckSelection(doc) { setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false)); } // Return a selection that does not partially select any atomic // ranges. function skipAtomicInSelection(doc, sel, bias, mayClear) { var out; for (var i = 0; i < sel.ranges.length; i++) { var range = sel.ranges[i]; var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i]; var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear); var newHead = range.head == range.anchor ? newAnchor : skipAtomic(doc, range.head, old && old.head, bias, mayClear); if (out || newAnchor != range.anchor || newHead != range.head) { if (!out) { out = sel.ranges.slice(0, i); } out[i] = new Range(newAnchor, newHead); } } return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel } function skipAtomicInner(doc, pos, oldPos, dir, mayClear) { var line = getLine(doc, pos.line); if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) { var sp = line.markedSpans[i], m = sp.marker; // Determine if we should prevent the cursor being placed to the left/right of an atomic marker // Historically this was determined using the inclusiveLeft/Right option, but the new way to control it // is with selectLeft/Right var preventCursorLeft = ("selectLeft" in m) ? !m.selectLeft : m.inclusiveLeft; var preventCursorRight = ("selectRight" in m) ? !m.selectRight : m.inclusiveRight; if ((sp.from == null || (preventCursorLeft ? sp.from <= pos.ch : sp.from < pos.ch)) && (sp.to == null || (preventCursorRight ? sp.to >= pos.ch : sp.to > pos.ch))) { if (mayClear) { signal(m, "beforeCursorEnter"); if (m.explicitlyCleared) { if (!line.markedSpans) { break } else {--i; continue} } } if (!m.atomic) { continue } if (oldPos) { var near = m.find(dir < 0 ? 1 : -1), diff = (void 0); if (dir < 0 ? preventCursorRight : preventCursorLeft) { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); } if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0)) { return skipAtomicInner(doc, near, pos, dir, mayClear) } } var far = m.find(dir < 0 ? -1 : 1); if (dir < 0 ? preventCursorLeft : preventCursorRight) { far = movePos(doc, far, dir, far.line == pos.line ? line : null); } return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null } } } return pos } // Ensure a given position is not inside an atomic range. function skipAtomic(doc, pos, oldPos, bias, mayClear) { var dir = bias || 1; var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) || (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) || skipAtomicInner(doc, pos, oldPos, -dir, mayClear) || (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true)); if (!found) { doc.cantEdit = true; return Pos(doc.first, 0) } return found } function movePos(doc, pos, dir, line) { if (dir < 0 && pos.ch == 0) { if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) } else { return null } } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) { if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) } else { return null } } else { return new Pos(pos.line, pos.ch + dir) } } function selectAll(cm) { cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll); } // UPDATING // Allow "beforeChange" event handlers to influence a change function filterChange(doc, change, update) { var obj = { canceled: false, from: change.from, to: change.to, text: change.text, origin: change.origin, cancel: function () { return obj.canceled = true; } }; if (update) { obj.update = function (from, to, text, origin) { if (from) { obj.from = clipPos(doc, from); } if (to) { obj.to = clipPos(doc, to); } if (text) { obj.text = text; } if (origin !== undefined) { obj.origin = origin; } }; } signal(doc, "beforeChange", doc, obj); if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj); } if (obj.canceled) { if (doc.cm) { doc.cm.curOp.updateInput = 2; } return null } return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin} } // Apply a change to a document, and add it to the document's // history, and propagating it to all linked documents. function makeChange(doc, change, ignoreReadOnly) { if (doc.cm) { if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) } if (doc.cm.state.suppressEdits) { return } } if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) { change = filterChange(doc, change, true); if (!change) { return } } // Possibly split or suppress the update based on the presence // of read-only spans in its range. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to); if (split) { for (var i = split.length - 1; i >= 0; --i) { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin}); } } else { makeChangeInner(doc, change); } } function makeChangeInner(doc, change) { if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return } var selAfter = computeSelAfterChange(doc, change); addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN); makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change)); var rebased = []; linkedDocs(doc, function (doc, sharedHist) { if (!sharedHist && indexOf(rebased, doc.history) == -1) { rebaseHist(doc.history, change); rebased.push(doc.history); } makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change)); }); } // Revert a change stored in a document's history. function makeChangeFromHistory(doc, type, allowSelectionOnly) { var suppress = doc.cm && doc.cm.state.suppressEdits; if (suppress && !allowSelectionOnly) { return } var hist = doc.history, event, selAfter = doc.sel; var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done; // Verify that there is a useable event (so that ctrl-z won't // needlessly clear selection events) var i = 0; for (; i < source.length; i++) { event = source[i]; if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges) { break } } if (i == source.length) { return } hist.lastOrigin = hist.lastSelOrigin = null; for (;;) { event = source.pop(); if (event.ranges) { pushSelectionToHistory(event, dest); if (allowSelectionOnly && !event.equals(doc.sel)) { setSelection(doc, event, {clearRedo: false}); return } selAfter = event; } else if (suppress) { source.push(event); return } else { break } } // Build up a reverse change object to add to the opposite history // stack (redo when undoing, and vice versa). var antiChanges = []; pushSelectionToHistory(selAfter, dest); dest.push({changes: antiChanges, generation: hist.generation}); hist.generation = event.generation || ++hist.maxGeneration; var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange"); var loop = function ( i ) { var change = event.changes[i]; change.origin = type; if (filter && !filterChange(doc, change, false)) { source.length = 0; return {} } antiChanges.push(historyChangeFromChange(doc, change)); var after = i ? computeSelAfterChange(doc, change) : lst(source); makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change)); if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); } var rebased = []; // Propagate to the linked documents linkedDocs(doc, function (doc, sharedHist) { if (!sharedHist && indexOf(rebased, doc.history) == -1) { rebaseHist(doc.history, change); rebased.push(doc.history); } makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change)); }); }; for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) { var returned = loop( i$1 ); if ( returned ) return returned.v; } } // Sub-views need their line numbers shifted when text is added // above or below them in the parent document. function shiftDoc(doc, distance) { if (distance == 0) { return } doc.first += distance; doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range( Pos(range.anchor.line + distance, range.anchor.ch), Pos(range.head.line + distance, range.head.ch) ); }), doc.sel.primIndex); if (doc.cm) { regChange(doc.cm, doc.first, doc.first - distance, distance); for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++) { regLineChange(doc.cm, l, "gutter"); } } } // More lower-level change function, handling only a single document // (not linked ones). function makeChangeSingleDoc(doc, change, selAfter, spans) { if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) } if (change.to.line < doc.first) { shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line)); return } if (change.from.line > doc.lastLine()) { return } // Clip the change to the size of this doc if (change.from.line < doc.first) { var shift = change.text.length - 1 - (doc.first - change.from.line); shiftDoc(doc, shift); change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch), text: [lst(change.text)], origin: change.origin}; } var last = doc.lastLine(); if (change.to.line > last) { change = {from: change.from, to: Pos(last, getLine(doc, last).text.length), text: [change.text[0]], origin: change.origin}; } change.removed = getBetween(doc, change.from, change.to); if (!selAfter) { selAfter = computeSelAfterChange(doc, change); } if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); } else { updateDoc(doc, change, spans); } setSelectionNoUndo(doc, selAfter, sel_dontScroll); if (doc.cantEdit && skipAtomic(doc, Pos(doc.firstLine(), 0))) { doc.cantEdit = false; } } // Handle the interaction of a change to a document with the editor // that this document is part of. function makeChangeSingleDocInEditor(cm, change, spans) { var doc = cm.doc, display = cm.display, from = change.from, to = change.to; var recomputeMaxLength = false, checkWidthStart = from.line; if (!cm.options.lineWrapping) { checkWidthStart = lineNo(visualLine(getLine(doc, from.line))); doc.iter(checkWidthStart, to.line + 1, function (line) { if (line == display.maxLine) { recomputeMaxLength = true; return true } }); } if (doc.sel.contains(change.from, change.to) > -1) { signalCursorActivity(cm); } updateDoc(doc, change, spans, estimateHeight(cm)); if (!cm.options.lineWrapping) { doc.iter(checkWidthStart, from.line + change.text.length, function (line) { var len = lineLength(line); if (len > display.maxLineLength) { display.maxLine = line; display.maxLineLength = len; display.maxLineChanged = true; recomputeMaxLength = false; } }); if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; } } retreatFrontier(doc, from.line); startWorker(cm, 400); var lendiff = change.text.length - (to.line - from.line) - 1; // Remember that these lines changed, for updating the display if (change.full) { regChange(cm); } else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change)) { regLineChange(cm, from.line, "text"); } else { regChange(cm, from.line, to.line + 1, lendiff); } var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change"); if (changeHandler || changesHandler) { var obj = { from: from, to: to, text: change.text, removed: change.removed, origin: change.origin }; if (changeHandler) { signalLater(cm, "change", cm, obj); } if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); } } cm.display.selForContextMenu = null; } function replaceRange(doc, code, from, to, origin) { var assign; if (!to) { to = from; } if (cmp(to, from) < 0) { (assign = [to, from], from = assign[0], to = assign[1]); } if (typeof code == "string") { code = doc.splitLines(code); } makeChange(doc, {from: from, to: to, text: code, origin: origin}); } // Rebasing/resetting history to deal with externally-sourced changes function rebaseHistSelSingle(pos, from, to, diff) { if (to < pos.line) { pos.line += diff; } else if (from < pos.line) { pos.line = from; pos.ch = 0; } } // Tries to rebase an array of history events given a change in the // document. If the change touches the same lines as the event, the // event, and everything 'behind' it, is discarded. If the change is // before the event, the event's positions are updated. Uses a // copy-on-write scheme for the positions, to avoid having to // reallocate them all on every rebase, but also avoid problems with // shared position objects being unsafely updated. function rebaseHistArray(array, from, to, diff) { for (var i = 0; i < array.length; ++i) { var sub = array[i], ok = true; if (sub.ranges) { if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; } for (var j = 0; j < sub.ranges.length; j++) { rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff); rebaseHistSelSingle(sub.ranges[j].head, from, to, diff); } continue } for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) { var cur = sub.changes[j$1]; if (to < cur.from.line) { cur.from = Pos(cur.from.line + diff, cur.from.ch); cur.to = Pos(cur.to.line + diff, cur.to.ch); } else if (from <= cur.to.line) { ok = false; break } } if (!ok) { array.splice(0, i + 1); i = 0; } } } function rebaseHist(hist, change) { var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1; rebaseHistArray(hist.done, from, to, diff); rebaseHistArray(hist.undone, from, to, diff); } // Utility for applying a change to a line by handle or number, // returning the number and optionally registering the line as // changed. function changeLine(doc, handle, changeType, op) { var no = handle, line = handle; if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)); } else { no = lineNo(handle); } if (no == null) { return null } if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); } return line } // The document is represented as a BTree consisting of leaves, with // chunk of lines in them, and branches, with up to ten leaves or // other branch nodes below them. The top node is always a branch // node, and is the document object itself (meaning it has // additional methods and properties). // // All nodes have parent links. The tree is used both to go from // line numbers to line objects, and to go from objects to numbers. // It also indexes by height, and is used to convert between height // and line object, and to find the total height of the document. // // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html function LeafChunk(lines) { this.lines = lines; this.parent = null; var height = 0; for (var i = 0; i < lines.length; ++i) { lines[i].parent = this; height += lines[i].height; } this.height = height; } LeafChunk.prototype = { chunkSize: function() { return this.lines.length }, // Remove the n lines at offset 'at'. removeInner: function(at, n) { for (var i = at, e = at + n; i < e; ++i) { var line = this.lines[i]; this.height -= line.height; cleanUpLine(line); signalLater(line, "delete"); } this.lines.splice(at, n); }, // Helper used to collapse a small branch into a single leaf. collapse: function(lines) { lines.push.apply(lines, this.lines); }, // Insert the given array of lines at offset 'at', count them as // having the given height. insertInner: function(at, lines, height) { this.height += height; this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)); for (var i = 0; i < lines.length; ++i) { lines[i].parent = this; } }, // Used to iterate over a part of the tree. iterN: function(at, n, op) { for (var e = at + n; at < e; ++at) { if (op(this.lines[at])) { return true } } } }; function BranchChunk(children) { this.children = children; var size = 0, height = 0; for (var i = 0; i < children.length; ++i) { var ch = children[i]; size += ch.chunkSize(); height += ch.height; ch.parent = this; } this.size = size; this.height = height; this.parent = null; } BranchChunk.prototype = { chunkSize: function() { return this.size }, removeInner: function(at, n) { this.size -= n; for (var i = 0; i < this.children.length; ++i) { var child = this.children[i], sz = child.chunkSize(); if (at < sz) { var rm = Math.min(n, sz - at), oldHeight = child.height; child.removeInner(at, rm); this.height -= oldHeight - child.height; if (sz == rm) { this.children.splice(i--, 1); child.parent = null; } if ((n -= rm) == 0) { break } at = 0; } else { at -= sz; } } // If the result is smaller than 25 lines, ensure that it is a // single leaf node. if (this.size - n < 25 && (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) { var lines = []; this.collapse(lines); this.children = [new LeafChunk(lines)]; this.children[0].parent = this; } }, collapse: function(lines) { for (var i = 0; i < this.children.length; ++i) { this.children[i].collapse(lines); } }, insertInner: function(at, lines, height) { this.size += lines.length; this.height += height; for (var i = 0; i < this.children.length; ++i) { var child = this.children[i], sz = child.chunkSize(); if (at <= sz) { child.insertInner(at, lines, height); if (child.lines && child.lines.length > 50) { // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced. // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest. var remaining = child.lines.length % 25 + 25; for (var pos = remaining; pos < child.lines.length;) { var leaf = new LeafChunk(child.lines.slice(pos, pos += 25)); child.height -= leaf.height; this.children.splice(++i, 0, leaf); leaf.parent = this; } child.lines = child.lines.slice(0, remaining); this.maybeSpill(); } break } at -= sz; } }, // When a node has grown, check whether it should be split. maybeSpill: function() { if (this.children.length <= 10) { return } var me = this; do { var spilled = me.children.splice(me.children.length - 5, 5); var sibling = new BranchChunk(spilled); if (!me.parent) { // Become the parent node var copy = new BranchChunk(me.children); copy.parent = me; me.children = [copy, sibling]; me = copy; } else { me.size -= sibling.size; me.height -= sibling.height; var myIndex = indexOf(me.parent.children, me); me.parent.children.splice(myIndex + 1, 0, sibling); } sibling.parent = me.parent; } while (me.children.length > 10) me.parent.maybeSpill(); }, iterN: function(at, n, op) { for (var i = 0; i < this.children.length; ++i) { var child = this.children[i], sz = child.chunkSize(); if (at < sz) { var used = Math.min(n, sz - at); if (child.iterN(at, used, op)) { return true } if ((n -= used) == 0) { break } at = 0; } else { at -= sz; } } } }; // Line widgets are block elements displayed above or below a line. var LineWidget = function(doc, node, options) { if (options) { for (var opt in options) { if (options.hasOwnProperty(opt)) { this[opt] = options[opt]; } } } this.doc = doc; this.node = node; }; LineWidget.prototype.clear = function () { var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line); if (no == null || !ws) { return } for (var i = 0; i < ws.length; ++i) { if (ws[i] == this) { ws.splice(i--, 1); } } if (!ws.length) { line.widgets = null; } var height = widgetHeight(this); updateLineHeight(line, Math.max(0, line.height - height)); if (cm) { runInOp(cm, function () { adjustScrollWhenAboveVisible(cm, line, -height); regLineChange(cm, no, "widget"); }); signalLater(cm, "lineWidgetCleared", cm, this, no); } }; LineWidget.prototype.changed = function () { var this$1 = this; var oldH = this.height, cm = this.doc.cm, line = this.line; this.height = null; var diff = widgetHeight(this) - oldH; if (!diff) { return } if (!lineIsHidden(this.doc, line)) { updateLineHeight(line, line.height + diff); } if (cm) { runInOp(cm, function () { cm.curOp.forceUpdate = true; adjustScrollWhenAboveVisible(cm, line, diff); signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line)); }); } }; eventMixin(LineWidget); function adjustScrollWhenAboveVisible(cm, line, diff) { if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop)) { addToScrollTop(cm, diff); } } function addLineWidget(doc, handle, node, options) { var widget = new LineWidget(doc, node, options); var cm = doc.cm; if (cm && widget.noHScroll) { cm.display.alignWidgets = true; } changeLine(doc, handle, "widget", function (line) { var widgets = line.widgets || (line.widgets = []); if (widget.insertAt == null) { widgets.push(widget); } else { widgets.splice(Math.min(widgets.length, Math.max(0, widget.insertAt)), 0, widget); } widget.line = line; if (cm && !lineIsHidden(doc, line)) { var aboveVisible = heightAtLine(line) < doc.scrollTop; updateLineHeight(line, line.height + widgetHeight(widget)); if (aboveVisible) { addToScrollTop(cm, widget.height); } cm.curOp.forceUpdate = true; } return true }); if (cm) { signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)); } return widget } // TEXTMARKERS // Created with markText and setBookmark methods. A TextMarker is a // handle that can be used to clear or find a marked position in the // document. Line objects hold arrays (markedSpans) containing // {from, to, marker} object pointing to such marker objects, and // indicating that such a marker is present on that line. Multiple // lines may point to the same marker when it spans across lines. // The spans will have null for their from/to properties when the // marker continues beyond the start/end of the line. Markers have // links back to the lines they currently touch. // Collapsed markers have unique ids, in order to be able to order // them, which is needed for uniquely determining an outer marker // when they overlap (they may nest, but not partially overlap). var nextMarkerId = 0; var TextMarker = function(doc, type) { this.lines = []; this.type = type; this.doc = doc; this.id = ++nextMarkerId; }; // Clear the marker. TextMarker.prototype.clear = function () { if (this.explicitlyCleared) { return } var cm = this.doc.cm, withOp = cm && !cm.curOp; if (withOp) { startOperation(cm); } if (hasHandler(this, "clear")) { var found = this.find(); if (found) { signalLater(this, "clear", found.from, found.to); } } var min = null, max = null; for (var i = 0; i < this.lines.length; ++i) { var line = this.lines[i]; var span = getMarkedSpanFor(line.markedSpans, this); if (cm && !this.collapsed) { regLineChange(cm, lineNo(line), "text"); } else if (cm) { if (span.to != null) { max = lineNo(line); } if (span.from != null) { min = lineNo(line); } } line.markedSpans = removeMarkedSpan(line.markedSpans, span); if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm) { updateLineHeight(line, textHeight(cm.display)); } } if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) { var visual = visualLine(this.lines[i$1]), len = lineLength(visual); if (len > cm.display.maxLineLength) { cm.display.maxLine = visual; cm.display.maxLineLength = len; cm.display.maxLineChanged = true; } } } if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); } this.lines.length = 0; this.explicitlyCleared = true; if (this.atomic && this.doc.cantEdit) { this.doc.cantEdit = false; if (cm) { reCheckSelection(cm.doc); } } if (cm) { signalLater(cm, "markerCleared", cm, this, min, max); } if (withOp) { endOperation(cm); } if (this.parent) { this.parent.clear(); } }; // Find the position of the marker in the document. Returns a {from, // to} object by default. Side can be passed to get a specific side // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the // Pos objects returned contain a line object, rather than a line // number (used to prevent looking up the same line twice). TextMarker.prototype.find = function (side, lineObj) { if (side == null && this.type == "bookmark") { side = 1; } var from, to; for (var i = 0; i < this.lines.length; ++i) { var line = this.lines[i]; var span = getMarkedSpanFor(line.markedSpans, this); if (span.from != null) { from = Pos(lineObj ? line : lineNo(line), span.from); if (side == -1) { return from } } if (span.to != null) { to = Pos(lineObj ? line : lineNo(line), span.to); if (side == 1) { return to } } } return from && {from: from, to: to} }; // Signals that the marker's widget changed, and surrounding layout // should be recomputed. TextMarker.prototype.changed = function () { var this$1 = this; var pos = this.find(-1, true), widget = this, cm = this.doc.cm; if (!pos || !cm) { return } runInOp(cm, function () { var line = pos.line, lineN = lineNo(pos.line); var view = findViewForLine(cm, lineN); if (view) { clearLineMeasurementCacheFor(view); cm.curOp.selectionChanged = cm.curOp.forceUpdate = true; } cm.curOp.updateMaxLine = true; if (!lineIsHidden(widget.doc, line) && widget.height != null) { var oldHeight = widget.height; widget.height = null; var dHeight = widgetHeight(widget) - oldHeight; if (dHeight) { updateLineHeight(line, line.height + dHeight); } } signalLater(cm, "markerChanged", cm, this$1); }); }; TextMarker.prototype.attachLine = function (line) { if (!this.lines.length && this.doc.cm) { var op = this.doc.cm.curOp; if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); } } this.lines.push(line); }; TextMarker.prototype.detachLine = function (line) { this.lines.splice(indexOf(this.lines, line), 1); if (!this.lines.length && this.doc.cm) { var op = this.doc.cm.curOp ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this); } }; eventMixin(TextMarker); // Create a marker, wire it up to the right lines, and function markText(doc, from, to, options, type) { // Shared markers (across linked documents) are handled separately // (markTextShared will call out to this again, once per // document). if (options && options.shared) { return markTextShared(doc, from, to, options, type) } // Ensure we are in an operation. if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) } var marker = new TextMarker(doc, type), diff = cmp(from, to); if (options) { copyObj(options, marker, false); } // Don't connect empty markers unless clearWhenEmpty is false if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false) { return marker } if (marker.replacedWith) { // Showing up as a widget implies collapsed (widget replaces text) marker.collapsed = true; marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget"); if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true"); } if (options.insertLeft) { marker.widgetNode.insertLeft = true; } } if (marker.collapsed) { if (conflictingCollapsedRange(doc, from.line, from, to, marker) || from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker)) { throw new Error("Inserting collapsed marker partially overlapping an existing one") } seeCollapsedSpans(); } if (marker.addToHistory) { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); } var curLine = from.line, cm = doc.cm, updateMaxLine; doc.iter(curLine, to.line + 1, function (line) { if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine) { updateMaxLine = true; } if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); } addMarkedSpan(line, new MarkedSpan(marker, curLine == from.line ? from.ch : null, curLine == to.line ? to.ch : null), doc.cm && doc.cm.curOp); ++curLine; }); // lineIsHidden depends on the presence of the spans, so needs a second pass if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) { if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); } }); } if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); } if (marker.readOnly) { seeReadOnlySpans(); if (doc.history.done.length || doc.history.undone.length) { doc.clearHistory(); } } if (marker.collapsed) { marker.id = ++nextMarkerId; marker.atomic = true; } if (cm) { // Sync editor state if (updateMaxLine) { cm.curOp.updateMaxLine = true; } if (marker.collapsed) { regChange(cm, from.line, to.line + 1); } else if (marker.className || marker.startStyle || marker.endStyle || marker.css || marker.attributes || marker.title) { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text"); } } if (marker.atomic) { reCheckSelection(cm.doc); } signalLater(cm, "markerAdded", cm, marker); } return marker } // SHARED TEXTMARKERS // A shared marker spans multiple linked documents. It is // implemented as a meta-marker-object controlling multiple normal // markers. var SharedTextMarker = function(markers, primary) { this.markers = markers; this.primary = primary; for (var i = 0; i < markers.length; ++i) { markers[i].parent = this; } }; SharedTextMarker.prototype.clear = function () { if (this.explicitlyCleared) { return } this.explicitlyCleared = true; for (var i = 0; i < this.markers.length; ++i) { this.markers[i].clear(); } signalLater(this, "clear"); }; SharedTextMarker.prototype.find = function (side, lineObj) { return this.primary.find(side, lineObj) }; eventMixin(SharedTextMarker); function markTextShared(doc, from, to, options, type) { options = copyObj(options); options.shared = false; var markers = [markText(doc, from, to, options, type)], primary = markers[0]; var widget = options.widgetNode; linkedDocs(doc, function (doc) { if (widget) { options.widgetNode = widget.cloneNode(true); } markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type)); for (var i = 0; i < doc.linked.length; ++i) { if (doc.linked[i].isParent) { return } } primary = lst(markers); }); return new SharedTextMarker(markers, primary) } function findSharedMarkers(doc) { return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; }) } function copySharedMarkers(doc, markers) { for (var i = 0; i < markers.length; i++) { var marker = markers[i], pos = marker.find(); var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to); if (cmp(mFrom, mTo)) { var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type); marker.markers.push(subMark); subMark.parent = marker; } } } function detachSharedMarkers(markers) { var loop = function ( i ) { var marker = markers[i], linked = [marker.primary.doc]; linkedDocs(marker.primary.doc, function (d) { return linked.push(d); }); for (var j = 0; j < marker.markers.length; j++) { var subMarker = marker.markers[j]; if (indexOf(linked, subMarker.doc) == -1) { subMarker.parent = null; marker.markers.splice(j--, 1); } } }; for (var i = 0; i < markers.length; i++) loop( i ); } var nextDocId = 0; var Doc = function(text, mode, firstLine, lineSep, direction) { if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) } if (firstLine == null) { firstLine = 0; } BranchChunk.call(this, [new LeafChunk([new Line("", null)])]); this.first = firstLine; this.scrollTop = this.scrollLeft = 0; this.cantEdit = false; this.cleanGeneration = 1; this.modeFrontier = this.highlightFrontier = firstLine; var start = Pos(firstLine, 0); this.sel = simpleSelection(start); this.history = new History(null); this.id = ++nextDocId; this.modeOption = mode; this.lineSep = lineSep; this.direction = (direction == "rtl") ? "rtl" : "ltr"; this.extend = false; if (typeof text == "string") { text = this.splitLines(text); } updateDoc(this, {from: start, to: start, text: text}); setSelection(this, simpleSelection(start), sel_dontScroll); }; Doc.prototype = createObj(BranchChunk.prototype, { constructor: Doc, // Iterate over the document. Supports two forms -- with only one // argument, it calls that for each line in the document. With // three, it iterates over the range given by the first two (with // the second being non-inclusive). iter: function(from, to, op) { if (op) { this.iterN(from - this.first, to - from, op); } else { this.iterN(this.first, this.first + this.size, from); } }, // Non-public interface for adding and removing lines. insert: function(at, lines) { var height = 0; for (var i = 0; i < lines.length; ++i) { height += lines[i].height; } this.insertInner(at - this.first, lines, height); }, remove: function(at, n) { this.removeInner(at - this.first, n); }, // From here, the methods are part of the public interface. Most // are also available from CodeMirror (editor) instances. getValue: function(lineSep) { var lines = getLines(this, this.first, this.first + this.size); if (lineSep === false) { return lines } return lines.join(lineSep || this.lineSeparator()) }, setValue: docMethodOp(function(code) { var top = Pos(this.first, 0), last = this.first + this.size - 1; makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length), text: this.splitLines(code), origin: "setValue", full: true}, true); if (this.cm) { scrollToCoords(this.cm, 0, 0); } setSelection(this, simpleSelection(top), sel_dontScroll); }), replaceRange: function(code, from, to, origin) { from = clipPos(this, from); to = to ? clipPos(this, to) : from; replaceRange(this, code, from, to, origin); }, getRange: function(from, to, lineSep) { var lines = getBetween(this, clipPos(this, from), clipPos(this, to)); if (lineSep === false) { return lines } if (lineSep === '') { return lines.join('') } return lines.join(lineSep || this.lineSeparator()) }, getLine: function(line) {var l = this.getLineHandle(line); return l && l.text}, getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }}, getLineNumber: function(line) {return lineNo(line)}, getLineHandleVisualStart: function(line) { if (typeof line == "number") { line = getLine(this, line); } return visualLine(line) }, lineCount: function() {return this.size}, firstLine: function() {return this.first}, lastLine: function() {return this.first + this.size - 1}, clipPos: function(pos) {return clipPos(this, pos)}, getCursor: function(start) { var range = this.sel.primary(), pos; if (start == null || start == "head") { pos = range.head; } else if (start == "anchor") { pos = range.anchor; } else if (start == "end" || start == "to" || start === false) { pos = range.to(); } else { pos = range.from(); } return pos }, listSelections: function() { return this.sel.ranges }, somethingSelected: function() {return this.sel.somethingSelected()}, setCursor: docMethodOp(function(line, ch, options) { setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options); }), setSelection: docMethodOp(function(anchor, head, options) { setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options); }), extendSelection: docMethodOp(function(head, other, options) { extendSelection(this, clipPos(this, head), other && clipPos(this, other), options); }), extendSelections: docMethodOp(function(heads, options) { extendSelections(this, clipPosArray(this, heads), options); }), extendSelectionsBy: docMethodOp(function(f, options) { var heads = map(this.sel.ranges, f); extendSelections(this, clipPosArray(this, heads), options); }), setSelections: docMethodOp(function(ranges, primary, options) { if (!ranges.length) { return } var out = []; for (var i = 0; i < ranges.length; i++) { out[i] = new Range(clipPos(this, ranges[i].anchor), clipPos(this, ranges[i].head || ranges[i].anchor)); } if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); } setSelection(this, normalizeSelection(this.cm, out, primary), options); }), addSelection: docMethodOp(function(anchor, head, options) { var ranges = this.sel.ranges.slice(0); ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor))); setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options); }), getSelection: function(lineSep) { var ranges = this.sel.ranges, lines; for (var i = 0; i < ranges.length; i++) { var sel = getBetween(this, ranges[i].from(), ranges[i].to()); lines = lines ? lines.concat(sel) : sel; } if (lineSep === false) { return lines } else { return lines.join(lineSep || this.lineSeparator()) } }, getSelections: function(lineSep) { var parts = [], ranges = this.sel.ranges; for (var i = 0; i < ranges.length; i++) { var sel = getBetween(this, ranges[i].from(), ranges[i].to()); if (lineSep !== false) { sel = sel.join(lineSep || this.lineSeparator()); } parts[i] = sel; } return parts }, replaceSelection: function(code, collapse, origin) { var dup = []; for (var i = 0; i < this.sel.ranges.length; i++) { dup[i] = code; } this.replaceSelections(dup, collapse, origin || "+input"); }, replaceSelections: docMethodOp(function(code, collapse, origin) { var changes = [], sel = this.sel; for (var i = 0; i < sel.ranges.length; i++) { var range = sel.ranges[i]; changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin}; } var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse); for (var i$1 = changes.length - 1; i$1 >= 0; i$1--) { makeChange(this, changes[i$1]); } if (newSel) { setSelectionReplaceHistory(this, newSel); } else if (this.cm) { ensureCursorVisible(this.cm); } }), undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}), redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}), undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}), redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}), setExtending: function(val) {this.extend = val;}, getExtending: function() {return this.extend}, historySize: function() { var hist = this.history, done = 0, undone = 0; for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } } for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } } return {undo: done, redo: undone} }, clearHistory: function() { var this$1 = this; this.history = new History(this.history); linkedDocs(this, function (doc) { return doc.history = this$1.history; }, true); }, markClean: function() { this.cleanGeneration = this.changeGeneration(true); }, changeGeneration: function(forceSplit) { if (forceSplit) { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; } return this.history.generation }, isClean: function (gen) { return this.history.generation == (gen || this.cleanGeneration) }, getHistory: function() { return {done: copyHistoryArray(this.history.done), undone: copyHistoryArray(this.history.undone)} }, setHistory: function(histData) { var hist = this.history = new History(this.history); hist.done = copyHistoryArray(histData.done.slice(0), null, true); hist.undone = copyHistoryArray(histData.undone.slice(0), null, true); }, setGutterMarker: docMethodOp(function(line, gutterID, value) { return changeLine(this, line, "gutter", function (line) { var markers = line.gutterMarkers || (line.gutterMarkers = {}); markers[gutterID] = value; if (!value && isEmpty(markers)) { line.gutterMarkers = null; } return true }) }), clearGutter: docMethodOp(function(gutterID) { var this$1 = this; this.iter(function (line) { if (line.gutterMarkers && line.gutterMarkers[gutterID]) { changeLine(this$1, line, "gutter", function () { line.gutterMarkers[gutterID] = null; if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; } return true }); } }); }), lineInfo: function(line) { var n; if (typeof line == "number") { if (!isLine(this, line)) { return null } n = line; line = getLine(this, line); if (!line) { return null } } else { n = lineNo(line); if (n == null) { return null } } return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers, textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass, widgets: line.widgets} }, addLineClass: docMethodOp(function(handle, where, cls) { return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : where == "gutter" ? "gutterClass" : "wrapClass"; if (!line[prop]) { line[prop] = cls; } else if (classTest(cls).test(line[prop])) { return false } else { line[prop] += " " + cls; } return true }) }), removeLineClass: docMethodOp(function(handle, where, cls) { return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : where == "gutter" ? "gutterClass" : "wrapClass"; var cur = line[prop]; if (!cur) { return false } else if (cls == null) { line[prop] = null; } else { var found = cur.match(classTest(cls)); if (!found) { return false } var end = found.index + found[0].length; line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null; } return true }) }), addLineWidget: docMethodOp(function(handle, node, options) { return addLineWidget(this, handle, node, options) }), removeLineWidget: function(widget) { widget.clear(); }, markText: function(from, to, options) { return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range") }, setBookmark: function(pos, options) { var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options), insertLeft: options && options.insertLeft, clearWhenEmpty: false, shared: options && options.shared, handleMouseEvents: options && options.handleMouseEvents}; pos = clipPos(this, pos); return markText(this, pos, pos, realOpts, "bookmark") }, findMarksAt: function(pos) { pos = clipPos(this, pos); var markers = [], spans = getLine(this, pos.line).markedSpans; if (spans) { for (var i = 0; i < spans.length; ++i) { var span = spans[i]; if ((span.from == null || span.from <= pos.ch) && (span.to == null || span.to >= pos.ch)) { markers.push(span.marker.parent || span.marker); } } } return markers }, findMarks: function(from, to, filter) { from = clipPos(this, from); to = clipPos(this, to); var found = [], lineNo = from.line; this.iter(from.line, to.line + 1, function (line) { var spans = line.markedSpans; if (spans) { for (var i = 0; i < spans.length; i++) { var span = spans[i]; if (!(span.to != null && lineNo == from.line && from.ch >= span.to || span.from == null && lineNo != from.line || span.from != null && lineNo == to.line && span.from >= to.ch) && (!filter || filter(span.marker))) { found.push(span.marker.parent || span.marker); } } } ++lineNo; }); return found }, getAllMarks: function() { var markers = []; this.iter(function (line) { var sps = line.markedSpans; if (sps) { for (var i = 0; i < sps.length; ++i) { if (sps[i].from != null) { markers.push(sps[i].marker); } } } }); return markers }, posFromIndex: function(off) { var ch, lineNo = this.first, sepSize = this.lineSeparator().length; this.iter(function (line) { var sz = line.text.length + sepSize; if (sz > off) { ch = off; return true } off -= sz; ++lineNo; }); return clipPos(this, Pos(lineNo, ch)) }, indexFromPos: function (coords) { coords = clipPos(this, coords); var index = coords.ch; if (coords.line < this.first || coords.ch < 0) { return 0 } var sepSize = this.lineSeparator().length; this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value index += line.text.length + sepSize; }); return index }, copy: function(copyHistory) { var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first, this.lineSep, this.direction); doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft; doc.sel = this.sel; doc.extend = false; if (copyHistory) { doc.history.undoDepth = this.history.undoDepth; doc.setHistory(this.getHistory()); } return doc }, linkedDoc: function(options) { if (!options) { options = {}; } var from = this.first, to = this.first + this.size; if (options.from != null && options.from > from) { from = options.from; } if (options.to != null && options.to < to) { to = options.to; } var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction); if (options.sharedHist) { copy.history = this.history ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist}); copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}]; copySharedMarkers(copy, findSharedMarkers(this)); return copy }, unlinkDoc: function(other) { if (other instanceof CodeMirror) { other = other.doc; } if (this.linked) { for (var i = 0; i < this.linked.length; ++i) { var link = this.linked[i]; if (link.doc != other) { continue } this.linked.splice(i, 1); other.unlinkDoc(this); detachSharedMarkers(findSharedMarkers(this)); break } } // If the histories were shared, split them again if (other.history == this.history) { var splitIds = [other.id]; linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true); other.history = new History(null); other.history.done = copyHistoryArray(this.history.done, splitIds); other.history.undone = copyHistoryArray(this.history.undone, splitIds); } }, iterLinkedDocs: function(f) {linkedDocs(this, f);}, getMode: function() {return this.mode}, getEditor: function() {return this.cm}, splitLines: function(str) { if (this.lineSep) { return str.split(this.lineSep) } return splitLinesAuto(str) }, lineSeparator: function() { return this.lineSep || "\n" }, setDirection: docMethodOp(function (dir) { if (dir != "rtl") { dir = "ltr"; } if (dir == this.direction) { return } this.direction = dir; this.iter(function (line) { return line.order = null; }); if (this.cm) { directionChanged(this.cm); } }) }); // Public alias. Doc.prototype.eachLine = Doc.prototype.iter; // Kludge to work around strange IE behavior where it'll sometimes // re-fire a series of drag-related events right after the drop (#1551) var lastDrop = 0; function onDrop(e) { var cm = this; clearDragCursor(cm); if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return } e_preventDefault(e); if (ie) { lastDrop = +new Date; } var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files; if (!pos || cm.isReadOnly()) { return } // Might be a file drop, in which case we simply extract the text // and insert it. if (files && files.length && window.FileReader && window.File) { var n = files.length, text = Array(n), read = 0; var markAsReadAndPasteIfAllFilesAreRead = function () { if (++read == n) { operation(cm, function () { pos = clipPos(cm.doc, pos); var change = {from: pos, to: pos, text: cm.doc.splitLines( text.filter(function (t) { return t != null; }).join(cm.doc.lineSeparator())), origin: "paste"}; makeChange(cm.doc, change); setSelectionReplaceHistory(cm.doc, simpleSelection(clipPos(cm.doc, pos), clipPos(cm.doc, changeEnd(change)))); })(); } }; var readTextFromFile = function (file, i) { if (cm.options.allowDropFileTypes && indexOf(cm.options.allowDropFileTypes, file.type) == -1) { markAsReadAndPasteIfAllFilesAreRead(); return } var reader = new FileReader; reader.onerror = function () { return markAsReadAndPasteIfAllFilesAreRead(); }; reader.onload = function () { var content = reader.result; if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { markAsReadAndPasteIfAllFilesAreRead(); return } text[i] = content; markAsReadAndPasteIfAllFilesAreRead(); }; reader.readAsText(file); }; for (var i = 0; i < files.length; i++) { readTextFromFile(files[i], i); } } else { // Normal drop // Don't do a replace if the drop happened inside of the selected text. if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) { cm.state.draggingText(e); // Ensure the editor is re-focused setTimeout(function () { return cm.display.input.focus(); }, 20); return } try { var text$1 = e.dataTransfer.getData("Text"); if (text$1) { var selected; if (cm.state.draggingText && !cm.state.draggingText.copy) { selected = cm.listSelections(); } setSelectionNoUndo(cm.doc, simpleSelection(pos, pos)); if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1) { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); } } cm.replaceSelection(text$1, "around", "paste"); cm.display.input.focus(); } } catch(e$1){} } } function onDragStart(cm, e) { if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return } if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return } e.dataTransfer.setData("Text", cm.getSelection()); e.dataTransfer.effectAllowed = "copyMove"; // Use dummy image instead of default browsers image. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there. if (e.dataTransfer.setDragImage && !safari) { var img = elt("img", null, null, "position: fixed; left: 0; top: 0;"); img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; if (presto) { img.width = img.height = 1; cm.display.wrapper.appendChild(img); // Force a relayout, or Opera won't use our image for some obscure reason img._top = img.offsetTop; } e.dataTransfer.setDragImage(img, 0, 0); if (presto) { img.parentNode.removeChild(img); } } } function onDragOver(cm, e) { var pos = posFromMouse(cm, e); if (!pos) { return } var frag = document.createDocumentFragment(); drawSelectionCursor(cm, pos, frag); if (!cm.display.dragCursor) { cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors"); cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv); } removeChildrenAndAdd(cm.display.dragCursor, frag); } function clearDragCursor(cm) { if (cm.display.dragCursor) { cm.display.lineSpace.removeChild(cm.display.dragCursor); cm.display.dragCursor = null; } } // These must be handled carefully, because naively registering a // handler for each editor will cause the editors to never be // garbage collected. function forEachCodeMirror(f) { if (!document.getElementsByClassName) { return } var byClass = document.getElementsByClassName("CodeMirror"), editors = []; for (var i = 0; i < byClass.length; i++) { var cm = byClass[i].CodeMirror; if (cm) { editors.push(cm); } } if (editors.length) { editors[0].operation(function () { for (var i = 0; i < editors.length; i++) { f(editors[i]); } }); } } var globalsRegistered = false; function ensureGlobalHandlers() { if (globalsRegistered) { return } registerGlobalHandlers(); globalsRegistered = true; } function registerGlobalHandlers() { // When the window resizes, we need to refresh active editors. var resizeTimer; on(window, "resize", function () { if (resizeTimer == null) { resizeTimer = setTimeout(function () { resizeTimer = null; forEachCodeMirror(onResize); }, 100); } }); // When the window loses focus, we want to show the editor as blurred on(window, "blur", function () { return forEachCodeMirror(onBlur); }); } // Called when the window resizes function onResize(cm) { var d = cm.display; // Might be a text scaling operation, clear size caches. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; d.scrollbarsClipped = false; cm.setSize(); } var keyNames = { 3: "Pause", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt", 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End", 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert", 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 145: "ScrollLock", 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", 221: "]", 222: "'", 224: "Mod", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete", 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert" }; // Number keys for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); } // Alphabetic keys for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); } // Function keys for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; } var keyMap = {}; keyMap.basic = { "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown", "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown", "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore", "Tab": "defaultTab", "Shift-Tab": "indentAuto", "Enter": "newlineAndIndent", "Insert": "toggleOverwrite", "Esc": "singleSelection" }; // Note that the save and find-related commands aren't defined by // default. User code or addons can define them. Unknown commands // are simply ignored. keyMap.pcDefault = { "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo", "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown", "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd", "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find", "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll", "Ctrl-[": "indentLess", "Ctrl-]": "indentMore", "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection", "fallthrough": "basic" }; // Very basic readline/emacs-style bindings, which are standard on Mac. keyMap.emacsy = { "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars", "Ctrl-O": "openLine" }; keyMap.macDefault = { "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo", "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft", "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore", "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find", "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll", "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight", "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd", "fallthrough": ["basic", "emacsy"] }; keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; // KEYMAP DISPATCH function normalizeKeyName(name) { var parts = name.split(/-(?!$)/); name = parts[parts.length - 1]; var alt, ctrl, shift, cmd; for (var i = 0; i < parts.length - 1; i++) { var mod = parts[i]; if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; } else if (/^a(lt)?$/i.test(mod)) { alt = true; } else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; } else if (/^s(hift)?$/i.test(mod)) { shift = true; } else { throw new Error("Unrecognized modifier name: " + mod) } } if (alt) { name = "Alt-" + name; } if (ctrl) { name = "Ctrl-" + name; } if (cmd) { name = "Cmd-" + name; } if (shift) { name = "Shift-" + name; } return name } // This is a kludge to keep keymaps mostly working as raw objects // (backwards compatibility) while at the same time support features // like normalization and multi-stroke key bindings. It compiles a // new normalized keymap, and then updates the old object to reflect // this. function normalizeKeyMap(keymap) { var copy = {}; for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) { var value = keymap[keyname]; if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue } if (value == "...") { delete keymap[keyname]; continue } var keys = map(keyname.split(" "), normalizeKeyName); for (var i = 0; i < keys.length; i++) { var val = (void 0), name = (void 0); if (i == keys.length - 1) { name = keys.join(" "); val = value; } else { name = keys.slice(0, i + 1).join(" "); val = "..."; } var prev = copy[name]; if (!prev) { copy[name] = val; } else if (prev != val) { throw new Error("Inconsistent bindings for " + name) } } delete keymap[keyname]; } } for (var prop in copy) { keymap[prop] = copy[prop]; } return keymap } function lookupKey(key, map, handle, context) { map = getKeyMap(map); var found = map.call ? map.call(key, context) : map[key]; if (found === false) { return "nothing" } if (found === "...") { return "multi" } if (found != null && handle(found)) { return "handled" } if (map.fallthrough) { if (Object.prototype.toString.call(map.fallthrough) != "[object Array]") { return lookupKey(key, map.fallthrough, handle, context) } for (var i = 0; i < map.fallthrough.length; i++) { var result = lookupKey(key, map.fallthrough[i], handle, context); if (result) { return result } } } } // Modifier key presses don't count as 'real' key presses for the // purpose of keymap fallthrough. function isModifierKey(value) { var name = typeof value == "string" ? value : keyNames[value.keyCode]; return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod" } function addModifierNames(name, event, noShift) { var base = name; if (event.altKey && base != "Alt") { name = "Alt-" + name; } if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name; } if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Mod") { name = "Cmd-" + name; } if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name; } return name } // Look up the name of a key as indicated by an event object. function keyName(event, noShift) { if (presto && event.keyCode == 34 && event["char"]) { return false } var name = keyNames[event.keyCode]; if (name == null || event.altGraphKey) { return false } // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause, // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+) if (event.keyCode == 3 && event.code) { name = event.code; } return addModifierNames(name, event, noShift) } function getKeyMap(val) { return typeof val == "string" ? keyMap[val] : val } // Helper for deleting text near the selection(s), used to implement // backspace, delete, and similar functionality. function deleteNearSelection(cm, compute) { var ranges = cm.doc.sel.ranges, kill = []; // Build up a set of ranges to kill first, merging overlapping // ranges. for (var i = 0; i < ranges.length; i++) { var toKill = compute(ranges[i]); while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) { var replaced = kill.pop(); if (cmp(replaced.from, toKill.from) < 0) { toKill.from = replaced.from; break } } kill.push(toKill); } // Next, remove those actual ranges. runInOp(cm, function () { for (var i = kill.length - 1; i >= 0; i--) { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); } ensureCursorVisible(cm); }); } function moveCharLogically(line, ch, dir) { var target = skipExtendingChars(line.text, ch + dir, dir); return target < 0 || target > line.text.length ? null : target } function moveLogically(line, start, dir) { var ch = moveCharLogically(line, start.ch, dir); return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before") } function endOfLine(visually, cm, lineObj, lineNo, dir) { if (visually) { if (cm.doc.direction == "rtl") { dir = -dir; } var order = getOrder(lineObj, cm.doc.direction); if (order) { var part = dir < 0 ? lst(order) : order[0]; var moveInStorageOrder = (dir < 0) == (part.level == 1); var sticky = moveInStorageOrder ? "after" : "before"; var ch; // With a wrapped rtl chunk (possibly spanning multiple bidi parts), // it could be that the last bidi part is not on the last visual line, // since visual lines contain content order-consecutive chunks. // Thus, in rtl, we are looking for the first (content-order) character // in the rtl chunk that is on the last line (that is, the same line // as the last (content-order) character). if (part.level > 0 || cm.doc.direction == "rtl") { var prep = prepareMeasureForLine(cm, lineObj); ch = dir < 0 ? lineObj.text.length - 1 : 0; var targetTop = measureCharPrepared(cm, prep, ch).top; ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch); if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1); } } else { ch = dir < 0 ? part.to : part.from; } return new Pos(lineNo, ch, sticky) } } return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after") } function moveVisually(cm, line, start, dir) { var bidi = getOrder(line, cm.doc.direction); if (!bidi) { return moveLogically(line, start, dir) } if (start.ch >= line.text.length) { start.ch = line.text.length; start.sticky = "before"; } else if (start.ch <= 0) { start.ch = 0; start.sticky = "after"; } var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos]; if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) { // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines, // nothing interesting happens. return moveLogically(line, start, dir) } var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); }; var prep; var getWrappedLineExtent = function (ch) { if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} } prep = prep || prepareMeasureForLine(cm, line); return wrappedLineExtentChar(cm, line, prep, ch) }; var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch); if (cm.doc.direction == "rtl" || part.level == 1) { var moveInStorageOrder = (part.level == 1) == (dir < 0); var ch = mv(start, moveInStorageOrder ? 1 : -1); if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) { // Case 2: We move within an rtl part or in an rtl editor on the same visual line var sticky = moveInStorageOrder ? "before" : "after"; return new Pos(start.line, ch, sticky) } } // Case 3: Could not move within this bidi part in this visual line, so leave // the current bidi part var searchInVisualLine = function (partPos, dir, wrappedLineExtent) { var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder ? new Pos(start.line, mv(ch, 1), "before") : new Pos(start.line, ch, "after"); }; for (; partPos >= 0 && partPos < bidi.length; partPos += dir) { var part = bidi[partPos]; var moveInStorageOrder = (dir > 0) == (part.level != 1); var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1); if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) } ch = moveInStorageOrder ? part.from : mv(part.to, -1); if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) } } }; // Case 3a: Look for other bidi parts on the same visual line var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent); if (res) { return res } // Case 3b: Look for other bidi parts on the next visual line var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1); if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) { res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh)); if (res) { return res } } // Case 4: Nowhere to move return null } // Commands are parameter-less actions that can be performed on an // editor, mostly used for keybindings. var commands = { selectAll: selectAll, singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); }, killLine: function (cm) { return deleteNearSelection(cm, function (range) { if (range.empty()) { var len = getLine(cm.doc, range.head.line).text.length; if (range.head.ch == len && range.head.line < cm.lastLine()) { return {from: range.head, to: Pos(range.head.line + 1, 0)} } else { return {from: range.head, to: Pos(range.head.line, len)} } } else { return {from: range.from(), to: range.to()} } }); }, deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({ from: Pos(range.from().line, 0), to: clipPos(cm.doc, Pos(range.to().line + 1, 0)) }); }); }, delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({ from: Pos(range.from().line, 0), to: range.from() }); }); }, delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { var top = cm.charCoords(range.head, "div").top + 5; var leftPos = cm.coordsChar({left: 0, top: top}, "div"); return {from: leftPos, to: range.from()} }); }, delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) { var top = cm.charCoords(range.head, "div").top + 5; var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"); return {from: range.from(), to: rightPos } }); }, undo: function (cm) { return cm.undo(); }, redo: function (cm) { return cm.redo(); }, undoSelection: function (cm) { return cm.undoSelection(); }, redoSelection: function (cm) { return cm.redoSelection(); }, goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); }, goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); }, goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); }, {origin: "+move", bias: 1} ); }, goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); }, {origin: "+move", bias: 1} ); }, goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); }, {origin: "+move", bias: -1} ); }, goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) { var top = cm.cursorCoords(range.head, "div").top + 5; return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div") }, sel_move); }, goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) { var top = cm.cursorCoords(range.head, "div").top + 5; return cm.coordsChar({left: 0, top: top}, "div") }, sel_move); }, goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) { var top = cm.cursorCoords(range.head, "div").top + 5; var pos = cm.coordsChar({left: 0, top: top}, "div"); if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) } return pos }, sel_move); }, goLineUp: function (cm) { return cm.moveV(-1, "line"); }, goLineDown: function (cm) { return cm.moveV(1, "line"); }, goPageUp: function (cm) { return cm.moveV(-1, "page"); }, goPageDown: function (cm) { return cm.moveV(1, "page"); }, goCharLeft: function (cm) { return cm.moveH(-1, "char"); }, goCharRight: function (cm) { return cm.moveH(1, "char"); }, goColumnLeft: function (cm) { return cm.moveH(-1, "column"); }, goColumnRight: function (cm) { return cm.moveH(1, "column"); }, goWordLeft: function (cm) { return cm.moveH(-1, "word"); }, goGroupRight: function (cm) { return cm.moveH(1, "group"); }, goGroupLeft: function (cm) { return cm.moveH(-1, "group"); }, goWordRight: function (cm) { return cm.moveH(1, "word"); }, delCharBefore: function (cm) { return cm.deleteH(-1, "codepoint"); }, delCharAfter: function (cm) { return cm.deleteH(1, "char"); }, delWordBefore: function (cm) { return cm.deleteH(-1, "word"); }, delWordAfter: function (cm) { return cm.deleteH(1, "word"); }, delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); }, delGroupAfter: function (cm) { return cm.deleteH(1, "group"); }, indentAuto: function (cm) { return cm.indentSelection("smart"); }, indentMore: function (cm) { return cm.indentSelection("add"); }, indentLess: function (cm) { return cm.indentSelection("subtract"); }, insertTab: function (cm) { return cm.replaceSelection("\t"); }, insertSoftTab: function (cm) { var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize; for (var i = 0; i < ranges.length; i++) { var pos = ranges[i].from(); var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize); spaces.push(spaceStr(tabSize - col % tabSize)); } cm.replaceSelections(spaces); }, defaultTab: function (cm) { if (cm.somethingSelected()) { cm.indentSelection("add"); } else { cm.execCommand("insertTab"); } }, // Swap the two chars left and right of each selection's head. // Move cursor behind the two swapped characters afterwards. // // Doesn't consider line feeds a character. // Doesn't scan more than one line above to find a character. // Doesn't do anything on an empty line. // Doesn't do anything with non-empty selections. transposeChars: function (cm) { return runInOp(cm, function () { var ranges = cm.listSelections(), newSel = []; for (var i = 0; i < ranges.length; i++) { if (!ranges[i].empty()) { continue } var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text; if (line) { if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); } if (cur.ch > 0) { cur = new Pos(cur.line, cur.ch + 1); cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2), Pos(cur.line, cur.ch - 2), cur, "+transpose"); } else if (cur.line > cm.doc.first) { var prev = getLine(cm.doc, cur.line - 1).text; if (prev) { cur = new Pos(cur.line, 1); cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() + prev.charAt(prev.length - 1), Pos(cur.line - 1, prev.length - 1), cur, "+transpose"); } } } newSel.push(new Range(cur, cur)); } cm.setSelections(newSel); }); }, newlineAndIndent: function (cm) { return runInOp(cm, function () { var sels = cm.listSelections(); for (var i = sels.length - 1; i >= 0; i--) { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); } sels = cm.listSelections(); for (var i$1 = 0; i$1 < sels.length; i$1++) { cm.indentLine(sels[i$1].from().line, null, true); } ensureCursorVisible(cm); }); }, openLine: function (cm) { return cm.replaceSelection("\n", "start"); }, toggleOverwrite: function (cm) { return cm.toggleOverwrite(); } }; function lineStart(cm, lineN) { var line = getLine(cm.doc, lineN); var visual = visualLine(line); if (visual != line) { lineN = lineNo(visual); } return endOfLine(true, cm, visual, lineN, 1) } function lineEnd(cm, lineN) { var line = getLine(cm.doc, lineN); var visual = visualLineEnd(line); if (visual != line) { lineN = lineNo(visual); } return endOfLine(true, cm, line, lineN, -1) } function lineStartSmart(cm, pos) { var start = lineStart(cm, pos.line); var line = getLine(cm.doc, start.line); var order = getOrder(line, cm.doc.direction); if (!order || order[0].level == 0) { var firstNonWS = Math.max(start.ch, line.text.search(/\S/)); var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch; return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky) } return start } // Run a handler that was bound to a key. function doHandleBinding(cm, bound, dropShift) { if (typeof bound == "string") { bound = commands[bound]; if (!bound) { return false } } // Ensure previous input has been read, so that the handler sees a // consistent view of the document cm.display.input.ensurePolled(); var prevShift = cm.display.shift, done = false; try { if (cm.isReadOnly()) { cm.state.suppressEdits = true; } if (dropShift) { cm.display.shift = false; } done = bound(cm) != Pass; } finally { cm.display.shift = prevShift; cm.state.suppressEdits = false; } return done } function lookupKeyForEditor(cm, name, handle) { for (var i = 0; i < cm.state.keyMaps.length; i++) { var result = lookupKey(name, cm.state.keyMaps[i], handle, cm); if (result) { return result } } return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm)) || lookupKey(name, cm.options.keyMap, handle, cm) } // Note that, despite the name, this function is also used to check // for bound mouse clicks. var stopSeq = new Delayed; function dispatchKey(cm, name, e, handle) { var seq = cm.state.keySeq; if (seq) { if (isModifierKey(name)) { return "handled" } if (/\'$/.test(name)) { cm.state.keySeq = null; } else { stopSeq.set(50, function () { if (cm.state.keySeq == seq) { cm.state.keySeq = null; cm.display.input.reset(); } }); } if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { return true } } return dispatchKeyInner(cm, name, e, handle) } function dispatchKeyInner(cm, name, e, handle) { var result = lookupKeyForEditor(cm, name, handle); if (result == "multi") { cm.state.keySeq = name; } if (result == "handled") { signalLater(cm, "keyHandled", cm, name, e); } if (result == "handled" || result == "multi") { e_preventDefault(e); restartBlink(cm); } return !!result } // Handle a key from the keydown event. function handleKeyBinding(cm, e) { var name = keyName(e, true); if (!name) { return false } if (e.shiftKey && !cm.state.keySeq) { // First try to resolve full name (including 'Shift-'). Failing // that, see if there is a cursor-motion command (starting with // 'go') bound to the keyname without 'Shift-'. return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); }) || dispatchKey(cm, name, e, function (b) { if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion) { return doHandleBinding(cm, b) } }) } else { return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); }) } } // Handle a key from the keypress event function handleCharBinding(cm, e, ch) { return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); }) } var lastStoppedKey = null; function onKeyDown(e) { var cm = this; if (e.target && e.target != cm.display.input.getField()) { return } cm.curOp.focus = activeElt(doc(cm)); if (signalDOMEvent(cm, e)) { return } // IE does strange things with escape. if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; } var code = e.keyCode; cm.display.shift = code == 16 || e.shiftKey; var handled = handleKeyBinding(cm, e); if (presto) { lastStoppedKey = handled ? code : null; // Opera has no cut event... we try to at least catch the key combo if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) { cm.replaceSelection("", null, "cut"); } } if (gecko && !mac && !handled && code == 46 && e.shiftKey && !e.ctrlKey && document.execCommand) { document.execCommand("cut"); } // Turn mouse into crosshair when Alt is held on Mac. if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)) { showCrossHair(cm); } } function showCrossHair(cm) { var lineDiv = cm.display.lineDiv; addClass(lineDiv, "CodeMirror-crosshair"); function up(e) { if (e.keyCode == 18 || !e.altKey) { rmClass(lineDiv, "CodeMirror-crosshair"); off(document, "keyup", up); off(document, "mouseover", up); } } on(document, "keyup", up); on(document, "mouseover", up); } function onKeyUp(e) { if (e.keyCode == 16) { this.doc.sel.shift = false; } signalDOMEvent(this, e); } function onKeyPress(e) { var cm = this; if (e.target && e.target != cm.display.input.getField()) { return } if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return } var keyCode = e.keyCode, charCode = e.charCode; if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return} if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return } var ch = String.fromCharCode(charCode == null ? keyCode : charCode); // Some browsers fire keypress events for backspace if (ch == "\x08") { return } if (handleCharBinding(cm, e, ch)) { return } cm.display.input.onKeyPress(e); } var DOUBLECLICK_DELAY = 400; var PastClick = function(time, pos, button) { this.time = time; this.pos = pos; this.button = button; }; PastClick.prototype.compare = function (time, pos, button) { return this.time + DOUBLECLICK_DELAY > time && cmp(pos, this.pos) == 0 && button == this.button }; var lastClick, lastDoubleClick; function clickRepeat(pos, button) { var now = +new Date; if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) { lastClick = lastDoubleClick = null; return "triple" } else if (lastClick && lastClick.compare(now, pos, button)) { lastDoubleClick = new PastClick(now, pos, button); lastClick = null; return "double" } else { lastClick = new PastClick(now, pos, button); lastDoubleClick = null; return "single" } } // A mouse down can be a single click, double click, triple click, // start of selection drag, start of text drag, new cursor // (ctrl-click), rectangle drag (alt-drag), or xwin // middle-click-paste. Or it might be a click on something we should // not interfere with, such as a scrollbar or widget. function onMouseDown(e) { var cm = this, display = cm.display; if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return } display.input.ensurePolled(); display.shift = e.shiftKey; if (eventInWidget(display, e)) { if (!webkit) { // Briefly turn off draggability, to allow widgets to do // normal dragging things. display.scroller.draggable = false; setTimeout(function () { return display.scroller.draggable = true; }, 100); } return } if (clickInGutter(cm, e)) { return } var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single"; win(cm).focus(); // #3261: make sure, that we're not starting a second selection if (button == 1 && cm.state.selectingText) { cm.state.selectingText(e); } if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return } if (button == 1) { if (pos) { leftButtonDown(cm, pos, repeat, e); } else if (e_target(e) == display.scroller) { e_preventDefault(e); } } else if (button == 2) { if (pos) { extendSelection(cm.doc, pos); } setTimeout(function () { return display.input.focus(); }, 20); } else if (button == 3) { if (captureRightClick) { cm.display.input.onContextMenu(e); } else { delayBlurEvent(cm); } } } function handleMappedButton(cm, button, pos, repeat, event) { var name = "Click"; if (repeat == "double") { name = "Double" + name; } else if (repeat == "triple") { name = "Triple" + name; } name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name; return dispatchKey(cm, addModifierNames(name, event), event, function (bound) { if (typeof bound == "string") { bound = commands[bound]; } if (!bound) { return false } var done = false; try { if (cm.isReadOnly()) { cm.state.suppressEdits = true; } done = bound(cm, pos) != Pass; } finally { cm.state.suppressEdits = false; } return done }) } function configureMouse(cm, repeat, event) { var option = cm.getOption("configureMouse"); var value = option ? option(cm, repeat, event) : {}; if (value.unit == null) { var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey; value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line"; } if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; } if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; } if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); } return value } function leftButtonDown(cm, pos, repeat, event) { if (ie) { setTimeout(bind(ensureFocus, cm), 0); } else { cm.curOp.focus = activeElt(doc(cm)); } var behavior = configureMouse(cm, repeat, event); var sel = cm.doc.sel, contained; if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() && repeat == "single" && (contained = sel.contains(pos)) > -1 && (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) && (cmp(contained.to(), pos) > 0 || pos.xRel < 0)) { leftButtonStartDrag(cm, event, pos, behavior); } else { leftButtonSelect(cm, event, pos, behavior); } } // Start a text drag. When it ends, see if any dragging actually // happen, and treat as a click if it didn't. function leftButtonStartDrag(cm, event, pos, behavior) { var display = cm.display, moved = false; var dragEnd = operation(cm, function (e) { if (webkit) { display.scroller.draggable = false; } cm.state.draggingText = false; if (cm.state.delayingBlurEvent) { if (cm.hasFocus()) { cm.state.delayingBlurEvent = false; } else { delayBlurEvent(cm); } } off(display.wrapper.ownerDocument, "mouseup", dragEnd); off(display.wrapper.ownerDocument, "mousemove", mouseMove); off(display.scroller, "dragstart", dragStart); off(display.scroller, "drop", dragEnd); if (!moved) { e_preventDefault(e); if (!behavior.addNew) { extendSelection(cm.doc, pos, null, null, behavior.extend); } // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081) if ((webkit && !safari) || ie && ie_version == 9) { setTimeout(function () {display.wrapper.ownerDocument.body.focus({preventScroll: true}); display.input.focus();}, 20); } else { display.input.focus(); } } }); var mouseMove = function(e2) { moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10; }; var dragStart = function () { return moved = true; }; // Let the drag handler handle this. if (webkit) { display.scroller.draggable = true; } cm.state.draggingText = dragEnd; dragEnd.copy = !behavior.moveOnDrag; on(display.wrapper.ownerDocument, "mouseup", dragEnd); on(display.wrapper.ownerDocument, "mousemove", mouseMove); on(display.scroller, "dragstart", dragStart); on(display.scroller, "drop", dragEnd); cm.state.delayingBlurEvent = true; setTimeout(function () { return display.input.focus(); }, 20); // IE's approach to draggable if (display.scroller.dragDrop) { display.scroller.dragDrop(); } } function rangeForUnit(cm, pos, unit) { if (unit == "char") { return new Range(pos, pos) } if (unit == "word") { return cm.findWordAt(pos) } if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) } var result = unit(cm, pos); return new Range(result.from, result.to) } // Normal selection, as opposed to text dragging. function leftButtonSelect(cm, event, start, behavior) { if (ie) { delayBlurEvent(cm); } var display = cm.display, doc$1 = cm.doc; e_preventDefault(event); var ourRange, ourIndex, startSel = doc$1.sel, ranges = startSel.ranges; if (behavior.addNew && !behavior.extend) { ourIndex = doc$1.sel.contains(start); if (ourIndex > -1) { ourRange = ranges[ourIndex]; } else { ourRange = new Range(start, start); } } else { ourRange = doc$1.sel.primary(); ourIndex = doc$1.sel.primIndex; } if (behavior.unit == "rectangle") { if (!behavior.addNew) { ourRange = new Range(start, start); } start = posFromMouse(cm, event, true, true); ourIndex = -1; } else { var range = rangeForUnit(cm, start, behavior.unit); if (behavior.extend) { ourRange = extendRange(ourRange, range.anchor, range.head, behavior.extend); } else { ourRange = range; } } if (!behavior.addNew) { ourIndex = 0; setSelection(doc$1, new Selection([ourRange], 0), sel_mouse); startSel = doc$1.sel; } else if (ourIndex == -1) { ourIndex = ranges.length; setSelection(doc$1, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex), {scroll: false, origin: "*mouse"}); } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) { setSelection(doc$1, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0), {scroll: false, origin: "*mouse"}); startSel = doc$1.sel; } else { replaceOneSelection(doc$1, ourIndex, ourRange, sel_mouse); } var lastPos = start; function extendTo(pos) { if (cmp(lastPos, pos) == 0) { return } lastPos = pos; if (behavior.unit == "rectangle") { var ranges = [], tabSize = cm.options.tabSize; var startCol = countColumn(getLine(doc$1, start.line).text, start.ch, tabSize); var posCol = countColumn(getLine(doc$1, pos.line).text, pos.ch, tabSize); var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol); for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line)); line <= end; line++) { var text = getLine(doc$1, line).text, leftPos = findColumn(text, left, tabSize); if (left == right) { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); } else if (text.length > leftPos) { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); } } if (!ranges.length) { ranges.push(new Range(start, start)); } setSelection(doc$1, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex), {origin: "*mouse", scroll: false}); cm.scrollIntoView(pos); } else { var oldRange = ourRange; var range = rangeForUnit(cm, pos, behavior.unit); var anchor = oldRange.anchor, head; if (cmp(range.anchor, anchor) > 0) { head = range.head; anchor = minPos(oldRange.from(), range.anchor); } else { head = range.anchor; anchor = maxPos(oldRange.to(), range.head); } var ranges$1 = startSel.ranges.slice(0); ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc$1, anchor), head)); setSelection(doc$1, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse); } } var editorSize = display.wrapper.getBoundingClientRect(); // Used to ensure timeout re-tries don't fire when another extend // happened in the meantime (clearTimeout isn't reliable -- at // least on Chrome, the timeouts still happen even when cleared, // if the clear happens after their scheduled firing time). var counter = 0; function extend(e) { var curCount = ++counter; var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle"); if (!cur) { return } if (cmp(cur, lastPos) != 0) { cm.curOp.focus = activeElt(doc(cm)); extendTo(cur); var visible = visibleLines(display, doc$1); if (cur.line >= visible.to || cur.line < visible.from) { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); } } else { var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0; if (outside) { setTimeout(operation(cm, function () { if (counter != curCount) { return } display.scroller.scrollTop += outside; extend(e); }), 50); } } } function done(e) { cm.state.selectingText = false; counter = Infinity; // If e is null or undefined we interpret this as someone trying // to explicitly cancel the selection rather than the user // letting go of the mouse button. if (e) { e_preventDefault(e); display.input.focus(); } off(display.wrapper.ownerDocument, "mousemove", move); off(display.wrapper.ownerDocument, "mouseup", up); doc$1.history.lastSelOrigin = null; } var move = operation(cm, function (e) { if (e.buttons === 0 || !e_button(e)) { done(e); } else { extend(e); } }); var up = operation(cm, done); cm.state.selectingText = up; on(display.wrapper.ownerDocument, "mousemove", move); on(display.wrapper.ownerDocument, "mouseup", up); } // Used when mouse-selecting to adjust the anchor to the proper side // of a bidi jump depending on the visual position of the head. function bidiSimplify(cm, range) { var anchor = range.anchor; var head = range.head; var anchorLine = getLine(cm.doc, anchor.line); if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range } var order = getOrder(anchorLine); if (!order) { return range } var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index]; if (part.from != anchor.ch && part.to != anchor.ch) { return range } var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1); if (boundary == 0 || boundary == order.length) { return range } // Compute the relative visual position of the head compared to the // anchor (<0 is to the left, >0 to the right) var leftSide; if (head.line != anchor.line) { leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0; } else { var headIndex = getBidiPartAt(order, head.ch, head.sticky); var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1); if (headIndex == boundary - 1 || headIndex == boundary) { leftSide = dir < 0; } else { leftSide = dir > 0; } } var usePart = order[boundary + (leftSide ? -1 : 0)]; var from = leftSide == (usePart.level == 1); var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before"; return anchor.ch == ch && anchor.sticky == sticky ? range : new Range(new Pos(anchor.line, ch, sticky), head) } // Determines whether an event happened in the gutter, and fires the // handlers for the corresponding event. function gutterEvent(cm, e, type, prevent) { var mX, mY; if (e.touches) { mX = e.touches[0].clientX; mY = e.touches[0].clientY; } else { try { mX = e.clientX; mY = e.clientY; } catch(e$1) { return false } } if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false } if (prevent) { e_preventDefault(e); } var display = cm.display; var lineBox = display.lineDiv.getBoundingClientRect(); if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) } mY -= lineBox.top - display.viewOffset; for (var i = 0; i < cm.display.gutterSpecs.length; ++i) { var g = display.gutters.childNodes[i]; if (g && g.getBoundingClientRect().right >= mX) { var line = lineAtHeight(cm.doc, mY); var gutter = cm.display.gutterSpecs[i]; signal(cm, type, cm, line, gutter.className, e); return e_defaultPrevented(e) } } } function clickInGutter(cm, e) { return gutterEvent(cm, e, "gutterClick", true) } // CONTEXT MENU HANDLING // To make the context menu work, we need to briefly unhide the // textarea (making it as unobtrusive as possible) to let the // right-click take effect on it. function onContextMenu(cm, e) { if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return } if (signalDOMEvent(cm, e, "contextmenu")) { return } if (!captureRightClick) { cm.display.input.onContextMenu(e); } } function contextMenuInGutter(cm, e) { if (!hasHandler(cm, "gutterContextMenu")) { return false } return gutterEvent(cm, e, "gutterContextMenu", false) } function themeChanged(cm) { cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") + cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-"); clearCaches(cm); } var Init = {toString: function(){return "CodeMirror.Init"}}; var defaults = {}; var optionHandlers = {}; function defineOptions(CodeMirror) { var optionHandlers = CodeMirror.optionHandlers; function option(name, deflt, handle, notOnInit) { CodeMirror.defaults[name] = deflt; if (handle) { optionHandlers[name] = notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; } } CodeMirror.defineOption = option; // Passed to option handlers when there is no old value. CodeMirror.Init = Init; // These two are, on init, called from the constructor because they // have to be initialized before the editor can start at all. option("value", "", function (cm, val) { return cm.setValue(val); }, true); option("mode", null, function (cm, val) { cm.doc.modeOption = val; loadMode(cm); }, true); option("indentUnit", 2, loadMode, true); option("indentWithTabs", false); option("smartIndent", true); option("tabSize", 4, function (cm) { resetModeState(cm); clearCaches(cm); regChange(cm); }, true); option("lineSeparator", null, function (cm, val) { cm.doc.lineSep = val; if (!val) { return } var newBreaks = [], lineNo = cm.doc.first; cm.doc.iter(function (line) { for (var pos = 0;;) { var found = line.text.indexOf(val, pos); if (found == -1) { break } pos = found + val.length; newBreaks.push(Pos(lineNo, found)); } lineNo++; }); for (var i = newBreaks.length - 1; i >= 0; i--) { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); } }); option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b\u200e\u200f\u2028\u2029\u202d\u202e\u2066\u2067\u2069\ufeff\ufff9-\ufffc]/g, function (cm, val, old) { cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g"); if (old != Init) { cm.refresh(); } }); option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true); option("electricChars", true); option("inputStyle", mobile ? "contenteditable" : "textarea", function () { throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME }, true); option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true); option("autocorrect", false, function (cm, val) { return cm.getInputField().autocorrect = val; }, true); option("autocapitalize", false, function (cm, val) { return cm.getInputField().autocapitalize = val; }, true); option("rtlMoveVisually", !windows); option("wholeLineUpdateBefore", true); option("theme", "default", function (cm) { themeChanged(cm); updateGutters(cm); }, true); option("keyMap", "default", function (cm, val, old) { var next = getKeyMap(val); var prev = old != Init && getKeyMap(old); if (prev && prev.detach) { prev.detach(cm, next); } if (next.attach) { next.attach(cm, prev || null); } }); option("extraKeys", null); option("configureMouse", null); option("lineWrapping", false, wrappingChanged, true); option("gutters", [], function (cm, val) { cm.display.gutterSpecs = getGutters(val, cm.options.lineNumbers); updateGutters(cm); }, true); option("fixedGutter", true, function (cm, val) { cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0"; cm.refresh(); }, true); option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true); option("scrollbarStyle", "native", function (cm) { initScrollbars(cm); updateScrollbars(cm); cm.display.scrollbars.setScrollTop(cm.doc.scrollTop); cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft); }, true); option("lineNumbers", false, function (cm, val) { cm.display.gutterSpecs = getGutters(cm.options.gutters, val); updateGutters(cm); }, true); option("firstLineNumber", 1, updateGutters, true); option("lineNumberFormatter", function (integer) { return integer; }, updateGutters, true); option("showCursorWhenSelecting", false, updateSelection, true); option("resetSelectionOnContextMenu", true); option("lineWiseCopyCut", true); option("pasteLinesPerSelection", true); option("selectionsMayTouch", false); option("readOnly", false, function (cm, val) { if (val == "nocursor") { onBlur(cm); cm.display.input.blur(); } cm.display.input.readOnlyChanged(val); }); option("screenReaderLabel", null, function (cm, val) { val = (val === '') ? null : val; cm.display.input.screenReaderLabelChanged(val); }); option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true); option("dragDrop", true, dragDropChanged); option("allowDropFileTypes", null); option("cursorBlinkRate", 530); option("cursorScrollMargin", 0); option("cursorHeight", 1, updateSelection, true); option("singleCursorHeightPerLine", true, updateSelection, true); option("workTime", 100); option("workDelay", 100); option("flattenSpans", true, resetModeState, true); option("addModeClass", false, resetModeState, true); option("pollInterval", 100); option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; }); option("historyEventDelay", 1250); option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true); option("maxHighlightLength", 10000, resetModeState, true); option("moveInputWithCursor", true, function (cm, val) { if (!val) { cm.display.input.resetPosition(); } }); option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; }); option("autofocus", null); option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true); option("phrases", null); } function dragDropChanged(cm, value, old) { var wasOn = old && old != Init; if (!value != !wasOn) { var funcs = cm.display.dragFunctions; var toggle = value ? on : off; toggle(cm.display.scroller, "dragstart", funcs.start); toggle(cm.display.scroller, "dragenter", funcs.enter); toggle(cm.display.scroller, "dragover", funcs.over); toggle(cm.display.scroller, "dragleave", funcs.leave); toggle(cm.display.scroller, "drop", funcs.drop); } } function wrappingChanged(cm) { if (cm.options.lineWrapping) { addClass(cm.display.wrapper, "CodeMirror-wrap"); cm.display.sizer.style.minWidth = ""; cm.display.sizerWidth = null; } else { rmClass(cm.display.wrapper, "CodeMirror-wrap"); findMaxLine(cm); } estimateLineHeights(cm); regChange(cm); clearCaches(cm); setTimeout(function () { return updateScrollbars(cm); }, 100); } // A CodeMirror instance represents an editor. This is the object // that user code is usually dealing with. function CodeMirror(place, options) { var this$1 = this; if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) } this.options = options = options ? copyObj(options) : {}; // Determine effective options based on given values and defaults. copyObj(defaults, options, false); var doc = options.value; if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); } else if (options.mode) { doc.modeOption = options.mode; } this.doc = doc; var input = new CodeMirror.inputStyles[options.inputStyle](this); var display = this.display = new Display(place, doc, input, options); display.wrapper.CodeMirror = this; themeChanged(this); if (options.lineWrapping) { this.display.wrapper.className += " CodeMirror-wrap"; } initScrollbars(this); this.state = { keyMaps: [], // stores maps added by addKeyMap overlays: [], // highlighting overlays, as added by addOverlay modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info overwrite: false, delayingBlurEvent: false, focused: false, suppressEdits: false, // used to disable editing during key handlers when in readOnly mode pasteIncoming: -1, cutIncoming: -1, // help recognize paste/cut edits in input.poll selectingText: false, draggingText: false, highlight: new Delayed(), // stores highlight worker timeout keySeq: null, // Unfinished key sequence specialChars: null }; if (options.autofocus && !mobile) { display.input.focus(); } // Override magic textarea content restore that IE sometimes does // on our hidden textarea on reload if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); } registerEventHandlers(this); ensureGlobalHandlers(); startOperation(this); this.curOp.forceUpdate = true; attachDoc(this, doc); if ((options.autofocus && !mobile) || this.hasFocus()) { setTimeout(function () { if (this$1.hasFocus() && !this$1.state.focused) { onFocus(this$1); } }, 20); } else { onBlur(this); } for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt)) { optionHandlers[opt](this, options[opt], Init); } } maybeUpdateLineNumberWidth(this); if (options.finishInit) { options.finishInit(this); } for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this); } endOperation(this); // Suppress optimizelegibility in Webkit, since it breaks text // measuring on line wrapping boundaries. if (webkit && options.lineWrapping && getComputedStyle(display.lineDiv).textRendering == "optimizelegibility") { display.lineDiv.style.textRendering = "auto"; } } // The default configuration options. CodeMirror.defaults = defaults; // Functions to run when options are changed. CodeMirror.optionHandlers = optionHandlers; // Attach the necessary event handlers when initializing the editor function registerEventHandlers(cm) { var d = cm.display; on(d.scroller, "mousedown", operation(cm, onMouseDown)); // Older IE's will not fire a second mousedown for a double click if (ie && ie_version < 11) { on(d.scroller, "dblclick", operation(cm, function (e) { if (signalDOMEvent(cm, e)) { return } var pos = posFromMouse(cm, e); if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return } e_preventDefault(e); var word = cm.findWordAt(pos); extendSelection(cm.doc, word.anchor, word.head); })); } else { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); } // Some browsers fire contextmenu *after* opening the menu, at // which point we can't mess with it anymore. Context menu is // handled in onMouseDown for these browsers. on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); }); on(d.input.getField(), "contextmenu", function (e) { if (!d.scroller.contains(e.target)) { onContextMenu(cm, e); } }); // Used to suppress mouse event handling when a touch happens var touchFinished, prevTouch = {end: 0}; function finishTouch() { if (d.activeTouch) { touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000); prevTouch = d.activeTouch; prevTouch.end = +new Date; } } function isMouseLikeTouchEvent(e) { if (e.touches.length != 1) { return false } var touch = e.touches[0]; return touch.radiusX <= 1 && touch.radiusY <= 1 } function farAway(touch, other) { if (other.left == null) { return true } var dx = other.left - touch.left, dy = other.top - touch.top; return dx * dx + dy * dy > 20 * 20 } on(d.scroller, "touchstart", function (e) { if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) { d.input.ensurePolled(); clearTimeout(touchFinished); var now = +new Date; d.activeTouch = {start: now, moved: false, prev: now - prevTouch.end <= 300 ? prevTouch : null}; if (e.touches.length == 1) { d.activeTouch.left = e.touches[0].pageX; d.activeTouch.top = e.touches[0].pageY; } } }); on(d.scroller, "touchmove", function () { if (d.activeTouch) { d.activeTouch.moved = true; } }); on(d.scroller, "touchend", function (e) { var touch = d.activeTouch; if (touch && !eventInWidget(d, e) && touch.left != null && !touch.moved && new Date - touch.start < 300) { var pos = cm.coordsChar(d.activeTouch, "page"), range; if (!touch.prev || farAway(touch, touch.prev)) // Single tap { range = new Range(pos, pos); } else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap { range = cm.findWordAt(pos); } else // Triple tap { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); } cm.setSelection(range.anchor, range.head); cm.focus(); e_preventDefault(e); } finishTouch(); }); on(d.scroller, "touchcancel", finishTouch); // Sync scrolling between fake scrollbars and real scrollable // area, ensure viewport is updated when scrolling. on(d.scroller, "scroll", function () { if (d.scroller.clientHeight) { updateScrollTop(cm, d.scroller.scrollTop); setScrollLeft(cm, d.scroller.scrollLeft, true); signal(cm, "scroll", cm); } }); // Listen to wheel events in order to try and update the viewport on time. on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); }); on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); }); // Prevent wrapper from ever scrolling on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; }); d.dragFunctions = { enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }}, over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }}, start: function (e) { return onDragStart(cm, e); }, drop: operation(cm, onDrop), leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }} }; var inp = d.input.getField(); on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); }); on(inp, "keydown", operation(cm, onKeyDown)); on(inp, "keypress", operation(cm, onKeyPress)); on(inp, "focus", function (e) { return onFocus(cm, e); }); on(inp, "blur", function (e) { return onBlur(cm, e); }); } var initHooks = []; CodeMirror.defineInitHook = function (f) { return initHooks.push(f); }; // Indent the given line. The how parameter can be "smart", // "add"/null, "subtract", or "prev". When aggressive is false // (typically set to true for forced single-line indents), empty // lines are not indented, and places where the mode returns Pass // are left alone. function indentLine(cm, n, how, aggressive) { var doc = cm.doc, state; if (how == null) { how = "add"; } if (how == "smart") { // Fall back to "prev" when the mode doesn't have an indentation // method. if (!doc.mode.indent) { how = "prev"; } else { state = getContextBefore(cm, n).state; } } var tabSize = cm.options.tabSize; var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize); if (line.stateAfter) { line.stateAfter = null; } var curSpaceString = line.text.match(/^\s*/)[0], indentation; if (!aggressive && !/\S/.test(line.text)) { indentation = 0; how = "not"; } else if (how == "smart") { indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text); if (indentation == Pass || indentation > 150) { if (!aggressive) { return } how = "prev"; } } if (how == "prev") { if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); } else { indentation = 0; } } else if (how == "add") { indentation = curSpace + cm.options.indentUnit; } else if (how == "subtract") { indentation = curSpace - cm.options.indentUnit; } else if (typeof how == "number") { indentation = curSpace + how; } indentation = Math.max(0, indentation); var indentString = "", pos = 0; if (cm.options.indentWithTabs) { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} } if (pos < indentation) { indentString += spaceStr(indentation - pos); } if (indentString != curSpaceString) { replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input"); line.stateAfter = null; return true } else { // Ensure that, if the cursor was in the whitespace at the start // of the line, it is moved to the end of that space. for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) { var range = doc.sel.ranges[i$1]; if (range.head.line == n && range.head.ch < curSpaceString.length) { var pos$1 = Pos(n, curSpaceString.length); replaceOneSelection(doc, i$1, new Range(pos$1, pos$1)); break } } } } // This will be set to a {lineWise: bool, text: [string]} object, so // that, when pasting, we know what kind of selections the copied // text was made out of. var lastCopied = null; function setLastCopied(newLastCopied) { lastCopied = newLastCopied; } function applyTextInput(cm, inserted, deleted, sel, origin) { var doc = cm.doc; cm.display.shift = false; if (!sel) { sel = doc.sel; } var recent = +new Date - 200; var paste = origin == "paste" || cm.state.pasteIncoming > recent; var textLines = splitLinesAuto(inserted), multiPaste = null; // When pasting N lines into N selections, insert one line per selection if (paste && sel.ranges.length > 1) { if (lastCopied && lastCopied.text.join("\n") == inserted) { if (sel.ranges.length % lastCopied.text.length == 0) { multiPaste = []; for (var i = 0; i < lastCopied.text.length; i++) { multiPaste.push(doc.splitLines(lastCopied.text[i])); } } } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) { multiPaste = map(textLines, function (l) { return [l]; }); } } var updateInput = cm.curOp.updateInput; // Normal behavior is to insert the new text into every selection for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) { var range = sel.ranges[i$1]; var from = range.from(), to = range.to(); if (range.empty()) { if (deleted && deleted > 0) // Handle deletion { from = Pos(from.line, from.ch - deleted); } else if (cm.state.overwrite && !paste) // Handle overwrite { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); } else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == textLines.join("\n")) { from = to = Pos(from.line, 0); } } var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines, origin: origin || (paste ? "paste" : cm.state.cutIncoming > recent ? "cut" : "+input")}; makeChange(cm.doc, changeEvent); signalLater(cm, "inputRead", cm, changeEvent); } if (inserted && !paste) { triggerElectric(cm, inserted); } ensureCursorVisible(cm); if (cm.curOp.updateInput < 2) { cm.curOp.updateInput = updateInput; } cm.curOp.typing = true; cm.state.pasteIncoming = cm.state.cutIncoming = -1; } function handlePaste(e, cm) { var pasted = e.clipboardData && e.clipboardData.getData("Text"); if (pasted) { e.preventDefault(); if (!cm.isReadOnly() && !cm.options.disableInput && cm.hasFocus()) { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }); } return true } } function triggerElectric(cm, inserted) { // When an 'electric' character is inserted, immediately trigger a reindent if (!cm.options.electricChars || !cm.options.smartIndent) { return } var sel = cm.doc.sel; for (var i = sel.ranges.length - 1; i >= 0; i--) { var range = sel.ranges[i]; if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) { continue } var mode = cm.getModeAt(range.head); var indented = false; if (mode.electricChars) { for (var j = 0; j < mode.electricChars.length; j++) { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) { indented = indentLine(cm, range.head.line, "smart"); break } } } else if (mode.electricInput) { if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch))) { indented = indentLine(cm, range.head.line, "smart"); } } if (indented) { signalLater(cm, "electricInput", cm, range.head.line); } } } function copyableRanges(cm) { var text = [], ranges = []; for (var i = 0; i < cm.doc.sel.ranges.length; i++) { var line = cm.doc.sel.ranges[i].head.line; var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)}; ranges.push(lineRange); text.push(cm.getRange(lineRange.anchor, lineRange.head)); } return {text: text, ranges: ranges} } function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) { field.setAttribute("autocorrect", autocorrect ? "on" : "off"); field.setAttribute("autocapitalize", autocapitalize ? "on" : "off"); field.setAttribute("spellcheck", !!spellcheck); } function hiddenTextarea() { var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; min-height: 1em; outline: none"); var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;"); // The textarea is kept positioned near the cursor to prevent the // fact that it'll be scrolled into view on input from scrolling // our fake cursor out of view. On webkit, when wrap=off, paste is // very slow. So make the area wide instead. if (webkit) { te.style.width = "1000px"; } else { te.setAttribute("wrap", "off"); } // If border: 0; -- iOS fails to open keyboard (issue #1287) if (ios) { te.style.border = "1px solid black"; } return div } // The publicly visible API. Note that methodOp(f) means // 'wrap f in an operation, performed on its `this` parameter'. // This is not the complete set of editor methods. Most of the // methods defined on the Doc type are also injected into // CodeMirror.prototype, for backwards compatibility and // convenience. function addEditorMethods(CodeMirror) { var optionHandlers = CodeMirror.optionHandlers; var helpers = CodeMirror.helpers = {}; CodeMirror.prototype = { constructor: CodeMirror, focus: function(){win(this).focus(); this.display.input.focus();}, setOption: function(option, value) { var options = this.options, old = options[option]; if (options[option] == value && option != "mode") { return } options[option] = value; if (optionHandlers.hasOwnProperty(option)) { operation(this, optionHandlers[option])(this, value, old); } signal(this, "optionChange", this, option); }, getOption: function(option) {return this.options[option]}, getDoc: function() {return this.doc}, addKeyMap: function(map, bottom) { this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map)); }, removeKeyMap: function(map) { var maps = this.state.keyMaps; for (var i = 0; i < maps.length; ++i) { if (maps[i] == map || maps[i].name == map) { maps.splice(i, 1); return true } } }, addOverlay: methodOp(function(spec, options) { var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec); if (mode.startState) { throw new Error("Overlays may not be stateful.") } insertSorted(this.state.overlays, {mode: mode, modeSpec: spec, opaque: options && options.opaque, priority: (options && options.priority) || 0}, function (overlay) { return overlay.priority; }); this.state.modeGen++; regChange(this); }), removeOverlay: methodOp(function(spec) { var overlays = this.state.overlays; for (var i = 0; i < overlays.length; ++i) { var cur = overlays[i].modeSpec; if (cur == spec || typeof spec == "string" && cur.name == spec) { overlays.splice(i, 1); this.state.modeGen++; regChange(this); return } } }), indentLine: methodOp(function(n, dir, aggressive) { if (typeof dir != "string" && typeof dir != "number") { if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev"; } else { dir = dir ? "add" : "subtract"; } } if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); } }), indentSelection: methodOp(function(how) { var ranges = this.doc.sel.ranges, end = -1; for (var i = 0; i < ranges.length; i++) { var range = ranges[i]; if (!range.empty()) { var from = range.from(), to = range.to(); var start = Math.max(end, from.line); end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1; for (var j = start; j < end; ++j) { indentLine(this, j, how); } var newRanges = this.doc.sel.ranges; if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0) { replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); } } else if (range.head.line > end) { indentLine(this, range.head.line, how, true); end = range.head.line; if (i == this.doc.sel.primIndex) { ensureCursorVisible(this); } } } }), // Fetch the parser token for a given character. Useful for hacks // that want to inspect the mode state (say, for completion). getTokenAt: function(pos, precise) { return takeToken(this, pos, precise) }, getLineTokens: function(line, precise) { return takeToken(this, Pos(line), precise, true) }, getTokenTypeAt: function(pos) { pos = clipPos(this.doc, pos); var styles = getLineStyles(this, getLine(this.doc, pos.line)); var before = 0, after = (styles.length - 1) / 2, ch = pos.ch; var type; if (ch == 0) { type = styles[2]; } else { for (;;) { var mid = (before + after) >> 1; if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; } else if (styles[mid * 2 + 1] < ch) { before = mid + 1; } else { type = styles[mid * 2 + 2]; break } } } var cut = type ? type.indexOf("overlay ") : -1; return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1) }, getModeAt: function(pos) { var mode = this.doc.mode; if (!mode.innerMode) { return mode } return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode }, getHelper: function(pos, type) { return this.getHelpers(pos, type)[0] }, getHelpers: function(pos, type) { var found = []; if (!helpers.hasOwnProperty(type)) { return found } var help = helpers[type], mode = this.getModeAt(pos); if (typeof mode[type] == "string") { if (help[mode[type]]) { found.push(help[mode[type]]); } } else if (mode[type]) { for (var i = 0; i < mode[type].length; i++) { var val = help[mode[type][i]]; if (val) { found.push(val); } } } else if (mode.helperType && help[mode.helperType]) { found.push(help[mode.helperType]); } else if (help[mode.name]) { found.push(help[mode.name]); } for (var i$1 = 0; i$1 < help._global.length; i$1++) { var cur = help._global[i$1]; if (cur.pred(mode, this) && indexOf(found, cur.val) == -1) { found.push(cur.val); } } return found }, getStateAfter: function(line, precise) { var doc = this.doc; line = clipLine(doc, line == null ? doc.first + doc.size - 1: line); return getContextBefore(this, line + 1, precise).state }, cursorCoords: function(start, mode) { var pos, range = this.doc.sel.primary(); if (start == null) { pos = range.head; } else if (typeof start == "object") { pos = clipPos(this.doc, start); } else { pos = start ? range.from() : range.to(); } return cursorCoords(this, pos, mode || "page") }, charCoords: function(pos, mode) { return charCoords(this, clipPos(this.doc, pos), mode || "page") }, coordsChar: function(coords, mode) { coords = fromCoordSystem(this, coords, mode || "page"); return coordsChar(this, coords.left, coords.top) }, lineAtHeight: function(height, mode) { height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top; return lineAtHeight(this.doc, height + this.display.viewOffset) }, heightAtLine: function(line, mode, includeWidgets) { var end = false, lineObj; if (typeof line == "number") { var last = this.doc.first + this.doc.size - 1; if (line < this.doc.first) { line = this.doc.first; } else if (line > last) { line = last; end = true; } lineObj = getLine(this.doc, line); } else { lineObj = line; } return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top + (end ? this.doc.height - heightAtLine(lineObj) : 0) }, defaultTextHeight: function() { return textHeight(this.display) }, defaultCharWidth: function() { return charWidth(this.display) }, getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}}, addWidget: function(pos, node, scroll, vert, horiz) { var display = this.display; pos = cursorCoords(this, clipPos(this.doc, pos)); var top = pos.bottom, left = pos.left; node.style.position = "absolute"; node.setAttribute("cm-ignore-events", "true"); this.display.input.setUneditable(node); display.sizer.appendChild(node); if (vert == "over") { top = pos.top; } else if (vert == "above" || vert == "near") { var vspace = Math.max(display.wrapper.clientHeight, this.doc.height), hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth); // Default to positioning above (if specified and possible); otherwise default to positioning below if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight) { top = pos.top - node.offsetHeight; } else if (pos.bottom + node.offsetHeight <= vspace) { top = pos.bottom; } if (left + node.offsetWidth > hspace) { left = hspace - node.offsetWidth; } } node.style.top = top + "px"; node.style.left = node.style.right = ""; if (horiz == "right") { left = display.sizer.clientWidth - node.offsetWidth; node.style.right = "0px"; } else { if (horiz == "left") { left = 0; } else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; } node.style.left = left + "px"; } if (scroll) { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); } }, triggerOnKeyDown: methodOp(onKeyDown), triggerOnKeyPress: methodOp(onKeyPress), triggerOnKeyUp: onKeyUp, triggerOnMouseDown: methodOp(onMouseDown), execCommand: function(cmd) { if (commands.hasOwnProperty(cmd)) { return commands[cmd].call(null, this) } }, triggerElectric: methodOp(function(text) { triggerElectric(this, text); }), findPosH: function(from, amount, unit, visually) { var dir = 1; if (amount < 0) { dir = -1; amount = -amount; } var cur = clipPos(this.doc, from); for (var i = 0; i < amount; ++i) { cur = findPosH(this.doc, cur, dir, unit, visually); if (cur.hitSide) { break } } return cur }, moveH: methodOp(function(dir, unit) { var this$1 = this; this.extendSelectionsBy(function (range) { if (this$1.display.shift || this$1.doc.extend || range.empty()) { return findPosH(this$1.doc, range.head, dir, unit, this$1.options.rtlMoveVisually) } else { return dir < 0 ? range.from() : range.to() } }, sel_move); }), deleteH: methodOp(function(dir, unit) { var sel = this.doc.sel, doc = this.doc; if (sel.somethingSelected()) { doc.replaceSelection("", null, "+delete"); } else { deleteNearSelection(this, function (range) { var other = findPosH(doc, range.head, dir, unit, false); return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other} }); } }), findPosV: function(from, amount, unit, goalColumn) { var dir = 1, x = goalColumn; if (amount < 0) { dir = -1; amount = -amount; } var cur = clipPos(this.doc, from); for (var i = 0; i < amount; ++i) { var coords = cursorCoords(this, cur, "div"); if (x == null) { x = coords.left; } else { coords.left = x; } cur = findPosV(this, coords, dir, unit); if (cur.hitSide) { break } } return cur }, moveV: methodOp(function(dir, unit) { var this$1 = this; var doc = this.doc, goals = []; var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected(); doc.extendSelectionsBy(function (range) { if (collapse) { return dir < 0 ? range.from() : range.to() } var headPos = cursorCoords(this$1, range.head, "div"); if (range.goalColumn != null) { headPos.left = range.goalColumn; } goals.push(headPos.left); var pos = findPosV(this$1, headPos, dir, unit); if (unit == "page" && range == doc.sel.primary()) { addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top); } return pos }, sel_move); if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++) { doc.sel.ranges[i].goalColumn = goals[i]; } } }), // Find the word at the given position (as returned by coordsChar). findWordAt: function(pos) { var doc = this.doc, line = getLine(doc, pos.line).text; var start = pos.ch, end = pos.ch; if (line) { var helper = this.getHelper(pos, "wordChars"); if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end; } var startChar = line.charAt(start); var check = isWordChar(startChar, helper) ? function (ch) { return isWordChar(ch, helper); } : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); } : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); }; while (start > 0 && check(line.charAt(start - 1))) { --start; } while (end < line.length && check(line.charAt(end))) { ++end; } } return new Range(Pos(pos.line, start), Pos(pos.line, end)) }, toggleOverwrite: function(value) { if (value != null && value == this.state.overwrite) { return } if (this.state.overwrite = !this.state.overwrite) { addClass(this.display.cursorDiv, "CodeMirror-overwrite"); } else { rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); } signal(this, "overwriteToggle", this, this.state.overwrite); }, hasFocus: function() { return this.display.input.getField() == activeElt(doc(this)) }, isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) }, scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }), getScrollInfo: function() { var scroller = this.display.scroller; return {left: scroller.scrollLeft, top: scroller.scrollTop, height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight, width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth, clientHeight: displayHeight(this), clientWidth: displayWidth(this)} }, scrollIntoView: methodOp(function(range, margin) { if (range == null) { range = {from: this.doc.sel.primary().head, to: null}; if (margin == null) { margin = this.options.cursorScrollMargin; } } else if (typeof range == "number") { range = {from: Pos(range, 0), to: null}; } else if (range.from == null) { range = {from: range, to: null}; } if (!range.to) { range.to = range.from; } range.margin = margin || 0; if (range.from.line != null) { scrollToRange(this, range); } else { scrollToCoordsRange(this, range.from, range.to, range.margin); } }), setSize: methodOp(function(width, height) { var this$1 = this; var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; }; if (width != null) { this.display.wrapper.style.width = interpret(width); } if (height != null) { this.display.wrapper.style.height = interpret(height); } if (this.options.lineWrapping) { clearLineMeasurementCache(this); } var lineNo = this.display.viewFrom; this.doc.iter(lineNo, this.display.viewTo, function (line) { if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo, "widget"); break } } } ++lineNo; }); this.curOp.forceUpdate = true; signal(this, "refresh", this); }), operation: function(f){return runInOp(this, f)}, startOperation: function(){return startOperation(this)}, endOperation: function(){return endOperation(this)}, refresh: methodOp(function() { var oldHeight = this.display.cachedTextHeight; regChange(this); this.curOp.forceUpdate = true; clearCaches(this); scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop); updateGutterSpace(this.display); if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5 || this.options.lineWrapping) { estimateLineHeights(this); } signal(this, "refresh", this); }), swapDoc: methodOp(function(doc) { var old = this.doc; old.cm = null; // Cancel the current text selection if any (#5821) if (this.state.selectingText) { this.state.selectingText(); } attachDoc(this, doc); clearCaches(this); this.display.input.reset(); scrollToCoords(this, doc.scrollLeft, doc.scrollTop); this.curOp.forceScroll = true; signalLater(this, "swapDoc", this, old); return old }), phrase: function(phraseText) { var phrases = this.options.phrases; return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText }, getInputField: function(){return this.display.input.getField()}, getWrapperElement: function(){return this.display.wrapper}, getScrollerElement: function(){return this.display.scroller}, getGutterElement: function(){return this.display.gutters} }; eventMixin(CodeMirror); CodeMirror.registerHelper = function(type, name, value) { if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; } helpers[type][name] = value; }; CodeMirror.registerGlobalHelper = function(type, name, predicate, value) { CodeMirror.registerHelper(type, name, value); helpers[type]._global.push({pred: predicate, val: value}); }; } // Used for horizontal relative motion. Dir is -1 or 1 (left or // right), unit can be "codepoint", "char", "column" (like char, but // doesn't cross line boundaries), "word" (across next word), or // "group" (to the start of next group of word or // non-word-non-whitespace chars). The visually param controls // whether, in right-to-left text, direction 1 means to move towards // the next index in the string, or towards the character to the right // of the current position. The resulting position will have a // hitSide=true property if it reached the end of the document. function findPosH(doc, pos, dir, unit, visually) { var oldPos = pos; var origDir = dir; var lineObj = getLine(doc, pos.line); var lineDir = visually && doc.direction == "rtl" ? -dir : dir; function findNextLine() { var l = pos.line + lineDir; if (l < doc.first || l >= doc.first + doc.size) { return false } pos = new Pos(l, pos.ch, pos.sticky); return lineObj = getLine(doc, l) } function moveOnce(boundToLine) { var next; if (unit == "codepoint") { var ch = lineObj.text.charCodeAt(pos.ch + (dir > 0 ? 0 : -1)); if (isNaN(ch)) { next = null; } else { var astral = dir > 0 ? ch >= 0xD800 && ch < 0xDC00 : ch >= 0xDC00 && ch < 0xDFFF; next = new Pos(pos.line, Math.max(0, Math.min(lineObj.text.length, pos.ch + dir * (astral ? 2 : 1))), -dir); } } else if (visually) { next = moveVisually(doc.cm, lineObj, pos, dir); } else { next = moveLogically(lineObj, pos, dir); } if (next == null) { if (!boundToLine && findNextLine()) { pos = endOfLine(visually, doc.cm, lineObj, pos.line, lineDir); } else { return false } } else { pos = next; } return true } if (unit == "char" || unit == "codepoint") { moveOnce(); } else if (unit == "column") { moveOnce(true); } else if (unit == "word" || unit == "group") { var sawType = null, group = unit == "group"; var helper = doc.cm && doc.cm.getHelper(pos, "wordChars"); for (var first = true;; first = false) { if (dir < 0 && !moveOnce(!first)) { break } var cur = lineObj.text.charAt(pos.ch) || "\n"; var type = isWordChar(cur, helper) ? "w" : group && cur == "\n" ? "n" : !group || /\s/.test(cur) ? null : "p"; if (group && !first && !type) { type = "s"; } if (sawType && sawType != type) { if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after";} break } if (type) { sawType = type; } if (dir > 0 && !moveOnce(!first)) { break } } } var result = skipAtomic(doc, pos, oldPos, origDir, true); if (equalCursorPos(oldPos, result)) { result.hitSide = true; } return result } // For relative vertical movement. Dir may be -1 or 1. Unit can be // "page" or "line". The resulting position will have a hitSide=true // property if it reached the end of the document. function findPosV(cm, pos, dir, unit) { var doc = cm.doc, x = pos.left, y; if (unit == "page") { var pageSize = Math.min(cm.display.wrapper.clientHeight, win(cm).innerHeight || doc(cm).documentElement.clientHeight); var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3); y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount; } else if (unit == "line") { y = dir > 0 ? pos.bottom + 3 : pos.top - 3; } var target; for (;;) { target = coordsChar(cm, x, y); if (!target.outside) { break } if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break } y += dir * 5; } return target } // CONTENTEDITABLE INPUT STYLE var ContentEditableInput = function(cm) { this.cm = cm; this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null; this.polling = new Delayed(); this.composing = null; this.gracePeriod = false; this.readDOMTimeout = null; }; ContentEditableInput.prototype.init = function (display) { var this$1 = this; var input = this, cm = input.cm; var div = input.div = display.lineDiv; div.contentEditable = true; disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize); function belongsToInput(e) { for (var t = e.target; t; t = t.parentNode) { if (t == div) { return true } if (/\bCodeMirror-(?:line)?widget\b/.test(t.className)) { break } } return false } on(div, "paste", function (e) { if (!belongsToInput(e) || signalDOMEvent(cm, e) || handlePaste(e, cm)) { return } // IE doesn't fire input events, so we schedule a read for the pasted content in this way if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); } }); on(div, "compositionstart", function (e) { this$1.composing = {data: e.data, done: false}; }); on(div, "compositionupdate", function (e) { if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; } }); on(div, "compositionend", function (e) { if (this$1.composing) { if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); } this$1.composing.done = true; } }); on(div, "touchstart", function () { return input.forceCompositionEnd(); }); on(div, "input", function () { if (!this$1.composing) { this$1.readFromDOMSoon(); } }); function onCopyCut(e) { if (!belongsToInput(e) || signalDOMEvent(cm, e)) { return } if (cm.somethingSelected()) { setLastCopied({lineWise: false, text: cm.getSelections()}); if (e.type == "cut") { cm.replaceSelection("", null, "cut"); } } else if (!cm.options.lineWiseCopyCut) { return } else { var ranges = copyableRanges(cm); setLastCopied({lineWise: true, text: ranges.text}); if (e.type == "cut") { cm.operation(function () { cm.setSelections(ranges.ranges, 0, sel_dontScroll); cm.replaceSelection("", null, "cut"); }); } } if (e.clipboardData) { e.clipboardData.clearData(); var content = lastCopied.text.join("\n"); // iOS exposes the clipboard API, but seems to discard content inserted into it e.clipboardData.setData("Text", content); if (e.clipboardData.getData("Text") == content) { e.preventDefault(); return } } // Old-fashioned briefly-focus-a-textarea hack var kludge = hiddenTextarea(), te = kludge.firstChild; disableBrowserMagic(te); cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild); te.value = lastCopied.text.join("\n"); var hadFocus = activeElt(div.ownerDocument); selectInput(te); setTimeout(function () { cm.display.lineSpace.removeChild(kludge); hadFocus.focus(); if (hadFocus == div) { input.showPrimarySelection(); } }, 50); } on(div, "copy", onCopyCut); on(div, "cut", onCopyCut); }; ContentEditableInput.prototype.screenReaderLabelChanged = function (label) { // Label for screenreaders, accessibility if(label) { this.div.setAttribute('aria-label', label); } else { this.div.removeAttribute('aria-label'); } }; ContentEditableInput.prototype.prepareSelection = function () { var result = prepareSelection(this.cm, false); result.focus = activeElt(this.div.ownerDocument) == this.div; return result }; ContentEditableInput.prototype.showSelection = function (info, takeFocus) { if (!info || !this.cm.display.view.length) { return } if (info.focus || takeFocus) { this.showPrimarySelection(); } this.showMultipleSelections(info); }; ContentEditableInput.prototype.getSelection = function () { return this.cm.display.wrapper.ownerDocument.getSelection() }; ContentEditableInput.prototype.showPrimarySelection = function () { var sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary(); var from = prim.from(), to = prim.to(); if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) { sel.removeAllRanges(); return } var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset); if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad && cmp(minPos(curAnchor, curFocus), from) == 0 && cmp(maxPos(curAnchor, curFocus), to) == 0) { return } var view = cm.display.view; var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) || {node: view[0].measure.map[2], offset: 0}; var end = to.line < cm.display.viewTo && posToDOM(cm, to); if (!end) { var measure = view[view.length - 1].measure; var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map; end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]}; } if (!start || !end) { sel.removeAllRanges(); return } var old = sel.rangeCount && sel.getRangeAt(0), rng; try { rng = range(start.node, start.offset, end.offset, end.node); } catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible if (rng) { if (!gecko && cm.state.focused) { sel.collapse(start.node, start.offset); if (!rng.collapsed) { sel.removeAllRanges(); sel.addRange(rng); } } else { sel.removeAllRanges(); sel.addRange(rng); } if (old && sel.anchorNode == null) { sel.addRange(old); } else if (gecko) { this.startGracePeriod(); } } this.rememberSelection(); }; ContentEditableInput.prototype.startGracePeriod = function () { var this$1 = this; clearTimeout(this.gracePeriod); this.gracePeriod = setTimeout(function () { this$1.gracePeriod = false; if (this$1.selectionChanged()) { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); } }, 20); }; ContentEditableInput.prototype.showMultipleSelections = function (info) { removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors); removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection); }; ContentEditableInput.prototype.rememberSelection = function () { var sel = this.getSelection(); this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset; this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset; }; ContentEditableInput.prototype.selectionInEditor = function () { var sel = this.getSelection(); if (!sel.rangeCount) { return false } var node = sel.getRangeAt(0).commonAncestorContainer; return contains(this.div, node) }; ContentEditableInput.prototype.focus = function () { if (this.cm.options.readOnly != "nocursor") { if (!this.selectionInEditor() || activeElt(this.div.ownerDocument) != this.div) { this.showSelection(this.prepareSelection(), true); } this.div.focus(); } }; ContentEditableInput.prototype.blur = function () { this.div.blur(); }; ContentEditableInput.prototype.getField = function () { return this.div }; ContentEditableInput.prototype.supportsTouch = function () { return true }; ContentEditableInput.prototype.receivedFocus = function () { var this$1 = this; var input = this; if (this.selectionInEditor()) { setTimeout(function () { return this$1.pollSelection(); }, 20); } else { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); } function poll() { if (input.cm.state.focused) { input.pollSelection(); input.polling.set(input.cm.options.pollInterval, poll); } } this.polling.set(this.cm.options.pollInterval, poll); }; ContentEditableInput.prototype.selectionChanged = function () { var sel = this.getSelection(); return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset || sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset }; ContentEditableInput.prototype.pollSelection = function () { if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return } var sel = this.getSelection(), cm = this.cm; // On Android Chrome (version 56, at least), backspacing into an // uneditable block element will put the cursor in that element, // and then, because it's not editable, hide the virtual keyboard. // Because Android doesn't allow us to actually detect backspace // presses in a sane way, this code checks for when that happens // and simulates a backspace press in this case. if (android && chrome && this.cm.display.gutterSpecs.length && isInGutter(sel.anchorNode)) { this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs}); this.blur(); this.focus(); return } if (this.composing) { return } this.rememberSelection(); var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); var head = domToPos(cm, sel.focusNode, sel.focusOffset); if (anchor && head) { runInOp(cm, function () { setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll); if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; } }); } }; ContentEditableInput.prototype.pollContent = function () { if (this.readDOMTimeout != null) { clearTimeout(this.readDOMTimeout); this.readDOMTimeout = null; } var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary(); var from = sel.from(), to = sel.to(); if (from.ch == 0 && from.line > cm.firstLine()) { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); } if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine()) { to = Pos(to.line + 1, 0); } if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false } var fromIndex, fromLine, fromNode; if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) { fromLine = lineNo(display.view[0].line); fromNode = display.view[0].node; } else { fromLine = lineNo(display.view[fromIndex].line); fromNode = display.view[fromIndex - 1].node.nextSibling; } var toIndex = findViewIndex(cm, to.line); var toLine, toNode; if (toIndex == display.view.length - 1) { toLine = display.viewTo - 1; toNode = display.lineDiv.lastChild; } else { toLine = lineNo(display.view[toIndex + 1].line) - 1; toNode = display.view[toIndex + 1].node.previousSibling; } if (!fromNode) { return false } var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine)); var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length)); while (newText.length > 1 && oldText.length > 1) { if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; } else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; } else { break } } var cutFront = 0, cutEnd = 0; var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length); while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront)) { ++cutFront; } var newBot = lst(newText), oldBot = lst(oldText); var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0), oldBot.length - (oldText.length == 1 ? cutFront : 0)); while (cutEnd < maxCutEnd && newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) { ++cutEnd; } // Try to move start of change to start of selection if ambiguous if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) { while (cutFront && cutFront > from.ch && newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) { cutFront--; cutEnd++; } } newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, ""); newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, ""); var chFrom = Pos(fromLine, cutFront); var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0); if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) { replaceRange(cm.doc, newText, chFrom, chTo, "+input"); return true } }; ContentEditableInput.prototype.ensurePolled = function () { this.forceCompositionEnd(); }; ContentEditableInput.prototype.reset = function () { this.forceCompositionEnd(); }; ContentEditableInput.prototype.forceCompositionEnd = function () { if (!this.composing) { return } clearTimeout(this.readDOMTimeout); this.composing = null; this.updateFromDOM(); this.div.blur(); this.div.focus(); }; ContentEditableInput.prototype.readFromDOMSoon = function () { var this$1 = this; if (this.readDOMTimeout != null) { return } this.readDOMTimeout = setTimeout(function () { this$1.readDOMTimeout = null; if (this$1.composing) { if (this$1.composing.done) { this$1.composing = null; } else { return } } this$1.updateFromDOM(); }, 80); }; ContentEditableInput.prototype.updateFromDOM = function () { var this$1 = this; if (this.cm.isReadOnly() || !this.pollContent()) { runInOp(this.cm, function () { return regChange(this$1.cm); }); } }; ContentEditableInput.prototype.setUneditable = function (node) { node.contentEditable = "false"; }; ContentEditableInput.prototype.onKeyPress = function (e) { if (e.charCode == 0 || this.composing) { return } e.preventDefault(); if (!this.cm.isReadOnly()) { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); } }; ContentEditableInput.prototype.readOnlyChanged = function (val) { this.div.contentEditable = String(val != "nocursor"); }; ContentEditableInput.prototype.onContextMenu = function () {}; ContentEditableInput.prototype.resetPosition = function () {}; ContentEditableInput.prototype.needsContentAttribute = true; function posToDOM(cm, pos) { var view = findViewForLine(cm, pos.line); if (!view || view.hidden) { return null } var line = getLine(cm.doc, pos.line); var info = mapFromLineView(view, line, pos.line); var order = getOrder(line, cm.doc.direction), side = "left"; if (order) { var partPos = getBidiPartAt(order, pos.ch); side = partPos % 2 ? "right" : "left"; } var result = nodeAndOffsetInLineMap(info.map, pos.ch, side); result.offset = result.collapse == "right" ? result.end : result.start; return result } function isInGutter(node) { for (var scan = node; scan; scan = scan.parentNode) { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } } return false } function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos } function domTextBetween(cm, from, to, fromLine, toLine) { var text = "", closing = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false; function recognizeMarker(id) { return function (marker) { return marker.id == id; } } function close() { if (closing) { text += lineSep; if (extraLinebreak) { text += lineSep; } closing = extraLinebreak = false; } } function addText(str) { if (str) { close(); text += str; } } function walk(node) { if (node.nodeType == 1) { var cmText = node.getAttribute("cm-text"); if (cmText) { addText(cmText); return } var markerID = node.getAttribute("cm-marker"), range; if (markerID) { var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID)); if (found.length && (range = found[0].find(0))) { addText(getBetween(cm.doc, range.from, range.to).join(lineSep)); } return } if (node.getAttribute("contenteditable") == "false") { return } var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName); if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { return } if (isBlock) { close(); } for (var i = 0; i < node.childNodes.length; i++) { walk(node.childNodes[i]); } if (/^(pre|p)$/i.test(node.nodeName)) { extraLinebreak = true; } if (isBlock) { closing = true; } } else if (node.nodeType == 3) { addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " ")); } } for (;;) { walk(from); if (from == to) { break } from = from.nextSibling; extraLinebreak = false; } return text } function domToPos(cm, node, offset) { var lineNode; if (node == cm.display.lineDiv) { lineNode = cm.display.lineDiv.childNodes[offset]; if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) } node = null; offset = 0; } else { for (lineNode = node;; lineNode = lineNode.parentNode) { if (!lineNode || lineNode == cm.display.lineDiv) { return null } if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break } } } for (var i = 0; i < cm.display.view.length; i++) { var lineView = cm.display.view[i]; if (lineView.node == lineNode) { return locateNodeInLineView(lineView, node, offset) } } } function locateNodeInLineView(lineView, node, offset) { var wrapper = lineView.text.firstChild, bad = false; if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) } if (node == wrapper) { bad = true; node = wrapper.childNodes[offset]; offset = 0; if (!node) { var line = lineView.rest ? lst(lineView.rest) : lineView.line; return badPos(Pos(lineNo(line), line.text.length), bad) } } var textNode = node.nodeType == 3 ? node : null, topNode = node; if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) { textNode = node.firstChild; if (offset) { offset = textNode.nodeValue.length; } } while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; } var measure = lineView.measure, maps = measure.maps; function find(textNode, topNode, offset) { for (var i = -1; i < (maps ? maps.length : 0); i++) { var map = i < 0 ? measure.map : maps[i]; for (var j = 0; j < map.length; j += 3) { var curNode = map[j + 2]; if (curNode == textNode || curNode == topNode) { var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]); var ch = map[j] + offset; if (offset < 0 || curNode != textNode) { ch = map[j + (offset ? 1 : 0)]; } return Pos(line, ch) } } } } var found = find(textNode, topNode, offset); if (found) { return badPos(found, bad) } // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) { found = find(after, after.firstChild, 0); if (found) { return badPos(Pos(found.line, found.ch - dist), bad) } else { dist += after.textContent.length; } } for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) { found = find(before, before.firstChild, -1); if (found) { return badPos(Pos(found.line, found.ch + dist$1), bad) } else { dist$1 += before.textContent.length; } } } // TEXTAREA INPUT STYLE var TextareaInput = function(cm) { this.cm = cm; // See input.poll and input.reset this.prevInput = ""; // Flag that indicates whether we expect input to appear real soon // now (after some event like 'keypress' or 'input') and are // polling intensively. this.pollingFast = false; // Self-resetting timeout for the poller this.polling = new Delayed(); // Used to work around IE issue with selection being forgotten when focus moves away from textarea this.hasSelection = false; this.composing = null; this.resetting = false; }; TextareaInput.prototype.init = function (display) { var this$1 = this; var input = this, cm = this.cm; this.createField(display); var te = this.textarea; display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild); // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore) if (ios) { te.style.width = "0px"; } on(te, "input", function () { if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; } input.poll(); }); on(te, "paste", function (e) { if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return } cm.state.pasteIncoming = +new Date; input.fastPoll(); }); function prepareCopyCut(e) { if (signalDOMEvent(cm, e)) { return } if (cm.somethingSelected()) { setLastCopied({lineWise: false, text: cm.getSelections()}); } else if (!cm.options.lineWiseCopyCut) { return } else { var ranges = copyableRanges(cm); setLastCopied({lineWise: true, text: ranges.text}); if (e.type == "cut") { cm.setSelections(ranges.ranges, null, sel_dontScroll); } else { input.prevInput = ""; te.value = ranges.text.join("\n"); selectInput(te); } } if (e.type == "cut") { cm.state.cutIncoming = +new Date; } } on(te, "cut", prepareCopyCut); on(te, "copy", prepareCopyCut); on(display.scroller, "paste", function (e) { if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return } if (!te.dispatchEvent) { cm.state.pasteIncoming = +new Date; input.focus(); return } // Pass the `paste` event to the textarea so it's handled by its event listener. var event = new Event("paste"); event.clipboardData = e.clipboardData; te.dispatchEvent(event); }); // Prevent normal selection in the editor (we handle our own) on(display.lineSpace, "selectstart", function (e) { if (!eventInWidget(display, e)) { e_preventDefault(e); } }); on(te, "compositionstart", function () { var start = cm.getCursor("from"); if (input.composing) { input.composing.range.clear(); } input.composing = { start: start, range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"}) }; }); on(te, "compositionend", function () { if (input.composing) { input.poll(); input.composing.range.clear(); input.composing = null; } }); }; TextareaInput.prototype.createField = function (_display) { // Wraps and hides input textarea this.wrapper = hiddenTextarea(); // The semihidden textarea that is focused when the editor is // focused, and receives input. this.textarea = this.wrapper.firstChild; var opts = this.cm.options; disableBrowserMagic(this.textarea, opts.spellcheck, opts.autocorrect, opts.autocapitalize); }; TextareaInput.prototype.screenReaderLabelChanged = function (label) { // Label for screenreaders, accessibility if(label) { this.textarea.setAttribute('aria-label', label); } else { this.textarea.removeAttribute('aria-label'); } }; TextareaInput.prototype.prepareSelection = function () { // Redraw the selection and/or cursor var cm = this.cm, display = cm.display, doc = cm.doc; var result = prepareSelection(cm); // Move the hidden textarea near the cursor to prevent scrolling artifacts if (cm.options.moveInputWithCursor) { var headPos = cursorCoords(cm, doc.sel.primary().head, "div"); var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect(); result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10, headPos.top + lineOff.top - wrapOff.top)); result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10, headPos.left + lineOff.left - wrapOff.left)); } return result }; TextareaInput.prototype.showSelection = function (drawn) { var cm = this.cm, display = cm.display; removeChildrenAndAdd(display.cursorDiv, drawn.cursors); removeChildrenAndAdd(display.selectionDiv, drawn.selection); if (drawn.teTop != null) { this.wrapper.style.top = drawn.teTop + "px"; this.wrapper.style.left = drawn.teLeft + "px"; } }; // Reset the input to correspond to the selection (or to be empty, // when not typing and nothing is selected) TextareaInput.prototype.reset = function (typing) { if (this.contextMenuPending || this.composing && typing) { return } var cm = this.cm; this.resetting = true; if (cm.somethingSelected()) { this.prevInput = ""; var content = cm.getSelection(); this.textarea.value = content; if (cm.state.focused) { selectInput(this.textarea); } if (ie && ie_version >= 9) { this.hasSelection = content; } } else if (!typing) { this.prevInput = this.textarea.value = ""; if (ie && ie_version >= 9) { this.hasSelection = null; } } this.resetting = false; }; TextareaInput.prototype.getField = function () { return this.textarea }; TextareaInput.prototype.supportsTouch = function () { return false }; TextareaInput.prototype.focus = function () { if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt(this.textarea.ownerDocument) != this.textarea)) { try { this.textarea.focus(); } catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM } }; TextareaInput.prototype.blur = function () { this.textarea.blur(); }; TextareaInput.prototype.resetPosition = function () { this.wrapper.style.top = this.wrapper.style.left = 0; }; TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); }; // Poll for input changes, using the normal rate of polling. This // runs as long as the editor is focused. TextareaInput.prototype.slowPoll = function () { var this$1 = this; if (this.pollingFast) { return } this.polling.set(this.cm.options.pollInterval, function () { this$1.poll(); if (this$1.cm.state.focused) { this$1.slowPoll(); } }); }; // When an event has just come in that is likely to add or change // something in the input textarea, we poll faster, to ensure that // the change appears on the screen quickly. TextareaInput.prototype.fastPoll = function () { var missed = false, input = this; input.pollingFast = true; function p() { var changed = input.poll(); if (!changed && !missed) {missed = true; input.polling.set(60, p);} else {input.pollingFast = false; input.slowPoll();} } input.polling.set(20, p); }; // Read input from the textarea, and update the document to match. // When something is selected, it is present in the textarea, and // selected (unless it is huge, in which case a placeholder is // used). When nothing is selected, the cursor sits after previously // seen text (can be empty), which is stored in prevInput (we must // not reset the textarea when typing, because that breaks IME). TextareaInput.prototype.poll = function () { var this$1 = this; var cm = this.cm, input = this.textarea, prevInput = this.prevInput; // Since this is called a *lot*, try to bail out as cheaply as // possible when it is clear that nothing happened. hasSelection // will be the case when there is a lot of text in the textarea, // in which case reading its value would be expensive. if (this.contextMenuPending || this.resetting || !cm.state.focused || (hasSelection(input) && !prevInput && !this.composing) || cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq) { return false } var text = input.value; // If nothing changed, bail. if (text == prevInput && !cm.somethingSelected()) { return false } // Work around nonsensical selection resetting in IE9/10, and // inexplicable appearance of private area unicode characters on // some key combos in Mac (#2689). if (ie && ie_version >= 9 && this.hasSelection === text || mac && /[\uf700-\uf7ff]/.test(text)) { cm.display.input.reset(); return false } if (cm.doc.sel == cm.display.selForContextMenu) { var first = text.charCodeAt(0); if (first == 0x200b && !prevInput) { prevInput = "\u200b"; } if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") } } // Find the part of the input that is actually new var same = 0, l = Math.min(prevInput.length, text.length); while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; } runInOp(cm, function () { applyTextInput(cm, text.slice(same), prevInput.length - same, null, this$1.composing ? "*compose" : null); // Don't leave long text in the textarea, since it makes further polling slow if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = ""; } else { this$1.prevInput = text; } if (this$1.composing) { this$1.composing.range.clear(); this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"), {className: "CodeMirror-composing"}); } }); return true }; TextareaInput.prototype.ensurePolled = function () { if (this.pollingFast && this.poll()) { this.pollingFast = false; } }; TextareaInput.prototype.onKeyPress = function () { if (ie && ie_version >= 9) { this.hasSelection = null; } this.fastPoll(); }; TextareaInput.prototype.onContextMenu = function (e) { var input = this, cm = input.cm, display = cm.display, te = input.textarea; if (input.contextMenuPending) { input.contextMenuPending(); } var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop; if (!pos || presto) { return } // Opera is difficult. // Reset the current text selection only if the click is done outside of the selection // and 'resetSelectionOnContextMenu' option is true. var reset = cm.options.resetSelectionOnContextMenu; if (reset && cm.doc.sel.contains(pos) == -1) { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); } var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText; var wrapperBox = input.wrapper.offsetParent.getBoundingClientRect(); input.wrapper.style.cssText = "position: static"; te.style.cssText = "position: absolute; width: 30px; height: 30px;\n top: " + (e.clientY - wrapperBox.top - 5) + "px; left: " + (e.clientX - wrapperBox.left - 5) + "px;\n z-index: 1000; background: " + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + ";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);"; var oldScrollY; if (webkit) { oldScrollY = te.ownerDocument.defaultView.scrollY; } // Work around Chrome issue (#2712) display.input.focus(); if (webkit) { te.ownerDocument.defaultView.scrollTo(null, oldScrollY); } display.input.reset(); // Adds "Select all" to context menu in FF if (!cm.somethingSelected()) { te.value = input.prevInput = " "; } input.contextMenuPending = rehide; display.selForContextMenu = cm.doc.sel; clearTimeout(display.detectingSelectAll); // Select-all will be greyed out if there's nothing to select, so // this adds a zero-width space so that we can later check whether // it got selected. function prepareSelectAllHack() { if (te.selectionStart != null) { var selected = cm.somethingSelected(); var extval = "\u200b" + (selected ? te.value : ""); te.value = "\u21da"; // Used to catch context-menu undo te.value = extval; input.prevInput = selected ? "" : "\u200b"; te.selectionStart = 1; te.selectionEnd = extval.length; // Re-set this, in case some other handler touched the // selection in the meantime. display.selForContextMenu = cm.doc.sel; } } function rehide() { if (input.contextMenuPending != rehide) { return } input.contextMenuPending = false; input.wrapper.style.cssText = oldWrapperCSS; te.style.cssText = oldCSS; if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); } // Try to detect the user choosing select-all if (te.selectionStart != null) { if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); } var i = 0, poll = function () { if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 && te.selectionEnd > 0 && input.prevInput == "\u200b") { operation(cm, selectAll)(cm); } else if (i++ < 10) { display.detectingSelectAll = setTimeout(poll, 500); } else { display.selForContextMenu = null; display.input.reset(); } }; display.detectingSelectAll = setTimeout(poll, 200); } } if (ie && ie_version >= 9) { prepareSelectAllHack(); } if (captureRightClick) { e_stop(e); var mouseup = function () { off(window, "mouseup", mouseup); setTimeout(rehide, 20); }; on(window, "mouseup", mouseup); } else { setTimeout(rehide, 50); } }; TextareaInput.prototype.readOnlyChanged = function (val) { if (!val) { this.reset(); } this.textarea.disabled = val == "nocursor"; this.textarea.readOnly = !!val; }; TextareaInput.prototype.setUneditable = function () {}; TextareaInput.prototype.needsContentAttribute = false; function fromTextArea(textarea, options) { options = options ? copyObj(options) : {}; options.value = textarea.value; if (!options.tabindex && textarea.tabIndex) { options.tabindex = textarea.tabIndex; } if (!options.placeholder && textarea.placeholder) { options.placeholder = textarea.placeholder; } // Set autofocus to true if this textarea is focused, or if it has // autofocus and no other element is focused. if (options.autofocus == null) { var hasFocus = activeElt(textarea.ownerDocument); options.autofocus = hasFocus == textarea || textarea.getAttribute("autofocus") != null && hasFocus == document.body; } function save() {textarea.value = cm.getValue();} var realSubmit; if (textarea.form) { on(textarea.form, "submit", save); // Deplorable hack to make the submit method do the right thing. if (!options.leaveSubmitMethodAlone) { var form = textarea.form; realSubmit = form.submit; try { var wrappedSubmit = form.submit = function () { save(); form.submit = realSubmit; form.submit(); form.submit = wrappedSubmit; }; } catch(e) {} } } options.finishInit = function (cm) { cm.save = save; cm.getTextArea = function () { return textarea; }; cm.toTextArea = function () { cm.toTextArea = isNaN; // Prevent this from being ran twice save(); textarea.parentNode.removeChild(cm.getWrapperElement()); textarea.style.display = ""; if (textarea.form) { off(textarea.form, "submit", save); if (!options.leaveSubmitMethodAlone && typeof textarea.form.submit == "function") { textarea.form.submit = realSubmit; } } }; }; textarea.style.display = "none"; var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); }, options); return cm } function addLegacyProps(CodeMirror) { CodeMirror.off = off; CodeMirror.on = on; CodeMirror.wheelEventPixels = wheelEventPixels; CodeMirror.Doc = Doc; CodeMirror.splitLines = splitLinesAuto; CodeMirror.countColumn = countColumn; CodeMirror.findColumn = findColumn; CodeMirror.isWordChar = isWordCharBasic; CodeMirror.Pass = Pass; CodeMirror.signal = signal; CodeMirror.Line = Line; CodeMirror.changeEnd = changeEnd; CodeMirror.scrollbarModel = scrollbarModel; CodeMirror.Pos = Pos; CodeMirror.cmpPos = cmp; CodeMirror.modes = modes; CodeMirror.mimeModes = mimeModes; CodeMirror.resolveMode = resolveMode; CodeMirror.getMode = getMode; CodeMirror.modeExtensions = modeExtensions; CodeMirror.extendMode = extendMode; CodeMirror.copyState = copyState; CodeMirror.startState = startState; CodeMirror.innerMode = innerMode; CodeMirror.commands = commands; CodeMirror.keyMap = keyMap; CodeMirror.keyName = keyName; CodeMirror.isModifierKey = isModifierKey; CodeMirror.lookupKey = lookupKey; CodeMirror.normalizeKeyMap = normalizeKeyMap; CodeMirror.StringStream = StringStream; CodeMirror.SharedTextMarker = SharedTextMarker; CodeMirror.TextMarker = TextMarker; CodeMirror.LineWidget = LineWidget; CodeMirror.e_preventDefault = e_preventDefault; CodeMirror.e_stopPropagation = e_stopPropagation; CodeMirror.e_stop = e_stop; CodeMirror.addClass = addClass; CodeMirror.contains = contains; CodeMirror.rmClass = rmClass; CodeMirror.keyNames = keyNames; } // EDITOR CONSTRUCTOR defineOptions(CodeMirror); addEditorMethods(CodeMirror); // Set up methods on CodeMirror's prototype to redirect to the editor's document. var dontDelegate = "iter insert remove copy getEditor constructor".split(" "); for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) { CodeMirror.prototype[prop] = (function(method) { return function() {return method.apply(this.doc, arguments)} })(Doc.prototype[prop]); } } eventMixin(Doc); CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput}; // Extra arguments are stored as the mode's dependencies, which is // used by (legacy) mechanisms like loadmode.js to automatically // load a mode. (Preferred mechanism is the require/define calls.) CodeMirror.defineMode = function(name/*, mode, …*/) { if (!CodeMirror.defaults.mode && name != "null") { CodeMirror.defaults.mode = name; } defineMode.apply(this, arguments); }; CodeMirror.defineMIME = defineMIME; // Minimal default mode. CodeMirror.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); }); CodeMirror.defineMIME("text/plain", "null"); // EXTENSIONS CodeMirror.defineExtension = function (name, func) { CodeMirror.prototype[name] = func; }; CodeMirror.defineDocExtension = function (name, func) { Doc.prototype[name] = func; }; CodeMirror.fromTextArea = fromTextArea; addLegacyProps(CodeMirror); CodeMirror.version = "5.65.15"; return CodeMirror; }))); /***/ }), /***/ 629: /***/ ((__unused_webpack_module, __unused_webpack_exports, __nested_webpack_require_513095__) => { // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/5/LICENSE (function(mod) { if (true) // CommonJS mod(__nested_webpack_require_513095__(631)); else {} })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("css", function(config, parserConfig) { var inline = parserConfig.inline if (!parserConfig.propertyKeywords) parserConfig = CodeMirror.resolveMode("text/css"); var indentUnit = config.indentUnit, tokenHooks = parserConfig.tokenHooks, documentTypes = parserConfig.documentTypes || {}, mediaTypes = parserConfig.mediaTypes || {}, mediaFeatures = parserConfig.mediaFeatures || {}, mediaValueKeywords = parserConfig.mediaValueKeywords || {}, propertyKeywords = parserConfig.propertyKeywords || {}, nonStandardPropertyKeywords = parserConfig.nonStandardPropertyKeywords || {}, fontProperties = parserConfig.fontProperties || {}, counterDescriptors = parserConfig.counterDescriptors || {}, colorKeywords = parserConfig.colorKeywords || {}, valueKeywords = parserConfig.valueKeywords || {}, allowNested = parserConfig.allowNested, lineComment = parserConfig.lineComment, supportsAtComponent = parserConfig.supportsAtComponent === true, highlightNonStandardPropertyKeywords = config.highlightNonStandardPropertyKeywords !== false; var type, override; function ret(style, tp) { type = tp; return style; } // Tokenizers function tokenBase(stream, state) { var ch = stream.next(); if (tokenHooks[ch]) { var result = tokenHooks[ch](stream, state); if (result !== false) return result; } if (ch == "@") { stream.eatWhile(/[\w\\\-]/); return ret("def", stream.current()); } else if (ch == "=" || (ch == "~" || ch == "|") && stream.eat("=")) { return ret(null, "compare"); } else if (ch == "\"" || ch == "'") { state.tokenize = tokenString(ch); return state.tokenize(stream, state); } else if (ch == "#") { stream.eatWhile(/[\w\\\-]/); return ret("atom", "hash"); } else if (ch == "!") { stream.match(/^\s*\w*/); return ret("keyword", "important"); } else if (/\d/.test(ch) || ch == "." && stream.eat(/\d/)) { stream.eatWhile(/[\w.%]/); return ret("number", "unit"); } else if (ch === "-") { if (/[\d.]/.test(stream.peek())) { stream.eatWhile(/[\w.%]/); return ret("number", "unit"); } else if (stream.match(/^-[\w\\\-]*/)) { stream.eatWhile(/[\w\\\-]/); if (stream.match(/^\s*:/, false)) return ret("variable-2", "variable-definition"); return ret("variable-2", "variable"); } else if (stream.match(/^\w+-/)) { return ret("meta", "meta"); } } else if (/[,+>*\/]/.test(ch)) { return ret(null, "select-op"); } else if (ch == "." && stream.match(/^-?[_a-z][_a-z0-9-]*/i)) { return ret("qualifier", "qualifier"); } else if (/[:;{}\[\]\(\)]/.test(ch)) { return ret(null, ch); } else if (stream.match(/^[\w-.]+(?=\()/)) { if (/^(url(-prefix)?|domain|regexp)$/i.test(stream.current())) { state.tokenize = tokenParenthesized; } return ret("variable callee", "variable"); } else if (/[\w\\\-]/.test(ch)) { stream.eatWhile(/[\w\\\-]/); return ret("property", "word"); } else { return ret(null, null); } } function tokenString(quote) { return function(stream, state) { var escaped = false, ch; while ((ch = stream.next()) != null) { if (ch == quote && !escaped) { if (quote == ")") stream.backUp(1); break; } escaped = !escaped && ch == "\\"; } if (ch == quote || !escaped && quote != ")") state.tokenize = null; return ret("string", "string"); }; } function tokenParenthesized(stream, state) { stream.next(); // Must be '(' if (!stream.match(/^\s*[\"\')]/, false)) state.tokenize = tokenString(")"); else state.tokenize = null; return ret(null, "("); } // Context management function Context(type, indent, prev) { this.type = type; this.indent = indent; this.prev = prev; } function pushContext(state, stream, type, indent) { state.context = new Context(type, stream.indentation() + (indent === false ? 0 : indentUnit), state.context); return type; } function popContext(state) { if (state.context.prev) state.context = state.context.prev; return state.context.type; } function pass(type, stream, state) { return states[state.context.type](type, stream, state); } function popAndPass(type, stream, state, n) { for (var i = n || 1; i > 0; i--) state.context = state.context.prev; return pass(type, stream, state); } // Parser function wordAsValue(stream) { var word = stream.current().toLowerCase(); if (valueKeywords.hasOwnProperty(word)) override = "atom"; else if (colorKeywords.hasOwnProperty(word)) override = "keyword"; else override = "variable"; } var states = {}; states.top = function(type, stream, state) { if (type == "{") { return pushContext(state, stream, "block"); } else if (type == "}" && state.context.prev) { return popContext(state); } else if (supportsAtComponent && /@component/i.test(type)) { return pushContext(state, stream, "atComponentBlock"); } else if (/^@(-moz-)?document$/i.test(type)) { return pushContext(state, stream, "documentTypes"); } else if (/^@(media|supports|(-moz-)?document|import)$/i.test(type)) { return pushContext(state, stream, "atBlock"); } else if (/^@(font-face|counter-style)/i.test(type)) { state.stateArg = type; return "restricted_atBlock_before"; } else if (/^@(-(moz|ms|o|webkit)-)?keyframes$/i.test(type)) { return "keyframes"; } else if (type && type.charAt(0) == "@") { return pushContext(state, stream, "at"); } else if (type == "hash") { override = "builtin"; } else if (type == "word") { override = "tag"; } else if (type == "variable-definition") { return "maybeprop"; } else if (type == "interpolation") { return pushContext(state, stream, "interpolation"); } else if (type == ":") { return "pseudo"; } else if (allowNested && type == "(") { return pushContext(state, stream, "parens"); } return state.context.type; }; states.block = function(type, stream, state) { if (type == "word") { var word = stream.current().toLowerCase(); if (propertyKeywords.hasOwnProperty(word)) { override = "property"; return "maybeprop"; } else if (nonStandardPropertyKeywords.hasOwnProperty(word)) { override = highlightNonStandardPropertyKeywords ? "string-2" : "property"; return "maybeprop"; } else if (allowNested) { override = stream.match(/^\s*:(?:\s|$)/, false) ? "property" : "tag"; return "block"; } else { override += " error"; return "maybeprop"; } } else if (type == "meta") { return "block"; } else if (!allowNested && (type == "hash" || type == "qualifier")) { override = "error"; return "block"; } else { return states.top(type, stream, state); } }; states.maybeprop = function(type, stream, state) { if (type == ":") return pushContext(state, stream, "prop"); return pass(type, stream, state); }; states.prop = function(type, stream, state) { if (type == ";") return popContext(state); if (type == "{" && allowNested) return pushContext(state, stream, "propBlock"); if (type == "}" || type == "{") return popAndPass(type, stream, state); if (type == "(") return pushContext(state, stream, "parens"); if (type == "hash" && !/^#([0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/.test(stream.current())) { override += " error"; } else if (type == "word") { wordAsValue(stream); } else if (type == "interpolation") { return pushContext(state, stream, "interpolation"); } return "prop"; }; states.propBlock = function(type, _stream, state) { if (type == "}") return popContext(state); if (type == "word") { override = "property"; return "maybeprop"; } return state.context.type; }; states.parens = function(type, stream, state) { if (type == "{" || type == "}") return popAndPass(type, stream, state); if (type == ")") return popContext(state); if (type == "(") return pushContext(state, stream, "parens"); if (type == "interpolation") return pushContext(state, stream, "interpolation"); if (type == "word") wordAsValue(stream); return "parens"; }; states.pseudo = function(type, stream, state) { if (type == "meta") return "pseudo"; if (type == "word") { override = "variable-3"; return state.context.type; } return pass(type, stream, state); }; states.documentTypes = function(type, stream, state) { if (type == "word" && documentTypes.hasOwnProperty(stream.current())) { override = "tag"; return state.context.type; } else { return states.atBlock(type, stream, state); } }; states.atBlock = function(type, stream, state) { if (type == "(") return pushContext(state, stream, "atBlock_parens"); if (type == "}" || type == ";") return popAndPass(type, stream, state); if (type == "{") return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top"); if (type == "interpolation") return pushContext(state, stream, "interpolation"); if (type == "word") { var word = stream.current().toLowerCase(); if (word == "only" || word == "not" || word == "and" || word == "or") override = "keyword"; else if (mediaTypes.hasOwnProperty(word)) override = "attribute"; else if (mediaFeatures.hasOwnProperty(word)) override = "property"; else if (mediaValueKeywords.hasOwnProperty(word)) override = "keyword"; else if (propertyKeywords.hasOwnProperty(word)) override = "property"; else if (nonStandardPropertyKeywords.hasOwnProperty(word)) override = highlightNonStandardPropertyKeywords ? "string-2" : "property"; else if (valueKeywords.hasOwnProperty(word)) override = "atom"; else if (colorKeywords.hasOwnProperty(word)) override = "keyword"; else override = "error"; } return state.context.type; }; states.atComponentBlock = function(type, stream, state) { if (type == "}") return popAndPass(type, stream, state); if (type == "{") return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top", false); if (type == "word") override = "error"; return state.context.type; }; states.atBlock_parens = function(type, stream, state) { if (type == ")") return popContext(state); if (type == "{" || type == "}") return popAndPass(type, stream, state, 2); return states.atBlock(type, stream, state); }; states.restricted_atBlock_before = function(type, stream, state) { if (type == "{") return pushContext(state, stream, "restricted_atBlock"); if (type == "word" && state.stateArg == "@counter-style") { override = "variable"; return "restricted_atBlock_before"; } return pass(type, stream, state); }; states.restricted_atBlock = function(type, stream, state) { if (type == "}") { state.stateArg = null; return popContext(state); } if (type == "word") { if ((state.stateArg == "@font-face" && !fontProperties.hasOwnProperty(stream.current().toLowerCase())) || (state.stateArg == "@counter-style" && !counterDescriptors.hasOwnProperty(stream.current().toLowerCase()))) override = "error"; else override = "property"; return "maybeprop"; } return "restricted_atBlock"; }; states.keyframes = function(type, stream, state) { if (type == "word") { override = "variable"; return "keyframes"; } if (type == "{") return pushContext(state, stream, "top"); return pass(type, stream, state); }; states.at = function(type, stream, state) { if (type == ";") return popContext(state); if (type == "{" || type == "}") return popAndPass(type, stream, state); if (type == "word") override = "tag"; else if (type == "hash") override = "builtin"; return "at"; }; states.interpolation = function(type, stream, state) { if (type == "}") return popContext(state); if (type == "{" || type == ";") return popAndPass(type, stream, state); if (type == "word") override = "variable"; else if (type != "variable" && type != "(" && type != ")") override = "error"; return "interpolation"; }; return { startState: function(base) { return {tokenize: null, state: inline ? "block" : "top", stateArg: null, context: new Context(inline ? "block" : "top", base || 0, null)}; }, token: function(stream, state) { if (!state.tokenize && stream.eatSpace()) return null; var style = (state.tokenize || tokenBase)(stream, state); if (style && typeof style == "object") { type = style[1]; style = style[0]; } override = style; if (type != "comment") state.state = states[state.state](type, stream, state); return override; }, indent: function(state, textAfter) { var cx = state.context, ch = textAfter && textAfter.charAt(0); var indent = cx.indent; if (cx.type == "prop" && (ch == "}" || ch == ")")) cx = cx.prev; if (cx.prev) { if (ch == "}" && (cx.type == "block" || cx.type == "top" || cx.type == "interpolation" || cx.type == "restricted_atBlock")) { // Resume indentation from parent context. cx = cx.prev; indent = cx.indent; } else if (ch == ")" && (cx.type == "parens" || cx.type == "atBlock_parens") || ch == "{" && (cx.type == "at" || cx.type == "atBlock")) { // Dedent relative to current context. indent = Math.max(0, cx.indent - indentUnit); } } return indent; }, electricChars: "}", blockCommentStart: "/*", blockCommentEnd: "*/", blockCommentContinue: " * ", lineComment: lineComment, fold: "brace" }; }); function keySet(array) { var keys = {}; for (var i = 0; i < array.length; ++i) { keys[array[i].toLowerCase()] = true; } return keys; } var documentTypes_ = [ "domain", "regexp", "url", "url-prefix" ], documentTypes = keySet(documentTypes_); var mediaTypes_ = [ "all", "aural", "braille", "handheld", "print", "projection", "screen", "tty", "tv", "embossed" ], mediaTypes = keySet(mediaTypes_); var mediaFeatures_ = [ "width", "min-width", "max-width", "height", "min-height", "max-height", "device-width", "min-device-width", "max-device-width", "device-height", "min-device-height", "max-device-height", "aspect-ratio", "min-aspect-ratio", "max-aspect-ratio", "device-aspect-ratio", "min-device-aspect-ratio", "max-device-aspect-ratio", "color", "min-color", "max-color", "color-index", "min-color-index", "max-color-index", "monochrome", "min-monochrome", "max-monochrome", "resolution", "min-resolution", "max-resolution", "scan", "grid", "orientation", "device-pixel-ratio", "min-device-pixel-ratio", "max-device-pixel-ratio", "pointer", "any-pointer", "hover", "any-hover", "prefers-color-scheme", "dynamic-range", "video-dynamic-range" ], mediaFeatures = keySet(mediaFeatures_); var mediaValueKeywords_ = [ "landscape", "portrait", "none", "coarse", "fine", "on-demand", "hover", "interlace", "progressive", "dark", "light", "standard", "high" ], mediaValueKeywords = keySet(mediaValueKeywords_); var propertyKeywords_ = [ "align-content", "align-items", "align-self", "alignment-adjust", "alignment-baseline", "all", "anchor-point", "animation", "animation-delay", "animation-direction", "animation-duration", "animation-fill-mode", "animation-iteration-count", "animation-name", "animation-play-state", "animation-timing-function", "appearance", "azimuth", "backdrop-filter", "backface-visibility", "background", "background-attachment", "background-blend-mode", "background-clip", "background-color", "background-image", "background-origin", "background-position", "background-position-x", "background-position-y", "background-repeat", "background-size", "baseline-shift", "binding", "bleed", "block-size", "bookmark-label", "bookmark-level", "bookmark-state", "bookmark-target", "border", "border-bottom", "border-bottom-color", "border-bottom-left-radius", "border-bottom-right-radius", "border-bottom-style", "border-bottom-width", "border-collapse", "border-color", "border-image", "border-image-outset", "border-image-repeat", "border-image-slice", "border-image-source", "border-image-width", "border-left", "border-left-color", "border-left-style", "border-left-width", "border-radius", "border-right", "border-right-color", "border-right-style", "border-right-width", "border-spacing", "border-style", "border-top", "border-top-color", "border-top-left-radius", "border-top-right-radius", "border-top-style", "border-top-width", "border-width", "bottom", "box-decoration-break", "box-shadow", "box-sizing", "break-after", "break-before", "break-inside", "caption-side", "caret-color", "clear", "clip", "color", "color-profile", "column-count", "column-fill", "column-gap", "column-rule", "column-rule-color", "column-rule-style", "column-rule-width", "column-span", "column-width", "columns", "contain", "content", "counter-increment", "counter-reset", "crop", "cue", "cue-after", "cue-before", "cursor", "direction", "display", "dominant-baseline", "drop-initial-after-adjust", "drop-initial-after-align", "drop-initial-before-adjust", "drop-initial-before-align", "drop-initial-size", "drop-initial-value", "elevation", "empty-cells", "fit", "fit-content", "fit-position", "flex", "flex-basis", "flex-direction", "flex-flow", "flex-grow", "flex-shrink", "flex-wrap", "float", "float-offset", "flow-from", "flow-into", "font", "font-family", "font-feature-settings", "font-kerning", "font-language-override", "font-optical-sizing", "font-size", "font-size-adjust", "font-stretch", "font-style", "font-synthesis", "font-variant", "font-variant-alternates", "font-variant-caps", "font-variant-east-asian", "font-variant-ligatures", "font-variant-numeric", "font-variant-position", "font-variation-settings", "font-weight", "gap", "grid", "grid-area", "grid-auto-columns", "grid-auto-flow", "grid-auto-rows", "grid-column", "grid-column-end", "grid-column-gap", "grid-column-start", "grid-gap", "grid-row", "grid-row-end", "grid-row-gap", "grid-row-start", "grid-template", "grid-template-areas", "grid-template-columns", "grid-template-rows", "hanging-punctuation", "height", "hyphens", "icon", "image-orientation", "image-rendering", "image-resolution", "inline-box-align", "inset", "inset-block", "inset-block-end", "inset-block-start", "inset-inline", "inset-inline-end", "inset-inline-start", "isolation", "justify-content", "justify-items", "justify-self", "left", "letter-spacing", "line-break", "line-height", "line-height-step", "line-stacking", "line-stacking-ruby", "line-stacking-shift", "line-stacking-strategy", "list-style", "list-style-image", "list-style-position", "list-style-type", "margin", "margin-bottom", "margin-left", "margin-right", "margin-top", "marks", "marquee-direction", "marquee-loop", "marquee-play-count", "marquee-speed", "marquee-style", "mask-clip", "mask-composite", "mask-image", "mask-mode", "mask-origin", "mask-position", "mask-repeat", "mask-size","mask-type", "max-block-size", "max-height", "max-inline-size", "max-width", "min-block-size", "min-height", "min-inline-size", "min-width", "mix-blend-mode", "move-to", "nav-down", "nav-index", "nav-left", "nav-right", "nav-up", "object-fit", "object-position", "offset", "offset-anchor", "offset-distance", "offset-path", "offset-position", "offset-rotate", "opacity", "order", "orphans", "outline", "outline-color", "outline-offset", "outline-style", "outline-width", "overflow", "overflow-style", "overflow-wrap", "overflow-x", "overflow-y", "padding", "padding-bottom", "padding-left", "padding-right", "padding-top", "page", "page-break-after", "page-break-before", "page-break-inside", "page-policy", "pause", "pause-after", "pause-before", "perspective", "perspective-origin", "pitch", "pitch-range", "place-content", "place-items", "place-self", "play-during", "position", "presentation-level", "punctuation-trim", "quotes", "region-break-after", "region-break-before", "region-break-inside", "region-fragment", "rendering-intent", "resize", "rest", "rest-after", "rest-before", "richness", "right", "rotate", "rotation", "rotation-point", "row-gap", "ruby-align", "ruby-overhang", "ruby-position", "ruby-span", "scale", "scroll-behavior", "scroll-margin", "scroll-margin-block", "scroll-margin-block-end", "scroll-margin-block-start", "scroll-margin-bottom", "scroll-margin-inline", "scroll-margin-inline-end", "scroll-margin-inline-start", "scroll-margin-left", "scroll-margin-right", "scroll-margin-top", "scroll-padding", "scroll-padding-block", "scroll-padding-block-end", "scroll-padding-block-start", "scroll-padding-bottom", "scroll-padding-inline", "scroll-padding-inline-end", "scroll-padding-inline-start", "scroll-padding-left", "scroll-padding-right", "scroll-padding-top", "scroll-snap-align", "scroll-snap-type", "shape-image-threshold", "shape-inside", "shape-margin", "shape-outside", "size", "speak", "speak-as", "speak-header", "speak-numeral", "speak-punctuation", "speech-rate", "stress", "string-set", "tab-size", "table-layout", "target", "target-name", "target-new", "target-position", "text-align", "text-align-last", "text-combine-upright", "text-decoration", "text-decoration-color", "text-decoration-line", "text-decoration-skip", "text-decoration-skip-ink", "text-decoration-style", "text-emphasis", "text-emphasis-color", "text-emphasis-position", "text-emphasis-style", "text-height", "text-indent", "text-justify", "text-orientation", "text-outline", "text-overflow", "text-rendering", "text-shadow", "text-size-adjust", "text-space-collapse", "text-transform", "text-underline-position", "text-wrap", "top", "touch-action", "transform", "transform-origin", "transform-style", "transition", "transition-delay", "transition-duration", "transition-property", "transition-timing-function", "translate", "unicode-bidi", "user-select", "vertical-align", "visibility", "voice-balance", "voice-duration", "voice-family", "voice-pitch", "voice-range", "voice-rate", "voice-stress", "voice-volume", "volume", "white-space", "widows", "width", "will-change", "word-break", "word-spacing", "word-wrap", "writing-mode", "z-index", // SVG-specific "clip-path", "clip-rule", "mask", "enable-background", "filter", "flood-color", "flood-opacity", "lighting-color", "stop-color", "stop-opacity", "pointer-events", "color-interpolation", "color-interpolation-filters", "color-rendering", "fill", "fill-opacity", "fill-rule", "image-rendering", "marker", "marker-end", "marker-mid", "marker-start", "paint-order", "shape-rendering", "stroke", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "text-rendering", "baseline-shift", "dominant-baseline", "glyph-orientation-horizontal", "glyph-orientation-vertical", "text-anchor", "writing-mode", ], propertyKeywords = keySet(propertyKeywords_); var nonStandardPropertyKeywords_ = [ "accent-color", "aspect-ratio", "border-block", "border-block-color", "border-block-end", "border-block-end-color", "border-block-end-style", "border-block-end-width", "border-block-start", "border-block-start-color", "border-block-start-style", "border-block-start-width", "border-block-style", "border-block-width", "border-inline", "border-inline-color", "border-inline-end", "border-inline-end-color", "border-inline-end-style", "border-inline-end-width", "border-inline-start", "border-inline-start-color", "border-inline-start-style", "border-inline-start-width", "border-inline-style", "border-inline-width", "content-visibility", "margin-block", "margin-block-end", "margin-block-start", "margin-inline", "margin-inline-end", "margin-inline-start", "overflow-anchor", "overscroll-behavior", "padding-block", "padding-block-end", "padding-block-start", "padding-inline", "padding-inline-end", "padding-inline-start", "scroll-snap-stop", "scrollbar-3d-light-color", "scrollbar-arrow-color", "scrollbar-base-color", "scrollbar-dark-shadow-color", "scrollbar-face-color", "scrollbar-highlight-color", "scrollbar-shadow-color", "scrollbar-track-color", "searchfield-cancel-button", "searchfield-decoration", "searchfield-results-button", "searchfield-results-decoration", "shape-inside", "zoom" ], nonStandardPropertyKeywords = keySet(nonStandardPropertyKeywords_); var fontProperties_ = [ "font-display", "font-family", "src", "unicode-range", "font-variant", "font-feature-settings", "font-stretch", "font-weight", "font-style" ], fontProperties = keySet(fontProperties_); var counterDescriptors_ = [ "additive-symbols", "fallback", "negative", "pad", "prefix", "range", "speak-as", "suffix", "symbols", "system" ], counterDescriptors = keySet(counterDescriptors_); var colorKeywords_ = [ "aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige", "bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown", "burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue", "cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod", "darkgray", "darkgreen", "darkgrey", "darkkhaki", "darkmagenta", "darkolivegreen", "darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen", "darkslateblue", "darkslategray", "darkslategrey", "darkturquoise", "darkviolet", "deeppink", "deepskyblue", "dimgray", "dimgrey", "dodgerblue", "firebrick", "floralwhite", "forestgreen", "fuchsia", "gainsboro", "ghostwhite", "gold", "goldenrod", "gray", "grey", "green", "greenyellow", "honeydew", "hotpink", "indianred", "indigo", "ivory", "khaki", "lavender", "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral", "lightcyan", "lightgoldenrodyellow", "lightgray", "lightgreen", "lightgrey", "lightpink", "lightsalmon", "lightseagreen", "lightskyblue", "lightslategray", "lightslategrey", "lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta", "maroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple", "mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise", "mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin", "navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange", "orangered", "orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred", "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue", "purple", "rebeccapurple", "red", "rosybrown", "royalblue", "saddlebrown", "salmon", "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue", "slateblue", "slategray", "slategrey", "snow", "springgreen", "steelblue", "tan", "teal", "thistle", "tomato", "turquoise", "violet", "wheat", "white", "whitesmoke", "yellow", "yellowgreen" ], colorKeywords = keySet(colorKeywords_); var valueKeywords_ = [ "above", "absolute", "activeborder", "additive", "activecaption", "afar", "after-white-space", "ahead", "alias", "all", "all-scroll", "alphabetic", "alternate", "always", "amharic", "amharic-abegede", "antialiased", "appworkspace", "arabic-indic", "armenian", "asterisks", "attr", "auto", "auto-flow", "avoid", "avoid-column", "avoid-page", "avoid-region", "axis-pan", "background", "backwards", "baseline", "below", "bidi-override", "binary", "bengali", "blink", "block", "block-axis", "blur", "bold", "bolder", "border", "border-box", "both", "bottom", "break", "break-all", "break-word", "brightness", "bullets", "button", "buttonface", "buttonhighlight", "buttonshadow", "buttontext", "calc", "cambodian", "capitalize", "caps-lock-indicator", "caption", "captiontext", "caret", "cell", "center", "checkbox", "circle", "cjk-decimal", "cjk-earthly-branch", "cjk-heavenly-stem", "cjk-ideographic", "clear", "clip", "close-quote", "col-resize", "collapse", "color", "color-burn", "color-dodge", "column", "column-reverse", "compact", "condensed", "conic-gradient", "contain", "content", "contents", "content-box", "context-menu", "continuous", "contrast", "copy", "counter", "counters", "cover", "crop", "cross", "crosshair", "cubic-bezier", "currentcolor", "cursive", "cyclic", "darken", "dashed", "decimal", "decimal-leading-zero", "default", "default-button", "dense", "destination-atop", "destination-in", "destination-out", "destination-over", "devanagari", "difference", "disc", "discard", "disclosure-closed", "disclosure-open", "document", "dot-dash", "dot-dot-dash", "dotted", "double", "down", "drop-shadow", "e-resize", "ease", "ease-in", "ease-in-out", "ease-out", "element", "ellipse", "ellipsis", "embed", "end", "ethiopic", "ethiopic-abegede", "ethiopic-abegede-am-et", "ethiopic-abegede-gez", "ethiopic-abegede-ti-er", "ethiopic-abegede-ti-et", "ethiopic-halehame-aa-er", "ethiopic-halehame-aa-et", "ethiopic-halehame-am-et", "ethiopic-halehame-gez", "ethiopic-halehame-om-et", "ethiopic-halehame-sid-et", "ethiopic-halehame-so-et", "ethiopic-halehame-ti-er", "ethiopic-halehame-ti-et", "ethiopic-halehame-tig", "ethiopic-numeric", "ew-resize", "exclusion", "expanded", "extends", "extra-condensed", "extra-expanded", "fantasy", "fast", "fill", "fill-box", "fixed", "flat", "flex", "flex-end", "flex-start", "footnotes", "forwards", "from", "geometricPrecision", "georgian", "grayscale", "graytext", "grid", "groove", "gujarati", "gurmukhi", "hand", "hangul", "hangul-consonant", "hard-light", "hebrew", "help", "hidden", "hide", "higher", "highlight", "highlighttext", "hiragana", "hiragana-iroha", "horizontal", "hsl", "hsla", "hue", "hue-rotate", "icon", "ignore", "inactiveborder", "inactivecaption", "inactivecaptiontext", "infinite", "infobackground", "infotext", "inherit", "initial", "inline", "inline-axis", "inline-block", "inline-flex", "inline-grid", "inline-table", "inset", "inside", "intrinsic", "invert", "italic", "japanese-formal", "japanese-informal", "justify", "kannada", "katakana", "katakana-iroha", "keep-all", "khmer", "korean-hangul-formal", "korean-hanja-formal", "korean-hanja-informal", "landscape", "lao", "large", "larger", "left", "level", "lighter", "lighten", "line-through", "linear", "linear-gradient", "lines", "list-item", "listbox", "listitem", "local", "logical", "loud", "lower", "lower-alpha", "lower-armenian", "lower-greek", "lower-hexadecimal", "lower-latin", "lower-norwegian", "lower-roman", "lowercase", "ltr", "luminosity", "malayalam", "manipulation", "match", "matrix", "matrix3d", "media-play-button", "media-slider", "media-sliderthumb", "media-volume-slider", "media-volume-sliderthumb", "medium", "menu", "menulist", "menulist-button", "menutext", "message-box", "middle", "min-intrinsic", "mix", "mongolian", "monospace", "move", "multiple", "multiple_mask_images", "multiply", "myanmar", "n-resize", "narrower", "ne-resize", "nesw-resize", "no-close-quote", "no-drop", "no-open-quote", "no-repeat", "none", "normal", "not-allowed", "nowrap", "ns-resize", "numbers", "numeric", "nw-resize", "nwse-resize", "oblique", "octal", "opacity", "open-quote", "optimizeLegibility", "optimizeSpeed", "oriya", "oromo", "outset", "outside", "outside-shape", "overlay", "overline", "padding", "padding-box", "painted", "page", "paused", "persian", "perspective", "pinch-zoom", "plus-darker", "plus-lighter", "pointer", "polygon", "portrait", "pre", "pre-line", "pre-wrap", "preserve-3d", "progress", "push-button", "radial-gradient", "radio", "read-only", "read-write", "read-write-plaintext-only", "rectangle", "region", "relative", "repeat", "repeating-linear-gradient", "repeating-radial-gradient", "repeating-conic-gradient", "repeat-x", "repeat-y", "reset", "reverse", "rgb", "rgba", "ridge", "right", "rotate", "rotate3d", "rotateX", "rotateY", "rotateZ", "round", "row", "row-resize", "row-reverse", "rtl", "run-in", "running", "s-resize", "sans-serif", "saturate", "saturation", "scale", "scale3d", "scaleX", "scaleY", "scaleZ", "screen", "scroll", "scrollbar", "scroll-position", "se-resize", "searchfield", "searchfield-cancel-button", "searchfield-decoration", "searchfield-results-button", "searchfield-results-decoration", "self-start", "self-end", "semi-condensed", "semi-expanded", "separate", "sepia", "serif", "show", "sidama", "simp-chinese-formal", "simp-chinese-informal", "single", "skew", "skewX", "skewY", "skip-white-space", "slide", "slider-horizontal", "slider-vertical", "sliderthumb-horizontal", "sliderthumb-vertical", "slow", "small", "small-caps", "small-caption", "smaller", "soft-light", "solid", "somali", "source-atop", "source-in", "source-out", "source-over", "space", "space-around", "space-between", "space-evenly", "spell-out", "square", "square-button", "start", "static", "status-bar", "stretch", "stroke", "stroke-box", "sub", "subpixel-antialiased", "svg_masks", "super", "sw-resize", "symbolic", "symbols", "system-ui", "table", "table-caption", "table-cell", "table-column", "table-column-group", "table-footer-group", "table-header-group", "table-row", "table-row-group", "tamil", "telugu", "text", "text-bottom", "text-top", "textarea", "textfield", "thai", "thick", "thin", "threeddarkshadow", "threedface", "threedhighlight", "threedlightshadow", "threedshadow", "tibetan", "tigre", "tigrinya-er", "tigrinya-er-abegede", "tigrinya-et", "tigrinya-et-abegede", "to", "top", "trad-chinese-formal", "trad-chinese-informal", "transform", "translate", "translate3d", "translateX", "translateY", "translateZ", "transparent", "ultra-condensed", "ultra-expanded", "underline", "unidirectional-pan", "unset", "up", "upper-alpha", "upper-armenian", "upper-greek", "upper-hexadecimal", "upper-latin", "upper-norwegian", "upper-roman", "uppercase", "urdu", "url", "var", "vertical", "vertical-text", "view-box", "visible", "visibleFill", "visiblePainted", "visibleStroke", "visual", "w-resize", "wait", "wave", "wider", "window", "windowframe", "windowtext", "words", "wrap", "wrap-reverse", "x-large", "x-small", "xor", "xx-large", "xx-small" ], valueKeywords = keySet(valueKeywords_); var allWords = documentTypes_.concat(mediaTypes_).concat(mediaFeatures_).concat(mediaValueKeywords_) .concat(propertyKeywords_).concat(nonStandardPropertyKeywords_).concat(colorKeywords_) .concat(valueKeywords_); CodeMirror.registerHelper("hintWords", "css", allWords); function tokenCComment(stream, state) { var maybeEnd = false, ch; while ((ch = stream.next()) != null) { if (maybeEnd && ch == "/") { state.tokenize = null; break; } maybeEnd = (ch == "*"); } return ["comment", "comment"]; } CodeMirror.defineMIME("text/css", { documentTypes: documentTypes, mediaTypes: mediaTypes, mediaFeatures: mediaFeatures, mediaValueKeywords: mediaValueKeywords, propertyKeywords: propertyKeywords, nonStandardPropertyKeywords: nonStandardPropertyKeywords, fontProperties: fontProperties, counterDescriptors: counterDescriptors, colorKeywords: colorKeywords, valueKeywords: valueKeywords, tokenHooks: { "/": function(stream, state) { if (!stream.eat("*")) return false; state.tokenize = tokenCComment; return tokenCComment(stream, state); } }, name: "css" }); CodeMirror.defineMIME("text/x-scss", { mediaTypes: mediaTypes, mediaFeatures: mediaFeatures, mediaValueKeywords: mediaValueKeywords, propertyKeywords: propertyKeywords, nonStandardPropertyKeywords: nonStandardPropertyKeywords, colorKeywords: colorKeywords, valueKeywords: valueKeywords, fontProperties: fontProperties, allowNested: true, lineComment: "//", tokenHooks: { "/": function(stream, state) { if (stream.eat("/")) { stream.skipToEnd(); return ["comment", "comment"]; } else if (stream.eat("*")) { state.tokenize = tokenCComment; return tokenCComment(stream, state); } else { return ["operator", "operator"]; } }, ":": function(stream) { if (stream.match(/^\s*\{/, false)) return [null, null] return false; }, "$": function(stream) { stream.match(/^[\w-]+/); if (stream.match(/^\s*:/, false)) return ["variable-2", "variable-definition"]; return ["variable-2", "variable"]; }, "#": function(stream) { if (!stream.eat("{")) return false; return [null, "interpolation"]; } }, name: "css", helperType: "scss" }); CodeMirror.defineMIME("text/x-less", { mediaTypes: mediaTypes, mediaFeatures: mediaFeatures, mediaValueKeywords: mediaValueKeywords, propertyKeywords: propertyKeywords, nonStandardPropertyKeywords: nonStandardPropertyKeywords, colorKeywords: colorKeywords, valueKeywords: valueKeywords, fontProperties: fontProperties, allowNested: true, lineComment: "//", tokenHooks: { "/": function(stream, state) { if (stream.eat("/")) { stream.skipToEnd(); return ["comment", "comment"]; } else if (stream.eat("*")) { state.tokenize = tokenCComment; return tokenCComment(stream, state); } else { return ["operator", "operator"]; } }, "@": function(stream) { if (stream.eat("{")) return [null, "interpolation"]; if (stream.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\b/i, false)) return false; stream.eatWhile(/[\w\\\-]/); if (stream.match(/^\s*:/, false)) return ["variable-2", "variable-definition"]; return ["variable-2", "variable"]; }, "&": function() { return ["atom", "atom"]; } }, name: "css", helperType: "less" }); CodeMirror.defineMIME("text/x-gss", { documentTypes: documentTypes, mediaTypes: mediaTypes, mediaFeatures: mediaFeatures, propertyKeywords: propertyKeywords, nonStandardPropertyKeywords: nonStandardPropertyKeywords, fontProperties: fontProperties, counterDescriptors: counterDescriptors, colorKeywords: colorKeywords, valueKeywords: valueKeywords, supportsAtComponent: true, tokenHooks: { "/": function(stream, state) { if (!stream.eat("*")) return false; state.tokenize = tokenCComment; return tokenCComment(stream, state); } }, name: "css", helperType: "gss" }); }); /***/ }), /***/ 531: /***/ ((__unused_webpack_module, __unused_webpack_exports, __nested_webpack_require_553496__) => { // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/5/LICENSE (function(mod) { if (true) // CommonJS mod(__nested_webpack_require_553496__(631), __nested_webpack_require_553496__(589), __nested_webpack_require_553496__(876), __nested_webpack_require_553496__(629)); else {} })(function(CodeMirror) { "use strict"; var defaultTags = { script: [ ["lang", /(javascript|babel)/i, "javascript"], ["type", /^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i, "javascript"], ["type", /./, "text/plain"], [null, null, "javascript"] ], style: [ ["lang", /^css$/i, "css"], ["type", /^(text\/)?(x-)?(stylesheet|css)$/i, "css"], ["type", /./, "text/plain"], [null, null, "css"] ] }; function maybeBackup(stream, pat, style) { var cur = stream.current(), close = cur.search(pat); if (close > -1) { stream.backUp(cur.length - close); } else if (cur.match(/<\/?$/)) { stream.backUp(cur.length); if (!stream.match(pat, false)) stream.match(cur); } return style; } var attrRegexpCache = {}; function getAttrRegexp(attr) { var regexp = attrRegexpCache[attr]; if (regexp) return regexp; return attrRegexpCache[attr] = new RegExp("\\s+" + attr + "\\s*=\\s*('|\")?([^'\"]+)('|\")?\\s*"); } function getAttrValue(text, attr) { var match = text.match(getAttrRegexp(attr)) return match ? /^\s*(.*?)\s*$/.exec(match[2])[1] : "" } function getTagRegexp(tagName, anchored) { return new RegExp((anchored ? "^" : "") + "<\/\\s*" + tagName + "\\s*>", "i"); } function addTags(from, to) { for (var tag in from) { var dest = to[tag] || (to[tag] = []); var source = from[tag]; for (var i = source.length - 1; i >= 0; i--) dest.unshift(source[i]) } } function findMatchingMode(tagInfo, tagText) { for (var i = 0; i < tagInfo.length; i++) { var spec = tagInfo[i]; if (!spec[0] || spec[1].test(getAttrValue(tagText, spec[0]))) return spec[2]; } } CodeMirror.defineMode("htmlmixed", function (config, parserConfig) { var htmlMode = CodeMirror.getMode(config, { name: "xml", htmlMode: true, multilineTagIndentFactor: parserConfig.multilineTagIndentFactor, multilineTagIndentPastTag: parserConfig.multilineTagIndentPastTag, allowMissingTagName: parserConfig.allowMissingTagName, }); var tags = {}; var configTags = parserConfig && parserConfig.tags, configScript = parserConfig && parserConfig.scriptTypes; addTags(defaultTags, tags); if (configTags) addTags(configTags, tags); if (configScript) for (var i = configScript.length - 1; i >= 0; i--) tags.script.unshift(["type", configScript[i].matches, configScript[i].mode]) function html(stream, state) { var style = htmlMode.token(stream, state.htmlState), tag = /\btag\b/.test(style), tagName if (tag && !/[<>\s\/]/.test(stream.current()) && (tagName = state.htmlState.tagName && state.htmlState.tagName.toLowerCase()) && tags.hasOwnProperty(tagName)) { state.inTag = tagName + " " } else if (state.inTag && tag && />$/.test(stream.current())) { var inTag = /^([\S]+) (.*)/.exec(state.inTag) state.inTag = null var modeSpec = stream.current() == ">" && findMatchingMode(tags[inTag[1]], inTag[2]) var mode = CodeMirror.getMode(config, modeSpec) var endTagA = getTagRegexp(inTag[1], true), endTag = getTagRegexp(inTag[1], false); state.token = function (stream, state) { if (stream.match(endTagA, false)) { state.token = html; state.localState = state.localMode = null; return null; } return maybeBackup(stream, endTag, state.localMode.token(stream, state.localState)); }; state.localMode = mode; state.localState = CodeMirror.startState(mode, htmlMode.indent(state.htmlState, "", "")); } else if (state.inTag) { state.inTag += stream.current() if (stream.eol()) state.inTag += " " } return style; }; return { startState: function () { var state = CodeMirror.startState(htmlMode); return {token: html, inTag: null, localMode: null, localState: null, htmlState: state}; }, copyState: function (state) { var local; if (state.localState) { local = CodeMirror.copyState(state.localMode, state.localState); } return {token: state.token, inTag: state.inTag, localMode: state.localMode, localState: local, htmlState: CodeMirror.copyState(htmlMode, state.htmlState)}; }, token: function (stream, state) { return state.token(stream, state); }, indent: function (state, textAfter, line) { if (!state.localMode || /^\s*<\//.test(textAfter)) return htmlMode.indent(state.htmlState, textAfter, line); else if (state.localMode.indent) return state.localMode.indent(state.localState, textAfter, line); else return CodeMirror.Pass; }, innerMode: function (state) { return {state: state.localState || state.htmlState, mode: state.localMode || htmlMode}; } }; }, "xml", "javascript", "css"); CodeMirror.defineMIME("text/html", "htmlmixed"); }); /***/ }), /***/ 876: /***/ ((__unused_webpack_module, __unused_webpack_exports, __nested_webpack_require_559032__) => { // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/5/LICENSE (function(mod) { if (true) // CommonJS mod(__nested_webpack_require_559032__(631)); else {} })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("javascript", function(config, parserConfig) { var indentUnit = config.indentUnit; var statementIndent = parserConfig.statementIndent; var jsonldMode = parserConfig.jsonld; var jsonMode = parserConfig.json || jsonldMode; var trackScope = parserConfig.trackScope !== false var isTS = parserConfig.typescript; var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/; // Tokenizer var keywords = function(){ function kw(type) {return {type: type, style: "keyword"};} var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c"), D = kw("keyword d"); var operator = kw("operator"), atom = {type: "atom", style: "atom"}; return { "if": kw("if"), "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B, "return": D, "break": D, "continue": D, "new": kw("new"), "delete": C, "void": C, "throw": C, "debugger": kw("debugger"), "var": kw("var"), "const": kw("var"), "let": kw("var"), "function": kw("function"), "catch": kw("catch"), "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"), "in": operator, "typeof": operator, "instanceof": operator, "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom, "this": kw("this"), "class": kw("class"), "super": kw("atom"), "yield": C, "export": kw("export"), "import": kw("import"), "extends": C, "await": C }; }(); var isOperatorChar = /[+\-*&%=<>!?|~^@]/; var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/; function readRegexp(stream) { var escaped = false, next, inSet = false; while ((next = stream.next()) != null) { if (!escaped) { if (next == "/" && !inSet) return; if (next == "[") inSet = true; else if (inSet && next == "]") inSet = false; } escaped = !escaped && next == "\\"; } } // Used as scratch variables to communicate multiple values without // consing up tons of objects. var type, content; function ret(tp, style, cont) { type = tp; content = cont; return style; } function tokenBase(stream, state) { var ch = stream.next(); if (ch == '"' || ch == "'") { state.tokenize = tokenString(ch); return state.tokenize(stream, state); } else if (ch == "." && stream.match(/^\d[\d_]*(?:[eE][+\-]?[\d_]+)?/)) { return ret("number", "number"); } else if (ch == "." && stream.match("..")) { return ret("spread", "meta"); } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) { return ret(ch); } else if (ch == "=" && stream.eat(">")) { return ret("=>", "operator"); } else if (ch == "0" && stream.match(/^(?:x[\dA-Fa-f_]+|o[0-7_]+|b[01_]+)n?/)) { return ret("number", "number"); } else if (/\d/.test(ch)) { stream.match(/^[\d_]*(?:n|(?:\.[\d_]*)?(?:[eE][+\-]?[\d_]+)?)?/); return ret("number", "number"); } else if (ch == "/") { if (stream.eat("*")) { state.tokenize = tokenComment; return tokenComment(stream, state); } else if (stream.eat("/")) { stream.skipToEnd(); return ret("comment", "comment"); } else if (expressionAllowed(stream, state, 1)) { readRegexp(stream); stream.match(/^\b(([gimyus])(?![gimyus]*\2))+\b/); return ret("regexp", "string-2"); } else { stream.eat("="); return ret("operator", "operator", stream.current()); } } else if (ch == "`") { state.tokenize = tokenQuasi; return tokenQuasi(stream, state); } else if (ch == "#" && stream.peek() == "!") { stream.skipToEnd(); return ret("meta", "meta"); } else if (ch == "#" && stream.eatWhile(wordRE)) { return ret("variable", "property") } else if (ch == "<" && stream.match("!--") || (ch == "-" && stream.match("->") && !/\S/.test(stream.string.slice(0, stream.start)))) { stream.skipToEnd() return ret("comment", "comment") } else if (isOperatorChar.test(ch)) { if (ch != ">" || !state.lexical || state.lexical.type != ">") { if (stream.eat("=")) { if (ch == "!" || ch == "=") stream.eat("=") } else if (/[<>*+\-|&?]/.test(ch)) { stream.eat(ch) if (ch == ">") stream.eat(ch) } } if (ch == "?" && stream.eat(".")) return ret(".") return ret("operator", "operator", stream.current()); } else if (wordRE.test(ch)) { stream.eatWhile(wordRE); var word = stream.current() if (state.lastType != ".") { if (keywords.propertyIsEnumerable(word)) { var kw = keywords[word] return ret(kw.type, kw.style, word) } if (word == "async" && stream.match(/^(\s|\/\*([^*]|\*(?!\/))*?\*\/)*[\[\(\w]/, false)) return ret("async", "keyword", word) } return ret("variable", "variable", word) } } function tokenString(quote) { return function(stream, state) { var escaped = false, next; if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)){ state.tokenize = tokenBase; return ret("jsonld-keyword", "meta"); } while ((next = stream.next()) != null) { if (next == quote && !escaped) break; escaped = !escaped && next == "\\"; } if (!escaped) state.tokenize = tokenBase; return ret("string", "string"); }; } function tokenComment(stream, state) { var maybeEnd = false, ch; while (ch = stream.next()) { if (ch == "/" && maybeEnd) { state.tokenize = tokenBase; break; } maybeEnd = (ch == "*"); } return ret("comment", "comment"); } function tokenQuasi(stream, state) { var escaped = false, next; while ((next = stream.next()) != null) { if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) { state.tokenize = tokenBase; break; } escaped = !escaped && next == "\\"; } return ret("quasi", "string-2", stream.current()); } var brackets = "([{}])"; // This is a crude lookahead trick to try and notice that we're // parsing the argument patterns for a fat-arrow function before we // actually hit the arrow token. It only works if the arrow is on // the same line as the arguments and there's no strange noise // (comments) in between. Fallback is to only notice when we hit the // arrow, and not declare the arguments as locals for the arrow // body. function findFatArrow(stream, state) { if (state.fatArrowAt) state.fatArrowAt = null; var arrow = stream.string.indexOf("=>", stream.start); if (arrow < 0) return; if (isTS) { // Try to skip TypeScript return type declarations after the arguments var m = /:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(stream.string.slice(stream.start, arrow)) if (m) arrow = m.index } var depth = 0, sawSomething = false; for (var pos = arrow - 1; pos >= 0; --pos) { var ch = stream.string.charAt(pos); var bracket = brackets.indexOf(ch); if (bracket >= 0 && bracket < 3) { if (!depth) { ++pos; break; } if (--depth == 0) { if (ch == "(") sawSomething = true; break; } } else if (bracket >= 3 && bracket < 6) { ++depth; } else if (wordRE.test(ch)) { sawSomething = true; } else if (/["'\/`]/.test(ch)) { for (;; --pos) { if (pos == 0) return var next = stream.string.charAt(pos - 1) if (next == ch && stream.string.charAt(pos - 2) != "\\") { pos--; break } } } else if (sawSomething && !depth) { ++pos; break; } } if (sawSomething && !depth) state.fatArrowAt = pos; } // Parser var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true, "import": true, "jsonld-keyword": true}; function JSLexical(indented, column, type, align, prev, info) { this.indented = indented; this.column = column; this.type = type; this.prev = prev; this.info = info; if (align != null) this.align = align; } function inScope(state, varname) { if (!trackScope) return false for (var v = state.localVars; v; v = v.next) if (v.name == varname) return true; for (var cx = state.context; cx; cx = cx.prev) { for (var v = cx.vars; v; v = v.next) if (v.name == varname) return true; } } function parseJS(state, style, type, content, stream) { var cc = state.cc; // Communicate our context to the combinators. // (Less wasteful than consing up a hundred closures on every call.) cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; cx.style = style; if (!state.lexical.hasOwnProperty("align")) state.lexical.align = true; while(true) { var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement; if (combinator(type, content)) { while(cc.length && cc[cc.length - 1].lex) cc.pop()(); if (cx.marked) return cx.marked; if (type == "variable" && inScope(state, content)) return "variable-2"; return style; } } } // Combinator utils var cx = {state: null, column: null, marked: null, cc: null}; function pass() { for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]); } function cont() { pass.apply(null, arguments); return true; } function inList(name, list) { for (var v = list; v; v = v.next) if (v.name == name) return true return false; } function register(varname) { var state = cx.state; cx.marked = "def"; if (!trackScope) return if (state.context) { if (state.lexical.info == "var" && state.context && state.context.block) { // FIXME function decls are also not block scoped var newContext = registerVarScoped(varname, state.context) if (newContext != null) { state.context = newContext return } } else if (!inList(varname, state.localVars)) { state.localVars = new Var(varname, state.localVars) return } } // Fall through means this is global if (parserConfig.globalVars && !inList(varname, state.globalVars)) state.globalVars = new Var(varname, state.globalVars) } function registerVarScoped(varname, context) { if (!context) { return null } else if (context.block) { var inner = registerVarScoped(varname, context.prev) if (!inner) return null if (inner == context.prev) return context return new Context(inner, context.vars, true) } else if (inList(varname, context.vars)) { return context } else { return new Context(context.prev, new Var(varname, context.vars), false) } } function isModifier(name) { return name == "public" || name == "private" || name == "protected" || name == "abstract" || name == "readonly" } // Combinators function Context(prev, vars, block) { this.prev = prev; this.vars = vars; this.block = block } function Var(name, next) { this.name = name; this.next = next } var defaultVars = new Var("this", new Var("arguments", null)) function pushcontext() { cx.state.context = new Context(cx.state.context, cx.state.localVars, false) cx.state.localVars = defaultVars } function pushblockcontext() { cx.state.context = new Context(cx.state.context, cx.state.localVars, true) cx.state.localVars = null } pushcontext.lex = pushblockcontext.lex = true function popcontext() { cx.state.localVars = cx.state.context.vars cx.state.context = cx.state.context.prev } popcontext.lex = true function pushlex(type, info) { var result = function() { var state = cx.state, indent = state.indented; if (state.lexical.type == "stat") indent = state.lexical.indented; else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev) indent = outer.indented; state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info); }; result.lex = true; return result; } function poplex() { var state = cx.state; if (state.lexical.prev) { if (state.lexical.type == ")") state.indented = state.lexical.indented; state.lexical = state.lexical.prev; } } poplex.lex = true; function expect(wanted) { function exp(type) { if (type == wanted) return cont(); else if (wanted == ";" || type == "}" || type == ")" || type == "]") return pass(); else return cont(exp); }; return exp; } function statement(type, value) { if (type == "var") return cont(pushlex("vardef", value), vardef, expect(";"), poplex); if (type == "keyword a") return cont(pushlex("form"), parenExpr, statement, poplex); if (type == "keyword b") return cont(pushlex("form"), statement, poplex); if (type == "keyword d") return cx.stream.match(/^\s*$/, false) ? cont() : cont(pushlex("stat"), maybeexpression, expect(";"), poplex); if (type == "debugger") return cont(expect(";")); if (type == "{") return cont(pushlex("}"), pushblockcontext, block, poplex, popcontext); if (type == ";") return cont(); if (type == "if") { if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex) cx.state.cc.pop()(); return cont(pushlex("form"), parenExpr, statement, poplex, maybeelse); } if (type == "function") return cont(functiondef); if (type == "for") return cont(pushlex("form"), pushblockcontext, forspec, statement, popcontext, poplex); if (type == "class" || (isTS && value == "interface")) { cx.marked = "keyword" return cont(pushlex("form", type == "class" ? type : value), className, poplex) } if (type == "variable") { if (isTS && value == "declare") { cx.marked = "keyword" return cont(statement) } else if (isTS && (value == "module" || value == "enum" || value == "type") && cx.stream.match(/^\s*\w/, false)) { cx.marked = "keyword" if (value == "enum") return cont(enumdef); else if (value == "type") return cont(typename, expect("operator"), typeexpr, expect(";")); else return cont(pushlex("form"), pattern, expect("{"), pushlex("}"), block, poplex, poplex) } else if (isTS && value == "namespace") { cx.marked = "keyword" return cont(pushlex("form"), expression, statement, poplex) } else if (isTS && value == "abstract") { cx.marked = "keyword" return cont(statement) } else { return cont(pushlex("stat"), maybelabel); } } if (type == "switch") return cont(pushlex("form"), parenExpr, expect("{"), pushlex("}", "switch"), pushblockcontext, block, poplex, poplex, popcontext); if (type == "case") return cont(expression, expect(":")); if (type == "default") return cont(expect(":")); if (type == "catch") return cont(pushlex("form"), pushcontext, maybeCatchBinding, statement, poplex, popcontext); if (type == "export") return cont(pushlex("stat"), afterExport, poplex); if (type == "import") return cont(pushlex("stat"), afterImport, poplex); if (type == "async") return cont(statement) if (value == "@") return cont(expression, statement) return pass(pushlex("stat"), expression, expect(";"), poplex); } function maybeCatchBinding(type) { if (type == "(") return cont(funarg, expect(")")) } function expression(type, value) { return expressionInner(type, value, false); } function expressionNoComma(type, value) { return expressionInner(type, value, true); } function parenExpr(type) { if (type != "(") return pass() return cont(pushlex(")"), maybeexpression, expect(")"), poplex) } function expressionInner(type, value, noComma) { if (cx.state.fatArrowAt == cx.stream.start) { var body = noComma ? arrowBodyNoComma : arrowBody; if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, expect("=>"), body, popcontext); else if (type == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext); } var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma; if (atomicTypes.hasOwnProperty(type)) return cont(maybeop); if (type == "function") return cont(functiondef, maybeop); if (type == "class" || (isTS && value == "interface")) { cx.marked = "keyword"; return cont(pushlex("form"), classExpression, poplex); } if (type == "keyword c" || type == "async") return cont(noComma ? expressionNoComma : expression); if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeop); if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression); if (type == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop); if (type == "{") return contCommasep(objprop, "}", null, maybeop); if (type == "quasi") return pass(quasi, maybeop); if (type == "new") return cont(maybeTarget(noComma)); return cont(); } function maybeexpression(type) { if (type.match(/[;\}\)\],]/)) return pass(); return pass(expression); } function maybeoperatorComma(type, value) { if (type == ",") return cont(maybeexpression); return maybeoperatorNoComma(type, value, false); } function maybeoperatorNoComma(type, value, noComma) { var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma; var expr = noComma == false ? expression : expressionNoComma; if (type == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext); if (type == "operator") { if (/\+\+|--/.test(value) || isTS && value == "!") return cont(me); if (isTS && value == "<" && cx.stream.match(/^([^<>]|<[^<>]*>)*>\s*\(/, false)) return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, me); if (value == "?") return cont(expression, expect(":"), expr); return cont(expr); } if (type == "quasi") { return pass(quasi, me); } if (type == ";") return; if (type == "(") return contCommasep(expressionNoComma, ")", "call", me); if (type == ".") return cont(property, me); if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me); if (isTS && value == "as") { cx.marked = "keyword"; return cont(typeexpr, me) } if (type == "regexp") { cx.state.lastType = cx.marked = "operator" cx.stream.backUp(cx.stream.pos - cx.stream.start - 1) return cont(expr) } } function quasi(type, value) { if (type != "quasi") return pass(); if (value.slice(value.length - 2) != "${") return cont(quasi); return cont(maybeexpression, continueQuasi); } function continueQuasi(type) { if (type == "}") { cx.marked = "string-2"; cx.state.tokenize = tokenQuasi; return cont(quasi); } } function arrowBody(type) { findFatArrow(cx.stream, cx.state); return pass(type == "{" ? statement : expression); } function arrowBodyNoComma(type) { findFatArrow(cx.stream, cx.state); return pass(type == "{" ? statement : expressionNoComma); } function maybeTarget(noComma) { return function(type) { if (type == ".") return cont(noComma ? targetNoComma : target); else if (type == "variable" && isTS) return cont(maybeTypeArgs, noComma ? maybeoperatorNoComma : maybeoperatorComma) else return pass(noComma ? expressionNoComma : expression); }; } function target(_, value) { if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorComma); } } function targetNoComma(_, value) { if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorNoComma); } } function maybelabel(type) { if (type == ":") return cont(poplex, statement); return pass(maybeoperatorComma, expect(";"), poplex); } function property(type) { if (type == "variable") {cx.marked = "property"; return cont();} } function objprop(type, value) { if (type == "async") { cx.marked = "property"; return cont(objprop); } else if (type == "variable" || cx.style == "keyword") { cx.marked = "property"; if (value == "get" || value == "set") return cont(getterSetter); var m // Work around fat-arrow-detection complication for detecting typescript typed arrow params if (isTS && cx.state.fatArrowAt == cx.stream.start && (m = cx.stream.match(/^\s*:\s*/, false))) cx.state.fatArrowAt = cx.stream.pos + m[0].length return cont(afterprop); } else if (type == "number" || type == "string") { cx.marked = jsonldMode ? "property" : (cx.style + " property"); return cont(afterprop); } else if (type == "jsonld-keyword") { return cont(afterprop); } else if (isTS && isModifier(value)) { cx.marked = "keyword" return cont(objprop) } else if (type == "[") { return cont(expression, maybetype, expect("]"), afterprop); } else if (type == "spread") { return cont(expressionNoComma, afterprop); } else if (value == "*") { cx.marked = "keyword"; return cont(objprop); } else if (type == ":") { return pass(afterprop) } } function getterSetter(type) { if (type != "variable") return pass(afterprop); cx.marked = "property"; return cont(functiondef); } function afterprop(type) { if (type == ":") return cont(expressionNoComma); if (type == "(") return pass(functiondef); } function commasep(what, end, sep) { function proceed(type, value) { if (sep ? sep.indexOf(type) > -1 : type == ",") { var lex = cx.state.lexical; if (lex.info == "call") lex.pos = (lex.pos || 0) + 1; return cont(function(type, value) { if (type == end || value == end) return pass() return pass(what) }, proceed); } if (type == end || value == end) return cont(); if (sep && sep.indexOf(";") > -1) return pass(what) return cont(expect(end)); } return function(type, value) { if (type == end || value == end) return cont(); return pass(what, proceed); }; } function contCommasep(what, end, info) { for (var i = 3; i < arguments.length; i++) cx.cc.push(arguments[i]); return cont(pushlex(end, info), commasep(what, end), poplex); } function block(type) { if (type == "}") return cont(); return pass(statement, block); } function maybetype(type, value) { if (isTS) { if (type == ":") return cont(typeexpr); if (value == "?") return cont(maybetype); } } function maybetypeOrIn(type, value) { if (isTS && (type == ":" || value == "in")) return cont(typeexpr) } function mayberettype(type) { if (isTS && type == ":") { if (cx.stream.match(/^\s*\w+\s+is\b/, false)) return cont(expression, isKW, typeexpr) else return cont(typeexpr) } } function isKW(_, value) { if (value == "is") { cx.marked = "keyword" return cont() } } function typeexpr(type, value) { if (value == "keyof" || value == "typeof" || value == "infer" || value == "readonly") { cx.marked = "keyword" return cont(value == "typeof" ? expressionNoComma : typeexpr) } if (type == "variable" || value == "void") { cx.marked = "type" return cont(afterType) } if (value == "|" || value == "&") return cont(typeexpr) if (type == "string" || type == "number" || type == "atom") return cont(afterType); if (type == "[") return cont(pushlex("]"), commasep(typeexpr, "]", ","), poplex, afterType) if (type == "{") return cont(pushlex("}"), typeprops, poplex, afterType) if (type == "(") return cont(commasep(typearg, ")"), maybeReturnType, afterType) if (type == "<") return cont(commasep(typeexpr, ">"), typeexpr) if (type == "quasi") { return pass(quasiType, afterType); } } function maybeReturnType(type) { if (type == "=>") return cont(typeexpr) } function typeprops(type) { if (type.match(/[\}\)\]]/)) return cont() if (type == "," || type == ";") return cont(typeprops) return pass(typeprop, typeprops) } function typeprop(type, value) { if (type == "variable" || cx.style == "keyword") { cx.marked = "property" return cont(typeprop) } else if (value == "?" || type == "number" || type == "string") { return cont(typeprop) } else if (type == ":") { return cont(typeexpr) } else if (type == "[") { return cont(expect("variable"), maybetypeOrIn, expect("]"), typeprop) } else if (type == "(") { return pass(functiondecl, typeprop) } else if (!type.match(/[;\}\)\],]/)) { return cont() } } function quasiType(type, value) { if (type != "quasi") return pass(); if (value.slice(value.length - 2) != "${") return cont(quasiType); return cont(typeexpr, continueQuasiType); } function continueQuasiType(type) { if (type == "}") { cx.marked = "string-2"; cx.state.tokenize = tokenQuasi; return cont(quasiType); } } function typearg(type, value) { if (type == "variable" && cx.stream.match(/^\s*[?:]/, false) || value == "?") return cont(typearg) if (type == ":") return cont(typeexpr) if (type == "spread") return cont(typearg) return pass(typeexpr) } function afterType(type, value) { if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType) if (value == "|" || type == "." || value == "&") return cont(typeexpr) if (type == "[") return cont(typeexpr, expect("]"), afterType) if (value == "extends" || value == "implements") { cx.marked = "keyword"; return cont(typeexpr) } if (value == "?") return cont(typeexpr, expect(":"), typeexpr) } function maybeTypeArgs(_, value) { if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType) } function typeparam() { return pass(typeexpr, maybeTypeDefault) } function maybeTypeDefault(_, value) { if (value == "=") return cont(typeexpr) } function vardef(_, value) { if (value == "enum") {cx.marked = "keyword"; return cont(enumdef)} return pass(pattern, maybetype, maybeAssign, vardefCont); } function pattern(type, value) { if (isTS && isModifier(value)) { cx.marked = "keyword"; return cont(pattern) } if (type == "variable") { register(value); return cont(); } if (type == "spread") return cont(pattern); if (type == "[") return contCommasep(eltpattern, "]"); if (type == "{") return contCommasep(proppattern, "}"); } function proppattern(type, value) { if (type == "variable" && !cx.stream.match(/^\s*:/, false)) { register(value); return cont(maybeAssign); } if (type == "variable") cx.marked = "property"; if (type == "spread") return cont(pattern); if (type == "}") return pass(); if (type == "[") return cont(expression, expect(']'), expect(':'), proppattern); return cont(expect(":"), pattern, maybeAssign); } function eltpattern() { return pass(pattern, maybeAssign) } function maybeAssign(_type, value) { if (value == "=") return cont(expressionNoComma); } function vardefCont(type) { if (type == ",") return cont(vardef); } function maybeelse(type, value) { if (type == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex); } function forspec(type, value) { if (value == "await") return cont(forspec); if (type == "(") return cont(pushlex(")"), forspec1, poplex); } function forspec1(type) { if (type == "var") return cont(vardef, forspec2); if (type == "variable") return cont(forspec2); return pass(forspec2) } function forspec2(type, value) { if (type == ")") return cont() if (type == ";") return cont(forspec2) if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression, forspec2) } return pass(expression, forspec2) } function functiondef(type, value) { if (value == "*") {cx.marked = "keyword"; return cont(functiondef);} if (type == "variable") {register(value); return cont(functiondef);} if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, statement, popcontext); if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondef) } function functiondecl(type, value) { if (value == "*") {cx.marked = "keyword"; return cont(functiondecl);} if (type == "variable") {register(value); return cont(functiondecl);} if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, popcontext); if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondecl) } function typename(type, value) { if (type == "keyword" || type == "variable") { cx.marked = "type" return cont(typename) } else if (value == "<") { return cont(pushlex(">"), commasep(typeparam, ">"), poplex) } } function funarg(type, value) { if (value == "@") cont(expression, funarg) if (type == "spread") return cont(funarg); if (isTS && isModifier(value)) { cx.marked = "keyword"; return cont(funarg); } if (isTS && type == "this") return cont(maybetype, maybeAssign) return pass(pattern, maybetype, maybeAssign); } function classExpression(type, value) { // Class expressions may have an optional name. if (type == "variable") return className(type, value); return classNameAfter(type, value); } function className(type, value) { if (type == "variable") {register(value); return cont(classNameAfter);} } function classNameAfter(type, value) { if (value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, classNameAfter) if (value == "extends" || value == "implements" || (isTS && type == ",")) { if (value == "implements") cx.marked = "keyword"; return cont(isTS ? typeexpr : expression, classNameAfter); } if (type == "{") return cont(pushlex("}"), classBody, poplex); } function classBody(type, value) { if (type == "async" || (type == "variable" && (value == "static" || value == "get" || value == "set" || (isTS && isModifier(value))) && cx.stream.match(/^\s+#?[\w$\xa1-\uffff]/, false))) { cx.marked = "keyword"; return cont(classBody); } if (type == "variable" || cx.style == "keyword") { cx.marked = "property"; return cont(classfield, classBody); } if (type == "number" || type == "string") return cont(classfield, classBody); if (type == "[") return cont(expression, maybetype, expect("]"), classfield, classBody) if (value == "*") { cx.marked = "keyword"; return cont(classBody); } if (isTS && type == "(") return pass(functiondecl, classBody) if (type == ";" || type == ",") return cont(classBody); if (type == "}") return cont(); if (value == "@") return cont(expression, classBody) } function classfield(type, value) { if (value == "!") return cont(classfield) if (value == "?") return cont(classfield) if (type == ":") return cont(typeexpr, maybeAssign) if (value == "=") return cont(expressionNoComma) var context = cx.state.lexical.prev, isInterface = context && context.info == "interface" return pass(isInterface ? functiondecl : functiondef) } function afterExport(type, value) { if (value == "*") { cx.marked = "keyword"; return cont(maybeFrom, expect(";")); } if (value == "default") { cx.marked = "keyword"; return cont(expression, expect(";")); } if (type == "{") return cont(commasep(exportField, "}"), maybeFrom, expect(";")); return pass(statement); } function exportField(type, value) { if (value == "as") { cx.marked = "keyword"; return cont(expect("variable")); } if (type == "variable") return pass(expressionNoComma, exportField); } function afterImport(type) { if (type == "string") return cont(); if (type == "(") return pass(expression); if (type == ".") return pass(maybeoperatorComma); return pass(importSpec, maybeMoreImports, maybeFrom); } function importSpec(type, value) { if (type == "{") return contCommasep(importSpec, "}"); if (type == "variable") register(value); if (value == "*") cx.marked = "keyword"; return cont(maybeAs); } function maybeMoreImports(type) { if (type == ",") return cont(importSpec, maybeMoreImports) } function maybeAs(_type, value) { if (value == "as") { cx.marked = "keyword"; return cont(importSpec); } } function maybeFrom(_type, value) { if (value == "from") { cx.marked = "keyword"; return cont(expression); } } function arrayLiteral(type) { if (type == "]") return cont(); return pass(commasep(expressionNoComma, "]")); } function enumdef() { return pass(pushlex("form"), pattern, expect("{"), pushlex("}"), commasep(enummember, "}"), poplex, poplex) } function enummember() { return pass(pattern, maybeAssign); } function isContinuedStatement(state, textAfter) { return state.lastType == "operator" || state.lastType == "," || isOperatorChar.test(textAfter.charAt(0)) || /[,.]/.test(textAfter.charAt(0)); } function expressionAllowed(stream, state, backUp) { return state.tokenize == tokenBase && /^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(state.lastType) || (state.lastType == "quasi" && /\{\s*$/.test(stream.string.slice(0, stream.pos - (backUp || 0)))) } // Interface return { startState: function(basecolumn) { var state = { tokenize: tokenBase, lastType: "sof", cc: [], lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false), localVars: parserConfig.localVars, context: parserConfig.localVars && new Context(null, null, false), indented: basecolumn || 0 }; if (parserConfig.globalVars && typeof parserConfig.globalVars == "object") state.globalVars = parserConfig.globalVars; return state; }, token: function(stream, state) { if (stream.sol()) { if (!state.lexical.hasOwnProperty("align")) state.lexical.align = false; state.indented = stream.indentation(); findFatArrow(stream, state); } if (state.tokenize != tokenComment && stream.eatSpace()) return null; var style = state.tokenize(stream, state); if (type == "comment") return style; state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type; return parseJS(state, style, type, content, stream); }, indent: function(state, textAfter) { if (state.tokenize == tokenComment || state.tokenize == tokenQuasi) return CodeMirror.Pass; if (state.tokenize != tokenBase) return 0; var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical, top // Kludge to prevent 'maybelse' from blocking lexical scope pops if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) { var c = state.cc[i]; if (c == poplex) lexical = lexical.prev; else if (c != maybeelse && c != popcontext) break; } while ((lexical.type == "stat" || lexical.type == "form") && (firstChar == "}" || ((top = state.cc[state.cc.length - 1]) && (top == maybeoperatorComma || top == maybeoperatorNoComma) && !/^[,\.=+\-*:?[\(]/.test(textAfter)))) lexical = lexical.prev; if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat") lexical = lexical.prev; var type = lexical.type, closing = firstChar == type; if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info.length + 1 : 0); else if (type == "form" && firstChar == "{") return lexical.indented; else if (type == "form") return lexical.indented + indentUnit; else if (type == "stat") return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0); else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false) return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit); else if (lexical.align) return lexical.column + (closing ? 0 : 1); else return lexical.indented + (closing ? 0 : indentUnit); }, electricInput: /^\s*(?:case .*?:|default:|\{|\})$/, blockCommentStart: jsonMode ? null : "/*", blockCommentEnd: jsonMode ? null : "*/", blockCommentContinue: jsonMode ? null : " * ", lineComment: jsonMode ? null : "//", fold: "brace", closeBrackets: "()[]{}''\"\"``", helperType: jsonMode ? "json" : "javascript", jsonldMode: jsonldMode, jsonMode: jsonMode, expressionAllowed: expressionAllowed, skipExpression: function(state) { parseJS(state, "atom", "atom", "true", new CodeMirror.StringStream("", 2, null)) } }; }); CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/); CodeMirror.defineMIME("text/javascript", "javascript"); CodeMirror.defineMIME("text/ecmascript", "javascript"); CodeMirror.defineMIME("application/javascript", "javascript"); CodeMirror.defineMIME("application/x-javascript", "javascript"); CodeMirror.defineMIME("application/ecmascript", "javascript"); CodeMirror.defineMIME("application/json", { name: "javascript", json: true }); CodeMirror.defineMIME("application/x-json", { name: "javascript", json: true }); CodeMirror.defineMIME("application/manifest+json", { name: "javascript", json: true }) CodeMirror.defineMIME("application/ld+json", { name: "javascript", jsonld: true }); CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true }); CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true }); }); /***/ }), /***/ 589: /***/ ((__unused_webpack_module, __unused_webpack_exports, __nested_webpack_require_597835__) => { // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/5/LICENSE (function(mod) { if (true) // CommonJS mod(__nested_webpack_require_597835__(631)); else {} })(function(CodeMirror) { "use strict"; var htmlConfig = { autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true, 'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true, 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true, 'track': true, 'wbr': true, 'menuitem': true}, implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true, 'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true, 'th': true, 'tr': true}, contextGrabbers: { 'dd': {'dd': true, 'dt': true}, 'dt': {'dd': true, 'dt': true}, 'li': {'li': true}, 'option': {'option': true, 'optgroup': true}, 'optgroup': {'optgroup': true}, 'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true, 'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true, 'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true, 'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true, 'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true}, 'rp': {'rp': true, 'rt': true}, 'rt': {'rp': true, 'rt': true}, 'tbody': {'tbody': true, 'tfoot': true}, 'td': {'td': true, 'th': true}, 'tfoot': {'tbody': true}, 'th': {'td': true, 'th': true}, 'thead': {'tbody': true, 'tfoot': true}, 'tr': {'tr': true} }, doNotIndent: {"pre": true}, allowUnquoted: true, allowMissing: true, caseFold: true } var xmlConfig = { autoSelfClosers: {}, implicitlyClosed: {}, contextGrabbers: {}, doNotIndent: {}, allowUnquoted: false, allowMissing: false, allowMissingTagName: false, caseFold: false } CodeMirror.defineMode("xml", function(editorConf, config_) { var indentUnit = editorConf.indentUnit var config = {} var defaults = config_.htmlMode ? htmlConfig : xmlConfig for (var prop in defaults) config[prop] = defaults[prop] for (var prop in config_) config[prop] = config_[prop] // Return variables for tokenizers var type, setStyle; function inText(stream, state) { function chain(parser) { state.tokenize = parser; return parser(stream, state); } var ch = stream.next(); if (ch == "<") { if (stream.eat("!")) { if (stream.eat("[")) { if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>")); else return null; } else if (stream.match("--")) { return chain(inBlock("comment", "-->")); } else if (stream.match("DOCTYPE", true, true)) { stream.eatWhile(/[\w\._\-]/); return chain(doctype(1)); } else { return null; } } else if (stream.eat("?")) { stream.eatWhile(/[\w\._\-]/); state.tokenize = inBlock("meta", "?>"); return "meta"; } else { type = stream.eat("/") ? "closeTag" : "openTag"; state.tokenize = inTag; return "tag bracket"; } } else if (ch == "&") { var ok; if (stream.eat("#")) { if (stream.eat("x")) { ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";"); } else { ok = stream.eatWhile(/[\d]/) && stream.eat(";"); } } else { ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";"); } return ok ? "atom" : "error"; } else { stream.eatWhile(/[^&<]/); return null; } } inText.isInText = true; function inTag(stream, state) { var ch = stream.next(); if (ch == ">" || (ch == "/" && stream.eat(">"))) { state.tokenize = inText; type = ch == ">" ? "endTag" : "selfcloseTag"; return "tag bracket"; } else if (ch == "=") { type = "equals"; return null; } else if (ch == "<") { state.tokenize = inText; state.state = baseState; state.tagName = state.tagStart = null; var next = state.tokenize(stream, state); return next ? next + " tag error" : "tag error"; } else if (/[\'\"]/.test(ch)) { state.tokenize = inAttribute(ch); state.stringStartCol = stream.column(); return state.tokenize(stream, state); } else { stream.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/); return "word"; } } function inAttribute(quote) { var closure = function(stream, state) { while (!stream.eol()) { if (stream.next() == quote) { state.tokenize = inTag; break; } } return "string"; }; closure.isInAttribute = true; return closure; } function inBlock(style, terminator) { return function(stream, state) { while (!stream.eol()) { if (stream.match(terminator)) { state.tokenize = inText; break; } stream.next(); } return style; } } function doctype(depth) { return function(stream, state) { var ch; while ((ch = stream.next()) != null) { if (ch == "<") { state.tokenize = doctype(depth + 1); return state.tokenize(stream, state); } else if (ch == ">") { if (depth == 1) { state.tokenize = inText; break; } else { state.tokenize = doctype(depth - 1); return state.tokenize(stream, state); } } } return "meta"; }; } function lower(tagName) { return tagName && tagName.toLowerCase(); } function Context(state, tagName, startOfLine) { this.prev = state.context; this.tagName = tagName || ""; this.indent = state.indented; this.startOfLine = startOfLine; if (config.doNotIndent.hasOwnProperty(tagName) || (state.context && state.context.noIndent)) this.noIndent = true; } function popContext(state) { if (state.context) state.context = state.context.prev; } function maybePopContext(state, nextTagName) { var parentTagName; while (true) { if (!state.context) { return; } parentTagName = state.context.tagName; if (!config.contextGrabbers.hasOwnProperty(lower(parentTagName)) || !config.contextGrabbers[lower(parentTagName)].hasOwnProperty(lower(nextTagName))) { return; } popContext(state); } } function baseState(type, stream, state) { if (type == "openTag") { state.tagStart = stream.column(); return tagNameState; } else if (type == "closeTag") { return closeTagNameState; } else { return baseState; } } function tagNameState(type, stream, state) { if (type == "word") { state.tagName = stream.current(); setStyle = "tag"; return attrState; } else if (config.allowMissingTagName && type == "endTag") { setStyle = "tag bracket"; return attrState(type, stream, state); } else { setStyle = "error"; return tagNameState; } } function closeTagNameState(type, stream, state) { if (type == "word") { var tagName = stream.current(); if (state.context && state.context.tagName != tagName && config.implicitlyClosed.hasOwnProperty(lower(state.context.tagName))) popContext(state); if ((state.context && state.context.tagName == tagName) || config.matchClosing === false) { setStyle = "tag"; return closeState; } else { setStyle = "tag error"; return closeStateErr; } } else if (config.allowMissingTagName && type == "endTag") { setStyle = "tag bracket"; return closeState(type, stream, state); } else { setStyle = "error"; return closeStateErr; } } function closeState(type, _stream, state) { if (type != "endTag") { setStyle = "error"; return closeState; } popContext(state); return baseState; } function closeStateErr(type, stream, state) { setStyle = "error"; return closeState(type, stream, state); } function attrState(type, _stream, state) { if (type == "word") { setStyle = "attribute"; return attrEqState; } else if (type == "endTag" || type == "selfcloseTag") { var tagName = state.tagName, tagStart = state.tagStart; state.tagName = state.tagStart = null; if (type == "selfcloseTag" || config.autoSelfClosers.hasOwnProperty(lower(tagName))) { maybePopContext(state, tagName); } else { maybePopContext(state, tagName); state.context = new Context(state, tagName, tagStart == state.indented); } return baseState; } setStyle = "error"; return attrState; } function attrEqState(type, stream, state) { if (type == "equals") return attrValueState; if (!config.allowMissing) setStyle = "error"; return attrState(type, stream, state); } function attrValueState(type, stream, state) { if (type == "string") return attrContinuedState; if (type == "word" && config.allowUnquoted) {setStyle = "string"; return attrState;} setStyle = "error"; return attrState(type, stream, state); } function attrContinuedState(type, stream, state) { if (type == "string") return attrContinuedState; return attrState(type, stream, state); } return { startState: function(baseIndent) { var state = {tokenize: inText, state: baseState, indented: baseIndent || 0, tagName: null, tagStart: null, context: null} if (baseIndent != null) state.baseIndent = baseIndent return state }, token: function(stream, state) { if (!state.tagName && stream.sol()) state.indented = stream.indentation(); if (stream.eatSpace()) return null; type = null; var style = state.tokenize(stream, state); if ((style || type) && style != "comment") { setStyle = null; state.state = state.state(type || style, stream, state); if (setStyle) style = setStyle == "error" ? style + " error" : setStyle; } return style; }, indent: function(state, textAfter, fullLine) { var context = state.context; // Indent multi-line strings (e.g. css). if (state.tokenize.isInAttribute) { if (state.tagStart == state.indented) return state.stringStartCol + 1; else return state.indented + indentUnit; } if (context && context.noIndent) return CodeMirror.Pass; if (state.tokenize != inTag && state.tokenize != inText) return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0; // Indent the starts of attribute names. if (state.tagName) { if (config.multilineTagIndentPastTag !== false) return state.tagStart + state.tagName.length + 2; else return state.tagStart + indentUnit * (config.multilineTagIndentFactor || 1); } if (config.alignCDATA && /<!\[CDATA\[/.test(textAfter)) return 0; var tagAfter = textAfter && /^<(\/)?([\w_:\.-]*)/.exec(textAfter); if (tagAfter && tagAfter[1]) { // Closing tag spotted while (context) { if (context.tagName == tagAfter[2]) { context = context.prev; break; } else if (config.implicitlyClosed.hasOwnProperty(lower(context.tagName))) { context = context.prev; } else { break; } } } else if (tagAfter) { // Opening tag spotted while (context) { var grabbers = config.contextGrabbers[lower(context.tagName)]; if (grabbers && grabbers.hasOwnProperty(lower(tagAfter[2]))) context = context.prev; else break; } } while (context && context.prev && !context.startOfLine) context = context.prev; if (context) return context.indent + indentUnit; else return state.baseIndent || 0; }, electricInput: /<\/[\s\w:]+>$/, blockCommentStart: "<!--", blockCommentEnd: "-->", configuration: config.htmlMode ? "html" : "xml", helperType: config.htmlMode ? "html" : "xml", skipAttribute: function(state) { if (state.state == attrValueState) state.state = attrState }, xmlCurrentTag: function(state) { return state.tagName ? {name: state.tagName, close: state.type == "closeTag"} : null }, xmlCurrentContext: function(state) { var context = [] for (var cx = state.context; cx; cx = cx.prev) context.push(cx.tagName) return context.reverse() } }; }); CodeMirror.defineMIME("text/xml", "xml"); CodeMirror.defineMIME("application/xml", "xml"); if (!CodeMirror.mimeModes.hasOwnProperty("text/html")) CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true}); }); /***/ }), /***/ 642: /***/ ((__unused_webpack_module, __nested_webpack_exports__, __nested_webpack_require_611092__) => { /* harmony export */ __nested_webpack_require_611092__.d(__nested_webpack_exports__, { /* harmony export */ Z: () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var _common__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_611092__(346); var __extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ModuleModel = /** @class */ (function (_super) { __extends(ModuleModel, _super); function ModuleModel(module, attributes, options) { var _this = _super.call(this, attributes, options) || this; _this._module = module; return _this; } Object.defineProperty(ModuleModel.prototype, "module", { get: function () { return this._module; }, enumerable: false, configurable: true }); Object.defineProperty(ModuleModel.prototype, "config", { get: function () { return this._module.config; }, enumerable: false, configurable: true }); Object.defineProperty(ModuleModel.prototype, "em", { get: function () { return this._module.em; }, enumerable: false, configurable: true }); return ModuleModel; }(_common__WEBPACK_IMPORTED_MODULE_0__/* .Model */ .Hn)); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (ModuleModel); /***/ }), /***/ 675: /***/ ((__unused_webpack_module, __nested_webpack_exports__, __nested_webpack_require_613235__) => { /* harmony export */ __nested_webpack_require_613235__.d(__nested_webpack_exports__, { /* harmony export */ Z: () => (__WEBPACK_DEFAULT_EXPORT__), /* harmony export */ q: () => (/* binding */ CanvasSpotBuiltInTypes) /* harmony export */ }); /* harmony import */ var _abstract__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_613235__(642); var __extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var CanvasSpotBuiltInTypes; (function (CanvasSpotBuiltInTypes) { CanvasSpotBuiltInTypes["Select"] = "select"; CanvasSpotBuiltInTypes["Hover"] = "hover"; CanvasSpotBuiltInTypes["Spacing"] = "spacing"; CanvasSpotBuiltInTypes["Target"] = "target"; CanvasSpotBuiltInTypes["Resize"] = "resize"; })(CanvasSpotBuiltInTypes || (CanvasSpotBuiltInTypes = {})); /** * Canvas spots are elements drawn on top of the canvas. They can be used to represent anything you * might need but the most common use case of canvas spots is rendering information and managing * components rendered in the canvas. * Read here for more information about [Canvas Spots](https://grapesjs.com/docs/modules/Canvas.html#canvas-spots) * * [Component]: component.html * * @property {String} id Spot ID. * @property {String} type Spot type. * @property {[Component]} [component] Component to which the spot will be attached. * @property {ComponentView} [componentView] ComponentView to which the spot will be attached. * @property {Object} [boxRect] Fixed box rect of the spot, eg. `{ width: 100, height: 100, x: 0, y: 0 }`. * */ var CanvasSpot = /** @class */ (function (_super) { __extends(CanvasSpot, _super); function CanvasSpot() { return _super !== null && _super.apply(this, arguments) || this; } CanvasSpot.prototype.defaults = function () { return { id: '', type: '', }; }; Object.defineProperty(CanvasSpot.prototype, "type", { get: function () { return this.get('type') || ''; }, enumerable: false, configurable: true }); Object.defineProperty(CanvasSpot.prototype, "component", { get: function () { var _a; var cmp = this.get('component'); return cmp || ((_a = this.get('componentView')) === null || _a === void 0 ? void 0 : _a.model); }, enumerable: false, configurable: true }); Object.defineProperty(CanvasSpot.prototype, "componentView", { get: function () { var _a; var cmpView = this.get('componentView'); return cmpView || ((_a = this.get('component')) === null || _a === void 0 ? void 0 : _a.getView()); }, enumerable: false, configurable: true }); Object.defineProperty(CanvasSpot.prototype, "el", { get: function () { var _a; return (_a = this.componentView) === null || _a === void 0 ? void 0 : _a.el; }, enumerable: false, configurable: true }); /** * Get the box rect of the spot. * @param {Object} [opts={}] * @returns {Object} The box rect object * @example * canvasSpot.getBoxRect(); * // { width: 100, height: 50, x: 0, y: 0 } */ CanvasSpot.prototype.getBoxRect = function (opts) { var _a = this, el = _a.el, em = _a.em; var cvView = em.Canvas.getCanvasView(); var boxRect = this.get('boxRect'); if (boxRect) { return boxRect; } else if (el && cvView) { return cvView.getElBoxRect(el, opts); } return { x: 0, y: 0, width: 0, height: 0, }; }; /** * Get the style object of the spot. * @param {Object} [opts={}] * @returns {CSSStyleDeclaration} [opts] * @example * canvasSpot.getStyle(); * // { width: '100px', height: '...', ... } */ CanvasSpot.prototype.getStyle = function (opts) { if (opts === void 0) { opts = {}; } var _a = opts.boxRect || this.getBoxRect(opts), width = _a.width, height = _a.height, x = _a.x, y = _a.y; return { width: "".concat(width, "px"), height: "".concat(height, "px"), top: '0', left: '0', position: 'absolute', translate: "".concat(x, "px ").concat(y, "px"), }; }; /** * Check the spot type. * @param {String} type * @returns {Boolean} * @example * canvasSpot.isType('select'); */ CanvasSpot.prototype.isType = function (type) { return this.type === type; }; return CanvasSpot; }(_abstract__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .Z)); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (CanvasSpot); /***/ }), /***/ 858: /***/ ((__unused_webpack_module, __nested_webpack_exports__, __nested_webpack_require_618838__) => { __nested_webpack_require_618838__.r(__nested_webpack_exports__); /* harmony export */ __nested_webpack_require_618838__.d(__nested_webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ run: function (ed) { ed.Components.clear(); ed.Css.clear(); }, }); /***/ }), /***/ 884: /***/ ((__unused_webpack_module, __nested_webpack_exports__, __nested_webpack_require_619305__) => { __nested_webpack_require_619305__.r(__nested_webpack_exports__); /* harmony export */ __nested_webpack_require_619305__.d(__nested_webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_619305__(50); /* harmony import */ var _utils_Dragger__WEBPACK_IMPORTED_MODULE_2__ = __nested_webpack_require_619305__(668); /* harmony import */ var _utils_dom__WEBPACK_IMPORTED_MODULE_1__ = __nested_webpack_require_619305__(491); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ run: function (ed) { (0,underscore__WEBPACK_IMPORTED_MODULE_0__.bindAll)(this, 'onKeyUp', 'enableDragger', 'disableDragger'); this.editor = ed; this.canvasModel = this.canvas.getCanvasView().model; this.toggleMove(1); }, stop: function (ed) { this.toggleMove(); this.disableDragger(); }, onKeyUp: function (ev) { if ((0,_utils_dom__WEBPACK_IMPORTED_MODULE_1__/* .getKeyChar */ .sN)(ev) === ' ') { this.editor.stopCommand(this.id); } }, enableDragger: function (ev) { this.toggleDragger(1, ev); }, disableDragger: function (ev) { this.toggleDragger(0, ev); }, toggleDragger: function (enable, ev) { var _a = this, canvasModel = _a.canvasModel, em = _a.em; var dragger = this.dragger; var methodCls = enable ? 'add' : 'remove'; this.getCanvas().classList[methodCls]("".concat(this.ppfx, "is__grabbing")); if (!dragger) { dragger = new _utils_Dragger__WEBPACK_IMPORTED_MODULE_2__/* ["default"] */ .Z({ getPosition: function () { return { x: canvasModel.get('x'), y: canvasModel.get('y'), }; }, setPosition: function (_a) { var x = _a.x, y = _a.y; canvasModel.set({ x: x, y: y }); }, onStart: function (ev, dragger) { em.trigger('canvas:move:start', dragger); }, onDrag: function (ev, dragger) { em.trigger('canvas:move', dragger); }, onEnd: function (ev, dragger) { em.trigger('canvas:move:end', dragger); }, }); this.dragger = dragger; } enable ? dragger.start(ev) : dragger.stop(); }, toggleMove: function (enable) { var ppfx = this.ppfx; var methodCls = enable ? 'add' : 'remove'; var methodEv = enable ? 'on' : 'off'; var methodsEv = { on: _utils_dom__WEBPACK_IMPORTED_MODULE_1__.on, off: _utils_dom__WEBPACK_IMPORTED_MODULE_1__/* .off */ .S1 }; var canvas = this.getCanvas(); var classes = ["".concat(ppfx, "is__grab")]; !enable && classes.push("".concat(ppfx, "is__grabbing")); classes.forEach(function (cls) { return canvas.classList[methodCls](cls); }); methodsEv[methodEv](document, 'keyup', this.onKeyUp); methodsEv[methodEv](canvas, 'mousedown', this.enableDragger); methodsEv[methodEv](document, 'mouseup', this.disableDragger); }, }); /***/ }), /***/ 790: /***/ ((__unused_webpack_module, __nested_webpack_exports__, __nested_webpack_require_622687__) => { __nested_webpack_require_622687__.r(__nested_webpack_exports__); /* harmony export */ __nested_webpack_require_622687__.d(__nested_webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__), /* harmony export */ defineCommand: () => (/* binding */ defineCommand) /* harmony export */ }); /* harmony import */ var _common__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_622687__(346); var __extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); function defineCommand(def) { return def; } var CommandAbstract = /** @class */ (function (_super) { __extends(CommandAbstract, _super); function CommandAbstract(o) { var _this = _super.call(this, 0) || this; _this.config = o || {}; _this.em = _this.config.em || {}; var pfx = _this.config.stylePrefix; _this.pfx = pfx; _this.ppfx = _this.config.pStylePrefix; _this.hoverClass = "".concat(pfx, "hover"); _this.badgeClass = "".concat(pfx, "badge"); _this.plhClass = "".concat(pfx, "placeholder"); _this.freezClass = "".concat(_this.ppfx, "freezed"); _this.canvas = _this.em.Canvas; _this.init(_this.config); return _this; } /** * On frame scroll callback * @param {[type]} e [description] * @return {[type]} [description] */ CommandAbstract.prototype.onFrameScroll = function (e) { }; /** * Returns canval element * @return {HTMLElement} */ CommandAbstract.prototype.getCanvas = function () { return this.canvas.getElement(); }; /** * Get canvas body element * @return {HTMLElement} */ CommandAbstract.prototype.getCanvasBody = function () { return this.canvas.getBody(); }; /** * Get canvas wrapper element * @return {HTMLElement} */ CommandAbstract.prototype.getCanvasTools = function () { return this.canvas.getToolsEl(); }; /** * Get the offset of the element * @param {HTMLElement} el * @return {Object} */ CommandAbstract.prototype.offset = function (el) { var rect = el.getBoundingClientRect(); return { top: rect.top + el.ownerDocument.body.scrollTop, left: rect.left + el.ownerDocument.body.scrollLeft, }; }; /** * Callback triggered after initialize * @param {Object} o Options * @private * */ CommandAbstract.prototype.init = function (o) { }; /** * Method that run command * @param {Object} editor Editor instance * @param {Object} [options={}] Options * @private * */ CommandAbstract.prototype.callRun = function (editor, options) { if (options === void 0) { options = {}; } var id = this.id; editor.trigger("run:".concat(id, ":before"), options); if (options && options.abort) { editor.trigger("abort:".concat(id), options); return; } var sender = options.sender || editor; var result = this.run(editor, sender, options); editor.trigger("run:".concat(id), result, options); editor.trigger('run', id, result, options); return result; }; /** * Method that run command * @param {Object} editor Editor instance * @param {Object} [options={}] Options * @private * */ CommandAbstract.prototype.callStop = function (editor, options) { if (options === void 0) { options = {}; } var id = this.id; var sender = options.sender || editor; editor.trigger("stop:".concat(id, ":before"), options); var result = this.stop(editor, sender, options); editor.trigger("stop:".concat(id), result, options); editor.trigger('stop', id, result, options); return result; }; /** * Stop current command */ CommandAbstract.prototype.stopCommand = function (opts) { this.em.Commands.stop(this.id, opts); }; /** * Method that run command * @param {Object} em Editor model * @param {Object} sender Button sender * @private * */ CommandAbstract.prototype.run = function (em, sender, options) { }; /** * Method that stop command * @param {Object} em Editor model * @param {Object} sender Button sender * @private * */ CommandAbstract.prototype.stop = function (em, sender, options) { }; return CommandAbstract; }(_common__WEBPACK_IMPORTED_MODULE_0__/* .Model */ .Hn)); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (CommandAbstract); /***/ }), /***/ 180: /***/ ((__unused_webpack_module, __nested_webpack_exports__, __nested_webpack_require_628099__) => { __nested_webpack_require_628099__.r(__nested_webpack_exports__); /* harmony export */ __nested_webpack_require_628099__.d(__nested_webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_628099__(50); var __spreadArray = ( false) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var command = { run: function (ed, s, opts) { var _this = this; if (opts === void 0) { opts = {}; } var toSelect = []; var components = opts.component || ed.getSelectedAll(); components = (0,underscore__WEBPACK_IMPORTED_MODULE_0__.isArray)(components) ? __spreadArray([], components, true) : [components]; components.filter(Boolean).forEach(function (component) { if (!component.get('removable')) { toSelect.push(component); return _this.em.logWarning('The element is not removable', { component: component, }); } component.remove(); }); ed.select(toSelect); return components; }, }; /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (command); /***/ }), /***/ 544: /***/ ((__unused_webpack_module, __nested_webpack_exports__, __nested_webpack_require_629735__) => { __nested_webpack_require_629735__.r(__nested_webpack_exports__); /* harmony export */ __nested_webpack_require_629735__.d(__nested_webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_629735__(50); /* harmony import */ var _utils_Dragger__WEBPACK_IMPORTED_MODULE_1__ = __nested_webpack_require_629735__(668); var __assign = ( false) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var evName = 'dmode'; /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ run: function (editor, sender, opts) { var _this = this; if (opts === void 0) { opts = {}; } (0,underscore__WEBPACK_IMPORTED_MODULE_0__.bindAll)(this, 'setPosition', 'onStart', 'onDrag', 'onEnd', 'getPosition', 'getGuidesStatic', 'renderGuide', 'getGuidesTarget'); var target = opts.target, event = opts.event, mode = opts.mode, _a = opts.dragger, dragger = _a === void 0 ? {} : _a; var el = target.getEl(); var config = __assign({ doc: el.ownerDocument, onStart: this.onStart, onEnd: this.onEnd, onDrag: this.onDrag, getPosition: this.getPosition, setPosition: this.setPosition, guidesStatic: function () { return _this.guidesStatic; }, guidesTarget: function () { return _this.guidesTarget; } }, dragger); this.setupGuides(); this.opts = opts; this.editor = editor; this.em = editor.getModel(); this.target = target; this.isTran = mode == 'translate'; this.guidesContainer = this.getGuidesContainer(); this.guidesTarget = this.getGuidesTarget(); this.guidesStatic = this.getGuidesStatic(); var drg = this.dragger; if (!drg) { drg = new _utils_Dragger__WEBPACK_IMPORTED_MODULE_1__/* ["default"] */ .Z(config); this.dragger = drg; } else { drg.setOptions(config); } event && drg.start(event); this.toggleDrag(1); this.em.trigger("".concat(evName, ":start"), this.getEventOpts()); return drg; }, getEventOpts: function () { return { mode: this.opts.mode, target: this.target, guidesTarget: this.guidesTarget, guidesStatic: this.guidesStatic, }; }, stop: function () { this.toggleDrag(); }, setupGuides: function () { (this.guides || []).forEach(function (item) { var guide = item.guide; guide && guide.parentNode.removeChild(guide); }); this.guides = []; }, getGuidesContainer: function () { var _this = this; var guidesEl = this.guidesEl; if (!guidesEl) { var _a = this, editor = _a.editor, em = _a.em, opts_1 = _a.opts; var pfx = editor.getConfig().stylePrefix; var elInfoX = document.createElement('div'); var elInfoY = document.createElement('div'); var guideContent = "<div class=\"".concat(pfx, "guide-info__line ").concat(pfx, "danger-bg\">\n <div class=\"").concat(pfx, "guide-info__content ").concat(pfx, "danger-color\"></div>\n </div>"); guidesEl = document.createElement('div'); guidesEl.className = "".concat(pfx, "guides"); elInfoX.className = "".concat(pfx, "guide-info ").concat(pfx, "guide-info__x"); elInfoY.className = "".concat(pfx, "guide-info ").concat(pfx, "guide-info__y"); elInfoX.innerHTML = guideContent; elInfoY.innerHTML = guideContent; guidesEl.appendChild(elInfoX); guidesEl.appendChild(elInfoY); editor.Canvas.getGlobalToolsEl().appendChild(guidesEl); this.guidesEl = guidesEl; this.elGuideInfoX = elInfoX; this.elGuideInfoY = elInfoY; this.elGuideInfoContentX = elInfoX.querySelector(".".concat(pfx, "guide-info__content")); this.elGuideInfoContentY = elInfoY.querySelector(".".concat(pfx, "guide-info__content")); em.on('canvas:update frame:scroll', (0,underscore__WEBPACK_IMPORTED_MODULE_0__.debounce)(function () { var _a; _this.updateGuides(); opts_1.debug && ((_a = _this.guides) === null || _a === void 0 ? void 0 : _a.forEach(function (item) { return _this.renderGuide(item); })); }, 200)); } return guidesEl; }, getGuidesStatic: function () { var _this = this; var result = []; var el = this.target.getEl(); var _a = el.parentNode, parentNode = _a === void 0 ? {} : _a; (0,underscore__WEBPACK_IMPORTED_MODULE_0__.each)(parentNode.children, function (item) { return (result = result.concat(el !== item ? _this.getElementGuides(item) : [])); }); return result.concat(this.getElementGuides(parentNode)); }, getGuidesTarget: function () { return this.getElementGuides(this.target.getEl()); }, updateGuides: function (guides) { var _this = this; var lastEl; var lastPos; (guides || this.guides).forEach(function (item) { var origin = item.origin; var pos = lastEl === origin ? lastPos : _this.getElementPos(origin); lastEl = origin; lastPos = pos; (0,underscore__WEBPACK_IMPORTED_MODULE_0__.each)(_this.getGuidePosUpdate(item, pos), function (val, key) { return (item[key] = val); }); item.originRect = pos; }); }, getGuidePosUpdate: function (item, rect) { var result = {}; var top = rect.top, height = rect.height, left = rect.left, width = rect.width; switch (item.type) { case 't': result.y = top; break; case 'b': result.y = top + height; break; case 'l': result.x = left; break; case 'r': result.x = left + width; break; case 'x': result.x = left + width / 2; break; case 'y': result.y = top + height / 2; break; } return result; }, renderGuide: function (item) { if (item === void 0) { item = {}; } var el = item.guide || document.createElement('div'); var un = 'px'; var guideSize = item.active ? 2 : 1; var numEl = el.children[0]; el.style = "position: absolute; background-color: ".concat(item.active ? 'green' : 'red', ";"); if (!el.children.length) { numEl = document.createElement('div'); numEl.style = 'position: absolute; color: red; padding: 5px; top: 0; left: 0;'; el.appendChild(numEl); } if (item.y) { el.style.width = '100%'; el.style.height = "".concat(guideSize).concat(un); el.style.top = "".concat(item.y).concat(un); el.style.left = 0; } else { el.style.width = "".concat(guideSize).concat(un); el.style.height = '100%'; el.style.left = "".concat(item.x).concat(un); el.style.top = "0".concat(un); } !item.guide && this.guidesContainer.appendChild(el); return el; }, getElementPos: function (el) { return this.editor.Canvas.getElementPos(el, { noScroll: 1 }); }, getElementGuides: function (el) { var _this = this; var opts = this.opts; var originRect = this.getElementPos(el); var top = originRect.top, height = originRect.height, left = originRect.left, width = originRect.width; // @ts-ignore var guides = [ { type: 't', y: top }, { type: 'b', y: top + height }, { type: 'l', x: left }, { type: 'r', x: left + width }, { type: 'x', x: left + width / 2 }, { type: 'y', y: top + height / 2 }, // Mid y ].map(function (item) { return (__assign(__assign({}, item), { origin: el, originRect: originRect, guide: opts.debug && _this.renderGuide(item) })); }); guides.forEach(function (item) { var _a; return (_a = _this.guides) === null || _a === void 0 ? void 0 : _a.push(item); }); return guides; }, getTranslate: function (transform, axis) { if (axis === void 0) { axis = 'x'; } var result = 0; (transform || '').split(' ').forEach(function (item) { var itemStr = item.trim(); var fn = "translate".concat(axis.toUpperCase(), "("); if (itemStr.indexOf(fn) === 0) result = parseFloat(itemStr.replace(fn, '')); }); return result; }, setTranslate: function (transform, axis, value) { var fn = "translate".concat(axis.toUpperCase(), "("); var val = "".concat(fn).concat(value, ")"); var result = (transform || '') .split(' ') .map(function (item) { var itemStr = item.trim(); if (itemStr.indexOf(fn) === 0) item = val; return item; }) .join(' '); if (result.indexOf(fn) < 0) result += " ".concat(val); return result; }, getPosition: function () { var _a = this, target = _a.target, isTran = _a.isTran; var _b = target.getStyle(), left = _b.left, top = _b.top, transform = _b.transform; var x = 0; var y = 0; if (isTran) { x = this.getTranslate(transform); y = this.getTranslate(transform, 'y'); } else { x = parseFloat(left || 0); y = parseFloat(top || 0); } return { x: x, y: y }; }, setPosition: function (_a) { var x = _a.x, y = _a.y, end = _a.end, position = _a.position, width = _a.width, height = _a.height; var _b = this, target = _b.target, isTran = _b.isTran, em = _b.em; var unit = 'px'; var __p = !end; // Indicate if partial change var left = "".concat(parseInt(x, 10)).concat(unit); var top = "".concat(parseInt(y, 10)).concat(unit); var styleUp = {}; if (isTran) { var transform = target.getStyle()['transform'] || ''; transform = this.setTranslate(transform, 'x', left); transform = this.setTranslate(transform, 'y', top); styleUp = { transform: transform, __p: __p }; target.addStyle(styleUp, { avoidStore: !end }); } else { var adds_1 = { position: position, width: width, height: height }; var style_1 = { left: left, top: top, __p: __p }; (0,underscore__WEBPACK_IMPORTED_MODULE_0__.keys)(adds_1).forEach(function (add) { var prop = adds_1[add]; if (prop) style_1[add] = prop; }); styleUp = style_1; target.addStyle(styleUp, { avoidStore: !end }); } em === null || em === void 0 ? void 0 : em.Styles.__emitCmpStyleUpdate(styleUp, { components: em.getSelected() }); }, _getDragData: function () { var target = this.target; return { target: target, parent: target.parent(), index: target.index(), }; }, onStart: function (event) { var _a = this, target = _a.target, editor = _a.editor, isTran = _a.isTran, opts = _a.opts; var center = opts.center, onStart = opts.onStart; var Canvas = editor.Canvas; var style = target.getStyle(); var position = 'absolute'; var relPos = [position, 'relative']; onStart && onStart(this._getDragData()); if (isTran) return; if (style.position !== position) { var _b = Canvas.offset(target.getEl()), left = _b.left, top_1 = _b.top, width = _b.width, height = _b.height; var parent_1 = target.parent(); var parentRel = void 0; // Check for the relative parent do { var pStyle = parent_1.getStyle(); parentRel = relPos.indexOf(pStyle.position) >= 0 ? parent_1 : null; parent_1 = parent_1.parent(); } while (parent_1 && !parentRel); // Center the target to the pointer position (used in Droppable for Blocks) if (center) { var _c = Canvas.getMouseRelativeCanvas(event), x = _c.x, y = _c.y; left = x; top_1 = y; } else if (parentRel) { var offsetP = Canvas.offset(parentRel.getEl()); left = left - offsetP.left; top_1 = top_1 - offsetP.top; } this.setPosition({ x: left, y: top_1, width: "".concat(width, "px"), height: "".concat(height, "px"), position: position, }); } }, onDrag: function () { var _this = this; var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var _a = this, guidesTarget = _a.guidesTarget, opts = _a.opts; var onDrag = opts.onDrag; this.updateGuides(guidesTarget); opts.debug && guidesTarget.forEach(function (item) { return _this.renderGuide(item); }); opts.guidesInfo && this.renderGuideInfo(guidesTarget.filter(function (item) { return item.active; })); onDrag && onDrag(this._getDragData()); }, onEnd: function (ev, dragger, opt) { if (opt === void 0) { opt = {}; } var _a = this, editor = _a.editor, opts = _a.opts, id = _a.id; var onEnd = opts.onEnd; onEnd && onEnd(ev, opt, __assign(__assign({ event: ev }, opt), this._getDragData())); editor.stopCommand(id); this.hideGuidesInfo(); this.em.trigger("".concat(evName, ":end"), this.getEventOpts()); }, hideGuidesInfo: function () { var _this = this; ['X', 'Y'].forEach(function (item) { var guide = _this["elGuideInfo".concat(item)]; if (guide) guide.style.display = 'none'; }); }, /** * Render guides with spacing information */ renderGuideInfo: function (guides) { var _this = this; if (guides === void 0) { guides = []; } var guidesStatic = this.guidesStatic; this.hideGuidesInfo(); guides.forEach(function (item) { var origin = item.origin, x = item.x; var rectOrigin = _this.getElementPos(origin); var axis = (0,underscore__WEBPACK_IMPORTED_MODULE_0__.isUndefined)(x) ? 'y' : 'x'; var isY = axis === 'y'; var origEdge1 = rectOrigin[isY ? 'left' : 'top']; var origEdge1Raw = rectOrigin.rect[isY ? 'left' : 'top']; var origEdge2 = isY ? origEdge1 + rectOrigin.width : origEdge1 + rectOrigin.height; var origEdge2Raw = isY ? origEdge1Raw + rectOrigin.rect.width : origEdge1Raw + rectOrigin.rect.height; var elGuideInfo = _this["elGuideInfo".concat(axis.toUpperCase())]; var elGuideInfoCnt = _this["elGuideInfoContent".concat(axis.toUpperCase())]; var guideInfoStyle = elGuideInfo.style; // Find the nearest element var res = guidesStatic === null || guidesStatic === void 0 ? void 0 : guidesStatic.filter(function (stat) { return stat.type === item.type; }).map(function (stat) { var _a = stat.originRect, left = _a.left, width = _a.width, top = _a.top, height = _a.height; var statEdge1 = isY ? left : top; var statEdge2 = isY ? left + width : top + height; return { gap: statEdge2 < origEdge1 ? origEdge1 - statEdge2 : statEdge1 - origEdge2, guide: stat, }; }).filter(function (item) { return item.gap > 0; }).sort(function (a, b) { return a.gap - b.gap; }).map(function (item) { return item.guide; })[0]; if (res) { var _a = res.originRect, left = _a.left, width = _a.width, top_2 = _a.top, height = _a.height, rect = _a.rect; var isEdge1 = isY ? left < rectOrigin.left : top_2 < rectOrigin.top; var statEdge1 = isY ? left : top_2; var statEdge1Raw = isY ? rect.left : rect.top; var statEdge2 = isY ? left + width : top_2 + height; var statEdge2Raw = isY ? rect.left + rect.width : rect.top + rect.height; var posFirst = isY ? item.y : item.x; var posSecond = isEdge1 ? statEdge2 : origEdge2; var pos2 = "".concat(posFirst, "px"); var size = isEdge1 ? origEdge1 - statEdge2 : statEdge1 - origEdge2; var sizeRaw = isEdge1 ? origEdge1Raw - statEdge2Raw : statEdge1Raw - origEdge2Raw; guideInfoStyle.display = ''; guideInfoStyle[isY ? 'top' : 'left'] = pos2; guideInfoStyle[isY ? 'left' : 'top'] = "".concat(posSecond, "px"); guideInfoStyle[isY ? 'width' : 'height'] = "".concat(size, "px"); elGuideInfoCnt.innerHTML = "".concat(Math.round(sizeRaw), "px"); _this.em.trigger("".concat(evName, ":active"), __assign(__assign({}, _this.getEventOpts()), { guide: item, guidesStatic: guidesStatic, matched: res, posFirst: posFirst, posSecond: posSecond, size: size, sizeRaw: sizeRaw, elGuideInfo: elGuideInfo, elGuideInfoCnt: elGuideInfoCnt })); } }); }, toggleDrag: function (enable) { var _a = this, ppfx = _a.ppfx, editor = _a.editor; var methodCls = enable ? 'add' : 'remove'; var classes = ["".concat(ppfx, "is__grabbing")]; var Canvas = editor.Canvas; var body = Canvas.getBody(); classes.forEach(function (cls) { return body.classList[methodCls](cls); }); Canvas[enable ? 'startAutoscroll' : 'stopAutoscroll'](); }, }); /***/ }), /***/ 236: /***/ ((__unused_webpack_module, __nested_webpack_exports__, __nested_webpack_require_648393__) => { __nested_webpack_require_648393__.r(__nested_webpack_exports__); /* harmony export */ __nested_webpack_require_648393__.d(__nested_webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ run: function (ed) { if (!ed.Canvas.hasFocus()) return; var toSelect = []; ed.getSelectedAll().forEach(function (component) { var coll = component.components(); var next = coll && coll.filter(function (c) { return c.get('selectable'); })[0]; next && toSelect.push(next); }); toSelect.length && ed.select(toSelect); }, }); /***/ }), /***/ 368: /***/ ((__unused_webpack_module, __nested_webpack_exports__, __nested_webpack_require_649187__) => { __nested_webpack_require_649187__.r(__nested_webpack_exports__); /* harmony export */ __nested_webpack_require_649187__.d(__nested_webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ run: function (ed, snd, opts) { if (opts === void 0) { opts = {}; } if (!ed.Canvas.hasFocus() && !opts.force) return; var toSelect = []; ed.getSelectedAll().forEach(function (component) { var next = component.parent(); // Recurse through the parent() chain until a selectable parent is found while (next && !next.get('selectable')) { next = next.parent(); } next && toSelect.push(next); }); toSelect.length && ed.select(toSelect); }, }); /***/ }), /***/ 243: /***/ ((__unused_webpack_module, __nested_webpack_exports__, __nested_webpack_require_650145__) => { __nested_webpack_require_650145__.r(__nested_webpack_exports__); /* harmony export */ __nested_webpack_require_650145__.d(__nested_webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ run: function (ed) { if (!ed.Canvas.hasFocus()) return; var toSelect = []; ed.getSelectedAll().forEach(function (cmp) { var parent = cmp.parent(); if (!parent) return; var len = parent.components().length; var incr = 0; var at = 0; var next; // Get the next selectable component do { incr++; at = cmp.index() + incr; next = at <= len ? parent.getChildAt(at) : null; } while (next && !next.get('selectable')); toSelect.push(next || cmp); }); toSelect.length && ed.select(toSelect); }, }); /***/ }), /***/ 400: /***/ ((__unused_webpack_module, __nested_webpack_exports__, __nested_webpack_require_651253__) => { __nested_webpack_require_651253__.r(__nested_webpack_exports__); /* harmony export */ __nested_webpack_require_651253__.d(__nested_webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ run: function (ed) { if (!ed.Canvas.hasFocus()) return; var toSelect = []; ed.getSelectedAll().forEach(function (cmp) { var parent = cmp.parent(); if (!parent) return; var incr = 0; var at = 0; var next; // Get the first selectable component do { incr++; at = cmp.index() - incr; next = at >= 0 ? parent.getChildAt(at) : null; } while (next && !next.get('selectable')); toSelect.push(next || cmp); }); toSelect.length && ed.select(toSelect); }, }); /***/ }), /***/ 910: /***/ ((__unused_webpack_module, __nested_webpack_exports__, __nested_webpack_require_652310__) => { __nested_webpack_require_652310__.r(__nested_webpack_exports__); /* harmony export */ __nested_webpack_require_652310__.d(__nested_webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_652310__(50); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ run: function (ed, s, opts) { if (opts === void 0) { opts = {}; } var target = opts.target; var toRemove = []; if (!target.get('styles')) return toRemove; // Find all components in the project, of the target component type var type = target.get('type'); var wrappers = ed.Pages.getAllWrappers(); var len = (0,underscore__WEBPACK_IMPORTED_MODULE_0__.flatten)(wrappers.map(function (wrp) { return wrp.findType(type); })).length; // Remove component related styles only if there are no more components // of that type in the project if (!len) { var rules = ed.CssComposer.getAll(); toRemove = rules.filter(function (rule) { return rule.get('group') === "cmp:".concat(type); }); rules.remove(toRemove); } return toRemove; }, }); /***/ }), /***/ 744: /***/ ((__unused_webpack_module, __nested_webpack_exports__, __nested_webpack_require_653664__) => { __nested_webpack_require_653664__.r(__nested_webpack_exports__); /* harmony export */ __nested_webpack_require_653664__.d(__nested_webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); var __spreadArray = ( false) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ run: function (ed) { var em = ed.getModel(); var models = __spreadArray([], ed.getSelectedAll(), true); models.length && em.set('clipboard', models); }, }); /***/ }), /***/ 517: /***/ ((__unused_webpack_module, __nested_webpack_exports__, __nested_webpack_require_654620__) => { __nested_webpack_require_654620__.r(__nested_webpack_exports__); /* harmony export */ __nested_webpack_require_654620__.d(__nested_webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_654620__(50); /* harmony import */ var _common__WEBPACK_IMPORTED_MODULE_2__ = __nested_webpack_require_654620__(895); /* harmony import */ var _SelectComponent__WEBPACK_IMPORTED_MODULE_1__ = __nested_webpack_require_654620__(407); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ((0,underscore__WEBPACK_IMPORTED_MODULE_0__.extend)({}, _SelectComponent__WEBPACK_IMPORTED_MODULE_1__["default"], { init: function () { (0,underscore__WEBPACK_IMPORTED_MODULE_0__.bindAll)(this, 'startDelete', 'stopDelete', 'onDelete'); this.hoverClass = this.pfx + 'hover-delete'; this.badgeClass = this.pfx + 'badge-red'; }, enable: function () { var that = this; this.$el.find('*').mouseover(this.startDelete).mouseout(this.stopDelete).click(this.onDelete); }, /** * Start command * @param {Object} e * @private */ startDelete: function (e) { e.stopPropagation(); var $this = (0,_common__WEBPACK_IMPORTED_MODULE_2__["default"])(e.target); // Show badge if possible if ($this.data('model').get('removable')) { $this.addClass(this.hoverClass); this.attachBadge($this.get(0)); } }, /** * Stop command * @param {Object} e * @private */ stopDelete: function (e) { e.stopPropagation(); var $this = (0,_common__WEBPACK_IMPORTED_MODULE_2__["default"])(e.target); $this.removeClass(this.hoverClass); // Hide badge if possible if (this.badge) this.badge.css({ left: -1000, top: -1000 }); }, /** * Delete command * @param {Object} e * @private */ onDelete: function (e) { e.stopPropagation(); var $this = (0,_common__WEBPACK_IMPORTED_MODULE_2__["default"])(e.target); // Do nothing in case can't remove if (!$this.data('model').get('removable')) return; $this.data('model').destroy(); this.removeBadge(); this.clean(); }, /** * Updates badge label * @param {Object} model * @private * */ updateBadgeLabel: function (model) { this.badge.html('Remove ' + model.getName()); }, })); /***/ }), /***/ 457: /***/ ((__unused_webpack_module, __nested_webpack_exports__, __nested_webpack_require_657229__) => { __nested_webpack_require_657229__.r(__nested_webpack_exports__); /* harmony export */ __nested_webpack_require_657229__.d(__nested_webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var _utils_dom__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_657229__(491); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ run: function (editor, sender, opts) { var _this = this; if (opts === void 0) { opts = {}; } sender && sender.set && sender.set('active', 0); var config = editor.getConfig(); var modal = editor.Modal; var pfx = config.stylePrefix; this.cm = editor.CodeManager || null; if (!this.editors) { var oHtmlEd = this.buildEditor('htmlmixed', 'hopscotch', 'HTML'); var oCsslEd = this.buildEditor('css', 'hopscotch', 'CSS'); this.htmlEditor = oHtmlEd.model; this.cssEditor = oCsslEd.model; var editors = (0,_utils_dom__WEBPACK_IMPORTED_MODULE_0__/* .createEl */ .ut)('div', { class: "".concat(pfx, "export-dl") }); editors.appendChild(oHtmlEd.el); editors.appendChild(oCsslEd.el); this.editors = editors; } modal .open({ title: config.textViewCode, content: this.editors, }) .getModel() .once('change:open', function () { return editor.stopCommand("".concat(_this.id)); }); this.htmlEditor.setContent(editor.getHtml(opts.optsHtml)); this.cssEditor.setContent(editor.getCss(opts.optsCss)); }, stop: function (editor) { var modal = editor.Modal; modal && modal.close(); }, buildEditor: function (codeName, theme, label) { var cm = this.em.CodeManager; var model = cm.createViewer({ label: label, codeName: codeName, theme: theme, }); var el = new cm.EditorView({ model: model, config: cm.getConfig(), }).render().el; return { model: model, el: el }; }, }); /***/ }), /***/ 975: /***/ ((__unused_webpack_module, __nested_webpack_exports__, __nested_webpack_require_659452__) => { __nested_webpack_require_659452__.r(__nested_webpack_exports__); /* harmony export */ __nested_webpack_require_659452__.d(__nested_webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_659452__(50); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ /** * Check if fullscreen mode is enabled * @return {Boolean} */ isEnabled: function () { var d = document; // @ts-ignore if (d.fullscreenElement || d.webkitFullscreenElement || d.mozFullScreenElement) { return true; } return false; }, /** * Enable fullscreen mode and return browser prefix * @param {HTMLElement} el * @return {string} */ enable: function (el) { var pfx = ''; if (el.requestFullscreen) { el.requestFullscreen(); } else if (el.webkitRequestFullscreen) { pfx = 'webkit'; el.webkitRequestFullscreen(); } else if (el.mozRequestFullScreen) { pfx = 'moz'; el.mozRequestFullScreen(); } else if (el.msRequestFullscreen) { el.msRequestFullscreen(); } return pfx; }, /** * Disable fullscreen mode */ disable: function () { var d = document; if (this.isEnabled()) { if (d.exitFullscreen) d.exitFullscreen(); else if (d.webkitExitFullscreen) d.webkitExitFullscreen(); else if (d.mozCancelFullScreen) d.mozCancelFullScreen(); else if (d.msExitFullscreen) d.msExitFullscreen(); } }, /** * Triggered when the state of the fullscreen is changed. Inside detects if * it's enabled * @param {strinf} pfx Browser prefix * @param {Event} e */ fsChanged: function (pfx) { if (!this.isEnabled()) { this.stopCommand({ sender: this.sender }); document.removeEventListener("".concat(pfx || '', "fullscreenchange"), this.fsChanged); } }, run: function (editor, sender, opts) { if (opts === void 0) { opts = {}; } this.sender = sender; var target = opts.target; var targetEl = (0,underscore__WEBPACK_IMPORTED_MODULE_0__.isElement)(target) ? target : document.querySelector(target); var pfx = this.enable(targetEl || editor.getContainer()); this.fsChanged = this.fsChanged.bind(this, pfx); document.addEventListener(pfx + 'fullscreenchange', this.fsChanged); editor.trigger('change:canvasOffset'); }, stop: function (editor, sender) { if (sender && sender.set) sender.set('active', false); this.disable(); if (editor) editor.trigger('change:canvasOffset'); }, }); /***/ }), /***/ 191: /***/ ((__unused_webpack_module, __nested_webpack_exports__, __nested_webpack_require_662502__) => { __nested_webpack_require_662502__.r(__nested_webpack_exports__); /* harmony export */ __nested_webpack_require_662502__.d(__nested_webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_662502__(50); /* harmony import */ var _common__WEBPACK_IMPORTED_MODULE_3__ = __nested_webpack_require_662502__(895); /* harmony import */ var _utils_dom__WEBPACK_IMPORTED_MODULE_4__ = __nested_webpack_require_662502__(491); /* harmony import */ var _SelectComponent__WEBPACK_IMPORTED_MODULE_2__ = __nested_webpack_require_662502__(407); /* harmony import */ var _SelectPosition__WEBPACK_IMPORTED_MODULE_1__ = __nested_webpack_require_662502__(189); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ((0,underscore__WEBPACK_IMPORTED_MODULE_0__.extend)({}, _SelectPosition__WEBPACK_IMPORTED_MODULE_1__["default"], _SelectComponent__WEBPACK_IMPORTED_MODULE_2__["default"], { init: function (o) { _SelectComponent__WEBPACK_IMPORTED_MODULE_2__["default"].init.apply(this, arguments); (0,underscore__WEBPACK_IMPORTED_MODULE_0__.bindAll)(this, 'initSorter', 'rollback', 'onEndMove'); this.opt = o; this.hoverClass = this.ppfx + 'highlighter-warning'; this.badgeClass = this.ppfx + 'badge-warning'; this.noSelClass = this.ppfx + 'no-select'; }, enable: function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } _SelectComponent__WEBPACK_IMPORTED_MODULE_2__["default"].enable.apply(this, args); this.getBadgeEl().addClass(this.badgeClass); this.getHighlighterEl().addClass(this.hoverClass); var wp = this.$wrapper; wp.css('cursor', 'move'); wp.on('mousedown', this.initSorter); // Avoid strange moving behavior wp.addClass(this.noSelClass); }, /** * Overwrite for doing nothing * @private */ toggleClipboard: function () { }, /** * Delegate sorting * @param {Event} e * @private * */ initSorter: function (e) { var el = (0,_common__WEBPACK_IMPORTED_MODULE_3__["default"])(e.target).data('model'); var drag = el.get('draggable'); if (!drag) return; // Avoid badge showing on move this.cacheEl = null; this.startSelectPosition(e.target, this.frameEl.contentDocument); this.sorter.draggable = drag; this.sorter.onEndMove = this.onEndMove.bind(this); this.stopSelectComponent(); this.$wrapper.off('mousedown', this.initSorter); (0,_utils_dom__WEBPACK_IMPORTED_MODULE_4__.on)(this.getContentWindow(), 'keydown', this.rollback); }, /** * Init sorter from model * @param {Object} model * @private */ initSorterFromModel: function (model) { var drag = model.get('draggable'); if (!drag) return; // Avoid badge showing on move this.cacheEl = null; // @ts-ignore var el = model.view.el; this.startSelectPosition(el, this.frameEl.contentDocument); this.sorter.draggable = drag; this.sorter.onEndMove = this.onEndMoveFromModel.bind(this); /* this.sorter.setDragHelper(el); var dragHelper = this.sorter.dragHelper; dragHelper.className = this.ppfx + 'drag-helper'; dragHelper.innerHTML = ''; dragHelper.backgroundColor = 'white'; */ this.stopSelectComponent(); (0,_utils_dom__WEBPACK_IMPORTED_MODULE_4__.on)(this.getContentWindow(), 'keydown', this.rollback); }, /** * Init sorter from models * @param {Object} model * @private */ initSorterFromModels: function (models) { // TODO: if one only check for `draggable` // Avoid badge showing on move this.cacheEl = null; var lastModel = models[models.length - 1]; var frameView = this.em.getCurrentFrame(); var el = lastModel.getEl(frameView === null || frameView === void 0 ? void 0 : frameView.model); var doc = el.ownerDocument; this.startSelectPosition(el, doc, { onStart: this.onStart }); this.sorter.draggable = lastModel.get('draggable'); this.sorter.toMove = models; this.sorter.onMoveClb = this.onDrag; this.sorter.onEndMove = this.onEndMoveFromModel.bind(this); this.stopSelectComponent(); (0,_utils_dom__WEBPACK_IMPORTED_MODULE_4__.on)(this.getContentWindow(), 'keydown', this.rollback); }, onEndMoveFromModel: function () { (0,_utils_dom__WEBPACK_IMPORTED_MODULE_4__/* .off */ .S1)(this.getContentWindow(), 'keydown', this.rollback); }, /** * Callback after sorting * @private */ onEndMove: function () { this.enable(); (0,_utils_dom__WEBPACK_IMPORTED_MODULE_4__/* .off */ .S1)(this.getContentWindow(), 'keydown', this.rollback); }, /** * Say what to do after the component was selected (selectComponent) * @param {Event} e * @param {Object} Selected element * @private * */ onSelect: function (e, el) { }, /** * Used to bring the previous situation before start moving the component * @param {Event} e * @param {Boolean} Indicates if rollback in anycase * @private * */ rollback: function (e, force) { var key = e.which || e.keyCode; if (key == 27 || force) { this.sorter.moved = false; this.sorter.endMove(); } return; }, /** * Returns badge element * @return {HTMLElement} * @private */ getBadgeEl: function () { if (!this.$badge) this.$badge = (0,_common__WEBPACK_IMPORTED_MODULE_3__["default"])(this.getBadge()); return this.$badge; }, /** * Returns highlighter element * @return {HTMLElement} * @private */ getHighlighterEl: function () { if (!this.$hl) this.$hl = (0,_common__WEBPACK_IMPORTED_MODULE_3__["default"])(this.canvas.getHighlighter()); return this.$hl; }, stop: function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } // @ts-ignore _SelectComponent__WEBPACK_IMPORTED_MODULE_2__["default"].stop.apply(this, args); this.getBadgeEl().removeClass(this.badgeClass); this.getHighlighterEl().removeClass(this.hoverClass); var wp = this.$wrapper; wp.css('cursor', '').unbind().removeClass(this.noSelClass); }, })); /***/ }), /***/ 912: /***/ ((__unused_webpack_module, __nested_webpack_exports__, __nested_webpack_require_669262__) => { __nested_webpack_require_669262__.r(__nested_webpack_exports__); /* harmony export */ __nested_webpack_require_669262__.d(__nested_webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_669262__(50); /* harmony import */ var _utils_dom__WEBPACK_IMPORTED_MODULE_1__ = __nested_webpack_require_669262__(491); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ open: function (content) { var _this = this; var _a = this, editor = _a.editor, title = _a.title, config = _a.config, am = _a.am; var custom = config.custom; if ((0,underscore__WEBPACK_IMPORTED_MODULE_0__.isFunction)(custom.open)) { return custom.open(am.__customData()); } var Modal = editor.Modal; Modal.open({ title: title, content: content }).onceClose(function () { return editor.stopCommand(_this.id); }); }, close: function () { var custom = this.config.custom; if ((0,underscore__WEBPACK_IMPORTED_MODULE_0__.isFunction)(custom.close)) { return custom.close(this.am.__customData()); } var Modal = this.editor.Modal; Modal && Modal.close(); }, run: function (editor, sender, opts) { if (opts === void 0) { opts = {}; } var am = editor.AssetManager; var config = am.getConfig(); var _a = opts.types, types = _a === void 0 ? [] : _a, accept = opts.accept, select = opts.select; this.title = opts.modalTitle || editor.t('assetManager.modalTitle') || ''; this.editor = editor; this.config = config; this.am = am; am.setTarget(opts.target); am.onClick(opts.onClick); am.onDblClick(opts.onDblClick); am.onSelect(opts.onSelect); am.__behaviour({ select: select, types: types, options: opts, }); if (config.custom) { this.rendered = this.rendered || (0,_utils_dom__WEBPACK_IMPORTED_MODULE_1__/* .createEl */ .ut)('div'); this.rendered.className = "".concat(config.stylePrefix, "custom-wrp"); am.__behaviour({ container: this.rendered }); am.__trgCustom(); } else { if (!this.rendered || types) { var assets = am.getAll().filter(function (i) { return i; }); if (types && types.length) { assets = assets.filter(function (a) { return types.indexOf(a.get('type')) !== -1; }); } am.render(assets); this.rendered = am.getContainer(); } if (accept) { var uploadEl = this.rendered.querySelector("input#".concat(config.stylePrefix, "uploadFile")); uploadEl && uploadEl.setAttribute('accept', accept); } } this.open(this.rendered); return this; }, stop: function (editor) { this.editor = editor; this.close(this.rendered); }, }); /***/ }), /***/ 117: /***/ ((__unused_webpack_module, __nested_webpack_exports__, __nested_webpack_require_672435__) => { __nested_webpack_require_672435__.r(__nested_webpack_exports__); /* harmony export */ __nested_webpack_require_672435__.d(__nested_webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_672435__(50); /* harmony import */ var _utils_dom__WEBPACK_IMPORTED_MODULE_1__ = __nested_webpack_require_672435__(491); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ open: function () { var _a = this, container = _a.container, editor = _a.editor, bm = _a.bm, config = _a.config; var custom = config.custom, appendTo = config.appendTo; if ((0,underscore__WEBPACK_IMPORTED_MODULE_0__.isFunction)(custom.open)) { return custom.open(bm.__customData()); } if (this.firstRender && !appendTo) { var id = 'views-container'; var pn = editor.Panels; var panels = pn.getPanel(id) || pn.addPanel({ id: id }); panels.set('appendContent', container).trigger('change:appendContent'); if (!custom) container.appendChild(bm.render()); } if (container) container.style.display = 'block'; }, close: function () { var _a = this, container = _a.container, config = _a.config; var custom = config.custom; if ((0,underscore__WEBPACK_IMPORTED_MODULE_0__.isFunction)(custom.close)) { return custom.close(this.bm.__customData()); } if (container) container.style.display = 'none'; }, run: function (editor) { var bm = editor.Blocks; this.config = bm.getConfig(); this.firstRender = !this.container; this.container = this.container || (0,_utils_dom__WEBPACK_IMPORTED_MODULE_1__/* .createEl */ .ut)('div'); this.editor = editor; this.bm = bm; var container = this.container; bm.__behaviour({ container: container, }); if (this.config.custom) { bm.__trgCustom(); } this.open(); }, stop: function () { this.close(); }, }); /***/ }), /***/ 614: /***/ ((__unused_webpack_module, __nested_webpack_exports__, __nested_webpack_require_674705__) => { __nested_webpack_require_674705__.r(__nested_webpack_exports__); /* harmony export */ __nested_webpack_require_674705__.d(__nested_webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ run: function (editor) { var lm = editor.LayerManager; var pn = editor.Panels; var lmConfig = lm.getConfig(); if (lmConfig.appendTo) return; if (!this.layers) { var id = 'views-container'; var layers = document.createElement('div'); // @ts-ignore var panels = pn.getPanel(id) || pn.addPanel({ id: id }); if (lmConfig.custom) { lm.__trgCustom({ container: layers }); } else { layers.appendChild(lm.render()); } panels.set('appendContent', layers).trigger('change:appendContent'); this.layers = layers; } this.layers.style.display = 'block'; }, stop: function () { var layers = this.layers; layers && (layers.style.display = 'none'); }, }); /***/ }), /***/ 801: /***/ ((__unused_webpack_module, __nested_webpack_exports__, __nested_webpack_require_675972__) => { __nested_webpack_require_675972__.r(__nested_webpack_exports__); /* harmony export */ __nested_webpack_require_675972__.d(__nested_webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var _common__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_675972__(895); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ run: function (editor, sender) { this.sender = sender; if (!this.$cnt) { var config = editor.getConfig(); var Panels = editor.Panels, DeviceManager = editor.DeviceManager, SelectorManager = editor.SelectorManager, StyleManager = editor.StyleManager; var trgEvCnt = 'change:appendContent'; var $cnt = (0,_common__WEBPACK_IMPORTED_MODULE_0__["default"])('<div></div>'); var $cntInner = (0,_common__WEBPACK_IMPORTED_MODULE_0__["default"])('<div></div>'); var $cntSlm = (0,_common__WEBPACK_IMPORTED_MODULE_0__["default"])('<div></div>'); var $cntSm = (0,_common__WEBPACK_IMPORTED_MODULE_0__["default"])('<div></div>'); this.$cnt = $cnt; this.$cntInner = $cntInner; $cntInner.append($cntSlm); $cntInner.append($cntSm); $cnt.append($cntInner); // Device Manager if (DeviceManager && config.showDevices) { var devicePanel = Panels.addPanel({ id: 'devices-c' }); var dvEl = DeviceManager.render(); devicePanel.set('appendContent', dvEl).trigger(trgEvCnt); } // Selector Manager container var slmConfig = SelectorManager.getConfig(); if (slmConfig.custom) { SelectorManager.__trgCustom({ container: $cntSlm.get(0) }); } else if (!slmConfig.appendTo) { $cntSlm.append(SelectorManager.render([])); } // Style Manager this.sm = StyleManager; var smConfig = StyleManager.getConfig(); var pfx = smConfig.stylePrefix; this.$header = (0,_common__WEBPACK_IMPORTED_MODULE_0__["default"])("<div class=\"".concat(pfx, "header\">").concat(editor.t('styleManager.empty'), "</div>")); $cnt.append(this.$header); if (smConfig.custom) { StyleManager.__trgCustom({ container: $cntSm.get(0) }); } else if (!smConfig.appendTo) { $cntSm.append(StyleManager.render()); } // Create panel if not exists var pnCnt = 'views-container'; var pnl = Panels.getPanel(pnCnt) || Panels.addPanel({ id: pnCnt }); // Add all containers to the panel pnl.set('appendContent', $cnt).trigger(trgEvCnt); // Toggle Style Manager on target selection var em = editor.getModel(); this.listenTo(em, StyleManager.events.target, this.toggleSm); } this.toggleSm(); }, /** * Toggle Style Manager visibility * @private */ toggleSm: function () { var _a = this, sender = _a.sender, sm = _a.sm, $cntInner = _a.$cntInner, $header = _a.$header; if ((sender && sender.get && !sender.get('active')) || !sm) return; if (sm.getSelected()) { $cntInner === null || $cntInner === void 0 ? void 0 : $cntInner.show(); $header === null || $header === void 0 ? void 0 : $header.hide(); } else { $cntInner === null || $cntInner === void 0 ? void 0 : $cntInner.hide(); $header === null || $header === void 0 ? void 0 : $header.show(); } }, stop: function () { var _a, _b; (_a = this.$cntInner) === null || _a === void 0 ? void 0 : _a.hide(); (_b = this.$header) === null || _b === void 0 ? void 0 : _b.hide(); }, }); /***/ }), /***/ 395: /***/ ((__unused_webpack_module, __nested_webpack_exports__, __nested_webpack_require_679967__) => { __nested_webpack_require_679967__.r(__nested_webpack_exports__); /* harmony export */ __nested_webpack_require_679967__.d(__nested_webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var _common__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_679967__(895); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ run: function (editor, sender) { this.sender = sender; var em = editor.getModel(); var config = editor.Config; var pfx = config.stylePrefix; var tm = editor.TraitManager; var confTm = tm.getConfig(); var panelC; if (confTm.appendTo) return; if (!this.$cn) { this.$cn = (0,_common__WEBPACK_IMPORTED_MODULE_0__["default"])('<div></div>'); this.$cn2 = (0,_common__WEBPACK_IMPORTED_MODULE_0__["default"])('<div></div>'); this.$cn.append(this.$cn2); this.$header = (0,_common__WEBPACK_IMPORTED_MODULE_0__["default"])('<div>').append("<div class=\"".concat(confTm.stylePrefix, "header\">").concat(em.t('traitManager.empty'), "</div>")); this.$cn.append(this.$header); if (confTm.custom) { tm.__trgCustom({ container: this.$cn2.get(0) }); } else { this.$cn2.append("<div class=\"".concat(pfx, "traits-label\">").concat(em.t('traitManager.label'), "</div>")); this.$cn2.append(tm.render()); } var panels = editor.Panels; if (!panels.getPanel('views-container')) { // @ts-ignore panelC = panels.addPanel({ id: 'views-container' }); } else { panelC = panels.getPanel('views-container'); } panelC === null || panelC === void 0 ? void 0 : panelC.set('appendContent', this.$cn.get(0)).trigger('change:appendContent'); this.target = editor.getModel(); this.listenTo(this.target, 'component:toggled', this.toggleTm); } this.toggleTm(); }, /** * Toggle Trait Manager visibility * @private */ toggleTm: function () { var sender = this.sender; if (sender && sender.get && !sender.get('active')) return; if (this.target.getSelectedAll().length === 1) { this.$cn2.show(); this.$header.hide(); } else { this.$cn2.hide(); this.$header.show(); } }, stop: function () { this.$cn2 && this.$cn2.hide(); this.$header && this.$header.hide(); }, }); /***/ }), /***/ 98: /***/ ((__unused_webpack_module, __nested_webpack_exports__, __nested_webpack_require_682721__) => { __nested_webpack_require_682721__.r(__nested_webpack_exports__); /* harmony export */ __nested_webpack_require_682721__.d(__nested_webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_682721__(50); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ run: function (ed, s, opts) { if (opts === void 0) { opts = {}; } var em = ed.getModel(); var clp = em.get('clipboard'); var lastSelected = ed.getSelected(); if (clp && lastSelected) { ed.getSelectedAll().forEach(function (selected) { var collection = selected.collection; if (!collection) return; var added; var at = selected.index() + 1; var addOpts = { at: at, action: opts.action || 'paste-component' }; if ((0,underscore__WEBPACK_IMPORTED_MODULE_0__.contains)(clp, selected) && selected.get('copyable')) { // @ts-ignore added = collection.add(selected.clone(), addOpts); } else { var copyable = clp.filter(function (cop) { return cop.get('copyable'); }); var pasteable = copyable.filter(function (cop) { return ed.Components.canMove(selected.parent(), cop).result; }); added = collection.add( // @ts-ignore pasteable.map(function (cop) { return cop.clone(); }), addOpts); } added = (0,underscore__WEBPACK_IMPORTED_MODULE_0__.isArray)(added) ? added : [added]; added.forEach(function (add) { return ed.trigger('component:paste', add); }); }); lastSelected.emitUpdate(); } }, }); /***/ }), /***/ 129: /***/ ((__unused_webpack_module, __nested_webpack_exports__, __nested_webpack_require_684701__) => { __nested_webpack_require_684701__.r(__nested_webpack_exports__); /* harmony export */ __nested_webpack_require_684701__.d(__nested_webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_684701__(50); var __spreadArray = ( false) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var cmdOutline = 'core:component-outline'; /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ getPanels: function (editor) { if (!this.panels) { this.panels = editor.Panels.getPanels(); } return this.panels; }, preventDrag: function (opts) { opts.abort = 1; }, tglEffects: function (on) { var em = this.em; var mthEv = on ? 'on' : 'off'; if (em) { var canvas = em.Canvas; var body = canvas.getBody(); var tlb = canvas.getToolbarEl(); tlb && (tlb.style.display = on ? 'none' : ''); var elP = body.querySelectorAll(".".concat(this.ppfx, "no-pointer")); (0,underscore__WEBPACK_IMPORTED_MODULE_0__.each)(elP, function (item) { return (item.style.pointerEvents = on ? 'all' : ''); }); em[mthEv]('run:tlb-move:before', this.preventDrag); } }, run: function (editor, sender) { var _this = this; this.sender = sender; this.selected = __spreadArray([], editor.getSelectedAll(), true); editor.select(); if (!this.shouldRunSwVisibility) { this.shouldRunSwVisibility = editor.Commands.isActive(cmdOutline); } this.shouldRunSwVisibility && editor.stopCommand(cmdOutline); editor.getModel().stopDefault(); var panels = this.getPanels(editor); var canvas = editor.Canvas.getElement(); var editorEl = editor.getEl(); var pfx = editor.Config.stylePrefix; if (!this.helper) { var helper = document.createElement('span'); helper.className = "".concat(pfx, "off-prv fa fa-eye-slash"); editorEl.appendChild(helper); helper.onclick = function () { return _this.stopCommand(); }; this.helper = helper; } this.helper.style.display = 'inline-block'; panels.forEach(function (panel) { return panel.set('visible', false); }); var canvasS = canvas.style; canvasS.width = '100%'; canvasS.height = '100%'; canvasS.top = '0'; canvasS.left = '0'; canvasS.padding = '0'; canvasS.margin = '0'; editor.refresh(); this.tglEffects(1); }, stop: function (editor) { var _a = this, _b = _a.sender, sender = _b === void 0 ? {} : _b, selected = _a.selected; sender.set && sender.set('active', 0); var panels = this.getPanels(editor); if (this.shouldRunSwVisibility) { editor.runCommand(cmdOutline); this.shouldRunSwVisibility = false; } editor.getModel().runDefault(); panels.forEach(function (panel) { return panel.set('visible', true); }); var canvas = editor.Canvas.getElement(); canvas.setAttribute('style', ''); selected && editor.select(selected); delete this.selected; if (this.helper) { this.helper.style.display = 'none'; } editor.refresh(); this.tglEffects(); }, }); /***/ }), /***/ 116: /***/ ((__unused_webpack_module, __nested_webpack_exports__, __nested_webpack_require_688573__) => { __nested_webpack_require_688573__.r(__nested_webpack_exports__); /* harmony export */ __nested_webpack_require_688573__.d(__nested_webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); var __assign = ( false) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ run: function (editor, sender, opts) { var opt = opts || {}; var canvas = editor.Canvas; var canvasView = canvas.getCanvasView(); var options = __assign({ appendTo: canvas.getResizerEl(), prefix: editor.getConfig().stylePrefix, posFetcher: canvasView.getElementPos.bind(canvasView), mousePosFetcher: canvas.getMouseRelativePos }, (opt.options || {})); var canvasResizer = this.canvasResizer; // Create the resizer for the canvas if not yet created if (!canvasResizer || opt.forceNew) { this.canvasResizer = new editor.Utils.Resizer(options); canvasResizer = this.canvasResizer; } canvasResizer.setOptions(options, true); canvasResizer.blur(); canvasResizer.focus(opt.el); return canvasResizer; }, stop: function () { var _a; (_a = this.canvasResizer) === null || _a === void 0 ? void 0 : _a.blur(); }, }); /***/ }), /***/ 407: /***/ ((__unused_webpack_module, __nested_webpack_exports__, __nested_webpack_require_690300__) => { // ESM COMPAT FLAG __nested_webpack_require_690300__.r(__nested_webpack_exports__); // EXPORTS __nested_webpack_require_690300__.d(__nested_webpack_exports__, { "default": () => (/* binding */ SelectComponent) }); // EXTERNAL MODULE: ./node_modules/underscore/modules/index-all.js + 160 modules var index_all = __nested_webpack_require_690300__(50); // EXTERNAL MODULE: ./src/common/index.ts var common = __nested_webpack_require_690300__(346); ;// CONCATENATED MODULE: ./src/dom_components/model/ToolbarButton.ts var __extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ToolbarButton = /** @class */ (function (_super) { __extends(ToolbarButton, _super); function ToolbarButton() { return _super !== null && _super.apply(this, arguments) || this; } ToolbarButton.prototype.defaults = function () { return { command: '', attributes: {}, }; }; return ToolbarButton; }(common/* Model */.Hn)); /* harmony default export */ const model_ToolbarButton = (ToolbarButton); ;// CONCATENATED MODULE: ./src/dom_components/model/Toolbar.ts var Toolbar_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var Toolbar = /** @class */ (function (_super) { Toolbar_extends(Toolbar, _super); function Toolbar() { return _super !== null && _super.apply(this, arguments) || this; } return Toolbar; }(common/* Collection */.FE)); /* harmony default export */ const model_Toolbar = (Toolbar); Toolbar.prototype.model = model_ToolbarButton; // EXTERNAL MODULE: ./src/domain_abstract/view/DomainViews.ts var DomainViews = __nested_webpack_require_690300__(330); ;// CONCATENATED MODULE: ./src/dom_components/view/ToolbarButtonView.ts var ToolbarButtonView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __assign = ( false) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var ToolbarButtonView = /** @class */ (function (_super) { ToolbarButtonView_extends(ToolbarButtonView, _super); function ToolbarButtonView(props) { var _this = _super.call(this, props) || this; _this.em = props.config.em; return _this; } ToolbarButtonView.prototype.events = function () { return (this.model.get('events') || { mousedown: 'handleClick', }); }; // @ts-ignore ToolbarButtonView.prototype.attributes = function () { return this.model.get('attributes'); }; ToolbarButtonView.prototype.handleClick = function (event) { event.preventDefault(); event.stopPropagation(); /* * Since the toolbar lives outside the canvas frame, the event's * generated on it have clientX and clientY relative to the page. * * This causes issues during events like dragging, where they depend * on the clientX and clientY. * * This makes sure the offsets are calculated. * * More information on * https://github.com/GrapesJS/grapesjs/issues/2372 * https://github.com/GrapesJS/grapesjs/issues/2207 */ var em = this.em; var _a = em.Canvas.getFrameEl().getBoundingClientRect(), left = _a.left, top = _a.top; var ev = __assign(__assign({}, event), { clientX: event.clientX - left, clientY: event.clientY - top }); em.trigger('toolbar:run:before', { event: ev }); this.execCommand(ev); }; ToolbarButtonView.prototype.execCommand = function (event) { var _a = this, em = _a.em, model = _a.model; var opts = { event: event }; var command = model.get('command'); var editor = em.Editor; if ((0,index_all.isFunction)(command)) { command(editor, null, opts); } if ((0,index_all.isString)(command)) { editor.runCommand(command, opts); } }; ToolbarButtonView.prototype.render = function () { var _a = this, em = _a.em, $el = _a.$el, model = _a.model; var id = model.get('id'); var label = model.get('label'); var pfx = em.getConfig().stylePrefix; $el.addClass("".concat(pfx, "toolbar-item")); id && $el.addClass("".concat(pfx, "toolbar-item__").concat(id)); label && $el.append(label); return this; }; return ToolbarButtonView; }(common/* View */.G7)); /* harmony default export */ const view_ToolbarButtonView = (ToolbarButtonView); ;// CONCATENATED MODULE: ./src/dom_components/view/ToolbarView.ts var ToolbarView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ToolbarView = /** @class */ (function (_super) { ToolbarView_extends(ToolbarView, _super); function ToolbarView(opts) { var _this = _super.call(this, opts) || this; var em = opts.em; _this.em = em; _this.config = { em: em }; _this.listenTo(_this.collection, 'reset', _this.render); return _this; } ToolbarView.prototype.onRender = function () { var pfx = this.em.config.stylePrefix; this.el.className = "".concat(pfx, "toolbar-items"); }; return ToolbarView; }(DomainViews/* default */.Z)); /* harmony default export */ const view_ToolbarView = (ToolbarView); // @ts-ignore ToolbarView.prototype.itemView = view_ToolbarButtonView; // EXTERNAL MODULE: ./src/utils/dom.ts var dom = __nested_webpack_require_690300__(491); // EXTERNAL MODULE: ./src/utils/mixins.ts var mixins = __nested_webpack_require_690300__(163); // EXTERNAL MODULE: ./src/canvas/model/CanvasSpot.ts var CanvasSpot = __nested_webpack_require_690300__(675); ;// CONCATENATED MODULE: ./src/commands/view/SelectComponent.ts var SelectComponent_assign = ( false) || function () { SelectComponent_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return SelectComponent_assign.apply(this, arguments); }; var showOffsets; /** * This command is responsible for show selecting components and displaying * all the necessary tools around (component toolbar, badge, highlight box, etc.) * * The command manages different boxes to display tools and when something in * the canvas is updated, the command triggers the appropriate method to update * their position (across multiple frames/components): * - Global Tools (updateToolsGlobal/updateGlobalPos) * This box contains tools intended to be displayed only on ONE component per time, * like Component Toolbar (updated by updateToolbar/updateToolbarPos), this means * you won't be able to see more than one Component Toolbar (even with multiple * frames or multiple selected components) * - Local Tools (updateToolsLocal/updateLocalPos) * Each frame in the canvas has its own local box, so we're able to see more than * one active container at the same time. When you put a mouse over an element * you can see stuff like the highlight box, badge, margins/paddings offsets, etc. * so those elements are inside the Local Tools box * * */ /* harmony default export */ const SelectComponent = ({ init: function () { this.onSelect = (0,index_all.debounce)(this.onSelect, 0); (0,index_all.bindAll)(this, 'onHover', 'onOut', 'onClick', 'onFrameScroll', 'onFrameResize', 'onFrameUpdated', 'onContainerChange'); }, enable: function () { this.frameOff = this.canvasOff = this.adjScroll = null; this.startSelectComponent(); showOffsets = true; }, /** * Start select component event * @private * */ startSelectComponent: function () { this.toggleSelectComponent(1); this.em.getSelected() && this.onSelect(); }, /** * Stop select component event * @private * */ stopSelectComponent: function () { this.toggleSelectComponent(); }, /** * Toggle select component event * @private * */ toggleSelectComponent: function (enable) { var _this = this; var em = this.em; var listenToEl = em.getConfig().listenToEl; var parentNode = em.getContainer().parentNode; var method = enable ? 'on' : 'off'; var methods = { on: dom.on, off: dom/* off */.S1 }; !listenToEl.length && parentNode && listenToEl.push(parentNode); var trigger = function (win, body) { methods[method](body, 'mouseover', _this.onHover); methods[method](body, 'mouseleave', _this.onOut); methods[method](body, 'click', _this.onClick); methods[method](win, 'scroll', _this.onFrameScroll, true); methods[method](win, 'resize', _this.onFrameResize); }; methods[method](window, 'resize', this.onFrameUpdated); methods[method](listenToEl, 'scroll', this.onContainerChange); em[method]('component:toggled component:update undo redo', this.onSelect, this); em[method]('change:componentHovered', this.onHovered, this); em[method]('component:resize styleable:change component:input', // component:styleUpdate this.updateGlobalPos, this); em[method]('component:update:toolbar', this._upToolbar, this); em[method]('change:canvasOffset', this.updateAttached, this); em[method]('frame:updated', this.onFrameUpdated, this); em[method]('canvas:updateTools', this.onFrameUpdated, this); em.Canvas.getFrames().forEach(function (frame) { var view = frame.view; var win = view === null || view === void 0 ? void 0 : view.getWindow(); win && trigger(win, view === null || view === void 0 ? void 0 : view.getBody()); }); }, /** * Hover command * @param {Object} e * @private */ onHover: function (ev) { ev.stopPropagation(); var em = this.em; var el = ev.target; var view = (0,mixins.getComponentView)(el); var frameView = view === null || view === void 0 ? void 0 : view.frameView; var model = view === null || view === void 0 ? void 0 : view.model; // Get first valid model if (!model) { var parentEl = el.parentNode; while (!model && parentEl && !(0,dom/* isDoc */.Mx)(parentEl)) { model = (0,mixins.getComponentModel)(parentEl); parentEl = parentEl.parentNode; } } this.currentDoc = el.ownerDocument; em.setHovered(model, { useValid: true }); frameView && em.setCurrentFrame(frameView); }, onFrameUpdated: function () { this.updateLocalPos(); this.updateGlobalPos(); }, onHovered: function (em, component) { var _this = this; var _a; var result = {}; if (component) { (_a = component.views) === null || _a === void 0 ? void 0 : _a.forEach(function (view) { var el = view.el; var pos = _this.getElementPos(el); result = { el: el, pos: pos, component: component, view: (0,mixins.getViewEl)(el) }; if (el.ownerDocument === _this.currentDoc) { _this.elHovered = result; } _this.updateToolsLocal(result); }); } else { this.currentDoc = null; this.elHovered = 0; this.updateToolsLocal(); this.canvas.getFrames().forEach(function (frame) { var view = frame.view; var el = view && view.getToolsEl(); el && _this.toggleToolsEl(0, 0, { el: el }); }); } }, /** * Say what to do after the component was selected * @param {Object} e * @param {Object} el * @private * */ onSelect: function () { var em = this.em; var component = em.getSelected(); var currentFrame = em.getCurrentFrame(); var view = component && component.getView(currentFrame === null || currentFrame === void 0 ? void 0 : currentFrame.model); var el = view && view.el; var result = {}; if (el && (0,dom/* isVisible */.pn)(el)) { var pos = this.getElementPos(el); result = { el: el, pos: pos, component: component, view: (0,mixins.getViewEl)(el) }; } this.elSelected = result; this.updateToolsGlobal(); // This will hide some elements from the select component this.updateLocalPos(result); this.initResize(component); }, updateGlobalPos: function () { var sel = this.getElSelected(); if (!sel.el) return; sel.pos = this.getElementPos(sel.el); this.updateToolsGlobal(); }, updateLocalPos: function (data) { var sel = this.getElHovered(); if (!sel.el) return; sel.pos = this.getElementPos(sel.el); this.updateToolsLocal(data); }, getElHovered: function () { return this.elHovered || {}; }, getElSelected: function () { return this.elSelected || {}; }, onOut: function () { this.em.setHovered(); }, toggleToolsEl: function (on, view, opts) { if (opts === void 0) { opts = {}; } var el = opts.el || this.canvas.getToolsEl(view); el && (el.style.display = on ? '' : 'none'); return el || {}; }, /** * Show element offset viewer * @param {HTMLElement} el * @param {Object} pos */ showElementOffset: function (el, pos, opts) { if (opts === void 0) { opts = {}; } if (!showOffsets) return; this.editor.runCommand('show-offset', { el: el, elPos: pos, view: opts.view, force: 1, top: 0, left: 0, }); }, /** * Hide element offset viewer * @param {HTMLElement} el * @param {Object} pos */ hideElementOffset: function (view) { this.editor.stopCommand('show-offset', { view: view, }); }, /** * Show fixed element offset viewer * @param {HTMLElement} el * @param {Object} pos */ showFixedElementOffset: function (el, pos) { this.editor.runCommand('show-offset', { el: el, elPos: pos, state: 'Fixed', }); }, /** * Hide fixed element offset viewer * @param {HTMLElement} el * @param {Object} pos */ hideFixedElementOffset: function () { if (this.editor) this.editor.stopCommand('show-offset', { state: 'Fixed' }); }, /** * Hide Highlighter element */ hideHighlighter: function (view) { this.canvas.getHighlighter(view).style.opacity = 0; }, /** * On element click * @param {Event} e * @private */ onClick: function (ev) { ev.stopPropagation(); ev.preventDefault(); var em = this.em; if (em.get('_cmpDrag')) return em.set('_cmpDrag'); var el = ev.target; var model = (0,mixins.getComponentModel)(el); if (!model) { var parentEl = el.parentNode; while (!model && parentEl && !(0,dom/* isDoc */.Mx)(parentEl)) { model = (0,mixins.getComponentModel)(parentEl); parentEl = parentEl.parentNode; } } if (model) { // Avoid selection of inner text components during editing if (em.isEditing() && !model.get('textable') && model.isChildOf('text')) { return; } this.select(model, ev); } }, /** * Select component * @param {Component} model * @param {Event} event */ select: function (model, event) { if (event === void 0) { event = {}; } if (!model) return; this.editor.select(model, { event: event, useValid: true }); this.initResize(model); }, /** * Update badge for the component * @param {Object} Component * @param {Object} pos Position object * @private * */ updateBadge: function (el, pos, opts) { if (opts === void 0) { opts = {}; } var canvas = this.canvas; var model = (0,mixins.getComponentModel)(el); var badge = this.getBadge(opts); var bStyle = badge.style; if (!model || !model.get('badgable')) { bStyle.display = 'none'; return; } if (!opts.posOnly) { var config = this.canvas.getConfig(); var icon = model.getIcon(); var ppfx = config.pStylePrefix || ''; var clsBadge = "".concat(ppfx, "badge"); var customeLabel = config.customBadgeLabel; var badgeLabel = "".concat(icon ? "<div class=\"".concat(clsBadge, "__icon\">").concat(icon, "</div>") : '', "\n <div class=\"").concat(clsBadge, "__name\">").concat(model.getName(), "</div>"); badge.innerHTML = customeLabel ? customeLabel(model) : badgeLabel; } var un = 'px'; bStyle.display = 'block'; var targetToElem = canvas.getTargetToElementFixed(el, badge, { pos: pos, }); var top = targetToElem.top; //opts.topOff - badgeH < 0 ? -opts.topOff : posTop; var left = opts.leftOff < 0 ? -opts.leftOff : 0; bStyle.top = top + un; bStyle.left = left + un; }, /** * Update highlighter element * @param {HTMLElement} el * @param {Object} pos Position object * @private */ showHighlighter: function (view) { this.canvas.getHighlighter(view).style.opacity = ''; }, /** * Init resizer on the element if possible * @param {HTMLElement|Component} elem * @private */ initResize: function (elem) { var _a = this, em = _a.em, canvas = _a.canvas; var editor = em.Editor; var model = !(0,index_all.isElement)(elem) && (0,dom/* isTaggableNode */.o5)(elem) ? elem : em.getSelected(); var resizable = model === null || model === void 0 ? void 0 : model.get('resizable'); var spotTypeResize = CanvasSpot/* CanvasSpotBuiltInTypes */.q.Resize; var hasCustomResize = canvas.hasCustomSpot(spotTypeResize); canvas.removeSpots({ type: spotTypeResize }); if (model && resizable) { canvas.addSpot({ type: spotTypeResize, component: model }); var el = (0,index_all.isElement)(elem) ? elem : model.getEl(); if (hasCustomResize || !el) return; var modelToStyle_1; var config = em.config; var pfx = config.stylePrefix || ''; var resizeClass_1 = "".concat(pfx, "resizing"); var toggleBodyClass_1 = function (method, e, opts) { var docs = opts.docs; docs && docs.forEach(function (doc) { var body = doc.body; var cls = body.className || ''; body.className = (method == 'add' ? "".concat(cls, " ").concat(resizeClass_1) : cls.replace(resizeClass_1, '')).trim(); }); }; var options = SelectComponent_assign({ // Here the resizer is updated with the current element height and width onStart: function (e, opts) { if (opts === void 0) { opts = {}; } var el = opts.el, config = opts.config, resizer = opts.resizer; var keyHeight = config.keyHeight, keyWidth = config.keyWidth, currentUnit = config.currentUnit, keepAutoHeight = config.keepAutoHeight, keepAutoWidth = config.keepAutoWidth; toggleBodyClass_1('add', e, opts); modelToStyle_1 = em.Styles.getModelToStyle(model); canvas.toggleFramesEvents(false); var computedStyle = getComputedStyle(el); var modelStyle = modelToStyle_1.getStyle(); var currentWidth = modelStyle[keyWidth]; config.autoWidth = keepAutoWidth && currentWidth === 'auto'; if (isNaN(parseFloat(currentWidth))) { currentWidth = computedStyle[keyWidth]; } var currentHeight = modelStyle[keyHeight]; config.autoHeight = keepAutoHeight && currentHeight === 'auto'; if (isNaN(parseFloat(currentHeight))) { currentHeight = computedStyle[keyHeight]; } resizer.startDim.w = parseFloat(currentWidth); resizer.startDim.h = parseFloat(currentHeight); showOffsets = false; if (currentUnit) { config.unitHeight = (0,mixins.getUnitFromValue)(currentHeight); config.unitWidth = (0,mixins.getUnitFromValue)(currentWidth); } }, // Update all positioned elements (eg. component toolbar) onMove: function () { editor.trigger('component:resize'); }, onEnd: function (e, opts) { toggleBodyClass_1('remove', e, opts); editor.trigger('component:resize'); canvas.toggleFramesEvents(true); showOffsets = true; }, updateTarget: function (el, rect, options) { if (options === void 0) { options = {}; } if (!modelToStyle_1) { return; } var store = options.store, selectedHandler = options.selectedHandler, config = options.config; var keyHeight = config.keyHeight, keyWidth = config.keyWidth, autoHeight = config.autoHeight, autoWidth = config.autoWidth, unitWidth = config.unitWidth, unitHeight = config.unitHeight; var onlyHeight = ['tc', 'bc'].indexOf(selectedHandler) >= 0; var onlyWidth = ['cl', 'cr'].indexOf(selectedHandler) >= 0; var style = {}; if (!onlyHeight) { var bodyw = canvas.getBody().offsetWidth; var width = rect.w < bodyw ? rect.w : bodyw; style[keyWidth] = autoWidth ? 'auto' : "".concat(width).concat(unitWidth); } if (!onlyWidth) { style[keyHeight] = autoHeight ? 'auto' : "".concat(rect.h).concat(unitHeight); } if (em.getDragMode(model)) { style.top = "".concat(rect.t).concat(unitHeight); style.left = "".concat(rect.l).concat(unitWidth); } var finalStyle = SelectComponent_assign(SelectComponent_assign({}, style), { // value for the partial update __p: !store }); modelToStyle_1.addStyle(finalStyle, { avoidStore: !store }); em.Styles.__emitCmpStyleUpdate(finalStyle, { components: em.getSelected() }); } }, ((0,mixins.isObject)(resizable) ? resizable : {})); this.resizer = editor.runCommand('resize', { el: el, options: options, force: 1 }); } else { if (hasCustomResize) return; editor.stopCommand('resize'); this.resizer = null; } }, /** * Update toolbar if the component has one * @param {Object} mod */ updateToolbar: function (mod) { var canvas = this.canvas; var em = this.config.em; var model = mod === em ? em.getSelected() : mod; var toolbarEl = canvas.getToolbarEl(); var toolbarStyle = toolbarEl.style; var toolbar = model.get('toolbar'); var showToolbar = em.config.showToolbar; var noCustomSpotSelect = !canvas.hasCustomSpot(CanvasSpot/* CanvasSpotBuiltInTypes */.q.Select); if (model && showToolbar && toolbar && toolbar.length && noCustomSpotSelect) { toolbarStyle.display = ''; if (!this.toolbar) { toolbarEl.innerHTML = ''; this.toolbar = new model_Toolbar(toolbar); // @ts-ignore var toolbarView = new view_ToolbarView({ collection: this.toolbar, em: em }); toolbarEl.appendChild(toolbarView.render().el); } this.toolbar.reset(toolbar); toolbarStyle.top = '-100px'; toolbarStyle.left = '0'; } else { toolbarStyle.display = 'none'; } }, /** * Update toolbar positions * @param {HTMLElement} el * @param {Object} pos */ updateToolbarPos: function (pos) { var unit = 'px'; var style = this.canvas.getToolbarEl().style; style.top = "".concat(pos.top).concat(unit); style.left = "".concat(pos.left).concat(unit); style.opacity = ''; }, /** * Return canvas dimensions and positions * @return {Object} */ getCanvasPosition: function () { return this.canvas.getCanvasView().getPosition(); }, /** * Returns badge element * @return {HTMLElement} * @private */ getBadge: function (opts) { if (opts === void 0) { opts = {}; } return this.canvas.getBadgeEl(opts.view); }, /** * On frame scroll callback * @private */ onFrameScroll: function () { this.updateTools(); this.canvas.refreshSpots(); }, onFrameResize: function () { this.canvas.refreshSpots(); }, updateTools: function () { this.updateLocalPos(); this.updateGlobalPos(); }, isCompSelected: function (comp) { return comp && comp.get('status') === 'selected'; }, /** * Update tools visible on hover * @param {HTMLElement} el * @param {Object} pos */ updateToolsLocal: function (data) { var config = this.em.getConfig(); var _a = data || this.getElHovered(), el = _a.el, pos = _a.pos, view = _a.view, component = _a.component; if (!el) { this.lastHovered = 0; return; } var isHoverEn = component.get('hoverable'); var isNewEl = this.lastHovered !== el; var badgeOpts = isNewEl ? {} : { posOnly: 1 }; var customHoverSpot = this.canvas.hasCustomSpot(CanvasSpot/* CanvasSpotBuiltInTypes */.q.Hover); if (isNewEl && isHoverEn) { this.lastHovered = el; customHoverSpot ? this.hideHighlighter(view) : this.showHighlighter(view); this.showElementOffset(el, pos, { view: view }); } if (this.isCompSelected(component)) { this.hideHighlighter(view); !config.showOffsetsSelected && this.hideElementOffset(view); } var unit = 'px'; var toolsEl = this.toggleToolsEl(1, view); var style = toolsEl.style; var frameOff = this.canvas.canvasRectOffset(el, pos); var topOff = frameOff.top; var leftOff = frameOff.left; !customHoverSpot && this.updateBadge(el, pos, SelectComponent_assign(SelectComponent_assign({}, badgeOpts), { view: view, topOff: topOff, leftOff: leftOff })); style.top = topOff + unit; style.left = leftOff + unit; style.width = pos.width + unit; style.height = pos.height + unit; this._trgToolUp('local', { component: component, el: toolsEl, top: topOff, left: leftOff, width: pos.width, height: pos.height, }); }, _upToolbar: (0,index_all.debounce)(function () { // @ts-ignore this.updateToolsGlobal({ force: 1 }); }, 0), _trgToolUp: function (type, opts) { if (opts === void 0) { opts = {}; } this.em.trigger('canvas:tools:update', SelectComponent_assign({ type: type }, opts)); }, updateToolsGlobal: function (opts) { if (opts === void 0) { opts = {}; } var _a = this.getElSelected(), el = _a.el, pos = _a.pos, component = _a.component; if (!el) { this.toggleToolsEl(); // Hides toolbar this.lastSelected = 0; return; } var canvas = this.canvas; var isNewEl = this.lastSelected !== el; if (isNewEl || opts.force) { this.lastSelected = el; this.updateToolbar(component); } var unit = 'px'; var toolsEl = this.toggleToolsEl(1); var style = toolsEl.style; var targetToElem = canvas.getTargetToElementFixed(el, canvas.getToolbarEl(), { pos: pos }); var topOff = targetToElem.canvasOffsetTop; var leftOff = targetToElem.canvasOffsetLeft; style.top = topOff + unit; style.left = leftOff + unit; style.width = pos.width + unit; style.height = pos.height + unit; this.updateToolbarPos({ top: targetToElem.top, left: targetToElem.left }); this._trgToolUp('global', { component: component, el: toolsEl, top: topOff, left: leftOff, width: pos.width, height: pos.height, }); }, /** * Update attached elements, eg. component toolbar */ updateAttached: (0,index_all.debounce)(function () { // @ts-ignore this.updateGlobalPos(); }, 0), onContainerChange: (0,index_all.debounce)(function () { // @ts-ignore this.em.refreshCanvas(); }, 150), /** * Returns element's data info * @param {HTMLElement} el * @return {Object} * @private */ getElementPos: function (el) { return this.canvas.getCanvasView().getElementPos(el, { noScroll: true }); }, /** * Hide badge * @private * */ hideBadge: function () { this.getBadge().style.display = 'none'; }, /** * Clean previous model from different states * @param {Component} model * @private */ cleanPrevious: function (model) { model && model.set({ status: '', state: '', }); }, /** * Returns content window * @private */ getContentWindow: function () { return this.canvas.getWindow(); }, run: function (editor) { if (!(0,mixins.hasWin)()) return; // @ts-ignore this.editor = editor && editor.get('Editor'); this.enable(); }, stop: function (ed, sender, opts) { if (opts === void 0) { opts = {}; } if (!(0,mixins.hasWin)()) return; var _a = this, em = _a.em, editor = _a.editor; this.onHovered(); // force to hide toolbar this.stopSelectComponent(); !opts.preserveSelected && em.setSelected(); this.toggleToolsEl(); editor && editor.stopCommand('resize'); }, }); /***/ }), /***/ 189: /***/ ((__unused_webpack_module, __nested_webpack_exports__, __nested_webpack_require_724905__) => { __nested_webpack_require_724905__.r(__nested_webpack_exports__); /* harmony export */ __nested_webpack_require_724905__.d(__nested_webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var _common__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_724905__(895); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ /** * Start select position event * @param {HTMLElement} trg * @private * */ startSelectPosition: function (trg, doc, opts) { var _this = this; if (opts === void 0) { opts = {}; } this.isPointed = false; var utils = this.em.Utils; var container = trg.ownerDocument.body; if (utils && !this.sorter) this.sorter = new utils.Sorter({ // @ts-ignore container: container, placer: this.canvas.getPlacerEl(), containerSel: '*', itemSel: '*', pfx: this.ppfx, direction: 'a', document: doc, wmargin: 1, nested: 1, em: this.em, canvasRelative: 1, scale: function () { return _this.em.getZoomDecimal(); }, }); if (opts.onStart) this.sorter.onStart = opts.onStart; trg && this.sorter.startSort(trg, { container: container }); }, /** * Get frame position * @return {Object} * @private */ getOffsetDim: function () { var frameOff = this.offset(this.canvas.getFrameEl()); var canvasOff = this.offset(this.canvas.getElement()); var top = frameOff.top - canvasOff.top; var left = frameOff.left - canvasOff.left; return { top: top, left: left }; }, /** * Stop select position event * @private * */ stopSelectPosition: function () { this.posTargetCollection = null; this.posIndex = this.posMethod == 'after' && this.cDim.length !== 0 ? this.posIndex + 1 : this.posIndex; //Normalize if (this.sorter) { this.sorter.moved = 0; this.sorter.endMove(); } if (this.cDim) { this.posIsLastEl = this.cDim.length !== 0 && this.posMethod == 'after' && this.posIndex == this.cDim.length; this.posTargetEl = this.cDim.length === 0 ? (0,_common__WEBPACK_IMPORTED_MODULE_0__["default"])(this.outsideElem) : !this.posIsLastEl && this.cDim[this.posIndex] ? (0,_common__WEBPACK_IMPORTED_MODULE_0__["default"])(this.cDim[this.posIndex][5]).parent() : (0,_common__WEBPACK_IMPORTED_MODULE_0__["default"])(this.outsideElem); this.posTargetModel = this.posTargetEl.data('model'); this.posTargetCollection = this.posTargetEl.data('model-comp'); } }, /** * Enabel select position * @private */ enable: function () { this.startSelectPosition(); }, /** * Check if the pointer is near to the float component * @param {number} index * @param {string} method * @param {Array<Array>} dims * @return {Boolean} * @private * */ nearFloat: function (index, method, dims) { var i = index || 0; var m = method || 'before'; var len = dims.length; var isLast = len !== 0 && m == 'after' && i == len; if (len !== 0 && ((!isLast && !dims[i][4]) || (dims[i - 1] && !dims[i - 1][4]) || (isLast && !dims[i - 1][4]))) return 1; return 0; }, run: function () { this.enable(); }, stop: function () { this.stopSelectPosition(); this.$wrapper.css('cursor', ''); this.$wrapper.unbind(); }, }); /***/ }), /***/ 804: /***/ ((__unused_webpack_module, __nested_webpack_exports__, __nested_webpack_require_728850__) => { __nested_webpack_require_728850__.r(__nested_webpack_exports__); /* harmony export */ __nested_webpack_require_728850__.d(__nested_webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_728850__(50); /* harmony import */ var _canvas_model_CanvasSpot__WEBPACK_IMPORTED_MODULE_2__ = __nested_webpack_require_728850__(675); /* harmony import */ var _common__WEBPACK_IMPORTED_MODULE_3__ = __nested_webpack_require_728850__(895); /* harmony import */ var _utils_dom__WEBPACK_IMPORTED_MODULE_1__ = __nested_webpack_require_728850__(491); var __assign = ( false) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ getOffsetMethod: function (state) { var method = state || ''; return 'get' + method + 'OffsetViewerEl'; }, run: function (editor, sender, opts) { var canvas = this.canvas; var opt = opts || {}; var state = opt.state || ''; var config = editor.getConfig(); var zoom = this.em.getZoomDecimal(); var el = opt.el; if (!config.showOffsets || !el || (0,_utils_dom__WEBPACK_IMPORTED_MODULE_1__/* .isTextNode */ .BM)(el) || (!config.showOffsetsSelected && state == 'Fixed')) { editor.stopCommand("".concat(this.id), opts); return; } if (canvas.hasCustomSpot(_canvas_model_CanvasSpot__WEBPACK_IMPORTED_MODULE_2__/* .CanvasSpotBuiltInTypes */ .q.Spacing)) { return; } var pos = __assign({}, (opt.elPos || canvas.getElementPos(el))); if (!(0,underscore__WEBPACK_IMPORTED_MODULE_0__.isUndefined)(opt.top)) { pos.top = opt.top; } if (!(0,underscore__WEBPACK_IMPORTED_MODULE_0__.isUndefined)(opt.left)) { pos.left = opt.left; } var style = window.getComputedStyle(el); var ppfx = this.ppfx; var stateVar = state + 'State'; var method = this.getOffsetMethod(state); // @ts-ignore var offsetViewer = canvas[method](opts.view); offsetViewer.style.opacity = ''; var marginT = this['marginT' + state]; var marginB = this['marginB' + state]; var marginL = this['marginL' + state]; var marginR = this['marginR' + state]; var padT = this['padT' + state]; var padB = this['padB' + state]; var padL = this['padL' + state]; var padR = this['padR' + state]; if (offsetViewer.childNodes.length) { this[stateVar] = '1'; marginT = offsetViewer.querySelector('[data-offset-m-t]'); marginB = offsetViewer.querySelector('[data-offset-m-b]'); marginL = offsetViewer.querySelector('[data-offset-m-l]'); marginR = offsetViewer.querySelector('[data-offset-m-r]'); padT = offsetViewer.querySelector('[data-offset-p-t]'); padB = offsetViewer.querySelector('[data-offset-p-b]'); padL = offsetViewer.querySelector('[data-offset-p-l]'); padR = offsetViewer.querySelector('[data-offset-p-r]'); } if (!this[stateVar]) { var stateLow = state.toLowerCase(); var marginName = stateLow + 'margin-v'; var paddingName = stateLow + 'padding-v'; var marginV = (0,_common__WEBPACK_IMPORTED_MODULE_3__["default"])("<div class=\"".concat(ppfx, "marginName\">")).get(0); var paddingV = (0,_common__WEBPACK_IMPORTED_MODULE_3__["default"])("<div class=\"".concat(ppfx, "paddingName\">")).get(0); var marginEls = ppfx + marginName + '-el'; var paddingEls = ppfx + paddingName + '-el'; var fullMargName = "".concat(marginEls, " ").concat(ppfx + marginName); var fullPadName = "".concat(paddingEls, " ").concat(ppfx + paddingName); marginT = (0,_common__WEBPACK_IMPORTED_MODULE_3__["default"])("<div class=\"".concat(fullMargName, "-top\"></div>")).get(0); marginB = (0,_common__WEBPACK_IMPORTED_MODULE_3__["default"])("<div class=\"".concat(fullMargName, "-bottom\"></div>")).get(0); marginL = (0,_common__WEBPACK_IMPORTED_MODULE_3__["default"])("<div class=\"".concat(fullMargName, "-left\"></div>")).get(0); marginR = (0,_common__WEBPACK_IMPORTED_MODULE_3__["default"])("<div class=\"".concat(fullMargName, "-right\"></div>")).get(0); padT = (0,_common__WEBPACK_IMPORTED_MODULE_3__["default"])("<div class=\"".concat(fullPadName, "-top\"></div>")).get(0); padB = (0,_common__WEBPACK_IMPORTED_MODULE_3__["default"])("<div class=\"".concat(fullPadName, "-bottom\"></div>")).get(0); padL = (0,_common__WEBPACK_IMPORTED_MODULE_3__["default"])("<div class=\"".concat(fullPadName, "-left\"></div>")).get(0); padR = (0,_common__WEBPACK_IMPORTED_MODULE_3__["default"])("<div class=\"".concat(fullPadName, "-right\"></div>")).get(0); this['marginT' + state] = marginT; this['marginB' + state] = marginB; this['marginL' + state] = marginL; this['marginR' + state] = marginR; this['padT' + state] = padT; this['padB' + state] = padB; this['padL' + state] = padL; this['padR' + state] = padR; marginV.appendChild(marginT); marginV.appendChild(marginB); marginV.appendChild(marginL); marginV.appendChild(marginR); paddingV.appendChild(padT); paddingV.appendChild(padB); paddingV.appendChild(padL); paddingV.appendChild(padR); offsetViewer.appendChild(marginV); offsetViewer.appendChild(paddingV); this[stateVar] = '1'; } var unit = 'px'; var marginLeftSt = parseFloat(style.marginLeft.replace(unit, '')) * zoom; var marginRightSt = parseFloat(style.marginRight.replace(unit, '')) * zoom; var marginTopSt = parseFloat(style.marginTop.replace(unit, '')) * zoom; var marginBottomSt = parseFloat(style.marginBottom.replace(unit, '')) * zoom; var mtStyle = marginT.style; var mbStyle = marginB.style; var mlStyle = marginL.style; var mrStyle = marginR.style; var ptStyle = padT.style; var pbStyle = padB.style; var plStyle = padL.style; var prStyle = padR.style; var posLeft = parseFloat(pos.left); var widthEl = parseFloat(style.width) * zoom + unit; // Margin style mtStyle.height = marginTopSt + unit; mtStyle.width = widthEl; mtStyle.top = pos.top - marginTopSt + unit; mtStyle.left = posLeft + unit; mbStyle.height = marginBottomSt + unit; mbStyle.width = widthEl; mbStyle.top = pos.top + pos.height + unit; mbStyle.left = posLeft + unit; var marginSideH = pos.height + marginTopSt + marginBottomSt + unit; var marginSideT = pos.top - marginTopSt + unit; mlStyle.height = marginSideH; mlStyle.width = marginLeftSt + unit; mlStyle.top = marginSideT; mlStyle.left = posLeft - marginLeftSt + unit; mrStyle.height = marginSideH; mrStyle.width = marginRightSt + unit; mrStyle.top = marginSideT; mrStyle.left = posLeft + pos.width + unit; // Padding style var padTop = parseFloat(style.paddingTop) * zoom; ptStyle.height = padTop + unit; // ptStyle.width = widthEl; // ptStyle.top = pos.top + unit; // ptStyle.left = posLeft + unit; var padBot = parseFloat(style.paddingBottom) * zoom; pbStyle.height = padBot + unit; // pbStyle.width = widthEl; // pbStyle.top = pos.top + pos.height - padBot + unit; // pbStyle.left = posLeft + unit; var padSideH = pos.height - padBot - padTop + unit; var padSideT = pos.top + padTop + unit; plStyle.height = padSideH; plStyle.width = parseFloat(style.paddingLeft) * zoom + unit; plStyle.top = padSideT; // plStyle.left = pos.left + unit; // plStyle.right = 0; var padRight = parseFloat(style.paddingRight) * zoom; prStyle.height = padSideH; prStyle.width = padRight + unit; prStyle.top = padSideT; // prStyle.left = pos.left + pos.width - padRight + unit; // prStyle.left = 0; }, stop: function (editor, sender, opts) { if (opts === void 0) { opts = {}; } var opt = opts || {}; var state = opt.state || ''; var method = this.getOffsetMethod(state); var view = opts.view; var canvas = this.canvas; // @ts-ignore var offsetViewer = canvas[method](view); offsetViewer.style.opacity = 0; }, }); /***/ }), /***/ 434: /***/ ((__unused_webpack_module, __nested_webpack_exports__, __nested_webpack_require_738106__) => { __nested_webpack_require_738106__.r(__nested_webpack_exports__); /* harmony export */ __nested_webpack_require_738106__.d(__nested_webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_738106__(50); /* harmony import */ var _utils_mixins__WEBPACK_IMPORTED_MODULE_1__ = __nested_webpack_require_738106__(163); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ init: function () { (0,underscore__WEBPACK_IMPORTED_MODULE_0__.bindAll)(this, '_onFramesChange'); }, run: function (ed) { this.toggleVis(ed, true); }, stop: function (ed) { this.toggleVis(ed, false); }, toggleVis: function (ed, active) { if (active === void 0) { active = true; } if (!ed.Commands.isActive('preview')) { var cv = ed.Canvas; var mth = active ? 'on' : 'off'; var canvasModel = cv.getModel(); canvasModel[mth]('change:frames', this._onFramesChange); this.handleFrames(cv.getFrames(), active); } }, handleFrames: function (frames, active) { var _this = this; frames.forEach(function (frame) { var _a; ((_a = frame.view) === null || _a === void 0 ? void 0 : _a.loaded) && _this._upFrame(frame, active); if (!frame.__ol) { frame.on('loaded', function () { return _this._upFrame(frame); }); frame.__ol = true; } }); }, _onFramesChange: function (_, frames) { this.handleFrames(frames); }, _upFrame: function (frame, active) { var _a; var _b = this, ppfx = _b.ppfx, em = _b.em, id = _b.id; var isActive = (0,_utils_mixins__WEBPACK_IMPORTED_MODULE_1__.isDef)(active) ? active : em.Commands.isActive(id); var method = isActive ? 'add' : 'remove'; var cls = "".concat(ppfx, "dashed"); (_a = frame.view) === null || _a === void 0 ? void 0 : _a.getBody().classList[method](cls); }, }); /***/ }), /***/ 346: /***/ ((__unused_webpack_module, __nested_webpack_exports__, __nested_webpack_require_740285__) => { /* harmony export */ __nested_webpack_require_740285__.d(__nested_webpack_exports__, { /* harmony export */ FE: () => (/* binding */ Collection), /* harmony export */ G7: () => (/* binding */ View), /* harmony export */ Hn: () => (/* binding */ Model), /* harmony export */ pH: () => (/* binding */ DEFAULT_COORDS), /* harmony export */ vA: () => (/* binding */ CoordinatesTypes) /* harmony export */ }); /* unused harmony export DEFAULT_BOXRECT */ /* harmony import */ var backbone__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_740285__(316); /* harmony import */ var backbone__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__nested_webpack_require_740285__.n(backbone__WEBPACK_IMPORTED_MODULE_0__); var __extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __assign = ( false) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var Model = /** @class */ (function (_super) { __extends(Model, _super); function Model() { return _super !== null && _super.apply(this, arguments) || this; } return Model; }((backbone__WEBPACK_IMPORTED_MODULE_0___default().Model))); var Collection = /** @class */ (function (_super) { __extends(Collection, _super); function Collection() { return _super !== null && _super.apply(this, arguments) || this; } return Collection; }((backbone__WEBPACK_IMPORTED_MODULE_0___default().Collection))); var View = /** @class */ (function (_super) { __extends(View, _super); function View() { return _super !== null && _super.apply(this, arguments) || this; } return View; }((backbone__WEBPACK_IMPORTED_MODULE_0___default().View))); var CoordinatesTypes; (function (CoordinatesTypes) { CoordinatesTypes["Screen"] = "screen"; CoordinatesTypes["World"] = "world"; })(CoordinatesTypes || (CoordinatesTypes = {})); var DEFAULT_COORDS = { x: 0, y: 0, }; var DEFAULT_BOXRECT = __assign(__assign({}, DEFAULT_COORDS), { width: 0, height: 0 }); /***/ }), /***/ 330: /***/ ((__unused_webpack_module, __nested_webpack_exports__, __nested_webpack_require_743351__) => { /* harmony export */ __nested_webpack_require_743351__.d(__nested_webpack_exports__, { /* harmony export */ Z: () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_743351__(50); /* harmony import */ var _common__WEBPACK_IMPORTED_MODULE_1__ = __nested_webpack_require_743351__(346); var __extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var DomainViews = /** @class */ (function (_super) { __extends(DomainViews, _super); function DomainViews(opts, config, autoAdd) { if (opts === void 0) { opts = {}; } if (autoAdd === void 0) { autoAdd = false; } var _this = _super.call(this, opts) || this; // Defines the View per type _this.itemsView = ''; _this.itemType = 'type'; _this.reuseView = false; _this.config = config || opts.config || {}; autoAdd && _this.listenTo(_this.collection, 'add', _this.addTo); _this.items = []; return _this; } /** * Add new model to the collection * @param {Model} model * @private * */ DomainViews.prototype.addTo = function (model) { this.add(model); }; DomainViews.prototype.itemViewNotFound = function (type) { var _a = this, config = _a.config, ns = _a.ns; var em = config.em; var warn = "".concat(ns ? "[".concat(ns, "]: ") : '', "'").concat(type, "' type not found"); em && em.logWarning(warn); }; /** * Render new model inside the view * @param {Model} model * @param {Object} fragment Fragment collection * @private * */ DomainViews.prototype.add = function (model, fragment) { var _a = this, config = _a.config, reuseView = _a.reuseView, items = _a.items; var itemsView = (this.itemsView || {}); var inputTypes = [ 'button', 'checkbox', 'color', 'date', 'datetime-local', 'email', 'file', 'hidden', 'image', 'month', 'number', 'password', 'radio', 'range', 'reset', 'search', 'submit', 'tel', 'text', 'time', 'url', 'week', ]; var frag = fragment || null; var itemView = this.itemView; var typeField = model.get(this.itemType); var view; if (itemsView[typeField]) { itemView = itemsView[typeField]; } else if (typeField && !itemsView[typeField] && !(0,underscore__WEBPACK_IMPORTED_MODULE_0__.includes)(inputTypes, typeField)) { this.itemViewNotFound(typeField); } if (model.view && reuseView) { view = model.view; } else { view = new itemView({ model: model, config: config }, config); } items && items.push(view); var rendered = view.render().el; if (frag) frag.appendChild(rendered); else this.$el.append(rendered); }; DomainViews.prototype.render = function () { var frag = document.createDocumentFragment(); this.clearItems(); this.$el.empty(); if (this.collection.length) this.collection.each(function (model) { // @ts-ignore this.add(model, frag); }, this); this.$el.append(frag); this.onRender(); return this; }; DomainViews.prototype.onRender = function () { }; DomainViews.prototype.onRemoveBefore = function (items, opts) { }; DomainViews.prototype.onRemove = function (items, opts) { }; DomainViews.prototype.remove = function (opts) { if (opts === void 0) { opts = {}; } var items = this.items; this.onRemoveBefore(items, opts); this.clearItems(); _super.prototype.remove.call(this); this.onRemove(items, opts); return this; }; DomainViews.prototype.clearItems = function () { var items = this.items || []; // TODO Traits do not update the target anymore // items.forEach(item => item.remove()); // this.items = []; }; return DomainViews; }(_common__WEBPACK_IMPORTED_MODULE_1__/* .View */ .G7)); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (DomainViews); // Default view DomainViews.prototype.itemView = ''; /***/ }), /***/ 668: /***/ ((__unused_webpack_module, __nested_webpack_exports__, __nested_webpack_require_748659__) => { /* harmony export */ __nested_webpack_require_748659__.d(__nested_webpack_exports__, { /* harmony export */ Z: () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_748659__(50); /* harmony import */ var _dom__WEBPACK_IMPORTED_MODULE_1__ = __nested_webpack_require_748659__(491); var __assign = ( false) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var resetPos = function () { return ({ x: 0, y: 0 }); }; var xyArr = ['x', 'y']; var Dragger = /** @class */ (function () { /** * Init the dragger * @param {Object} opts */ function Dragger(opts) { if (opts === void 0) { opts = {}; } this.opts = { snapOffset: 5, scale: 1, }; (0,underscore__WEBPACK_IMPORTED_MODULE_0__.bindAll)(this, 'drag', 'stop', 'keyHandle', 'handleScroll'); this.setOptions(opts); this.delta = resetPos(); this.lastScroll = resetPos(); this.lastScrollDiff = resetPos(); this.startPointer = resetPos(); this.startPosition = resetPos(); this.globScrollDiff = resetPos(); this.currentPointer = resetPos(); this.position = resetPos(); this.guidesStatic = []; this.guidesTarget = []; this.docs = []; return this; } /** * Update options * @param {Object} options */ Dragger.prototype.setOptions = function (opts) { if (opts === void 0) { opts = {}; } this.opts = __assign(__assign({}, this.opts), opts); }; Dragger.prototype.toggleDrag = function (enable) { var docs = this.getDocumentEl(); var container = this.getContainerEl(); var win = this.getWindowEl(); var method = enable ? 'on' : 'off'; var methods = { on: _dom__WEBPACK_IMPORTED_MODULE_1__.on, off: _dom__WEBPACK_IMPORTED_MODULE_1__/* .off */ .S1 }; methods[method](container, 'mousemove dragover', this.drag); methods[method](docs, 'mouseup dragend touchend', this.stop); methods[method](docs, 'keydown', this.keyHandle); methods[method](win, 'scroll', this.handleScroll); }; Dragger.prototype.handleScroll = function () { var _a = this, lastScroll = _a.lastScroll, delta = _a.delta; var actualScroll = this.getScrollInfo(); var scrollDiff = { x: actualScroll.x - lastScroll.x, y: actualScroll.y - lastScroll.y, }; this.move(delta.x + scrollDiff.x, delta.y + scrollDiff.y); this.lastScrollDiff = scrollDiff; }; /** * Start dragging * @param {Event} e */ Dragger.prototype.start = function (ev) { var opts = this.opts; var onStart = opts.onStart; this.toggleDrag(true); this.startPointer = this.getPointerPos(ev); this.guidesStatic = (0,underscore__WEBPACK_IMPORTED_MODULE_0__.result)(opts, 'guidesStatic') || []; this.guidesTarget = (0,underscore__WEBPACK_IMPORTED_MODULE_0__.result)(opts, 'guidesTarget') || []; (0,underscore__WEBPACK_IMPORTED_MODULE_0__.isFunction)(onStart) && onStart(ev, this); this.startPosition = this.getStartPosition(); this.lastScrollDiff = resetPos(); this.globScrollDiff = resetPos(); this.drag(ev); }; /** * Drag event * @param {Event} event */ Dragger.prototype.drag = function (ev) { var _this = this; var _a = this, opts = _a.opts, lastScrollDiff = _a.lastScrollDiff, globScrollDiff = _a.globScrollDiff; var onDrag = opts.onDrag; var startPointer = this.startPointer; var currentPos = this.getPointerPos(ev); var glDiff = { x: globScrollDiff.x + lastScrollDiff.x, y: globScrollDiff.y + lastScrollDiff.y, }; this.globScrollDiff = glDiff; var delta = { x: currentPos.x - startPointer.x + glDiff.x, y: currentPos.y - startPointer.y + glDiff.y, }; this.lastScrollDiff = resetPos(); var lockedAxis = this.lockedAxis; // @ts-ignore Lock one axis if (ev.shiftKey) { lockedAxis = !lockedAxis && this.detectAxisLock(delta.x, delta.y); } else { lockedAxis = null; } if (lockedAxis === 'x') { delta.x = startPointer.x; } else if (lockedAxis === 'y') { delta.y = startPointer.y; } var moveDelta = function (delta) { xyArr.forEach(function (co) { return (delta[co] = delta[co] * (0,underscore__WEBPACK_IMPORTED_MODULE_0__.result)(opts, 'scale')); }); _this.delta = delta; _this.move(delta.x, delta.y); (0,underscore__WEBPACK_IMPORTED_MODULE_0__.isFunction)(onDrag) && onDrag(ev, _this); }; var deltaPre = __assign({}, delta); this.currentPointer = currentPos; this.lockedAxis = lockedAxis; this.lastScroll = this.getScrollInfo(); moveDelta(delta); if (this.guidesTarget.length) { var _b = this.snapGuides(deltaPre), newDelta = _b.newDelta, trgX = _b.trgX, trgY = _b.trgY; (trgX || trgY) && moveDelta(newDelta); } // @ts-ignore In case the mouse button was released outside of the window ev.which === 0 && this.stop(ev); }; /** * Check if the delta hits some guide */ Dragger.prototype.snapGuides = function (delta) { var _this = this; var newDelta = delta; var _a = this, trgX = _a.trgX, trgY = _a.trgY; this.guidesTarget.forEach(function (trg) { // Skip the guide if its locked axis already exists if ((trg.x && _this.trgX) || (trg.y && _this.trgY)) return; trg.active = false; _this.guidesStatic.forEach(function (stat) { if ((trg.y && stat.x) || (trg.x && stat.y)) return; var isY = trg.y && stat.y; var axs = isY ? 'y' : 'x'; var trgPoint = trg[axs]; var statPoint = stat[axs]; var deltaPoint = delta[axs]; var trgGuide = isY ? trgY : trgX; if (_this.isPointIn(trgPoint, statPoint)) { if ((0,underscore__WEBPACK_IMPORTED_MODULE_0__.isUndefined)(trgGuide)) { var trgValue = deltaPoint - (trgPoint - statPoint); _this.setGuideLock(trg, trgValue); } } }); }); trgX = this.trgX; trgY = this.trgY; xyArr.forEach(function (co) { var axis = co.toUpperCase(); // @ts-ignore var trg = _this["trg".concat(axis)]; if (trg && !_this.isPointIn(delta[co], trg.lock)) { _this.setGuideLock(trg, null); trg = null; } if (trg && !(0,underscore__WEBPACK_IMPORTED_MODULE_0__.isUndefined)(trg.lock)) { newDelta[co] = trg.lock; } }); return { newDelta: newDelta, trgX: this.trgX, trgY: this.trgY, }; }; Dragger.prototype.isPointIn = function (src, trg, _a) { var _b = _a === void 0 ? {} : _a, offset = _b.offset; var ofst = offset || this.opts.snapOffset || 0; return (src >= trg && src <= trg + ofst) || (src <= trg && src >= trg - ofst); }; Dragger.prototype.setGuideLock = function (guide, value) { var axis = !(0,underscore__WEBPACK_IMPORTED_MODULE_0__.isUndefined)(guide.x) ? 'X' : 'Y'; var trgName = "trg".concat(axis); if (value !== null) { guide.active = true; guide.lock = value; // @ts-ignore this[trgName] = guide; } else { delete guide.active; delete guide.lock; // @ts-ignore delete this[trgName]; } return guide; }; /** * Stop dragging */ Dragger.prototype.stop = function (ev, opts) { if (opts === void 0) { opts = {}; } var delta = this.delta; var cancelled = !!opts.cancel; var x = cancelled ? 0 : delta.x; var y = cancelled ? 0 : delta.y; this.toggleDrag(); this.lockedAxis = null; this.move(x, y, true); var onEnd = this.opts.onEnd; (0,underscore__WEBPACK_IMPORTED_MODULE_0__.isFunction)(onEnd) && onEnd(ev, this, { cancelled: cancelled }); }; Dragger.prototype.keyHandle = function (ev) { if ((0,_dom__WEBPACK_IMPORTED_MODULE_1__/* .isEscKey */ .kl)(ev)) { this.stop(ev, { cancel: true }); } }; /** * Move the element * @param {integer} x * @param {integer} y */ Dragger.prototype.move = function (x, y, end) { var _a = this, el = _a.el, opts = _a.opts; var pos = this.startPosition; if (!pos) return; var setPosition = opts.setPosition; var xPos = pos.x + x; var yPos = pos.y + y; this.position = { x: xPos, y: yPos, end: end, }; (0,underscore__WEBPACK_IMPORTED_MODULE_0__.isFunction)(setPosition) && setPosition(this.position); if (el) { el.style.left = "".concat(xPos, "px"); el.style.top = "".concat(yPos, "px"); } }; Dragger.prototype.getContainerEl = function () { var container = this.opts.container; return container ? [container] : this.getDocumentEl(); }; Dragger.prototype.getWindowEl = function () { var cont = this.getContainerEl(); return cont.map(function (item) { var doc = item.ownerDocument || item; // @ts-ignore return doc.defaultView || doc.parentWindow; }); }; /** * Returns documents */ Dragger.prototype.getDocumentEl = function (el) { var doc = this.opts.doc; el = el || this.el; if (!this.docs.length) { var docs = [document]; el && docs.push(el.ownerDocument); doc && docs.push(doc); this.docs = docs; } return this.docs; }; /** * Get mouse coordinates * @param {Event} event * @return {Object} */ Dragger.prototype.getPointerPos = function (ev) { var getPos = this.opts.getPointerPosition; var pEv = (0,_dom__WEBPACK_IMPORTED_MODULE_1__/* .getPointerEvent */ .VB)(ev); return getPos ? getPos(ev) : { x: pEv.clientX, y: pEv.clientY, }; }; Dragger.prototype.getStartPosition = function () { var _a = this, el = _a.el, opts = _a.opts; var getPos = opts.getPosition; var result = resetPos(); if ((0,underscore__WEBPACK_IMPORTED_MODULE_0__.isFunction)(getPos)) { result = getPos(); } else if (el) { result = { x: parseFloat(el.style.left), y: parseFloat(el.style.top), }; } return result; }; Dragger.prototype.getScrollInfo = function () { var doc = this.opts.doc; var body = doc && doc.body; return { y: body ? body.scrollTop : 0, x: body ? body.scrollLeft : 0, }; }; Dragger.prototype.detectAxisLock = function (x, y) { var relX = x; var relY = y; var absX = Math.abs(relX); var absY = Math.abs(relY); // Vertical or Horizontal lock if (relY >= absX || relY <= -absX) { return 'x'; } else if (relX > absY || relX < -absY) { return 'y'; } }; return Dragger; }()); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (Dragger); /***/ }), /***/ 895: /***/ ((__unused_webpack_module, __nested_webpack_exports__, __nested_webpack_require_761079__) => { __nested_webpack_require_761079__.r(__nested_webpack_exports__); /* harmony export */ __nested_webpack_require_761079__.d(__nested_webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); // @ts-nocheck /* Adapted for headless */ /* MIT https://github.com/kenwheeler/cash */ var doc = typeof document !== 'undefined' ? document : null, win = typeof window !== 'undefined' ? window : null, _Array$prototype = Array.prototype, filter = _Array$prototype.filter, indexOf = _Array$prototype.indexOf, map = _Array$prototype.map, push = _Array$prototype.push, reverse = _Array$prototype.reverse, slice = _Array$prototype.slice, splice = _Array$prototype.splice; var idRe = /^#[\w-]*$/, classRe = /^\.[\w-]*$/, htmlRe = /<.+>/, tagRe = /^\w+$/; // @require ./variables.js function find(selector, context) { if (context === void 0) { context = doc; } return classRe.test(selector) ? context.getElementsByClassName(selector.slice(1)) : tagRe.test(selector) ? context.getElementsByTagName(selector) : context.querySelectorAll(selector); } // @require ./find.js // @require ./variables.js function Cash(selector, context) { if (context === void 0) { context = doc; } if (!selector) return; if (selector.__cash) return selector; var eles = selector; if (isString(selector)) { if (context.__cash) context = context[0]; eles = idRe.test(selector) ? context.getElementById(selector.slice(1)) : htmlRe.test(selector) ? parseHTML(selector) : find(selector, context); if (!eles) return; } else if (isFunction(selector)) { return this.ready(selector); //FIXME: `fn.ready` is not included in `core`, but it's actually a core functionality } if (eles.nodeType || eles === win) eles = [eles]; this.length = eles.length; for (var i = 0, l = this.length; i < l; i++) { this[i] = eles[i]; } } function cash(selector, context) { return new Cash(selector, context); } /* PROTOTYPE */ var fn = (cash.fn = cash.prototype = Cash.prototype = { constructor: cash, __cash: true, length: 0, splice: splice, // Ensures a cash collection gets printed as array-like in Chrome }); // @require core/cash.js // @require core/variables.js fn.get = function (index) { if (index === undefined) return slice.call(this); return this[index < 0 ? index + this.length : index]; }; // @require core/cash.js // @require ./get.js fn.eq = function (index) { return cash(this.get(index)); }; // @require core/cash.js // @require ./eq.js fn.first = function () { return this.eq(0); }; // @require core/cash.js // @require ./eq.js fn.last = function () { return this.eq(-1); }; // @require core/cash.js // @require core/variables.js fn.map = function (callback) { return cash(map.call(this, function (ele, i) { return callback.call(ele, i, ele); })); }; // @require core/cash.js // @require core/variables.js fn.slice = function () { return cash(slice.apply(this, arguments)); }; // @require ./cash.js var camelCaseRe = /(?:^\w|[A-Z]|\b\w)/g, camelCaseWhitespaceRe = /[\s-_]+/g; function camelCase(str) { return str .replace(camelCaseRe, function (letter, index) { return letter[!index ? 'toLowerCase' : 'toUpperCase'](); }) .replace(camelCaseWhitespaceRe, ''); } cash.camelCase = camelCase; // @require ./cash.js function each(arr, callback) { for (var i = 0, l = arr.length; i < l; i++) { if (callback.call(arr[i], arr[i], i, arr) === false) break; } } cash.each = each; // @require core/cash.js // @require core/each.js fn.each = function (callback) { each(this, function (ele, i) { return callback.call(ele, i, ele); }); return this; }; // @require core/cash.js // @require collection/each.js fn.removeProp = function (prop) { return this.each(function (i, ele) { delete ele[prop]; }); }; // @require ./cash.js function extend(target) { if (target === void 0) { target = this; } var args = arguments, length = args.length; for (var i = length < 2 ? 0 : 1; i < length; i++) { for (var key in args[i]) { target[key] = args[i][key]; } } return target; } cash.extend = fn.extend = extend; // @require ./cash.js var guid = 1; cash.guid = guid; // @require ./cash.js function matches(ele, selector) { var matches = ele && (ele.matches || ele.webkitMatchesSelector || ele.mozMatchesSelector || ele.msMatchesSelector || ele.oMatchesSelector); return !!matches && matches.call(ele, selector); } cash.matches = matches; // @require ./cash.js function isFunction(x) { return typeof x === 'function'; } cash.isFunction = isFunction; function isString(x) { return typeof x === 'string'; } cash.isString = isString; function isNumeric(x) { return !isNaN(parseFloat(x)) && isFinite(x); } cash.isNumeric = isNumeric; var isArray = Array.isArray; cash.isArray = isArray; // @require core/cash.js // @require core/type_checking.js // @require collection/each.js fn.prop = function (prop, value) { if (!prop) return; if (isString(prop)) { if (arguments.length < 2) return this[0] && this[0][prop]; return this.each(function (i, ele) { ele[prop] = value; }); } for (var key in prop) { this.prop(key, prop[key]); } return this; }; // @require ./matches.js // @require ./type_checking.js function getCompareFunction(selector) { return isString(selector) ? function (i, ele) { return matches(ele, selector); } : selector.__cash ? function (i, ele) { return selector.is(ele); } : function (i, ele, selector) { return ele === selector; }; } // @require core/cash.js // @require core/get_compare_function.js // @require core/type_checking.js // @require core/variables.js // @require collection/get.js fn.filter = function (selector) { if (!selector) return cash(); var comparator = isFunction(selector) ? selector : getCompareFunction(selector); return cash(filter.call(this, function (ele, i) { return comparator.call(ele, i, ele, selector); })); }; // @require ./type_checking.js var splitValuesRe = /\S+/g; function getSplitValues(str) { return isString(str) ? str.match(splitValuesRe) || [] : []; } // @require core/cash.js // @require core/get_split_values.js // @require collection/each.js fn.hasClass = function (cls) { var classes = getSplitValues(cls); var check = false; if (classes.length) { this.each(function (i, ele) { check = ele.classList.contains(classes[0]); return !check; }); } return check; }; // @require core/cash.js // @require core/get_split_values.js // @require collection/each.js fn.removeAttr = function (attr) { var attrs = getSplitValues(attr); if (!attrs.length) return this; return this.each(function (i, ele) { each(attrs, function (a) { ele.removeAttribute(a); }); }); }; // @require core/cash.js // @require core/type_checking.js // @require collection/each.js // @require ./remove_attr.js fn.attr = function (attr, value) { if (!attr) return; if (isString(attr)) { if (arguments.length < 2) { if (!this[0]) return; var _value = this[0].getAttribute(attr); return _value === null ? undefined : _value; } if (value === null) return this.removeAttr(attr); return this.each(function (i, ele) { ele.setAttribute(attr, value); }); } for (var key in attr) { this.attr(key, attr[key]); } return this; }; // @require core/cash.js // @require core/each.js // @require core/get_split_values.js // @require collection/each.js fn.toggleClass = function (cls, force) { var classes = getSplitValues(cls), isForce = force !== undefined; if (!classes.length) return this; return this.each(function (i, ele) { each(classes, function (c) { if (isForce) { force ? ele.classList.add(c) : ele.classList.remove(c); } else { ele.classList.toggle(c); } }); }); }; // @require core/cash.js // @require ./toggle_class.js fn.addClass = function (cls) { return this.toggleClass(cls, true); }; // @require core/cash.js // @require ./attr.js // @require ./toggle_class.js fn.removeClass = function (cls) { return !arguments.length ? this.attr('class', '') : this.toggleClass(cls, false); }; // @optional ./add_class.js // @optional ./attr.js // @optional ./has_class.js // @optional ./prop.js // @optional ./remove_attr.js // @optional ./remove_class.js // @optional ./remove_prop.js // @optional ./toggle_class.js // @require ./cash.js function unique(arr) { return arr.filter(function (item, index, self) { return self.indexOf(item) === index; }); } cash.unique = unique; // @require core/cash.js // @require core/unique.js // @require ./get.js fn.add = function (selector, context) { return cash(unique(this.get().concat(cash(selector, context).get()))); }; // @require core/variables.js function computeStyle(ele, prop, isVariable) { if (ele.nodeType !== 1) return; var style = win.getComputedStyle(ele, null); return prop ? (isVariable ? style.getPropertyValue(prop) : style[prop]) : style; } // @require ./compute_style.js function computeStyleInt(ele, prop) { return parseInt(computeStyle(ele, prop), 10) || 0; } var cssVariableRe = /^--/; // @require ./variables.js function isCSSVariable(prop) { return cssVariableRe.test(prop); } // @require core/camel_case.js // @require core/cash.js // @require core/each.js // @require core/variables.js // @require ./is_css_variable.js var prefixedProps = {}, docEl = doc && doc.createElement('div'), style = docEl ? docEl.style : {}, vendorsPrefixes = ['webkit', 'moz', 'ms', 'o']; function getPrefixedProp(prop, isVariable) { if (isVariable === void 0) { isVariable = isCSSVariable(prop); } if (isVariable) return prop; if (!prefixedProps[prop]) { var propCC = camelCase(prop), propUC = '' + propCC.charAt(0).toUpperCase() + propCC.slice(1), props = (propCC + ' ' + vendorsPrefixes.join(propUC + ' ') + propUC).split(' '); each(props, function (p) { if (p in style) { prefixedProps[prop] = p; return false; } }); } return prefixedProps[prop]; } cash.prefixedProp = getPrefixedProp; // @require core/type_checking.js // @require ./is_css_variable.js var numericProps = { animationIterationCount: true, columnCount: true, flexGrow: true, flexShrink: true, fontWeight: true, lineHeight: true, opacity: true, order: true, orphans: true, widows: true, zIndex: true, }; function getSuffixedValue(prop, value, isVariable) { if (isVariable === void 0) { isVariable = isCSSVariable(prop); } return !isVariable && !numericProps[prop] && isNumeric(value) ? value + 'px' : value; } // @require core/cash.js // @require core/type_checking.js // @require collection/each.js // @require ./helpers/compute_style.js // @require ./helpers/get_prefixed_prop.js // @require ./helpers/get_suffixed_value.js // @require ./helpers/is_css_variable.js fn.css = function (prop, value) { if (isString(prop)) { var isVariable = isCSSVariable(prop); prop = getPrefixedProp(prop, isVariable); if (arguments.length < 2) return this[0] && computeStyle(this[0], prop, isVariable); if (!prop) return this; value = getSuffixedValue(prop, value, isVariable); return this.each(function (i, ele) { if (ele.nodeType !== 1) return; if (isVariable) { ele.style.setProperty(prop, value); } else { ele.style[prop] = value; } }); } for (var key in prop) { this.css(key, prop[key]); } return this; }; // @optional ./css.js var dataNamespace = '__cashData', dataAttributeRe = /^data-(.*)/; // @require core/cash.js // @require ./helpers/variables.js cash.hasData = function (ele) { return dataNamespace in ele; }; // @require ./variables.js function getDataCache(ele) { return (ele[dataNamespace] = ele[dataNamespace] || {}); } // @require attributes/attr.js // @require ./get_data_cache.js function getData(ele, key) { var cache = getDataCache(ele); if (key) { if (!(key in cache)) { var value = ele.dataset ? ele.dataset[key] || ele.dataset[camelCase(key)] : cash(ele).attr('data-' + key); if (value !== undefined) { try { value = JSON.parse(value); } catch (e) { } cache[key] = value; } } return cache[key]; } return cache; } // @require ./variables.js // @require ./get_data_cache.js function removeData(ele, key) { if (key === undefined) { delete ele[dataNamespace]; } else { delete getDataCache(ele)[key]; } } // @require ./get_data_cache.js function setData(ele, key, value) { getDataCache(ele)[key] = value; } // @require core/cash.js // @require core/type_checking.js // @require collection/each.js // @require ./helpers/get_data.js // @require ./helpers/set_data.js // @require ./helpers/variables.js fn.data = function (name, value) { var _this = this; if (!name) { if (!this[0]) return; each(this[0].attributes, function (attr) { var match = attr.name.match(dataAttributeRe); if (!match) return; _this.data(match[1]); }); return getData(this[0]); } if (isString(name)) { if (value === undefined) return this[0] && getData(this[0], name); return this.each(function (i, ele) { return setData(ele, name, value); }); } for (var key in name) { this.data(key, name[key]); } return this; }; // @require core/cash.js // @require collection/each.js // @require ./helpers/remove_data.js fn.removeData = function (key) { return this.each(function (i, ele) { return removeData(ele, key); }); }; // @optional ./data.js // @optional ./remove_data.js // @require css/helpers/compute_style_int.js function getExtraSpace(ele, xAxis) { return (computeStyleInt(ele, 'border' + (xAxis ? 'Left' : 'Top') + 'Width') + computeStyleInt(ele, 'padding' + (xAxis ? 'Left' : 'Top')) + computeStyleInt(ele, 'padding' + (xAxis ? 'Right' : 'Bottom')) + computeStyleInt(ele, 'border' + (xAxis ? 'Right' : 'Bottom') + 'Width')); } // @require core/cash.js // @require core/each.js // @require core/variables.js each(['Width', 'Height'], function (prop) { fn['inner' + prop] = function () { if (!this[0]) return; if (this[0] === win) return win['inner' + prop]; return this[0]['client' + prop]; }; }); // @require core/camel_case.js // @require core/cash.js // @require core/each.js // @require core/variables.js // @require css/helpers/compute_style.js // @require css/helpers/get_suffixed_value.js // @require ./helpers/get_extra_space.js each(['width', 'height'], function (prop, index) { fn[prop] = function (value) { if (!this[0]) return value === undefined ? undefined : this; if (!arguments.length) { if (this[0] === win) return this[0][camelCase('outer-' + prop)]; return this[0].getBoundingClientRect()[prop] - getExtraSpace(this[0], !index); } value = parseInt(value, 10); return this.each(function (i, ele) { if (ele.nodeType !== 1) return; var boxSizing = computeStyle(ele, 'boxSizing'); ele.style[prop] = getSuffixedValue(prop, value + (boxSizing === 'border-box' ? getExtraSpace(ele, !index) : 0)); }); }; }); // @require core/cash.js // @require core/each.js // @require core/variables.js // @require css/helpers/compute_style_int.js each(['Width', 'Height'], function (prop, index) { fn['outer' + prop] = function (includeMargins) { if (!this[0]) return; if (this[0] === win) return win['outer' + prop]; return (this[0]['offset' + prop] + (includeMargins ? computeStyleInt(this[0], 'margin' + (!index ? 'Left' : 'Top')) + computeStyleInt(this[0], 'margin' + (!index ? 'Right' : 'Bottom')) : 0)); }; }); // @optional ./inner.js // @optional ./normal.js // @optional ./outer.js function hasNamespaces(ns1, ns2) { for (var i = 0, l = ns2.length; i < l; i++) { if (ns1.indexOf(ns2[i]) < 0) return false; } return true; } // @require core/each.js function removeEventListeners(cache, ele, name) { each(cache[name], function (_ref) { var namespaces = _ref[0], callback = _ref[1]; ele.removeEventListener(name, callback); }); delete cache[name]; } var eventsNamespace = '__cashEvents', eventsNamespacesSeparator = '.'; // @require ./variables.js function getEventsCache(ele) { return (ele[eventsNamespace] = ele[eventsNamespace] || {}); } // @require core/guid.js // @require events/helpers/get_events_cache.js function addEvent(ele, name, namespaces, callback) { callback.guid = callback.guid || guid++; var eventCache = getEventsCache(ele); eventCache[name] = eventCache[name] || []; eventCache[name].push([namespaces, callback]); ele.addEventListener(name, callback); } // @require ./variables.js function parseEventName(eventName) { var parts = eventName.split(eventsNamespacesSeparator); return [parts[0], parts.slice(1).sort()]; // [name, namespaces] } // @require core/guid.js // @require ./get_events_cache.js // @require ./has_namespaces.js // @require ./parse_event_name.js // @require ./remove_event_listeners.js function removeEvent(ele, name, namespaces, callback) { var cache = getEventsCache(ele); if (!name) { if (!namespaces || !namespaces.length) { for (name in cache) { removeEventListeners(cache, ele, name); } } else { for (name in cache) { removeEvent(ele, name, namespaces, callback); } } } else { var eventCache = cache[name]; if (!eventCache) return; if (callback) callback.guid = callback.guid || guid++; cache[name] = eventCache.filter(function (_ref2) { var ns = _ref2[0], cb = _ref2[1]; if ((callback && cb.guid !== callback.guid) || !hasNamespaces(ns, namespaces)) return true; ele.removeEventListener(name, cb); }); } } // @require core/cash.js // @require core/each.js // @require collection/each.js // @require ./helpers/parse_event_name.js // @require ./helpers/remove_event.js fn.off = function (eventFullName, callback) { var _this2 = this; if (eventFullName === undefined) { this.each(function (i, ele) { return removeEvent(ele); }); } else { each(getSplitValues(eventFullName), function (eventFullName) { var _parseEventName = parseEventName(eventFullName), name = _parseEventName[0], namespaces = _parseEventName[1]; _this2.each(function (i, ele) { return removeEvent(ele, name, namespaces, callback); }); }); } return this; }; // @require core/cash.js // @require core/get_split_values.js // @require core/guid.js // @require core/matches.js // @require core/type_checking.js // @require collection/each.js // @require ./helpers/variables.js // @require ./helpers/add_event.js // @require ./helpers/has_namespaces.js // @require ./helpers/parse_event_name.js // @require ./helpers/remove_event.js fn.on = function (eventFullName, selector, callback, _one) { var _this3 = this; if (!isString(eventFullName)) { for (var key in eventFullName) { this.on(key, selector, eventFullName[key]); } return this; } if (isFunction(selector)) { callback = selector; selector = false; } each(getSplitValues(eventFullName), function (eventFullName) { var _parseEventName2 = parseEventName(eventFullName), name = _parseEventName2[0], namespaces = _parseEventName2[1]; _this3.each(function (i, ele) { var finalCallback = function finalCallback(event) { if (event.namespace && !hasNamespaces(namespaces, event.namespace.split(eventsNamespacesSeparator))) return; var thisArg = ele; if (selector) { var target = event.target; while (!matches(target, selector)) { if (target === ele) return; target = target.parentNode; if (!target) return; } thisArg = target; } event.namespace = event.namespace || ''; var returnValue = callback.call(thisArg, event, event.data); if (_one) { removeEvent(ele, name, namespaces, finalCallback); } if (returnValue === false) { event.preventDefault(); event.stopPropagation(); } }; finalCallback.guid = callback.guid = callback.guid || guid++; addEvent(ele, name, namespaces, finalCallback); }); }); return this; }; // @require core/cash.js // @require ./on.js fn.one = function (eventFullName, delegate, callback) { return this.on(eventFullName, delegate, callback, true); }; // @require core/cash.js // @require core/variables.js fn.ready = function (callback) { var finalCallback = function finalCallback() { return callback(cash); }; if (doc.readyState !== 'loading') { setTimeout(finalCallback); } else { doc.addEventListener('DOMContentLoaded', finalCallback); } return this; }; // @require core/cash.js // @require core/type_checking.js // @require core/variables.js // @require collection/each.js // @require ./helpers/parse_event_name.js // @require ./helpers/variables.js fn.trigger = function (eventFullName, data) { var evt = eventFullName; if (isString(eventFullName)) { var _parseEventName3 = parseEventName(eventFullName), name = _parseEventName3[0], namespaces = _parseEventName3[1]; evt = doc.createEvent('HTMLEvents'); evt.initEvent(name, true, true); evt.namespace = namespaces.join(eventsNamespacesSeparator); } evt.data = data; return this.each(function (i, ele) { ele.dispatchEvent(evt); }); }; // @optional ./off.js // @optional ./on.js // @optional ./one.js // @optional ./ready.js // @optional ./trigger.js // @require core/each.js function getValueSelectMultiple(ele) { var values = []; each(ele.options, function (option) { if (option.selected && !option.disabled && !option.parentNode.disabled) { values.push(option.value); } }); return values; } function getValueSelectSingle(ele) { return ele.selectedIndex < 0 ? null : ele.options[ele.selectedIndex].value; } // @require ./get_value_select_single.js // @require ./get_value_select_multiple.js var selectOneRe = /select-one/i, selectMultipleRe = /select-multiple/i; function getValue(ele) { var type = ele.type; if (selectOneRe.test(type)) return getValueSelectSingle(ele); if (selectMultipleRe.test(type)) return getValueSelectMultiple(ele); return ele.value; } var queryEncodeSpaceRe = /%20/g; function queryEncode(prop, value) { return '&' + encodeURIComponent(prop) + '=' + encodeURIComponent(value).replace(queryEncodeSpaceRe, '+'); } // @require core/cash.js // @require core/each.js // @require core/type_checking.js // @require ./helpers/get_value.js // @require ./helpers/query_encode.js var skippableRe = /file|reset|submit|button|image/i, checkableRe = /radio|checkbox/i; fn.serialize = function () { var query = ''; this.each(function (i, ele) { each(ele.elements || [ele], function (ele) { if (ele.disabled || !ele.name || ele.tagName === 'FIELDSET') return; if (skippableRe.test(ele.type)) return; if (checkableRe.test(ele.type) && !ele.checked) return; var value = getValue(ele); if (value === undefined) return; var values = isArray(value) ? value : [value]; each(values, function (value) { query += queryEncode(ele.name, value); }); }); }); return query.substr(1); }; // @require core/cash.js // @require core/each.js // @require core/type_checking.js // @require collection/each.js // @require ./helpers/get_value.js fn.val = function (value) { if (value === undefined) return this[0] && getValue(this[0]); return this.each(function (i, ele) { var isMultiple = selectMultipleRe.test(ele.type), eleValue = value === null ? (isMultiple ? [] : '') : value; if (isMultiple && isArray(eleValue)) { each(ele.options, function (option) { option.selected = eleValue.indexOf(option.value) >= 0; }); } else { ele.value = eleValue; } }); }; // @optional ./serialize.js // @optional ./val.js // @require core/cash.js // @require collection/map.js fn.clone = function () { return this.map(function (i, ele) { return ele.cloneNode(true); }); }; // @require core/cash.js // @require collection/each.js fn.detach = function () { return this.each(function (i, ele) { if (ele.parentNode) { ele.parentNode.removeChild(ele); } }); }; // @require ./cash.js // @require ./variables.js // @require ./type_checking.js // @require collection/get.js // @require manipulation/detach.js var fragmentRe = /^\s*<(\w+)[^>]*>/, singleTagRe = /^\s*<(\w+)\s*\/?>(?:<\/\1>)?\s*$/; var containers; function initContainers() { if (containers) return; var table = doc.createElement('table'), tr = doc.createElement('tr'); containers = { '*': doc.createElement('div'), tr: doc.createElement('tbody'), td: tr, th: tr, thead: table, tbody: table, tfoot: table, }; } function parseHTML(html) { initContainers(); if (!isString(html)) return []; if (singleTagRe.test(html)) return [doc.createElement(RegExp.$1)]; var fragment = fragmentRe.test(html) && RegExp.$1, container = containers[fragment] || containers['*']; container.innerHTML = html; return cash(container.childNodes).detach().get(); } cash.parseHTML = parseHTML; // @optional ./camel_case.js // @optional ./each.js // @optional ./export.js // @optional ./extend.js // @optional ./find.js // @optional ./get_compare_function.js // @optional ./get_split_values.js // @optional ./guid.js // @optional ./matches.js // @optional ./parse_html.js // @optional ./unique.js // @optional ./variables.js // @require ./cash.js // @require ./type_checking.js // @require core/cash.js fn.empty = function () { var ele = this[0]; if (ele) { while (ele.firstChild) { ele.removeChild(ele.firstChild); } } return this; }; function insertElement(ele, child, prepend) { if (prepend) { ele.insertBefore(child, ele.childNodes[0]); } else { ele.appendChild(child); } } // @require core/each.js // @require core/type_checking.js // @require ./insert_element.js function insertContent(parent, child, prepend) { if (child === undefined) return; var isStr = isString(child); if (!isStr && child.length) { each(child, function (ele) { return insertContent(parent, ele, prepend); }); } else { each(parent, isStr ? function (ele) { ele.insertAdjacentHTML(prepend ? 'afterbegin' : 'beforeend', child); } : function (ele, index) { return insertElement(ele, !index ? child : child.cloneNode(true), prepend); }); } } // @require core/cash.js // @require core/each.js // @require ./helpers/insert_content.js fn.append = function () { var _this4 = this; each(arguments, function (content) { insertContent(_this4, content); }); return this; }; // @require core/cash.js // @require ./helpers/insert_content.js fn.appendTo = function (parent) { insertContent(cash(parent), this); return this; }; // @require core/cash.js // @require collection/each.js fn.html = function (content) { if (content === undefined) return this[0] && this[0].innerHTML; var source = content.nodeType ? content[0].outerHTML : content; return this.each(function (i, ele) { ele.innerHTML = source; }); }; // @require core/cash.js // @require collection/each.js fn.insertAfter = function (content) { var _this5 = this; cash(content).each(function (index, ele) { var parent = ele.parentNode; _this5.each(function (i, e) { parent.insertBefore(!index ? e : e.cloneNode(true), ele.nextSibling); }); }); return this; }; // @require core/cash.js // @require core/each.js // @require core/variables.js // @require collection/slice.js // @require ./insert_after.js fn.after = function () { var _this6 = this; each(reverse.apply(arguments), function (content) { reverse.apply(cash(content).slice()).insertAfter(_this6); }); return this; }; // @require core/cash.js // @require collection/each.js fn.insertBefore = function (selector) { var _this7 = this; cash(selector).each(function (index, ele) { var parent = ele.parentNode; _this7.each(function (i, e) { parent.insertBefore(!index ? e : e.cloneNode(true), ele); }); }); return this; }; // @require core/cash.js // @require core/each.js // @require ./insert_before.js fn.before = function () { var _this8 = this; each(arguments, function (content) { cash(content).insertBefore(_this8); }); return this; }; // @require core/cash.js // @require core/each.js // @require ./helpers/insert_content.js fn.prepend = function () { var _this9 = this; each(arguments, function (content) { insertContent(_this9, content, true); }); return this; }; // @require core/cash.js // @require core/variables.js // @require collection/slice.js // @require ./helpers/insert_content.js fn.prependTo = function (parent) { insertContent(cash(parent), reverse.apply(this.slice()), true); return this; }; // @require core/cash.js // @require events/off.js // @require ./detach.js fn.remove = function () { return this.detach().off(); }; // @require core/cash.js // @require collection/each.js // @require collection/slice.js // @require ./after.js // @require ./remove.js fn.replaceWith = function (content) { var _this10 = this; return this.each(function (i, ele) { var parent = ele.parentNode; if (!parent) return; var $eles = i ? cash(content).clone() : cash(content); if (!$eles[0]) { _this10.remove(); return false; } parent.replaceChild($eles[0], ele); cash($eles[0]).after($eles.slice(1)); }); }; // @require core/cash.js // @require ./replace_with.js fn.replaceAll = function (content) { cash(content).replaceWith(this); return this; }; // @require core/cash.js // @require collection/each.js fn.text = function (content) { if (content === undefined) return this[0] ? this[0].textContent : ''; return this.each(function (i, ele) { ele.textContent = content; }); }; // @optional ./after.js // @optional ./append.js // @optional ./append_to.js // @optional ./before.js // @optional ./clone.js // @optional ./detach.js // @optional ./empty.js // @optional ./html.js // @optional ./insert_after.js // @optional ./insert_before.js // @optional ./prepend.js // @optional ./prepend_to.js // @optional ./remove.js // @optional ./replace_all.js // @optional ./replace_with.js // @optional ./text.js // @require core/cash.js // @require core/variables.js var docEle = doc && doc.documentElement; fn.offset = function () { var ele = this[0]; if (!ele) return; var rect = ele.getBoundingClientRect(); return { top: rect.top + win.pageYOffset - docEle.clientTop, left: rect.left + win.pageXOffset - docEle.clientLeft, }; }; // @require core/cash.js fn.offsetParent = function () { return cash(this[0] && this[0].offsetParent); }; // @require core/cash.js fn.position = function () { var ele = this[0]; if (!ele) return; return { left: ele.offsetLeft, top: ele.offsetTop, }; }; // @optional ./offset.js // @optional ./offset_parent.js // @optional ./position.js // @require core/cash.js // @require core/matches.js // @require core/unique.js // @require collection/each.js // @require collection/filter.js fn.children = function (selector) { var result = []; this.each(function (i, ele) { push.apply(result, ele.children); }); result = cash(unique(result)); if (!selector) return result; return result.filter(function (i, ele) { return matches(ele, selector); }); }; // @require core/cash.js // @require core/unique.js // @require collection/each.js fn.contents = function () { var result = []; this.each(function (i, ele) { push.apply(result, ele.tagName === 'IFRAME' ? [ele.contentDocument] : ele.childNodes); }); return cash(result.length && unique(result)); }; // @require core/cash.js // @require core/unique.js // @require core/find.js // @require core/variables.js fn.find = function (selector) { var result = []; for (var i = 0, l = this.length; i < l; i++) { var found = find(selector, this[i]); if (found.length) { push.apply(result, found); } } return cash(result.length && unique(result)); }; // @require core/cash.js // @require core/find.js // @require core/type_checking.js // @require collection/filter.js fn.has = function (selector) { var comparator = isString(selector) ? function (i, ele) { return !!find(selector, ele).length; } : function (i, ele) { return ele.contains(selector); }; return this.filter(comparator); }; // @require core/cash.js // @require core/get_compare_function.js // @require collection/each.js fn.is = function (selector) { if (!selector || !this[0]) return false; var comparator = getCompareFunction(selector); var check = false; this.each(function (i, ele) { check = comparator(i, ele, selector); return !check; }); return check; }; // @require core/cash.js fn.next = function () { return cash(this[0] && this[0].nextElementSibling); }; // @require core/cash.js // @require core/get_compare_function.js // @require collection/filter.js fn.not = function (selector) { if (!selector || !this[0]) return this; var comparator = getCompareFunction(selector); return this.filter(function (i, ele) { return !comparator(i, ele, selector); }); }; // @require core/cash.js // @require core/unique.js // @require collection/each.js fn.parent = function () { var result = []; this.each(function (i, ele) { if (ele && ele.parentNode) { result.push(ele.parentNode); } }); return cash(unique(result)); }; // @require core/cash.js // @require core/variables.js // @require traversal/children.js // @require traversal/parent.js // @require ./get.js //FIXME Ugly file name, is there a better option? fn.index = function (ele) { var child = ele ? cash(ele)[0] : this[0], collection = ele ? this : cash(child).parent().children(); return indexOf.call(collection, child); }; // @optional ./add.js // @optional ./each.js // @optional ./eq.js // @optional ./filter.js // @optional ./first.js // @optional ./get.js // @optional ./indexFn.js // @optional ./last.js // @optional ./map.js // @optional ./slice.js // @require core/cash.js // @require collection/filter.js // @require ./is.js // @require ./parent.js fn.closest = function (selector) { if (!selector || !this[0]) return cash(); if (this.is(selector)) return this.filter(selector); return this.parent().closest(selector); }; // @require core/cash.js // @require core/matches.js // @require core/unique.js // @require core/variables.js // @require collection/each.js fn.parents = function (selector) { var result = []; var last; this.each(function (i, ele) { last = ele; while (last && last.parentNode && last !== doc.body.parentNode) { last = last.parentNode; if (!selector || (selector && matches(last, selector))) { result.push(last); } } }); return cash(unique(result)); }; // @require core/cash.js fn.prev = function () { return cash(this[0] && this[0].previousElementSibling); }; // @require core/cash.js // @require collection/filter.js // @require ./children.js // @require ./parent.js fn.siblings = function () { var ele = this[0]; return this.parent() .children() .filter(function (i, child) { return child !== ele; }); }; // @optional ./children.js // @optional ./closest.js // @optional ./contents.js // @optional ./find.js // @optional ./has.js // @optional ./is.js // @optional ./next.js // @optional ./not.js // @optional ./parent.js // @optional ./parents.js // @optional ./prev.js // @optional ./siblings.js // @optional attributes/index.js // @optional collection/index.js // @optional css/index.js // @optional data/index.js // @optional dimensions/index.js // @optional events/index.js // @optional forms/index.js // @optional manipulation/index.js // @optional offset/index.js // @optional traversal/index.js // @require core/index.js /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (cash); /***/ }), /***/ 491: /***/ ((__unused_webpack_module, __nested_webpack_exports__, __nested_webpack_require_800502__) => { /* harmony export */ __nested_webpack_require_800502__.d(__nested_webpack_exports__, { /* harmony export */ $Q: () => (/* binding */ appendAtIndex), /* harmony export */ BM: () => (/* binding */ isTextNode), /* harmony export */ FW: () => (/* binding */ attrUp), /* harmony export */ G1: () => (/* binding */ motionsEv), /* harmony export */ GX: () => (/* binding */ getDocumentScroll), /* harmony export */ L_: () => (/* binding */ removeEl), /* harmony export */ Mx: () => (/* binding */ isDoc), /* harmony export */ R3: () => (/* binding */ append), /* harmony export */ S1: () => (/* binding */ off), /* harmony export */ SJ: () => (/* binding */ appendVNodes), /* harmony export */ Ut: () => (/* binding */ getElRect), /* harmony export */ VB: () => (/* binding */ getPointerEvent), /* harmony export */ Vb: () => (/* binding */ hasModifierKey), /* harmony export */ cx: () => (/* binding */ cx), /* harmony export */ dL: () => (/* binding */ replaceWith), /* harmony export */ kl: () => (/* binding */ isEscKey), /* harmony export */ o5: () => (/* binding */ isTaggableNode), /* harmony export */ on: () => (/* binding */ on), /* harmony export */ pn: () => (/* binding */ isVisible), /* harmony export */ r$: () => (/* binding */ isEnterKey), /* harmony export */ rw: () => (/* binding */ createText), /* harmony export */ sE: () => (/* binding */ find), /* harmony export */ sN: () => (/* binding */ getKeyChar), /* harmony export */ t3: () => (/* binding */ createCustomEvent), /* harmony export */ ut: () => (/* binding */ createEl) /* harmony export */ }); /* unused harmony exports empty, isCommentNode, getKeyCode, hasCtrlKey */ /* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_800502__(50); var __spreadArray = ( false) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var KEY_TAG = 'tag'; var KEY_ATTR = 'attributes'; var KEY_CHILD = 'children'; var motionsEv = 'transitionend oTransitionEnd transitionend webkitTransitionEnd'; var isDoc = function (el) { return (el === null || el === void 0 ? void 0 : el.nodeType) === Node.DOCUMENT_NODE; }; var removeEl = function (el) { var parent = el && el.parentNode; parent && parent.removeChild(el); }; function cx() { var inputs = []; for (var _i = 0; _i < arguments.length; _i++) { inputs[_i] = arguments[_i]; } var inp = Array.isArray(inputs[0]) ? inputs[0] : __spreadArray([], inputs, true); return inp.filter(Boolean).join(' '); } var find = function (el, query) { return el.querySelectorAll(query); }; var attrUp = function (el, attrs) { if (attrs === void 0) { attrs = {}; } return el && el.setAttribute && (0,underscore__WEBPACK_IMPORTED_MODULE_0__.each)(attrs, function (value, key) { return el.setAttribute(key, value); }); }; var isVisible = function (el) { return el && !!(el.offsetWidth || el.offsetHeight || el.getClientRects().length); }; var empty = function (node) { while (node.firstChild) node.removeChild(node.firstChild); }; var replaceWith = function (oldEl, newEl) { var _a; (_a = oldEl.parentNode) === null || _a === void 0 ? void 0 : _a.replaceChild(newEl, oldEl); }; var appendAtIndex = function (parent, child, index) { var childNodes = parent.childNodes; var total = childNodes.length; var at = (0,underscore__WEBPACK_IMPORTED_MODULE_0__.isUndefined)(index) ? total : index; if ((0,underscore__WEBPACK_IMPORTED_MODULE_0__.isString)(child)) { // @ts-ignore parent.insertAdjacentHTML('beforeEnd', child); child = parent.lastChild; parent.removeChild(child); } if (at >= total) { parent.appendChild(child); } else { parent.insertBefore(child, childNodes[at]); } }; var append = function (parent, child) { return appendAtIndex(parent, child); }; var createEl = function (tag, attrs, child) { if (attrs === void 0) { attrs = {}; } var el = document.createElement(tag); attrs && (0,underscore__WEBPACK_IMPORTED_MODULE_0__.each)(attrs, function (value, key) { return el.setAttribute(key, value); }); if (child) { if ((0,underscore__WEBPACK_IMPORTED_MODULE_0__.isString)(child)) el.innerHTML = child; else el.appendChild(child); } return el; }; var createText = function (str) { return document.createTextNode(str); }; // Unfortunately just creating `KeyboardEvent(e.type, e)` is not enough, // the keyCode/which will be always `0`. Even if it's an old/deprecated // property keymaster (and many others) still use it... using `defineProperty` // hack seems the only way var createCustomEvent = function (e, cls) { var oEvent; var type = e.type; try { // @ts-ignore oEvent = new window[cls](type, e); } catch (err) { oEvent = document.createEvent(cls); oEvent.initEvent(type, true, true); } oEvent._parentEvent = e; if (type.indexOf('key') === 0) { oEvent.keyCodeVal = e.keyCode; ['keyCode', 'which'].forEach(function (prop) { Object.defineProperty(oEvent, prop, { get: function () { return this.keyCodeVal; }, }); }); } return oEvent; }; /** * Append an array of vNodes to an element * @param {HTMLElement} node HTML element * @param {Array} vNodes Array of node objects */ var appendVNodes = function (node, vNodes) { if (vNodes === void 0) { vNodes = []; } var vNodesArr = Array.isArray(vNodes) ? vNodes : [vNodes]; vNodesArr.forEach(function (vnode) { var tag = vnode[KEY_TAG] || 'div'; var attr = vnode[KEY_ATTR] || {}; var el = document.createElement(tag); (0,underscore__WEBPACK_IMPORTED_MODULE_0__.each)(attr, function (value, key) { el.setAttribute(key, value); }); node.appendChild(el); }); }; /** * Check if element is a text node * @param {Node} el * @return {Boolean} */ var isTextNode = function (el) { return (el === null || el === void 0 ? void 0 : el.nodeType) === Node.TEXT_NODE; }; /** * Check if element is a comment node * @param {Node} el * @return {Boolean} */ var isCommentNode = function (el) { return (el === null || el === void 0 ? void 0 : el.nodeType) === Node.COMMENT_NODE; }; /** * Check if taggable node * @param {Node} el * @return {Boolean} */ var isTaggableNode = function (el) { return el && !isTextNode(el) && !isCommentNode(el); }; /** * Get DOMRect of the element. * @param el * @returns {DOMRect} */ var getElRect = function (el) { var def = { top: 0, left: 0, width: 0, height: 0, }; if (!el) return def; var rectText; if (isTextNode(el)) { var range = document.createRange(); range.selectNode(el); rectText = range.getBoundingClientRect(); range.detach(); } return rectText || (el.getBoundingClientRect ? el.getBoundingClientRect() : def); }; /** * Get document scroll coordinates */ var getDocumentScroll = function (el) { var doc = (el === null || el === void 0 ? void 0 : el.ownerDocument) || document; var docEl = doc.documentElement; var win = doc.defaultView || window; return { x: (win.pageXOffset || docEl.scrollLeft || 0) - (docEl.clientLeft || 0), y: (win.pageYOffset || docEl.scrollTop || 0) - (docEl.clientTop || 0), }; }; var getKeyCode = function (ev) { return ev.which || ev.keyCode; }; var getKeyChar = function (ev) { return String.fromCharCode(getKeyCode(ev)); }; var getPointerEvent = function (ev) { return (ev.touches && ev.touches[0] ? ev.touches[0] : ev); }; var isEscKey = function (ev) { return getKeyCode(ev) === 27; }; var isEnterKey = function (ev) { return getKeyCode(ev) === 13; }; var hasCtrlKey = function (ev) { return ev.ctrlKey; }; var hasModifierKey = function (ev) { return hasCtrlKey(ev) || ev.metaKey; }; var on = function (el, ev, fn, opts) { var evs = ev.split(/\s+/); var els = (0,underscore__WEBPACK_IMPORTED_MODULE_0__.isArray)(el) ? el : [el]; evs.forEach(function (ev) { els.forEach(function (el) { return el === null || el === void 0 ? void 0 : el.addEventListener(ev, fn, opts); }); }); }; var off = function (el, ev, fn, opts) { var evs = ev.split(/\s+/); var els = (0,underscore__WEBPACK_IMPORTED_MODULE_0__.isArray)(el) ? el : [el]; evs.forEach(function (ev) { els.forEach(function (el) { return el === null || el === void 0 ? void 0 : el.removeEventListener(ev, fn, opts); }); }); }; /***/ }), /***/ 163: /***/ ((__unused_webpack_module, __nested_webpack_exports__, __nested_webpack_require_809507__) => { __nested_webpack_require_809507__.r(__nested_webpack_exports__); /* harmony export */ __nested_webpack_require_809507__.d(__nested_webpack_exports__, { /* harmony export */ appendStyles: () => (/* binding */ appendStyles), /* harmony export */ buildBase64UrlFromSvg: () => (/* binding */ buildBase64UrlFromSvg), /* harmony export */ camelCase: () => (/* binding */ camelCase), /* harmony export */ capitalize: () => (/* binding */ capitalize), /* harmony export */ createId: () => (/* binding */ createId), /* harmony export */ deepMerge: () => (/* binding */ deepMerge), /* harmony export */ escape: () => (/* binding */ escape), /* harmony export */ escapeNodeContent: () => (/* binding */ escapeNodeContent), /* harmony export */ find: () => (/* binding */ find), /* harmony export */ getComponentModel: () => (/* binding */ getComponentModel), /* harmony export */ getComponentView: () => (/* binding */ getComponentView), /* harmony export */ getElement: () => (/* binding */ getElement), /* harmony export */ getGlobal: () => (/* binding */ getGlobal), /* harmony export */ getModel: () => (/* binding */ getModel), /* harmony export */ getUiClass: () => (/* binding */ getUiClass), /* harmony export */ getUnitFromValue: () => (/* binding */ getUnitFromValue), /* harmony export */ getViewEl: () => (/* binding */ getViewEl), /* harmony export */ hasDnd: () => (/* binding */ hasDnd), /* harmony export */ hasWin: () => (/* binding */ hasWin), /* harmony export */ isComponent: () => (/* binding */ isComponent), /* harmony export */ isDef: () => (/* binding */ isDef), /* harmony export */ isEmptyObj: () => (/* binding */ isEmptyObj), /* harmony export */ isObject: () => (/* binding */ isObject), /* harmony export */ isRule: () => (/* binding */ isRule), /* harmony export */ matches: () => (/* binding */ matches), /* harmony export */ normalizeFloat: () => (/* binding */ normalizeFloat), /* harmony export */ setViewEl: () => (/* binding */ setViewEl), /* harmony export */ shallowDiff: () => (/* binding */ shallowDiff), /* harmony export */ toLowerCase: () => (/* binding */ toLowerCase), /* harmony export */ upFirst: () => (/* binding */ upFirst), /* harmony export */ wait: () => (/* binding */ wait) /* harmony export */ }); /* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_809507__(50); /* harmony import */ var _dom__WEBPACK_IMPORTED_MODULE_1__ = __nested_webpack_require_809507__(491); var __assign = ( false) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __spreadArray = ( false) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var wait = function (mls) { if (mls === void 0) { mls = 0; } return new Promise(function (res) { return setTimeout(res, mls); }); }; var isDef = function (value) { return typeof value !== 'undefined'; }; var hasWin = function () { return typeof window !== 'undefined'; }; var getGlobal = function () { return typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : __nested_webpack_require_809507__.g; }; var toLowerCase = function (str) { return (str || '').toLowerCase(); }; var elProt = hasWin() ? window.Element.prototype : {}; // @ts-ignore var matches = elProt.matches || elProt.webkitMatchesSelector || elProt.mozMatchesSelector || elProt.msMatchesSelector; var getUiClass = function (em, defCls) { var _a = em.getConfig(), stylePrefix = _a.stylePrefix, customUI = _a.customUI; return [customUI && "".concat(stylePrefix, "cui"), defCls].filter(function (i) { return i; }).join(' '); }; /** * Import styles asynchronously * @param {String|Array<String>} styles */ var appendStyles = function (styles, opts) { if (opts === void 0) { opts = {}; } var stls = (0,underscore__WEBPACK_IMPORTED_MODULE_0__.isArray)(styles) ? __spreadArray([], styles, true) : [styles]; if (stls.length) { var href = stls.shift(); if (href && (!opts.unique || !document.querySelector("link[href=\"".concat(href, "\"]")))) { var head = document.head; var link = document.createElement('link'); link.href = href; link.rel = 'stylesheet'; if (opts.prepand) { head.insertBefore(link, head.firstChild); } else { head.appendChild(link); } } appendStyles(stls); } }; /** * Returns shallow diff between 2 objects * @param {Object} objOrig * @param {Objec} objNew * @return {Object} * @example * var a = {foo: 'bar', baz: 1, faz: 'sop'}; * var b = {foo: 'bar', baz: 2, bar: ''}; * shallowDiff(a, b); * // -> {baz: 2, faz: null, bar: ''}; */ var shallowDiff = function (objOrig, objNew) { var result = {}; var keysNew = (0,underscore__WEBPACK_IMPORTED_MODULE_0__.keys)(objNew); for (var prop in objOrig) { if (objOrig.hasOwnProperty(prop)) { var origValue = objOrig[prop]; var newValue = objNew[prop]; if (keysNew.indexOf(prop) >= 0) { if (origValue !== newValue) { result[prop] = newValue; } } else { result[prop] = null; } } } for (var prop in objNew) { if (objNew.hasOwnProperty(prop)) { if ((0,underscore__WEBPACK_IMPORTED_MODULE_0__.isUndefined)(objOrig[prop])) { result[prop] = objNew[prop]; } } } return result; }; var getUnitFromValue = function (value) { return value.replace(parseFloat(value), ''); }; var upFirst = function (value) { return value[0].toUpperCase() + value.toLowerCase().slice(1); }; var camelCase = function (value) { return value.replace(/-./g, function (x) { return x[1].toUpperCase(); }); }; var normalizeFloat = function (value, step, valueDef) { if (step === void 0) { step = 1; } if (valueDef === void 0) { valueDef = 0; } var stepDecimals = 0; if (isNaN(value)) return valueDef; value = parseFloat(value); if (Math.floor(value) !== value) { var side = step.toString().split('.')[1]; stepDecimals = side ? side.length : 0; } return stepDecimals ? parseFloat(value.toFixed(stepDecimals)) : value; }; var hasDnd = function (em) { return 'draggable' in document.createElement('i') && (em ? em.config.nativeDnD : true); }; /** * Ensure to fetch the element from the input argument * @param {HTMLElement|Component} el Component or HTML element * @return {HTMLElement} */ var getElement = function (el) { if ((0,underscore__WEBPACK_IMPORTED_MODULE_0__.isElement)(el) || (0,_dom__WEBPACK_IMPORTED_MODULE_1__/* .isTextNode */ .BM)(el)) { return el; // @ts-ignore } else if (el && el.getEl) { // @ts-ignore return el.getEl(); } }; var find = function (arr, test) { var result = null; arr.some(function (el, i) { return (test(el, i, arr) ? ((result = el), 1) : 0); }); return result; }; var escape = function (str) { if (str === void 0) { str = ''; } return "".concat(str) .replace(/&/g, '&') .replace(/</g, '<') .replace(/>/g, '>') .replace(/"/g, '"') .replace(/'/g, ''') .replace(/`/g, '`'); }; var escapeNodeContent = function (str) { if (str === void 0) { str = ''; } return "".concat(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>'); }; var deepMerge = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var target = __assign({}, args[0]); for (var i = 1; i < args.length; i++) { var source = __assign({}, args[i]); for (var key in source) { var targValue = target[key]; var srcValue = source[key]; if (isObject(targValue) && isObject(srcValue)) { target[key] = deepMerge(targValue, srcValue); } else { target[key] = srcValue; } } } return target; }; /** * Ensure to fetch the model from the input argument * @param {HTMLElement|Component} el Component or HTML element * @return {Component} */ var getModel = function (el, $) { var model = el; if (!$ && el && el.__cashData) { model = el.__cashData.model; } else if ((0,underscore__WEBPACK_IMPORTED_MODULE_0__.isElement)(el)) { model = $(el).data('model'); } return model; }; var isObject = function (val) { return val && !Array.isArray(val) && typeof val === 'object'; }; var isEmptyObj = function (val) { return Object.keys(val).length <= 0; }; var capitalize = function (str) { if (str === void 0) { str = ''; } return str && str.charAt(0).toUpperCase() + str.substring(1); }; var isRule = function (obj) { return obj && obj.toCSS; }; var getViewEl = function (el) { return el === null || el === void 0 ? void 0 : el.__gjsv; }; var isComponent = function (obj) { return !!(obj === null || obj === void 0 ? void 0 : obj.toHTML); }; var getComponentView = function (el) { return getViewEl(el); }; var getComponentModel = function (el) { var _a; return (_a = getComponentView(el)) === null || _a === void 0 ? void 0 : _a.model; }; var setViewEl = function (el, view) { el.__gjsv = view; }; var createId = function (length) { if (length === void 0) { length = 16; } var result = ''; var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; var len = chars.length; for (var i = 0; i < length; i++) { result += chars.charAt(Math.floor(Math.random() * len)); } return result; }; var buildBase64UrlFromSvg = function (svg) { if (svg && svg.substr(0, 4) === '<svg') { var base64Str = ''; if (hasWin()) { base64Str = window.btoa(svg); } else if (typeof Buffer !== 'undefined') { base64Str = Buffer.from(svg, 'utf8').toString('base64'); } return base64Str ? "data:image/svg+xml;base64,".concat(base64Str) : svg; } return svg; }; /***/ }), /***/ 828: /***/ ((module, __unused_webpack_exports, __nested_webpack_require_820332__) => { var map = { "./CanvasClear": 858, "./CanvasClear.ts": 858, "./CanvasMove": 884, "./CanvasMove.ts": 884, "./CommandAbstract": 790, "./CommandAbstract.ts": 790, "./ComponentDelete": 180, "./ComponentDelete.ts": 180, "./ComponentDrag": 544, "./ComponentDrag.ts": 544, "./ComponentEnter": 236, "./ComponentEnter.ts": 236, "./ComponentExit": 368, "./ComponentExit.ts": 368, "./ComponentNext": 243, "./ComponentNext.ts": 243, "./ComponentPrev": 400, "./ComponentPrev.ts": 400, "./ComponentStyleClear": 910, "./ComponentStyleClear.ts": 910, "./CopyComponent": 744, "./CopyComponent.ts": 744, "./DeleteComponent": 517, "./DeleteComponent.ts": 517, "./ExportTemplate": 457, "./ExportTemplate.ts": 457, "./Fullscreen": 975, "./Fullscreen.ts": 975, "./MoveComponent": 191, "./MoveComponent.ts": 191, "./OpenAssets": 912, "./OpenAssets.ts": 912, "./OpenBlocks": 117, "./OpenBlocks.ts": 117, "./OpenLayers": 614, "./OpenLayers.ts": 614, "./OpenStyleManager": 801, "./OpenStyleManager.ts": 801, "./OpenTraitManager": 395, "./OpenTraitManager.ts": 395, "./PasteComponent": 98, "./PasteComponent.ts": 98, "./Preview": 129, "./Preview.ts": 129, "./Resize": 116, "./Resize.ts": 116, "./SelectComponent": 407, "./SelectComponent.ts": 407, "./SelectPosition": 189, "./SelectPosition.ts": 189, "./ShowOffset": 804, "./ShowOffset.ts": 804, "./SwitchVisibility": 434, "./SwitchVisibility.ts": 434 }; function webpackContext(req) { var id = webpackContextResolve(req); return __nested_webpack_require_820332__(id); } function webpackContextResolve(req) { if(!__nested_webpack_require_820332__.o(map, req)) { var e = new Error("Cannot find module '" + req + "'"); e.code = 'MODULE_NOT_FOUND'; throw e; } return map[req]; } webpackContext.keys = function webpackContextKeys() { return Object.keys(map); }; webpackContext.resolve = webpackContextResolve; module.exports = webpackContext; webpackContext.id = 828; /***/ }), /***/ 50: /***/ ((__unused_webpack___webpack_module__, __nested_webpack_exports__, __nested_webpack_require_822373__) => { // ESM COMPAT FLAG __nested_webpack_require_822373__.r(__nested_webpack_exports__); // EXPORTS __nested_webpack_require_822373__.d(__nested_webpack_exports__, { VERSION: () => (/* reexport */ VERSION), after: () => (/* reexport */ after), all: () => (/* reexport */ every), allKeys: () => (/* reexport */ allKeys), any: () => (/* reexport */ some), assign: () => (/* reexport */ extendOwn), before: () => (/* reexport */ before), bind: () => (/* reexport */ bind), bindAll: () => (/* reexport */ bindAll), chain: () => (/* reexport */ chain), chunk: () => (/* reexport */ chunk), clone: () => (/* reexport */ clone), collect: () => (/* reexport */ map), compact: () => (/* reexport */ compact), compose: () => (/* reexport */ compose), constant: () => (/* reexport */ constant), contains: () => (/* reexport */ contains), countBy: () => (/* reexport */ countBy), create: () => (/* reexport */ create), debounce: () => (/* reexport */ debounce), "default": () => (/* reexport */ index_default), defaults: () => (/* reexport */ defaults), defer: () => (/* reexport */ defer), delay: () => (/* reexport */ delay), detect: () => (/* reexport */ find), difference: () => (/* reexport */ difference), drop: () => (/* reexport */ rest), each: () => (/* reexport */ each), escape: () => (/* reexport */ modules_escape), every: () => (/* reexport */ every), extend: () => (/* reexport */ extend), extendOwn: () => (/* reexport */ extendOwn), filter: () => (/* reexport */ filter), find: () => (/* reexport */ find), findIndex: () => (/* reexport */ findIndex), findKey: () => (/* reexport */ findKey), findLastIndex: () => (/* reexport */ findLastIndex), findWhere: () => (/* reexport */ findWhere), first: () => (/* reexport */ first), flatten: () => (/* reexport */ flatten_flatten), foldl: () => (/* reexport */ reduce), foldr: () => (/* reexport */ reduceRight), forEach: () => (/* reexport */ each), functions: () => (/* reexport */ functions), get: () => (/* reexport */ get), groupBy: () => (/* reexport */ groupBy), has: () => (/* reexport */ has_has), head: () => (/* reexport */ first), identity: () => (/* reexport */ identity), include: () => (/* reexport */ contains), includes: () => (/* reexport */ contains), indexBy: () => (/* reexport */ indexBy), indexOf: () => (/* reexport */ indexOf), initial: () => (/* reexport */ initial), inject: () => (/* reexport */ reduce), intersection: () => (/* reexport */ intersection), invert: () => (/* reexport */ invert), invoke: () => (/* reexport */ invoke), isArguments: () => (/* reexport */ modules_isArguments), isArray: () => (/* reexport */ isArray), isArrayBuffer: () => (/* reexport */ isArrayBuffer), isBoolean: () => (/* reexport */ isBoolean), isDataView: () => (/* reexport */ modules_isDataView), isDate: () => (/* reexport */ isDate), isElement: () => (/* reexport */ isElement), isEmpty: () => (/* reexport */ isEmpty), isEqual: () => (/* reexport */ isEqual), isError: () => (/* reexport */ isError), isFinite: () => (/* reexport */ isFinite_isFinite), isFunction: () => (/* reexport */ modules_isFunction), isMap: () => (/* reexport */ isMap), isMatch: () => (/* reexport */ isMatch), isNaN: () => (/* reexport */ isNaN_isNaN), isNull: () => (/* reexport */ isNull), isNumber: () => (/* reexport */ isNumber), isObject: () => (/* reexport */ isObject), isRegExp: () => (/* reexport */ isRegExp), isSet: () => (/* reexport */ isSet), isString: () => (/* reexport */ isString), isSymbol: () => (/* reexport */ isSymbol), isTypedArray: () => (/* reexport */ modules_isTypedArray), isUndefined: () => (/* reexport */ isUndefined), isWeakMap: () => (/* reexport */ isWeakMap), isWeakSet: () => (/* reexport */ isWeakSet), iteratee: () => (/* reexport */ iteratee), keys: () => (/* reexport */ keys), last: () => (/* reexport */ last), lastIndexOf: () => (/* reexport */ lastIndexOf), map: () => (/* reexport */ map), mapObject: () => (/* reexport */ mapObject), matcher: () => (/* reexport */ matcher), matches: () => (/* reexport */ matcher), max: () => (/* reexport */ max), memoize: () => (/* reexport */ memoize), methods: () => (/* reexport */ functions), min: () => (/* reexport */ min), mixin: () => (/* reexport */ mixin), negate: () => (/* reexport */ negate), noop: () => (/* reexport */ noop), now: () => (/* reexport */ now), object: () => (/* reexport */ object), omit: () => (/* reexport */ omit), once: () => (/* reexport */ once), pairs: () => (/* reexport */ pairs), partial: () => (/* reexport */ modules_partial), partition: () => (/* reexport */ partition), pick: () => (/* reexport */ pick), pluck: () => (/* reexport */ pluck), property: () => (/* reexport */ property), propertyOf: () => (/* reexport */ propertyOf), random: () => (/* reexport */ random), range: () => (/* reexport */ range), reduce: () => (/* reexport */ reduce), reduceRight: () => (/* reexport */ reduceRight), reject: () => (/* reexport */ reject), rest: () => (/* reexport */ rest), restArguments: () => (/* reexport */ restArguments), result: () => (/* reexport */ result), sample: () => (/* reexport */ sample), select: () => (/* reexport */ filter), shuffle: () => (/* reexport */ shuffle), size: () => (/* reexport */ size), some: () => (/* reexport */ some), sortBy: () => (/* reexport */ sortBy), sortedIndex: () => (/* reexport */ sortedIndex), tail: () => (/* reexport */ rest), take: () => (/* reexport */ first), tap: () => (/* reexport */ tap), template: () => (/* reexport */ template), templateSettings: () => (/* reexport */ templateSettings), throttle: () => (/* reexport */ throttle), times: () => (/* reexport */ times), toArray: () => (/* reexport */ toArray), toPath: () => (/* reexport */ toPath), transpose: () => (/* reexport */ unzip), unescape: () => (/* reexport */ modules_unescape), union: () => (/* reexport */ union), uniq: () => (/* reexport */ uniq), unique: () => (/* reexport */ uniq), uniqueId: () => (/* reexport */ uniqueId), unzip: () => (/* reexport */ unzip), values: () => (/* reexport */ values), where: () => (/* reexport */ where), without: () => (/* reexport */ without), wrap: () => (/* reexport */ wrap), zip: () => (/* reexport */ zip) }); // NAMESPACE OBJECT: ./node_modules/underscore/modules/index.js var modules_namespaceObject = {}; __nested_webpack_require_822373__.r(modules_namespaceObject); __nested_webpack_require_822373__.d(modules_namespaceObject, { VERSION: () => (VERSION), after: () => (after), all: () => (every), allKeys: () => (allKeys), any: () => (some), assign: () => (extendOwn), before: () => (before), bind: () => (bind), bindAll: () => (bindAll), chain: () => (chain), chunk: () => (chunk), clone: () => (clone), collect: () => (map), compact: () => (compact), compose: () => (compose), constant: () => (constant), contains: () => (contains), countBy: () => (countBy), create: () => (create), debounce: () => (debounce), "default": () => (underscore_array_methods), defaults: () => (defaults), defer: () => (defer), delay: () => (delay), detect: () => (find), difference: () => (difference), drop: () => (rest), each: () => (each), escape: () => (modules_escape), every: () => (every), extend: () => (extend), extendOwn: () => (extendOwn), filter: () => (filter), find: () => (find), findIndex: () => (findIndex), findKey: () => (findKey), findLastIndex: () => (findLastIndex), findWhere: () => (findWhere), first: () => (first), flatten: () => (flatten_flatten), foldl: () => (reduce), foldr: () => (reduceRight), forEach: () => (each), functions: () => (functions), get: () => (get), groupBy: () => (groupBy), has: () => (has_has), head: () => (first), identity: () => (identity), include: () => (contains), includes: () => (contains), indexBy: () => (indexBy), indexOf: () => (indexOf), initial: () => (initial), inject: () => (reduce), intersection: () => (intersection), invert: () => (invert), invoke: () => (invoke), isArguments: () => (modules_isArguments), isArray: () => (isArray), isArrayBuffer: () => (isArrayBuffer), isBoolean: () => (isBoolean), isDataView: () => (modules_isDataView), isDate: () => (isDate), isElement: () => (isElement), isEmpty: () => (isEmpty), isEqual: () => (isEqual), isError: () => (isError), isFinite: () => (isFinite_isFinite), isFunction: () => (modules_isFunction), isMap: () => (isMap), isMatch: () => (isMatch), isNaN: () => (isNaN_isNaN), isNull: () => (isNull), isNumber: () => (isNumber), isObject: () => (isObject), isRegExp: () => (isRegExp), isSet: () => (isSet), isString: () => (isString), isSymbol: () => (isSymbol), isTypedArray: () => (modules_isTypedArray), isUndefined: () => (isUndefined), isWeakMap: () => (isWeakMap), isWeakSet: () => (isWeakSet), iteratee: () => (iteratee), keys: () => (keys), last: () => (last), lastIndexOf: () => (lastIndexOf), map: () => (map), mapObject: () => (mapObject), matcher: () => (matcher), matches: () => (matcher), max: () => (max), memoize: () => (memoize), methods: () => (functions), min: () => (min), mixin: () => (mixin), negate: () => (negate), noop: () => (noop), now: () => (now), object: () => (object), omit: () => (omit), once: () => (once), pairs: () => (pairs), partial: () => (modules_partial), partition: () => (partition), pick: () => (pick), pluck: () => (pluck), property: () => (property), propertyOf: () => (propertyOf), random: () => (random), range: () => (range), reduce: () => (reduce), reduceRight: () => (reduceRight), reject: () => (reject), rest: () => (rest), restArguments: () => (restArguments), result: () => (result), sample: () => (sample), select: () => (filter), shuffle: () => (shuffle), size: () => (size), some: () => (some), sortBy: () => (sortBy), sortedIndex: () => (sortedIndex), tail: () => (rest), take: () => (first), tap: () => (tap), template: () => (template), templateSettings: () => (templateSettings), throttle: () => (throttle), times: () => (times), toArray: () => (toArray), toPath: () => (toPath), transpose: () => (unzip), unescape: () => (modules_unescape), union: () => (union), uniq: () => (uniq), unique: () => (uniq), uniqueId: () => (uniqueId), unzip: () => (unzip), values: () => (values), where: () => (where), without: () => (without), wrap: () => (wrap), zip: () => (zip) }); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/_setup.js // Current version. var VERSION = '1.13.6'; // Establish the root object, `window` (`self`) in the browser, `global` // on the server, or `this` in some virtual machines. We use `self` // instead of `window` for `WebWorker` support. var root = (typeof self == 'object' && self.self === self && self) || (typeof global == 'object' && global.global === global && global) || Function('return this')() || {}; // Save bytes in the minified (but not gzipped) version: var ArrayProto = Array.prototype, ObjProto = Object.prototype; var SymbolProto = typeof Symbol !== 'undefined' ? Symbol.prototype : null; // Create quick reference variables for speed access to core prototypes. var push = ArrayProto.push, slice = ArrayProto.slice, _setup_toString = ObjProto.toString, _setup_hasOwnProperty = ObjProto.hasOwnProperty; // Modern feature detection. var supportsArrayBuffer = typeof ArrayBuffer !== 'undefined', supportsDataView = typeof DataView !== 'undefined'; // All **ECMAScript 5+** native function implementations that we hope to use // are declared here. var nativeIsArray = Array.isArray, nativeKeys = Object.keys, nativeCreate = Object.create, nativeIsView = supportsArrayBuffer && ArrayBuffer.isView; // Create references to these builtin functions because we override them. var _isNaN = isNaN, _isFinite = isFinite; // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed. var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString'); var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString', 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString']; // The largest integer that can be represented exactly. var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1; ;// CONCATENATED MODULE: ./node_modules/underscore/modules/restArguments.js // Some functions take a variable number of arguments, or a few expected // arguments at the beginning and then a variable number of values to operate // on. This helper accumulates all remaining arguments past the function’s // argument length (or an explicit `startIndex`), into an array that becomes // the last argument. Similar to ES6’s "rest parameter". function restArguments(func, startIndex) { startIndex = startIndex == null ? func.length - 1 : +startIndex; return function() { var length = Math.max(arguments.length - startIndex, 0), rest = Array(length), index = 0; for (; index < length; index++) { rest[index] = arguments[index + startIndex]; } switch (startIndex) { case 0: return func.call(this, rest); case 1: return func.call(this, arguments[0], rest); case 2: return func.call(this, arguments[0], arguments[1], rest); } var args = Array(startIndex + 1); for (index = 0; index < startIndex; index++) { args[index] = arguments[index]; } args[startIndex] = rest; return func.apply(this, args); }; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/isObject.js // Is a given variable an object? function isObject(obj) { var type = typeof obj; return type === 'function' || (type === 'object' && !!obj); } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/isNull.js // Is a given value equal to null? function isNull(obj) { return obj === null; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/isUndefined.js // Is a given variable undefined? function isUndefined(obj) { return obj === void 0; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/isBoolean.js // Is a given value a boolean? function isBoolean(obj) { return obj === true || obj === false || _setup_toString.call(obj) === '[object Boolean]'; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/isElement.js // Is a given value a DOM element? function isElement(obj) { return !!(obj && obj.nodeType === 1); } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/_tagTester.js // Internal function for creating a `toString`-based type tester. function tagTester(name) { var tag = '[object ' + name + ']'; return function(obj) { return _setup_toString.call(obj) === tag; }; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/isString.js /* harmony default export */ const isString = (tagTester('String')); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/isNumber.js /* harmony default export */ const isNumber = (tagTester('Number')); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/isDate.js /* harmony default export */ const isDate = (tagTester('Date')); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/isRegExp.js /* harmony default export */ const isRegExp = (tagTester('RegExp')); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/isError.js /* harmony default export */ const isError = (tagTester('Error')); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/isSymbol.js /* harmony default export */ const isSymbol = (tagTester('Symbol')); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/isArrayBuffer.js /* harmony default export */ const isArrayBuffer = (tagTester('ArrayBuffer')); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/isFunction.js var isFunction = tagTester('Function'); // Optimize `isFunction` if appropriate. Work around some `typeof` bugs in old // v8, IE 11 (#1621), Safari 8 (#1929), and PhantomJS (#2236). var nodelist = root.document && root.document.childNodes; if ( true && typeof Int8Array != 'object' && typeof nodelist != 'function') { isFunction = function(obj) { return typeof obj == 'function' || false; }; } /* harmony default export */ const modules_isFunction = (isFunction); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/_hasObjectTag.js /* harmony default export */ const _hasObjectTag = (tagTester('Object')); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/_stringTagBug.js // In IE 10 - Edge 13, `DataView` has string tag `'[object Object]'`. // In IE 11, the most common among them, this problem also applies to // `Map`, `WeakMap` and `Set`. var hasStringTagBug = ( supportsDataView && _hasObjectTag(new DataView(new ArrayBuffer(8))) ), isIE11 = (typeof Map !== 'undefined' && _hasObjectTag(new Map)); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/isDataView.js var isDataView = tagTester('DataView'); // In IE 10 - Edge 13, we need a different heuristic // to determine whether an object is a `DataView`. function ie10IsDataView(obj) { return obj != null && modules_isFunction(obj.getInt8) && isArrayBuffer(obj.buffer); } /* harmony default export */ const modules_isDataView = (hasStringTagBug ? ie10IsDataView : isDataView); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/isArray.js // Is a given value an array? // Delegates to ECMA5's native `Array.isArray`. /* harmony default export */ const isArray = (nativeIsArray || tagTester('Array')); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/_has.js // Internal function to check whether `key` is an own property name of `obj`. function has(obj, key) { return obj != null && _setup_hasOwnProperty.call(obj, key); } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/isArguments.js var isArguments = tagTester('Arguments'); // Define a fallback version of the method in browsers (ahem, IE < 9), where // there isn't any inspectable "Arguments" type. (function() { if (!isArguments(arguments)) { isArguments = function(obj) { return has(obj, 'callee'); }; } }()); /* harmony default export */ const modules_isArguments = (isArguments); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/isFinite.js // Is a given object a finite number? function isFinite_isFinite(obj) { return !isSymbol(obj) && _isFinite(obj) && !isNaN(parseFloat(obj)); } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/isNaN.js // Is the given value `NaN`? function isNaN_isNaN(obj) { return isNumber(obj) && _isNaN(obj); } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/constant.js // Predicate-generating function. Often useful outside of Underscore. function constant(value) { return function() { return value; }; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/_createSizePropertyCheck.js // Common internal logic for `isArrayLike` and `isBufferLike`. function createSizePropertyCheck(getSizeProperty) { return function(collection) { var sizeProperty = getSizeProperty(collection); return typeof sizeProperty == 'number' && sizeProperty >= 0 && sizeProperty <= MAX_ARRAY_INDEX; } } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/_shallowProperty.js // Internal helper to generate a function to obtain property `key` from `obj`. function shallowProperty(key) { return function(obj) { return obj == null ? void 0 : obj[key]; }; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/_getByteLength.js // Internal helper to obtain the `byteLength` property of an object. /* harmony default export */ const _getByteLength = (shallowProperty('byteLength')); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/_isBufferLike.js // Internal helper to determine whether we should spend extensive checks against // `ArrayBuffer` et al. /* harmony default export */ const _isBufferLike = (createSizePropertyCheck(_getByteLength)); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/isTypedArray.js // Is a given value a typed array? var typedArrayPattern = /\[object ((I|Ui)nt(8|16|32)|Float(32|64)|Uint8Clamped|Big(I|Ui)nt64)Array\]/; function isTypedArray(obj) { // `ArrayBuffer.isView` is the most future-proof, so use it when available. // Otherwise, fall back on the above regular expression. return nativeIsView ? (nativeIsView(obj) && !modules_isDataView(obj)) : _isBufferLike(obj) && typedArrayPattern.test(_setup_toString.call(obj)); } /* harmony default export */ const modules_isTypedArray = (supportsArrayBuffer ? isTypedArray : constant(false)); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/_getLength.js // Internal helper to obtain the `length` property of an object. /* harmony default export */ const _getLength = (shallowProperty('length')); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/_collectNonEnumProps.js // Internal helper to create a simple lookup structure. // `collectNonEnumProps` used to depend on `_.contains`, but this led to // circular imports. `emulatedSet` is a one-off solution that only works for // arrays of strings. function emulatedSet(keys) { var hash = {}; for (var l = keys.length, i = 0; i < l; ++i) hash[keys[i]] = true; return { contains: function(key) { return hash[key] === true; }, push: function(key) { hash[key] = true; return keys.push(key); } }; } // Internal helper. Checks `keys` for the presence of keys in IE < 9 that won't // be iterated by `for key in ...` and thus missed. Extends `keys` in place if // needed. function collectNonEnumProps(obj, keys) { keys = emulatedSet(keys); var nonEnumIdx = nonEnumerableProps.length; var constructor = obj.constructor; var proto = (modules_isFunction(constructor) && constructor.prototype) || ObjProto; // Constructor is a special case. var prop = 'constructor'; if (has(obj, prop) && !keys.contains(prop)) keys.push(prop); while (nonEnumIdx--) { prop = nonEnumerableProps[nonEnumIdx]; if (prop in obj && obj[prop] !== proto[prop] && !keys.contains(prop)) { keys.push(prop); } } } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/keys.js // Retrieve the names of an object's own properties. // Delegates to **ECMAScript 5**'s native `Object.keys`. function keys(obj) { if (!isObject(obj)) return []; if (nativeKeys) return nativeKeys(obj); var keys = []; for (var key in obj) if (has(obj, key)) keys.push(key); // Ahem, IE < 9. if (hasEnumBug) collectNonEnumProps(obj, keys); return keys; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/isEmpty.js // Is a given array, string, or object empty? // An "empty" object has no enumerable own-properties. function isEmpty(obj) { if (obj == null) return true; // Skip the more expensive `toString`-based type checks if `obj` has no // `.length`. var length = _getLength(obj); if (typeof length == 'number' && ( isArray(obj) || isString(obj) || modules_isArguments(obj) )) return length === 0; return _getLength(keys(obj)) === 0; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/isMatch.js // Returns whether an object has a given set of `key:value` pairs. function isMatch(object, attrs) { var _keys = keys(attrs), length = _keys.length; if (object == null) return !length; var obj = Object(object); for (var i = 0; i < length; i++) { var key = _keys[i]; if (attrs[key] !== obj[key] || !(key in obj)) return false; } return true; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/underscore.js // If Underscore is called as a function, it returns a wrapped object that can // be used OO-style. This wrapper holds altered versions of all functions added // through `_.mixin`. Wrapped objects may be chained. function _(obj) { if (obj instanceof _) return obj; if (!(this instanceof _)) return new _(obj); this._wrapped = obj; } _.VERSION = VERSION; // Extracts the result from a wrapped and chained object. _.prototype.value = function() { return this._wrapped; }; // Provide unwrapping proxies for some methods used in engine operations // such as arithmetic and JSON stringification. _.prototype.valueOf = _.prototype.toJSON = _.prototype.value; _.prototype.toString = function() { return String(this._wrapped); }; ;// CONCATENATED MODULE: ./node_modules/underscore/modules/_toBufferView.js // Internal function to wrap or shallow-copy an ArrayBuffer, // typed array or DataView to a new view, reusing the buffer. function toBufferView(bufferSource) { return new Uint8Array( bufferSource.buffer || bufferSource, bufferSource.byteOffset || 0, _getByteLength(bufferSource) ); } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/isEqual.js // We use this string twice, so give it a name for minification. var tagDataView = '[object DataView]'; // Internal recursive comparison function for `_.isEqual`. function eq(a, b, aStack, bStack) { // Identical objects are equal. `0 === -0`, but they aren't identical. // See the [Harmony `egal` proposal](https://wiki.ecmascript.org/doku.php?id=harmony:egal). if (a === b) return a !== 0 || 1 / a === 1 / b; // `null` or `undefined` only equal to itself (strict comparison). if (a == null || b == null) return false; // `NaN`s are equivalent, but non-reflexive. if (a !== a) return b !== b; // Exhaust primitive checks var type = typeof a; if (type !== 'function' && type !== 'object' && typeof b != 'object') return false; return deepEq(a, b, aStack, bStack); } // Internal recursive comparison function for `_.isEqual`. function deepEq(a, b, aStack, bStack) { // Unwrap any wrapped objects. if (a instanceof _) a = a._wrapped; if (b instanceof _) b = b._wrapped; // Compare `[[Class]]` names. var className = _setup_toString.call(a); if (className !== _setup_toString.call(b)) return false; // Work around a bug in IE 10 - Edge 13. if (hasStringTagBug && className == '[object Object]' && modules_isDataView(a)) { if (!modules_isDataView(b)) return false; className = tagDataView; } switch (className) { // These types are compared by value. case '[object RegExp]': // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i') case '[object String]': // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is // equivalent to `new String("5")`. return '' + a === '' + b; case '[object Number]': // `NaN`s are equivalent, but non-reflexive. // Object(NaN) is equivalent to NaN. if (+a !== +a) return +b !== +b; // An `egal` comparison is performed for other numeric values. return +a === 0 ? 1 / +a === 1 / b : +a === +b; case '[object Date]': case '[object Boolean]': // Coerce dates and booleans to numeric primitive values. Dates are compared by their // millisecond representations. Note that invalid dates with millisecond representations // of `NaN` are not equivalent. return +a === +b; case '[object Symbol]': return SymbolProto.valueOf.call(a) === SymbolProto.valueOf.call(b); case '[object ArrayBuffer]': case tagDataView: // Coerce to typed array so we can fall through. return deepEq(toBufferView(a), toBufferView(b), aStack, bStack); } var areArrays = className === '[object Array]'; if (!areArrays && modules_isTypedArray(a)) { var byteLength = _getByteLength(a); if (byteLength !== _getByteLength(b)) return false; if (a.buffer === b.buffer && a.byteOffset === b.byteOffset) return true; areArrays = true; } if (!areArrays) { if (typeof a != 'object' || typeof b != 'object') return false; // Objects with different constructors are not equivalent, but `Object`s or `Array`s // from different frames are. var aCtor = a.constructor, bCtor = b.constructor; if (aCtor !== bCtor && !(modules_isFunction(aCtor) && aCtor instanceof aCtor && modules_isFunction(bCtor) && bCtor instanceof bCtor) && ('constructor' in a && 'constructor' in b)) { return false; } } // Assume equality for cyclic structures. The algorithm for detecting cyclic // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. // Initializing stack of traversed objects. // It's done here since we only need them for objects and arrays comparison. aStack = aStack || []; bStack = bStack || []; var length = aStack.length; while (length--) { // Linear search. Performance is inversely proportional to the number of // unique nested structures. if (aStack[length] === a) return bStack[length] === b; } // Add the first object to the stack of traversed objects. aStack.push(a); bStack.push(b); // Recursively compare objects and arrays. if (areArrays) { // Compare array lengths to determine if a deep comparison is necessary. length = a.length; if (length !== b.length) return false; // Deep compare the contents, ignoring non-numeric properties. while (length--) { if (!eq(a[length], b[length], aStack, bStack)) return false; } } else { // Deep compare objects. var _keys = keys(a), key; length = _keys.length; // Ensure that both objects contain the same number of properties before comparing deep equality. if (keys(b).length !== length) return false; while (length--) { // Deep compare each member key = _keys[length]; if (!(has(b, key) && eq(a[key], b[key], aStack, bStack))) return false; } } // Remove the first object from the stack of traversed objects. aStack.pop(); bStack.pop(); return true; } // Perform a deep comparison to check if two objects are equal. function isEqual(a, b) { return eq(a, b); } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/allKeys.js // Retrieve all the enumerable property names of an object. function allKeys(obj) { if (!isObject(obj)) return []; var keys = []; for (var key in obj) keys.push(key); // Ahem, IE < 9. if (hasEnumBug) collectNonEnumProps(obj, keys); return keys; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/_methodFingerprint.js // Since the regular `Object.prototype.toString` type tests don't work for // some types in IE 11, we use a fingerprinting heuristic instead, based // on the methods. It's not great, but it's the best we got. // The fingerprint method lists are defined below. function ie11fingerprint(methods) { var length = _getLength(methods); return function(obj) { if (obj == null) return false; // `Map`, `WeakMap` and `Set` have no enumerable keys. var keys = allKeys(obj); if (_getLength(keys)) return false; for (var i = 0; i < length; i++) { if (!modules_isFunction(obj[methods[i]])) return false; } // If we are testing against `WeakMap`, we need to ensure that // `obj` doesn't have a `forEach` method in order to distinguish // it from a regular `Map`. return methods !== weakMapMethods || !modules_isFunction(obj[forEachName]); }; } // In the interest of compact minification, we write // each string in the fingerprints only once. var forEachName = 'forEach', hasName = 'has', commonInit = ['clear', 'delete'], mapTail = ['get', hasName, 'set']; // `Map`, `WeakMap` and `Set` each have slightly different // combinations of the above sublists. var mapMethods = commonInit.concat(forEachName, mapTail), weakMapMethods = commonInit.concat(mapTail), setMethods = ['add'].concat(commonInit, forEachName, hasName); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/isMap.js /* harmony default export */ const isMap = (isIE11 ? ie11fingerprint(mapMethods) : tagTester('Map')); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/isWeakMap.js /* harmony default export */ const isWeakMap = (isIE11 ? ie11fingerprint(weakMapMethods) : tagTester('WeakMap')); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/isSet.js /* harmony default export */ const isSet = (isIE11 ? ie11fingerprint(setMethods) : tagTester('Set')); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/isWeakSet.js /* harmony default export */ const isWeakSet = (tagTester('WeakSet')); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/values.js // Retrieve the values of an object's properties. function values(obj) { var _keys = keys(obj); var length = _keys.length; var values = Array(length); for (var i = 0; i < length; i++) { values[i] = obj[_keys[i]]; } return values; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/pairs.js // Convert an object into a list of `[key, value]` pairs. // The opposite of `_.object` with one argument. function pairs(obj) { var _keys = keys(obj); var length = _keys.length; var pairs = Array(length); for (var i = 0; i < length; i++) { pairs[i] = [_keys[i], obj[_keys[i]]]; } return pairs; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/invert.js // Invert the keys and values of an object. The values must be serializable. function invert(obj) { var result = {}; var _keys = keys(obj); for (var i = 0, length = _keys.length; i < length; i++) { result[obj[_keys[i]]] = _keys[i]; } return result; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/functions.js // Return a sorted list of the function names available on the object. function functions(obj) { var names = []; for (var key in obj) { if (modules_isFunction(obj[key])) names.push(key); } return names.sort(); } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/_createAssigner.js // An internal function for creating assigner functions. function createAssigner(keysFunc, defaults) { return function(obj) { var length = arguments.length; if (defaults) obj = Object(obj); if (length < 2 || obj == null) return obj; for (var index = 1; index < length; index++) { var source = arguments[index], keys = keysFunc(source), l = keys.length; for (var i = 0; i < l; i++) { var key = keys[i]; if (!defaults || obj[key] === void 0) obj[key] = source[key]; } } return obj; }; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/extend.js // Extend a given object with all the properties in passed-in object(s). /* harmony default export */ const extend = (createAssigner(allKeys)); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/extendOwn.js // Assigns a given object with all the own properties in the passed-in // object(s). // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) /* harmony default export */ const extendOwn = (createAssigner(keys)); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/defaults.js // Fill in a given object with default properties. /* harmony default export */ const defaults = (createAssigner(allKeys, true)); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/_baseCreate.js // Create a naked function reference for surrogate-prototype-swapping. function ctor() { return function(){}; } // An internal function for creating a new object that inherits from another. function baseCreate(prototype) { if (!isObject(prototype)) return {}; if (nativeCreate) return nativeCreate(prototype); var Ctor = ctor(); Ctor.prototype = prototype; var result = new Ctor; Ctor.prototype = null; return result; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/create.js // Creates an object that inherits from the given prototype object. // If additional properties are provided then they will be added to the // created object. function create(prototype, props) { var result = baseCreate(prototype); if (props) extendOwn(result, props); return result; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/clone.js // Create a (shallow-cloned) duplicate of an object. function clone(obj) { if (!isObject(obj)) return obj; return isArray(obj) ? obj.slice() : extend({}, obj); } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/tap.js // Invokes `interceptor` with the `obj` and then returns `obj`. // The primary purpose of this method is to "tap into" a method chain, in // order to perform operations on intermediate results within the chain. function tap(obj, interceptor) { interceptor(obj); return obj; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/toPath.js // Normalize a (deep) property `path` to array. // Like `_.iteratee`, this function can be customized. function toPath(path) { return isArray(path) ? path : [path]; } _.toPath = toPath; ;// CONCATENATED MODULE: ./node_modules/underscore/modules/_toPath.js // Internal wrapper for `_.toPath` to enable minification. // Similar to `cb` for `_.iteratee`. function _toPath_toPath(path) { return _.toPath(path); } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/_deepGet.js // Internal function to obtain a nested property in `obj` along `path`. function deepGet(obj, path) { var length = path.length; for (var i = 0; i < length; i++) { if (obj == null) return void 0; obj = obj[path[i]]; } return length ? obj : void 0; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/get.js // Get the value of the (deep) property on `path` from `object`. // If any property in `path` does not exist or if the value is // `undefined`, return `defaultValue` instead. // The `path` is normalized through `_.toPath`. function get(object, path, defaultValue) { var value = deepGet(object, _toPath_toPath(path)); return isUndefined(value) ? defaultValue : value; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/has.js // Shortcut function for checking if an object has a given property directly on // itself (in other words, not on a prototype). Unlike the internal `has` // function, this public version can also traverse nested properties. function has_has(obj, path) { path = _toPath_toPath(path); var length = path.length; for (var i = 0; i < length; i++) { var key = path[i]; if (!has(obj, key)) return false; obj = obj[key]; } return !!length; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/identity.js // Keep the identity function around for default iteratees. function identity(value) { return value; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/matcher.js // Returns a predicate for checking whether an object has a given set of // `key:value` pairs. function matcher(attrs) { attrs = extendOwn({}, attrs); return function(obj) { return isMatch(obj, attrs); }; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/property.js // Creates a function that, when passed an object, will traverse that object’s // properties down the given `path`, specified as an array of keys or indices. function property(path) { path = _toPath_toPath(path); return function(obj) { return deepGet(obj, path); }; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/_optimizeCb.js // Internal function that returns an efficient (for current engines) version // of the passed-in callback, to be repeatedly applied in other Underscore // functions. function optimizeCb(func, context, argCount) { if (context === void 0) return func; switch (argCount == null ? 3 : argCount) { case 1: return function(value) { return func.call(context, value); }; // The 2-argument case is omitted because we’re not using it. case 3: return function(value, index, collection) { return func.call(context, value, index, collection); }; case 4: return function(accumulator, value, index, collection) { return func.call(context, accumulator, value, index, collection); }; } return function() { return func.apply(context, arguments); }; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/_baseIteratee.js // An internal function to generate callbacks that can be applied to each // element in a collection, returning the desired result — either `_.identity`, // an arbitrary callback, a property matcher, or a property accessor. function baseIteratee(value, context, argCount) { if (value == null) return identity; if (modules_isFunction(value)) return optimizeCb(value, context, argCount); if (isObject(value) && !isArray(value)) return matcher(value); return property(value); } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/iteratee.js // External wrapper for our callback generator. Users may customize // `_.iteratee` if they want additional predicate/iteratee shorthand styles. // This abstraction hides the internal-only `argCount` argument. function iteratee(value, context) { return baseIteratee(value, context, Infinity); } _.iteratee = iteratee; ;// CONCATENATED MODULE: ./node_modules/underscore/modules/_cb.js // The function we call internally to generate a callback. It invokes // `_.iteratee` if overridden, otherwise `baseIteratee`. function cb(value, context, argCount) { if (_.iteratee !== iteratee) return _.iteratee(value, context); return baseIteratee(value, context, argCount); } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/mapObject.js // Returns the results of applying the `iteratee` to each element of `obj`. // In contrast to `_.map` it returns an object. function mapObject(obj, iteratee, context) { iteratee = cb(iteratee, context); var _keys = keys(obj), length = _keys.length, results = {}; for (var index = 0; index < length; index++) { var currentKey = _keys[index]; results[currentKey] = iteratee(obj[currentKey], currentKey, obj); } return results; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/noop.js // Predicate-generating function. Often useful outside of Underscore. function noop(){} ;// CONCATENATED MODULE: ./node_modules/underscore/modules/propertyOf.js // Generates a function for a given object that returns a given property. function propertyOf(obj) { if (obj == null) return noop; return function(path) { return get(obj, path); }; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/times.js // Run a function **n** times. function times(n, iteratee, context) { var accum = Array(Math.max(0, n)); iteratee = optimizeCb(iteratee, context, 1); for (var i = 0; i < n; i++) accum[i] = iteratee(i); return accum; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/random.js // Return a random integer between `min` and `max` (inclusive). function random(min, max) { if (max == null) { max = min; min = 0; } return min + Math.floor(Math.random() * (max - min + 1)); } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/now.js // A (possibly faster) way to get the current timestamp as an integer. /* harmony default export */ const now = (Date.now || function() { return new Date().getTime(); }); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/_createEscaper.js // Internal helper to generate functions for escaping and unescaping strings // to/from HTML interpolation. function createEscaper(map) { var escaper = function(match) { return map[match]; }; // Regexes for identifying a key that needs to be escaped. var source = '(?:' + keys(map).join('|') + ')'; var testRegexp = RegExp(source); var replaceRegexp = RegExp(source, 'g'); return function(string) { string = string == null ? '' : '' + string; return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string; }; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/_escapeMap.js // Internal list of HTML entities for escaping. /* harmony default export */ const _escapeMap = ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''', '`': '`' }); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/escape.js // Function for escaping strings to HTML interpolation. /* harmony default export */ const modules_escape = (createEscaper(_escapeMap)); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/_unescapeMap.js // Internal list of HTML entities for unescaping. /* harmony default export */ const _unescapeMap = (invert(_escapeMap)); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/unescape.js // Function for unescaping strings from HTML interpolation. /* harmony default export */ const modules_unescape = (createEscaper(_unescapeMap)); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/templateSettings.js // By default, Underscore uses ERB-style template delimiters. Change the // following template settings to use alternative delimiters. /* harmony default export */ const templateSettings = (_.templateSettings = { evaluate: /<%([\s\S]+?)%>/g, interpolate: /<%=([\s\S]+?)%>/g, escape: /<%-([\s\S]+?)%>/g }); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/template.js // When customizing `_.templateSettings`, if you don't want to define an // interpolation, evaluation or escaping regex, we need one that is // guaranteed not to match. var noMatch = /(.)^/; // Certain characters need to be escaped so that they can be put into a // string literal. var escapes = { "'": "'", '\\': '\\', '\r': 'r', '\n': 'n', '\u2028': 'u2028', '\u2029': 'u2029' }; var escapeRegExp = /\\|'|\r|\n|\u2028|\u2029/g; function escapeChar(match) { return '\\' + escapes[match]; } // In order to prevent third-party code injection through // `_.templateSettings.variable`, we test it against the following regular // expression. It is intentionally a bit more liberal than just matching valid // identifiers, but still prevents possible loopholes through defaults or // destructuring assignment. var bareIdentifier = /^\s*(\w|\$)+\s*$/; // JavaScript micro-templating, similar to John Resig's implementation. // Underscore templating handles arbitrary delimiters, preserves whitespace, // and correctly escapes quotes within interpolated code. // NB: `oldSettings` only exists for backwards compatibility. function template(text, settings, oldSettings) { if (!settings && oldSettings) settings = oldSettings; settings = defaults({}, settings, _.templateSettings); // Combine delimiters into one regular expression via alternation. var matcher = RegExp([ (settings.escape || noMatch).source, (settings.interpolate || noMatch).source, (settings.evaluate || noMatch).source ].join('|') + '|$', 'g'); // Compile the template source, escaping string literals appropriately. var index = 0; var source = "__p+='"; text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { source += text.slice(index, offset).replace(escapeRegExp, escapeChar); index = offset + match.length; if (escape) { source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; } else if (interpolate) { source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; } else if (evaluate) { source += "';\n" + evaluate + "\n__p+='"; } // Adobe VMs need the match returned to produce the correct offset. return match; }); source += "';\n"; var argument = settings.variable; if (argument) { // Insure against third-party code injection. (CVE-2021-23358) if (!bareIdentifier.test(argument)) throw new Error( 'variable is not a bare identifier: ' + argument ); } else { // If a variable is not specified, place data values in local scope. source = 'with(obj||{}){\n' + source + '}\n'; argument = 'obj'; } source = "var __t,__p='',__j=Array.prototype.join," + "print=function(){__p+=__j.call(arguments,'');};\n" + source + 'return __p;\n'; var render; try { render = new Function(argument, '_', source); } catch (e) { e.source = source; throw e; } var template = function(data) { return render.call(this, data, _); }; // Provide the compiled source as a convenience for precompilation. template.source = 'function(' + argument + '){\n' + source + '}'; return template; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/result.js // Traverses the children of `obj` along `path`. If a child is a function, it // is invoked with its parent as context. Returns the value of the final // child, or `fallback` if any child is undefined. function result(obj, path, fallback) { path = _toPath_toPath(path); var length = path.length; if (!length) { return modules_isFunction(fallback) ? fallback.call(obj) : fallback; } for (var i = 0; i < length; i++) { var prop = obj == null ? void 0 : obj[path[i]]; if (prop === void 0) { prop = fallback; i = length; // Ensure we don't continue iterating. } obj = modules_isFunction(prop) ? prop.call(obj) : prop; } return obj; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/uniqueId.js // Generate a unique integer id (unique within the entire client session). // Useful for temporary DOM ids. var idCounter = 0; function uniqueId(prefix) { var id = ++idCounter + ''; return prefix ? prefix + id : id; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/chain.js // Start chaining a wrapped Underscore object. function chain(obj) { var instance = _(obj); instance._chain = true; return instance; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/_executeBound.js // Internal function to execute `sourceFunc` bound to `context` with optional // `args`. Determines whether to execute a function as a constructor or as a // normal function. function executeBound(sourceFunc, boundFunc, context, callingContext, args) { if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args); var self = baseCreate(sourceFunc.prototype); var result = sourceFunc.apply(self, args); if (isObject(result)) return result; return self; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/partial.js // Partially apply a function by creating a version that has had some of its // arguments pre-filled, without changing its dynamic `this` context. `_` acts // as a placeholder by default, allowing any combination of arguments to be // pre-filled. Set `_.partial.placeholder` for a custom placeholder argument. var partial = restArguments(function(func, boundArgs) { var placeholder = partial.placeholder; var bound = function() { var position = 0, length = boundArgs.length; var args = Array(length); for (var i = 0; i < length; i++) { args[i] = boundArgs[i] === placeholder ? arguments[position++] : boundArgs[i]; } while (position < arguments.length) args.push(arguments[position++]); return executeBound(func, bound, this, this, args); }; return bound; }); partial.placeholder = _; /* harmony default export */ const modules_partial = (partial); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/bind.js // Create a function bound to a given object (assigning `this`, and arguments, // optionally). /* harmony default export */ const bind = (restArguments(function(func, context, args) { if (!modules_isFunction(func)) throw new TypeError('Bind must be called on a function'); var bound = restArguments(function(callArgs) { return executeBound(func, bound, context, this, args.concat(callArgs)); }); return bound; })); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/_isArrayLike.js // Internal helper for collection methods to determine whether a collection // should be iterated as an array or as an object. // Related: https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094 /* harmony default export */ const _isArrayLike = (createSizePropertyCheck(_getLength)); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/_flatten.js // Internal implementation of a recursive `flatten` function. function flatten(input, depth, strict, output) { output = output || []; if (!depth && depth !== 0) { depth = Infinity; } else if (depth <= 0) { return output.concat(input); } var idx = output.length; for (var i = 0, length = _getLength(input); i < length; i++) { var value = input[i]; if (_isArrayLike(value) && (isArray(value) || modules_isArguments(value))) { // Flatten current level of array or arguments object. if (depth > 1) { flatten(value, depth - 1, strict, output); idx = output.length; } else { var j = 0, len = value.length; while (j < len) output[idx++] = value[j++]; } } else if (!strict) { output[idx++] = value; } } return output; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/bindAll.js // Bind a number of an object's methods to that object. Remaining arguments // are the method names to be bound. Useful for ensuring that all callbacks // defined on an object belong to it. /* harmony default export */ const bindAll = (restArguments(function(obj, keys) { keys = flatten(keys, false, false); var index = keys.length; if (index < 1) throw new Error('bindAll must be passed function names'); while (index--) { var key = keys[index]; obj[key] = bind(obj[key], obj); } return obj; })); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/memoize.js // Memoize an expensive function by storing its results. function memoize(func, hasher) { var memoize = function(key) { var cache = memoize.cache; var address = '' + (hasher ? hasher.apply(this, arguments) : key); if (!has(cache, address)) cache[address] = func.apply(this, arguments); return cache[address]; }; memoize.cache = {}; return memoize; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/delay.js // Delays a function for the given number of milliseconds, and then calls // it with the arguments supplied. /* harmony default export */ const delay = (restArguments(function(func, wait, args) { return setTimeout(function() { return func.apply(null, args); }, wait); })); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/defer.js // Defers a function, scheduling it to run after the current call stack has // cleared. /* harmony default export */ const defer = (modules_partial(delay, _, 1)); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/throttle.js // Returns a function, that, when invoked, will only be triggered at most once // during a given window of time. Normally, the throttled function will run // as much as it can, without ever going more than once per `wait` duration; // but if you'd like to disable the execution on the leading edge, pass // `{leading: false}`. To disable execution on the trailing edge, ditto. function throttle(func, wait, options) { var timeout, context, args, result; var previous = 0; if (!options) options = {}; var later = function() { previous = options.leading === false ? 0 : now(); timeout = null; result = func.apply(context, args); if (!timeout) context = args = null; }; var throttled = function() { var _now = now(); if (!previous && options.leading === false) previous = _now; var remaining = wait - (_now - previous); context = this; args = arguments; if (remaining <= 0 || remaining > wait) { if (timeout) { clearTimeout(timeout); timeout = null; } previous = _now; result = func.apply(context, args); if (!timeout) context = args = null; } else if (!timeout && options.trailing !== false) { timeout = setTimeout(later, remaining); } return result; }; throttled.cancel = function() { clearTimeout(timeout); previous = 0; timeout = context = args = null; }; return throttled; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/debounce.js // When a sequence of calls of the returned function ends, the argument // function is triggered. The end of a sequence is defined by the `wait` // parameter. If `immediate` is passed, the argument function will be // triggered at the beginning of the sequence instead of at the end. function debounce(func, wait, immediate) { var timeout, previous, args, result, context; var later = function() { var passed = now() - previous; if (wait > passed) { timeout = setTimeout(later, wait - passed); } else { timeout = null; if (!immediate) result = func.apply(context, args); // This check is needed because `func` can recursively invoke `debounced`. if (!timeout) args = context = null; } }; var debounced = restArguments(function(_args) { context = this; args = _args; previous = now(); if (!timeout) { timeout = setTimeout(later, wait); if (immediate) result = func.apply(context, args); } return result; }); debounced.cancel = function() { clearTimeout(timeout); timeout = args = context = null; }; return debounced; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/wrap.js // Returns the first function passed as an argument to the second, // allowing you to adjust arguments, run code before and after, and // conditionally execute the original function. function wrap(func, wrapper) { return modules_partial(wrapper, func); } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/negate.js // Returns a negated version of the passed-in predicate. function negate(predicate) { return function() { return !predicate.apply(this, arguments); }; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/compose.js // Returns a function that is the composition of a list of functions, each // consuming the return value of the function that follows. function compose() { var args = arguments; var start = args.length - 1; return function() { var i = start; var result = args[start].apply(this, arguments); while (i--) result = args[i].call(this, result); return result; }; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/after.js // Returns a function that will only be executed on and after the Nth call. function after(times, func) { return function() { if (--times < 1) { return func.apply(this, arguments); } }; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/before.js // Returns a function that will only be executed up to (but not including) the // Nth call. function before(times, func) { var memo; return function() { if (--times > 0) { memo = func.apply(this, arguments); } if (times <= 1) func = null; return memo; }; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/once.js // Returns a function that will be executed at most one time, no matter how // often you call it. Useful for lazy initialization. /* harmony default export */ const once = (modules_partial(before, 2)); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/findKey.js // Returns the first key on an object that passes a truth test. function findKey(obj, predicate, context) { predicate = cb(predicate, context); var _keys = keys(obj), key; for (var i = 0, length = _keys.length; i < length; i++) { key = _keys[i]; if (predicate(obj[key], key, obj)) return key; } } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/_createPredicateIndexFinder.js // Internal function to generate `_.findIndex` and `_.findLastIndex`. function createPredicateIndexFinder(dir) { return function(array, predicate, context) { predicate = cb(predicate, context); var length = _getLength(array); var index = dir > 0 ? 0 : length - 1; for (; index >= 0 && index < length; index += dir) { if (predicate(array[index], index, array)) return index; } return -1; }; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/findIndex.js // Returns the first index on an array-like that passes a truth test. /* harmony default export */ const findIndex = (createPredicateIndexFinder(1)); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/findLastIndex.js // Returns the last index on an array-like that passes a truth test. /* harmony default export */ const findLastIndex = (createPredicateIndexFinder(-1)); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/sortedIndex.js // Use a comparator function to figure out the smallest index at which // an object should be inserted so as to maintain order. Uses binary search. function sortedIndex(array, obj, iteratee, context) { iteratee = cb(iteratee, context, 1); var value = iteratee(obj); var low = 0, high = _getLength(array); while (low < high) { var mid = Math.floor((low + high) / 2); if (iteratee(array[mid]) < value) low = mid + 1; else high = mid; } return low; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/_createIndexFinder.js // Internal function to generate the `_.indexOf` and `_.lastIndexOf` functions. function createIndexFinder(dir, predicateFind, sortedIndex) { return function(array, item, idx) { var i = 0, length = _getLength(array); if (typeof idx == 'number') { if (dir > 0) { i = idx >= 0 ? idx : Math.max(idx + length, i); } else { length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1; } } else if (sortedIndex && idx && length) { idx = sortedIndex(array, item); return array[idx] === item ? idx : -1; } if (item !== item) { idx = predicateFind(slice.call(array, i, length), isNaN_isNaN); return idx >= 0 ? idx + i : -1; } for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) { if (array[idx] === item) return idx; } return -1; }; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/indexOf.js // Return the position of the first occurrence of an item in an array, // or -1 if the item is not included in the array. // If the array is large and already in sort order, pass `true` // for **isSorted** to use binary search. /* harmony default export */ const indexOf = (createIndexFinder(1, findIndex, sortedIndex)); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/lastIndexOf.js // Return the position of the last occurrence of an item in an array, // or -1 if the item is not included in the array. /* harmony default export */ const lastIndexOf = (createIndexFinder(-1, findLastIndex)); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/find.js // Return the first value which passes a truth test. function find(obj, predicate, context) { var keyFinder = _isArrayLike(obj) ? findIndex : findKey; var key = keyFinder(obj, predicate, context); if (key !== void 0 && key !== -1) return obj[key]; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/findWhere.js // Convenience version of a common use case of `_.find`: getting the first // object containing specific `key:value` pairs. function findWhere(obj, attrs) { return find(obj, matcher(attrs)); } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/each.js // The cornerstone for collection functions, an `each` // implementation, aka `forEach`. // Handles raw objects in addition to array-likes. Treats all // sparse array-likes as if they were dense. function each(obj, iteratee, context) { iteratee = optimizeCb(iteratee, context); var i, length; if (_isArrayLike(obj)) { for (i = 0, length = obj.length; i < length; i++) { iteratee(obj[i], i, obj); } } else { var _keys = keys(obj); for (i = 0, length = _keys.length; i < length; i++) { iteratee(obj[_keys[i]], _keys[i], obj); } } return obj; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/map.js // Return the results of applying the iteratee to each element. function map(obj, iteratee, context) { iteratee = cb(iteratee, context); var _keys = !_isArrayLike(obj) && keys(obj), length = (_keys || obj).length, results = Array(length); for (var index = 0; index < length; index++) { var currentKey = _keys ? _keys[index] : index; results[index] = iteratee(obj[currentKey], currentKey, obj); } return results; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/_createReduce.js // Internal helper to create a reducing function, iterating left or right. function createReduce(dir) { // Wrap code that reassigns argument variables in a separate function than // the one that accesses `arguments.length` to avoid a perf hit. (#1991) var reducer = function(obj, iteratee, memo, initial) { var _keys = !_isArrayLike(obj) && keys(obj), length = (_keys || obj).length, index = dir > 0 ? 0 : length - 1; if (!initial) { memo = obj[_keys ? _keys[index] : index]; index += dir; } for (; index >= 0 && index < length; index += dir) { var currentKey = _keys ? _keys[index] : index; memo = iteratee(memo, obj[currentKey], currentKey, obj); } return memo; }; return function(obj, iteratee, memo, context) { var initial = arguments.length >= 3; return reducer(obj, optimizeCb(iteratee, context, 4), memo, initial); }; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/reduce.js // **Reduce** builds up a single result from a list of values, aka `inject`, // or `foldl`. /* harmony default export */ const reduce = (createReduce(1)); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/reduceRight.js // The right-associative version of reduce, also known as `foldr`. /* harmony default export */ const reduceRight = (createReduce(-1)); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/filter.js // Return all the elements that pass a truth test. function filter(obj, predicate, context) { var results = []; predicate = cb(predicate, context); each(obj, function(value, index, list) { if (predicate(value, index, list)) results.push(value); }); return results; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/reject.js // Return all the elements for which a truth test fails. function reject(obj, predicate, context) { return filter(obj, negate(cb(predicate)), context); } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/every.js // Determine whether all of the elements pass a truth test. function every(obj, predicate, context) { predicate = cb(predicate, context); var _keys = !_isArrayLike(obj) && keys(obj), length = (_keys || obj).length; for (var index = 0; index < length; index++) { var currentKey = _keys ? _keys[index] : index; if (!predicate(obj[currentKey], currentKey, obj)) return false; } return true; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/some.js // Determine if at least one element in the object passes a truth test. function some(obj, predicate, context) { predicate = cb(predicate, context); var _keys = !_isArrayLike(obj) && keys(obj), length = (_keys || obj).length; for (var index = 0; index < length; index++) { var currentKey = _keys ? _keys[index] : index; if (predicate(obj[currentKey], currentKey, obj)) return true; } return false; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/contains.js // Determine if the array or object contains a given item (using `===`). function contains(obj, item, fromIndex, guard) { if (!_isArrayLike(obj)) obj = values(obj); if (typeof fromIndex != 'number' || guard) fromIndex = 0; return indexOf(obj, item, fromIndex) >= 0; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/invoke.js // Invoke a method (with arguments) on every item in a collection. /* harmony default export */ const invoke = (restArguments(function(obj, path, args) { var contextPath, func; if (modules_isFunction(path)) { func = path; } else { path = _toPath_toPath(path); contextPath = path.slice(0, -1); path = path[path.length - 1]; } return map(obj, function(context) { var method = func; if (!method) { if (contextPath && contextPath.length) { context = deepGet(context, contextPath); } if (context == null) return void 0; method = context[path]; } return method == null ? method : method.apply(context, args); }); })); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/pluck.js // Convenience version of a common use case of `_.map`: fetching a property. function pluck(obj, key) { return map(obj, property(key)); } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/where.js // Convenience version of a common use case of `_.filter`: selecting only // objects containing specific `key:value` pairs. function where(obj, attrs) { return filter(obj, matcher(attrs)); } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/max.js // Return the maximum element (or element-based computation). function max(obj, iteratee, context) { var result = -Infinity, lastComputed = -Infinity, value, computed; if (iteratee == null || (typeof iteratee == 'number' && typeof obj[0] != 'object' && obj != null)) { obj = _isArrayLike(obj) ? obj : values(obj); for (var i = 0, length = obj.length; i < length; i++) { value = obj[i]; if (value != null && value > result) { result = value; } } } else { iteratee = cb(iteratee, context); each(obj, function(v, index, list) { computed = iteratee(v, index, list); if (computed > lastComputed || (computed === -Infinity && result === -Infinity)) { result = v; lastComputed = computed; } }); } return result; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/min.js // Return the minimum element (or element-based computation). function min(obj, iteratee, context) { var result = Infinity, lastComputed = Infinity, value, computed; if (iteratee == null || (typeof iteratee == 'number' && typeof obj[0] != 'object' && obj != null)) { obj = _isArrayLike(obj) ? obj : values(obj); for (var i = 0, length = obj.length; i < length; i++) { value = obj[i]; if (value != null && value < result) { result = value; } } } else { iteratee = cb(iteratee, context); each(obj, function(v, index, list) { computed = iteratee(v, index, list); if (computed < lastComputed || (computed === Infinity && result === Infinity)) { result = v; lastComputed = computed; } }); } return result; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/toArray.js // Safely create a real, live array from anything iterable. var reStrSymbol = /[^\ud800-\udfff]|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g; function toArray(obj) { if (!obj) return []; if (isArray(obj)) return slice.call(obj); if (isString(obj)) { // Keep surrogate pair characters together. return obj.match(reStrSymbol); } if (_isArrayLike(obj)) return map(obj, identity); return values(obj); } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/sample.js // Sample **n** random values from a collection using the modern version of the // [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher–Yates_shuffle). // If **n** is not specified, returns a single random element. // The internal `guard` argument allows it to work with `_.map`. function sample(obj, n, guard) { if (n == null || guard) { if (!_isArrayLike(obj)) obj = values(obj); return obj[random(obj.length - 1)]; } var sample = toArray(obj); var length = _getLength(sample); n = Math.max(Math.min(n, length), 0); var last = length - 1; for (var index = 0; index < n; index++) { var rand = random(index, last); var temp = sample[index]; sample[index] = sample[rand]; sample[rand] = temp; } return sample.slice(0, n); } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/shuffle.js // Shuffle a collection. function shuffle(obj) { return sample(obj, Infinity); } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/sortBy.js // Sort the object's values by a criterion produced by an iteratee. function sortBy(obj, iteratee, context) { var index = 0; iteratee = cb(iteratee, context); return pluck(map(obj, function(value, key, list) { return { value: value, index: index++, criteria: iteratee(value, key, list) }; }).sort(function(left, right) { var a = left.criteria; var b = right.criteria; if (a !== b) { if (a > b || a === void 0) return 1; if (a < b || b === void 0) return -1; } return left.index - right.index; }), 'value'); } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/_group.js // An internal function used for aggregate "group by" operations. function group(behavior, partition) { return function(obj, iteratee, context) { var result = partition ? [[], []] : {}; iteratee = cb(iteratee, context); each(obj, function(value, index) { var key = iteratee(value, index, obj); behavior(result, value, key); }); return result; }; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/groupBy.js // Groups the object's values by a criterion. Pass either a string attribute // to group by, or a function that returns the criterion. /* harmony default export */ const groupBy = (group(function(result, value, key) { if (has(result, key)) result[key].push(value); else result[key] = [value]; })); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/indexBy.js // Indexes the object's values by a criterion, similar to `_.groupBy`, but for // when you know that your index values will be unique. /* harmony default export */ const indexBy = (group(function(result, value, key) { result[key] = value; })); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/countBy.js // Counts instances of an object that group by a certain criterion. Pass // either a string attribute to count by, or a function that returns the // criterion. /* harmony default export */ const countBy = (group(function(result, value, key) { if (has(result, key)) result[key]++; else result[key] = 1; })); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/partition.js // Split a collection into two arrays: one whose elements all pass the given // truth test, and one whose elements all do not pass the truth test. /* harmony default export */ const partition = (group(function(result, value, pass) { result[pass ? 0 : 1].push(value); }, true)); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/size.js // Return the number of elements in a collection. function size(obj) { if (obj == null) return 0; return _isArrayLike(obj) ? obj.length : keys(obj).length; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/_keyInObj.js // Internal `_.pick` helper function to determine whether `key` is an enumerable // property name of `obj`. function keyInObj(value, key, obj) { return key in obj; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/pick.js // Return a copy of the object only containing the allowed properties. /* harmony default export */ const pick = (restArguments(function(obj, keys) { var result = {}, iteratee = keys[0]; if (obj == null) return result; if (modules_isFunction(iteratee)) { if (keys.length > 1) iteratee = optimizeCb(iteratee, keys[1]); keys = allKeys(obj); } else { iteratee = keyInObj; keys = flatten(keys, false, false); obj = Object(obj); } for (var i = 0, length = keys.length; i < length; i++) { var key = keys[i]; var value = obj[key]; if (iteratee(value, key, obj)) result[key] = value; } return result; })); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/omit.js // Return a copy of the object without the disallowed properties. /* harmony default export */ const omit = (restArguments(function(obj, keys) { var iteratee = keys[0], context; if (modules_isFunction(iteratee)) { iteratee = negate(iteratee); if (keys.length > 1) context = keys[1]; } else { keys = map(flatten(keys, false, false), String); iteratee = function(value, key) { return !contains(keys, key); }; } return pick(obj, iteratee, context); })); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/initial.js // Returns everything but the last entry of the array. Especially useful on // the arguments object. Passing **n** will return all the values in // the array, excluding the last N. function initial(array, n, guard) { return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n))); } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/first.js // Get the first element of an array. Passing **n** will return the first N // values in the array. The **guard** check allows it to work with `_.map`. function first(array, n, guard) { if (array == null || array.length < 1) return n == null || guard ? void 0 : []; if (n == null || guard) return array[0]; return initial(array, array.length - n); } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/rest.js // Returns everything but the first entry of the `array`. Especially useful on // the `arguments` object. Passing an **n** will return the rest N values in the // `array`. function rest(array, n, guard) { return slice.call(array, n == null || guard ? 1 : n); } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/last.js // Get the last element of an array. Passing **n** will return the last N // values in the array. function last(array, n, guard) { if (array == null || array.length < 1) return n == null || guard ? void 0 : []; if (n == null || guard) return array[array.length - 1]; return rest(array, Math.max(0, array.length - n)); } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/compact.js // Trim out all falsy values from an array. function compact(array) { return filter(array, Boolean); } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/flatten.js // Flatten out an array, either recursively (by default), or up to `depth`. // Passing `true` or `false` as `depth` means `1` or `Infinity`, respectively. function flatten_flatten(array, depth) { return flatten(array, depth, false); } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/difference.js // Take the difference between one array and a number of other arrays. // Only the elements present in just the first array will remain. /* harmony default export */ const difference = (restArguments(function(array, rest) { rest = flatten(rest, true, true); return filter(array, function(value){ return !contains(rest, value); }); })); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/without.js // Return a version of the array that does not contain the specified value(s). /* harmony default export */ const without = (restArguments(function(array, otherArrays) { return difference(array, otherArrays); })); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/uniq.js // Produce a duplicate-free version of the array. If the array has already // been sorted, you have the option of using a faster algorithm. // The faster algorithm will not work with an iteratee if the iteratee // is not a one-to-one function, so providing an iteratee will disable // the faster algorithm. function uniq(array, isSorted, iteratee, context) { if (!isBoolean(isSorted)) { context = iteratee; iteratee = isSorted; isSorted = false; } if (iteratee != null) iteratee = cb(iteratee, context); var result = []; var seen = []; for (var i = 0, length = _getLength(array); i < length; i++) { var value = array[i], computed = iteratee ? iteratee(value, i, array) : value; if (isSorted && !iteratee) { if (!i || seen !== computed) result.push(value); seen = computed; } else if (iteratee) { if (!contains(seen, computed)) { seen.push(computed); result.push(value); } } else if (!contains(result, value)) { result.push(value); } } return result; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/union.js // Produce an array that contains the union: each distinct element from all of // the passed-in arrays. /* harmony default export */ const union = (restArguments(function(arrays) { return uniq(flatten(arrays, true, true)); })); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/intersection.js // Produce an array that contains every item shared between all the // passed-in arrays. function intersection(array) { var result = []; var argsLength = arguments.length; for (var i = 0, length = _getLength(array); i < length; i++) { var item = array[i]; if (contains(result, item)) continue; var j; for (j = 1; j < argsLength; j++) { if (!contains(arguments[j], item)) break; } if (j === argsLength) result.push(item); } return result; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/unzip.js // Complement of zip. Unzip accepts an array of arrays and groups // each array's elements on shared indices. function unzip(array) { var length = (array && max(array, _getLength).length) || 0; var result = Array(length); for (var index = 0; index < length; index++) { result[index] = pluck(array, index); } return result; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/zip.js // Zip together multiple lists into a single array -- elements that share // an index go together. /* harmony default export */ const zip = (restArguments(unzip)); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/object.js // Converts lists into objects. Pass either a single array of `[key, value]` // pairs, or two parallel arrays of the same length -- one of keys, and one of // the corresponding values. Passing by pairs is the reverse of `_.pairs`. function object(list, values) { var result = {}; for (var i = 0, length = _getLength(list); i < length; i++) { if (values) { result[list[i]] = values[i]; } else { result[list[i][0]] = list[i][1]; } } return result; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/range.js // Generate an integer Array containing an arithmetic progression. A port of // the native Python `range()` function. See // [the Python documentation](https://docs.python.org/library/functions.html#range). function range(start, stop, step) { if (stop == null) { stop = start || 0; start = 0; } if (!step) { step = stop < start ? -1 : 1; } var length = Math.max(Math.ceil((stop - start) / step), 0); var range = Array(length); for (var idx = 0; idx < length; idx++, start += step) { range[idx] = start; } return range; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/chunk.js // Chunk a single array into multiple arrays, each containing `count` or fewer // items. function chunk(array, count) { if (count == null || count < 1) return []; var result = []; var i = 0, length = array.length; while (i < length) { result.push(slice.call(array, i, i += count)); } return result; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/_chainResult.js // Helper function to continue chaining intermediate results. function chainResult(instance, obj) { return instance._chain ? _(obj).chain() : obj; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/mixin.js // Add your own custom functions to the Underscore object. function mixin(obj) { each(functions(obj), function(name) { var func = _[name] = obj[name]; _.prototype[name] = function() { var args = [this._wrapped]; push.apply(args, arguments); return chainResult(this, func.apply(_, args)); }; }); return _; } ;// CONCATENATED MODULE: ./node_modules/underscore/modules/underscore-array-methods.js // Add all mutator `Array` functions to the wrapper. each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { var obj = this._wrapped; if (obj != null) { method.apply(obj, arguments); if ((name === 'shift' || name === 'splice') && obj.length === 0) { delete obj[0]; } } return chainResult(this, obj); }; }); // Add all accessor `Array` functions to the wrapper. each(['concat', 'join', 'slice'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { var obj = this._wrapped; if (obj != null) obj = method.apply(obj, arguments); return chainResult(this, obj); }; }); /* harmony default export */ const underscore_array_methods = (_); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/index.js // Named Exports // ============= // Underscore.js 1.13.6 // https://underscorejs.org // (c) 2009-2022 Jeremy Ashkenas, Julian Gonggrijp, and DocumentCloud and Investigative Reporters & Editors // Underscore may be freely distributed under the MIT license. // Baseline setup. // Object Functions // ---------------- // Our most fundamental functions operate on any JavaScript object. // Most functions in Underscore depend on at least one function in this section. // A group of functions that check the types of core JavaScript values. // These are often informally referred to as the "isType" functions. // Functions that treat an object as a dictionary of key-value pairs. // Utility Functions // ----------------- // A bit of a grab bag: Predicate-generating functions for use with filters and // loops, string escaping and templating, create random numbers and unique ids, // and functions that facilitate Underscore's chaining and iteration conventions. // Function (ahem) Functions // ------------------------- // These functions take a function as an argument and return a new function // as the result. Also known as higher-order functions. // Finders // ------- // Functions that extract (the position of) a single element from an object // or array based on some criterion. // Collection Functions // -------------------- // Functions that work on any collection of elements: either an array, or // an object of key-value pairs. // `_.pick` and `_.omit` are actually object functions, but we put // them here in order to create a more natural reading order in the // monolithic build as they depend on `_.contains`. // Array Functions // --------------- // Functions that operate on arrays (and array-likes) only, because they’re // expressed in terms of operations on an ordered list of values. // OOP // --- // These modules support the "object-oriented" calling style. See also // `underscore.js` and `index-default.js`. ;// CONCATENATED MODULE: ./node_modules/underscore/modules/index-default.js // Default Export // ============== // In this module, we mix our bundled exports into the `_` object and export // the result. This is analogous to setting `module.exports = _` in CommonJS. // Hence, this module is also the entry point of our UMD bundle and the package // entry point for CommonJS and AMD users. In other words, this is (the source // of) the module you are interfacing with when you do any of the following: // // ```js // // CommonJS // var _ = require('underscore'); // // // AMD // define(['underscore'], function(_) {...}); // // // UMD in the browser // // _ is available as a global variable // ``` // Add all of the Underscore functions to the wrapper object. var index_default_ = mixin(modules_namespaceObject); // Legacy Node.js API. index_default_._ = index_default_; // Export the Underscore API. /* harmony default export */ const index_default = (index_default_); ;// CONCATENATED MODULE: ./node_modules/underscore/modules/index-all.js // ESM Exports // =========== // This module is the package entry point for ES module users. In other words, // it is the module they are interfacing with when they import from the whole // package instead of from a submodule, like this: // // ```js // import { map } from 'underscore'; // ``` // // The difference with `./index-default`, which is the package entry point for // CommonJS, AMD and UMD users, is purely technical. In ES modules, named and // default exports are considered to be siblings, so when you have a default // export, its properties are not automatically available as named exports. For // this reason, we re-export the named exports in addition to providing the same // default export as in `./index-default`. /***/ }) /******/ }); /************************************************************************/ /******/ // The module cache /******/ var __webpack_module_cache__ = {}; /******/ /******/ // The require function /******/ function __nested_webpack_require_911993__(moduleId) { /******/ // Check if module is in cache /******/ var cachedModule = __webpack_module_cache__[moduleId]; /******/ if (cachedModule !== undefined) { /******/ return cachedModule.exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = __webpack_module_cache__[moduleId] = { /******/ // no module.id needed /******/ // no module.loaded needed /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __nested_webpack_require_911993__); /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /************************************************************************/ /******/ /* webpack/runtime/compat get default export */ /******/ (() => { /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __nested_webpack_require_911993__.n = (module) => { /******/ var getter = module && module.__esModule ? /******/ () => (module['default']) : /******/ () => (module); /******/ __nested_webpack_require_911993__.d(getter, { a: getter }); /******/ return getter; /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/define property getters */ /******/ (() => { /******/ // define getter functions for harmony exports /******/ __nested_webpack_require_911993__.d = (exports, definition) => { /******/ for(var key in definition) { /******/ if(__nested_webpack_require_911993__.o(definition, key) && !__nested_webpack_require_911993__.o(exports, key)) { /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); /******/ } /******/ } /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/global */ /******/ (() => { /******/ __nested_webpack_require_911993__.g = (function() { /******/ if (typeof globalThis === 'object') return globalThis; /******/ try { /******/ return this || new Function('return this')(); /******/ } catch (e) { /******/ if (typeof window === 'object') return window; /******/ } /******/ })(); /******/ })(); /******/ /******/ /* webpack/runtime/hasOwnProperty shorthand */ /******/ (() => { /******/ __nested_webpack_require_911993__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) /******/ })(); /******/ /******/ /* webpack/runtime/make namespace object */ /******/ (() => { /******/ // define __esModule on exports /******/ __nested_webpack_require_911993__.r = (exports) => { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ })(); /******/ /************************************************************************/ var __nested_webpack_exports__ = {}; // This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk. (() => { // EXPORTS __nested_webpack_require_911993__.d(__nested_webpack_exports__, { ZP: () => (/* binding */ src_0), kr: () => (/* binding */ grapesjs), j7: () => (/* binding */ usePlugin) }); // EXTERNAL MODULE: ./node_modules/underscore/modules/index-all.js + 160 modules var index_all = __nested_webpack_require_911993__(50); // EXTERNAL MODULE: ./src/utils/mixins.ts var mixins = __nested_webpack_require_911993__(163); ;// CONCATENATED MODULE: ./src/utils/html.ts /** * Safe ES6 tagged template strings * @param {Array<String>} literals * @param {Array<String>} substs * @returns {String} * @example * const str = '<b>Hello</b>'; * const strHtml = html`Escaped ${str}, unescaped $${str}`; */ function html(literals) { var substs = []; for (var _i = 1; _i < arguments.length; _i++) { substs[_i - 1] = arguments[_i]; } var raw = literals.raw; return raw.reduce(function (acc, lit, i) { var subst = substs[i - 1]; var last = raw[i - 1]; if (Array.isArray(subst)) { subst = subst.join(''); } else if (last && last.slice(-1) === '$') { // If the interpolation is preceded by a dollar sign, it won't be escaped acc = acc.slice(0, -1); } else { subst = (0,mixins.escape)(subst); } return acc + subst + lit; }); } ;// CONCATENATED MODULE: ./src/editor/config/config.ts var config = { stylePrefix: 'gjs-', components: '', style: '', fromElement: false, projectData: undefined, noticeOnUnload: true, showOffsets: false, showOffsetsSelected: false, forceClass: true, height: '900px', width: '100%', log: ['warning', 'error'], baseCss: '', protectedCss: '* { box-sizing: border-box; } body {margin: 0;}', canvasCss: '', defaultCommand: 'select-comp', showToolbar: true, showDevices: true, devicePreviewMode: false, mediaCondition: 'max-width', tagVarStart: '{[ ', tagVarEnd: ' ]}', keepEmptyTextNodes: false, jsInHtml: true, nativeDnD: true, multipleSelection: true, optsHtml: {}, optsCss: {}, avoidInlineStyle: true, avoidDefaults: true, clearStyles: false, listenToEl: [], cssIcons: 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css', icons: { close: '<svg viewBox="0 0 24 24"><path fill="currentColor" d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12 19 6.41z"></path></svg>', move: '<svg viewBox="0 0 24 24"><path fill="currentColor" d="M13,6V11H18V7.75L22.25,12L18,16.25V13H13V18H16.25L12,22.25L7.75,18H11V13H6V16.25L1.75,12L6,7.75V11H11V6H7.75L12,1.75L16.25,6H13Z"/></svg>', plus: '<svg viewBox="0 0 24 24"><path fill="currentColor" d="M19,13H13V19H11V13H5V11H11V5H13V11H19V13Z" /></svg>', caret: '<svg viewBox="0 0 24 24"><path fill="currentColor" d="M7,10L12,15L17,10H7Z" /></svg>', delete: '<svg viewBox="0 0 24 24"><path fill="currentColor" d="M19,4H15.5L14.5,3H9.5L8.5,4H5V6H19M6,19A2,2 0 0,0 8,21H16A2,2 0 0,0 18,19V7H6V19Z" /></svg>', copy: '<svg viewBox="0 0 24 24"><path fill="currentColor" d="M19,21H8V7H19M19,5H8A2,2 0 0,0 6,7V21A2,2 0 0,0 8,23H19A2,2 0 0,0 21,21V7A2,2 0 0,0 19,5M16,1H4A2,2 0 0,0 2,3V17H4V3H16V1Z" /></svg>', arrowUp: '<svg viewBox="0 0 24 24"><path fill="currentColor" d="M13,20H11V8L5.5,13.5L4.08,12.08L12,4.16L19.92,12.08L18.5,13.5L13,8V20Z" /></svg>', chevron: '<svg viewBox="0 0 24 24"><path fill="currentColor" d="M7.41,15.41L12,10.83L16.59,15.41L18,14L12,8L6,14L7.41,15.41Z" /></svg>', eye: '<svg viewBox="0 0 24 24"><path fill="currentColor" d="M12,9A3,3 0 0,0 9,12A3,3 0 0,0 12,15A3,3 0 0,0 15,12A3,3 0 0,0 12,9M12,17A5,5 0 0,1 7,12A5,5 0 0,1 12,7A5,5 0 0,1 17,12A5,5 0 0,1 12,17M12,4.5C7,4.5 2.73,7.61 1,12C2.73,16.39 7,19.5 12,19.5C17,19.5 21.27,16.39 23,12C21.27,7.61 17,4.5 12,4.5Z" /></svg>', eyeOff: '<svg viewBox="0 0 24 24"><path fill="currentColor" d="M11.83,9L15,12.16C15,12.11 15,12.05 15,12A3,3 0 0,0 12,9C11.94,9 11.89,9 11.83,9M7.53,9.8L9.08,11.35C9.03,11.56 9,11.77 9,12A3,3 0 0,0 12,15C12.22,15 12.44,14.97 12.65,14.92L14.2,16.47C13.53,16.8 12.79,17 12,17A5,5 0 0,1 7,12C7,11.21 7.2,10.47 7.53,9.8M2,4.27L4.28,6.55L4.73,7C3.08,8.3 1.78,10 1,12C2.73,16.39 7,19.5 12,19.5C13.55,19.5 15.03,19.2 16.38,18.66L16.81,19.08L19.73,22L21,20.73L3.27,3M12,7A5,5 0 0,1 17,12C17,12.64 16.87,13.26 16.64,13.82L19.57,16.75C21.07,15.5 22.27,13.86 23,12C21.27,7.61 17,4.5 12,4.5C10.6,4.5 9.26,4.75 8,5.2L10.17,7.35C10.74,7.13 11.35,7 12,7Z" /></svg>', }, i18n: {}, undoManager: {}, assetManager: {}, canvas: {}, layerManager: {}, storageManager: {}, richTextEditor: {}, domComponents: {}, modal: {}, codeManager: {}, panels: {}, commands: {}, cssComposer: {}, selectorManager: {}, deviceManager: {}, styleManager: {}, blockManager: {}, traitManager: {}, textViewCode: 'Code', keepUnusedStyles: false, customUI: false, }; /* harmony default export */ const config_config = (config); // EXTERNAL MODULE: ./node_modules/backbone/backbone.js var backbone = __nested_webpack_require_911993__(316); var backbone_default = /*#__PURE__*/__nested_webpack_require_911993__.n(backbone); // EXTERNAL MODULE: ./src/utils/cash-dom.ts var cash_dom = __nested_webpack_require_911993__(895); ;// CONCATENATED MODULE: ./src/utils/extender.ts /* harmony default export */ const extender = (function (_a) { var $ = _a.$; if ($ && $.prototype && $.prototype.constructor.name !== 'jQuery') { var fn = $.fn; // Additional helpers fn.hide = function () { return this.css('display', 'none'); }; fn.show = function () { return this.css('display', 'block'); }; fn.focus = function () { var el = this.get(0); el && el.focus(); return this; }; // For spectrum compatibility fn.bind = function (ev, h) { return this.on(ev, h); }; fn.unbind = function (ev, h) { if ((0,index_all.isObject)(ev)) { for (var name_1 in ev) { ev.hasOwnProperty(name_1) && this.off(name_1, ev[name_1]); } return this; } else { return this.off(ev, h); } }; fn.click = function (h) { return h ? this.on('click', h) : this.trigger('click'); }; fn.change = function (h) { return h ? this.on('change', h) : this.trigger('change'); }; fn.keydown = function (h) { return h ? this.on('keydown', h) : this.trigger('keydown'); }; fn.delegate = function (selector, events, data, handler) { if (!handler) { handler = data; } return this.on(events, selector, function (e) { e.data = data; handler(e); }); }; fn.scrollLeft = function () { var el = this.get(0); el = el.nodeType == 9 ? el.defaultView : el; var win = el instanceof Window ? el : null; return win ? win.pageXOffset : el.scrollLeft || 0; }; fn.scrollTop = function () { var el = this.get(0); el = el.nodeType == 9 ? el.defaultView : el; var win = el instanceof Window ? el : null; return win ? win.pageYOffset : el.scrollTop || 0; }; var offset_1 = $.prototype.offset; fn.offset = function (coords) { var top, left; if (coords) { top = coords.top; left = coords.left; } if (typeof top != 'undefined') { this.css('top', "".concat(top, "px")); } if (typeof left != 'undefined') { this.css('left', "".concat(left, "px")); } return offset_1.call(this); }; $.map = function (items, clb) { var ar = []; for (var i = 0; i < items.length; i++) { ar.push(clb(items[i], i)); } return ar; }; var indexOf_1 = Array.prototype.indexOf; $.inArray = function (val, arr, i) { return arr == null ? -1 : indexOf_1.call(arr, val, i); }; $.Event = function (src, props) { if (!(this instanceof $.Event)) { return new $.Event(src, props); } this.type = src; this.isDefaultPrevented = function () { return false; }; }; } }); // EXTERNAL MODULE: ./src/common/index.ts var common = __nested_webpack_require_911993__(346); ;// CONCATENATED MODULE: ./src/editor/model/Selected.ts var __extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var Selectable = /** @class */ (function (_super) { __extends(Selectable, _super); function Selectable() { return _super !== null && _super.apply(this, arguments) || this; } return Selectable; }(common/* Model */.Hn)); var Selected = /** @class */ (function (_super) { __extends(Selected, _super); function Selected() { return _super !== null && _super.apply(this, arguments) || this; } Selected.prototype.getByComponent = function (component) { var _this = this; return this.filter(function (s) { return _this.getComponent(s) === component; })[0]; }; Selected.prototype.addComponent = function (component, opts) { var _this = this; var toAdd = ((0,index_all.isArray)(component) ? component : [component]) .filter(function (c) { return !_this.hasComponent(c); }) .map(function (component) { return new Selectable({ component: component }); })[0]; return this.push(toAdd, opts); }; Selected.prototype.getComponent = function (model) { return model.get('component'); }; Selected.prototype.hasComponent = function (component) { var model = this.getByComponent(component); return model && this.contains(model); }; Selected.prototype.lastComponent = function () { var last = this.last(); return last ? this.getComponent(last) : undefined; }; Selected.prototype.allComponents = function () { var _this = this; return this.map(function (s) { return _this.getComponent(s); }).filter(function (i) { return i; }); }; Selected.prototype.removeComponent = function (component, opts) { var _this = this; var toRemove = ((0,index_all.isArray)(component) ? component : [component]).map(function (c) { return _this.getByComponent(c); }); return this.remove(toRemove, opts); }; return Selected; }(common/* Collection */.FE)); /* harmony default export */ const model_Selected = (Selected); ;// CONCATENATED MODULE: ./src/abstract/Module.ts var Module_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __assign = ( false) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __spreadArray = ( false) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var Module = /** @class */ (function () { function Module(em, moduleName, defaults) { this.cls = []; this._em = em; this._name = moduleName; var name = (this.name.charAt(0).toLowerCase() + this.name.slice(1)); var cfgParent = !(0,index_all.isUndefined)(em.config[name]) ? em.config[name] : em.config[this.name]; var cfg = (cfgParent === true ? {} : cfgParent || {}); cfg.pStylePrefix = em.config.pStylePrefix || ''; if (!(0,index_all.isUndefined)(cfgParent) && !cfgParent) { cfg._disable = 1; } cfg.em = em; this._config = (0,mixins.deepMerge)(defaults || {}, cfg); } Object.defineProperty(Module.prototype, "em", { get: function () { return this._em; }, enumerable: false, configurable: true }); Object.defineProperty(Module.prototype, "config", { get: function () { return this._config; }, enumerable: false, configurable: true }); Module.prototype.render = function (opts) { }; Module.prototype.postLoad = function (key) { }; Object.defineProperty(Module.prototype, "name", { get: function () { return this._name; }, enumerable: false, configurable: true }); Module.prototype.getConfig = function (name) { // @ts-ignore return name ? this.config[name] : this.config; }; Module.prototype.__logWarn = function (str, opts) { if (opts === void 0) { opts = {}; } this.em.logWarning("[".concat(this.name, "]: ").concat(str), opts); }; /** * Move the main DOM element of the module. * To execute only post editor render (in postRender) */ Module.prototype.__appendTo = function () { var elTo = this.getConfig().appendTo; if (elTo) { var el = (0,index_all.isElement)(elTo) ? elTo : document.querySelector(elTo); if (!el) return this.__logWarn('"appendTo" element not found'); el.appendChild(this.render()); } }; return Module; }()); /* harmony default export */ const abstract_Module = (Module); var ItemManagerModule = /** @class */ (function (_super) { Module_extends(ItemManagerModule, _super); function ItemManagerModule(em, moduleName, all, events, defaults, opts) { if (opts === void 0) { opts = {}; } var _this = _super.call(this, em, moduleName, defaults) || this; _this.cls = []; _this.private = false; _this.all = all; _this.events = events; !opts.skipListen && _this.__initListen(); return _this; } ItemManagerModule.prototype.postLoad = function (key) { }; ItemManagerModule.prototype.render = function (opts) { }; ItemManagerModule.prototype.getProjectData = function (data) { var obj = {}; var key = this.storageKey; if (key) { obj[key] = data || this.getAll(); } return obj; }; ItemManagerModule.prototype.loadProjectData = function (data, param) { if (data === void 0) { data = {}; } if (param === void 0) { param = {}; } var all = param.all, onResult = param.onResult, reset = param.reset; var key = this.storageKey; var opts = { action: 'load' }; var coll = all || this.all; var result = data[key]; if (typeof result == 'string') { try { result = JSON.parse(result); } catch (err) { this.__logWarn('Data parsing failed', { input: result }); } } reset && result && coll.reset(undefined, opts); if (onResult) { result && onResult(result, opts); } else if (result && (0,mixins.isDef)(result.length)) { coll.reset(result, opts); } return result; }; ItemManagerModule.prototype.clear = function (opts) { if (opts === void 0) { opts = {}; } var all = this.all; all && all.reset(undefined, opts); return this; }; // getAll(): TCollection extends Collection<infer C> ? C[] : TCollection { ItemManagerModule.prototype.getAll = function () { return __spreadArray([], this.all.models, true); }; ItemManagerModule.prototype.getAllMap = function () { return this.getAll().reduce(function (acc, i) { acc[i.get(i.idAttribute)] = i; return acc; }, {}); }; ItemManagerModule.prototype.__initListen = function (opts) { if (opts === void 0) { opts = {}; } var _a = this, all = _a.all, em = _a.em, events = _a.events; all && em && all .on('add', function (m, c, o) { return em.trigger(events.add, m, o); }) .on('remove', function (m, c, o) { return em.trigger(events.remove, m, o); }) .on('change', function (p, c) { return em.trigger(events.update, p, p.changedAttributes(), c); }) .on('all', this.__catchAllEvent, this); // Register collections this.cls = [all].concat(opts.collections || []); // Propagate events (opts.propagate || []).forEach(function (_a) { var entity = _a.entity, event = _a.event; entity.on('all', function (ev, model, coll, opts) { var options = opts || coll; var opt = __assign({ event: ev }, options); [em, all].map(function (md) { return md.trigger(event, model, opt); }); }); }); }; ItemManagerModule.prototype.__remove = function (model, opts) { var _this = this; if (opts === void 0) { opts = {}; } var em = this.em; //@ts-ignore var md = (0,index_all.isString)(model) ? this.get(model) : model; var rm = function () { md && _this.all.remove(md, opts); return md; }; !opts.silent && (em === null || em === void 0 ? void 0 : em.trigger(this.events.removeBefore, md, rm, opts)); return !opts.abort && rm(); }; ItemManagerModule.prototype.__catchAllEvent = function (event, model, coll, opts) { var _a = this, em = _a.em, events = _a.events; var options = opts || coll; em && events.all && em.trigger(events.all, { event: event, model: model, options: options }); this.__onAllEvent(); }; ItemManagerModule.prototype.__appendTo = function (renderProps) { //@ts-ignore var elTo = this.config.appendTo; if (elTo) { var el = (0,index_all.isElement)(elTo) ? elTo : document.querySelector(elTo); if (!el) return this.__logWarn('"appendTo" element not found'); // @ts-ignore el.appendChild(this.render(renderProps)); } }; ItemManagerModule.prototype.__onAllEvent = function () { }; ItemManagerModule.prototype._createId = function (len) { if (len === void 0) { len = 16; } var all = this.getAll(); var ln = all.length + len; var allMap = this.getAllMap(); var id; do { id = (0,mixins.createId)(ln); } while (allMap[id]); return id; }; ItemManagerModule.prototype.__listenAdd = function (model, event) { var _this = this; model.on('add', function (m, c, o) { return _this.em.trigger(event, m, o); }); }; ItemManagerModule.prototype.__listenRemove = function (model, event) { var _this = this; model.on('remove', function (m, c, o) { return _this.em.trigger(event, m, o); }); }; ItemManagerModule.prototype.__listenUpdate = function (model, event) { var _this = this; model.on('change', function (p, c) { return _this.em.trigger(event, p, p.changedAttributes(), c); }); }; ItemManagerModule.prototype.__destroy = function () { var _a; this.cls.forEach(function (coll) { coll.stopListening(); coll.reset(); }); (_a = this.view) === null || _a === void 0 ? void 0 : _a.remove(); this.view = undefined; }; return ItemManagerModule; }(Module)); ;// CONCATENATED MODULE: ./src/canvas/config/config.ts var config_config_config = { stylePrefix: 'cv-', scripts: [], styles: [], customBadgeLabel: undefined, autoscrollLimit: 50, extHl: false, frameContent: '<!DOCTYPE html>', frameStyle: "\n body { background-color: #fff }\n * ::-webkit-scrollbar-track { background: rgba(0, 0, 0, 0.1) }\n * ::-webkit-scrollbar-thumb { background: rgba(255, 255, 255, 0.2) }\n * ::-webkit-scrollbar { width: 10px }\n ", notTextable: ['button', 'a', 'input[type=checkbox]', 'input[type=radio]'], allowExternalDrop: true, }; /* harmony default export */ const canvas_config_config = (config_config_config); // EXTERNAL MODULE: ./src/abstract/ModuleModel.ts var ModuleModel = __nested_webpack_require_911993__(642); ;// CONCATENATED MODULE: ./src/device_manager/config/config.ts var device_manager_config_config_config = { default: '', devices: [ { id: 'desktop', name: 'Desktop', width: '', }, { id: 'tablet', name: 'Tablet', width: '770px', widthMedia: '992px', }, { id: 'mobileLandscape', name: 'Mobile landscape', width: '568px', widthMedia: '768px', }, { id: 'mobilePortrait', name: 'Mobile portrait', width: '320px', widthMedia: '480px', }, ], }; /* harmony default export */ const device_manager_config_config = (device_manager_config_config_config); ;// CONCATENATED MODULE: ./src/device_manager/model/Device.ts var Device_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); /** * @typedef Device * @property {String} [name=''] Device type, eg. `Mobile` * @property {String} [width] Width to set for the editor iframe, eg. '900px' * @property {String} [height=''] Height to set for the editor iframe, eg. '600px' * @property {String} [widthMedia=''] The width which will be used in media queries, If empty the width will be used * @property {Number} [priority=null] Setup the order of media queries */ var Device = /** @class */ (function (_super) { Device_extends(Device, _super); function Device() { return _super !== null && _super.apply(this, arguments) || this; } Device.prototype.defaults = function () { return { name: '', width: null, height: '', widthMedia: null, priority: null, }; }; Device.prototype.initialize = function () { var _this = this; this.get('widthMedia') === null && this.set('widthMedia', this.get('width')); this.get('width') === null && this.set('width', this.get('widthMedia')); !this.get('priority') && this.set('priority', parseFloat(this.get('widthMedia')) || 0); var toCheck = ['width', 'height', 'widthMedia']; toCheck.forEach(function (prop) { return _this.checkUnit(prop); }); }; Device.prototype.checkUnit = function (prop) { var pr = (this.get(prop) || ''); var noUnit = (parseFloat(pr) || 0).toString() === pr.toString(); noUnit && this.set(prop, "".concat(pr, "px")); }; Device.prototype.getName = function () { return this.get('name') || this.get('id'); }; Device.prototype.getWidthMedia = function () { return this.get('widthMedia') || ''; }; return Device; }(common/* Model */.Hn)); /* harmony default export */ const model_Device = (Device); ;// CONCATENATED MODULE: ./src/device_manager/model/Devices.ts var Devices_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var Devices = /** @class */ (function (_super) { Devices_extends(Devices, _super); function Devices() { return _super !== null && _super.apply(this, arguments) || this; } return Devices; }(common/* Collection */.FE)); /* harmony default export */ const model_Devices = (Devices); Devices.prototype.model = model_Device; ;// CONCATENATED MODULE: ./src/device_manager/view/DevicesView.ts var DevicesView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __makeTemplateObject = ( false) || function (cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; }; var DevicesView = /** @class */ (function (_super) { DevicesView_extends(DevicesView, _super); function DevicesView(o) { var _this = _super.call(this, o) || this; _this.config = o.config || {}; _this.em = _this.config.em; _this.ppfx = _this.config.pStylePrefix || ''; _this.listenTo(_this.em, 'change:device', _this.updateSelect); return _this; } DevicesView.prototype.template = function (_a) { var ppfx = _a.ppfx, label = _a.label; return html(templateObject_1 || (templateObject_1 = __makeTemplateObject(["\n <div class=\"", "device-label\">", "</div>\n <div class=\"", "field ", "select\">\n <span id=\"", "input-holder\">\n <select class=\"", "devices\"></select>\n </span>\n <div class=\"", "sel-arrow\">\n <div class=\"", "d-s-arrow\"></div>\n </div>\n </div>\n <button style=\"display:none\" class=\"", "add-trasp\" data-add-trasp>+</button>\n "], ["\n <div class=\"", "device-label\">", "</div>\n <div class=\"", "field ", "select\">\n <span id=\"", "input-holder\">\n <select class=\"", "devices\"></select>\n </span>\n <div class=\"", "sel-arrow\">\n <div class=\"", "d-s-arrow\"></div>\n </div>\n </div>\n <button style=\"display:none\" class=\"", "add-trasp\" data-add-trasp>+</button>\n "])), ppfx, label, ppfx, ppfx, ppfx, ppfx, ppfx, ppfx, ppfx); }; DevicesView.prototype.events = function () { return { change: 'updateDevice', 'click [data-add-trasp]': 'startAdd', }; }; /** * Start adding new device * @return {[type]} [description] * @private */ DevicesView.prototype.startAdd = function () { }; /** * Update device of the editor * @private */ DevicesView.prototype.updateDevice = function () { var em = this.em; if (em) { var devEl = this.devicesEl; em.set('device', devEl ? devEl.val() : ''); } }; /** * Update select value on device update * @private */ DevicesView.prototype.updateSelect = function () { var _a = this, em = _a.em, devicesEl = _a.devicesEl; if (em && em.getDeviceModel && devicesEl) { var device = em.getDeviceModel(); devicesEl.val(device ? device.get('id') : ''); } }; /** * Return devices options * @return {string} String of options * @private */ DevicesView.prototype.getOptions = function () { var _a = this, collection = _a.collection, em = _a.em; var result = ''; collection.forEach(function (device) { var _a = device.attributes, name = _a.name, id = _a.id; var label = (em && em.t && em.t("deviceManager.devices.".concat(id))) || name; result += "<option value=\"".concat(id || name, "\">").concat(label, "</option>"); }); return result; }; DevicesView.prototype.render = function () { var _a = this, em = _a.em, ppfx = _a.ppfx, $el = _a.$el, el = _a.el; var label = em && em.t && em.t('deviceManager.device'); $el.html(this.template({ ppfx: ppfx, label: label })); this.devicesEl = $el.find(".".concat(ppfx, "devices")); this.devicesEl.append(this.getOptions()); this.devicesEl.val(em.get('device')); el.className = "".concat(ppfx, "devices-c"); return this; }; return DevicesView; }(common/* View */.G7)); /* harmony default export */ const view_DevicesView = (DevicesView); var templateObject_1; ;// CONCATENATED MODULE: ./src/device_manager/index.ts var device_manager_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var device_manager_assign = ( false) || function () { device_manager_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return device_manager_assign.apply(this, arguments); }; /** * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/GrapesJS/grapesjs/blob/master/src/device_manager/config/config.ts) * ```js * const editor = grapesjs.init({ * deviceManager: { * // options * } * }) * ``` * * Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance * * ```js * const deviceManager = editor.Devices; * ``` * ## Available Events * * `device:add` - Added new device. The [Device] is passed as an argument to the callback * * `device:remove` - Device removed. The [Device] is passed as an argument to the callback * * `device:select` - New device selected. The newly selected [Device] and the previous one, are passed as arguments to the callback * * `device:update` - Device updated. The updated [Device] and the object containing changes are passed as arguments to the callback * * `device` - Catch-all event for all the events mentioned above. An object containing all the available data about the triggered event is passed as an argument to the callback * * ## Methods * * [add](#add) * * [get](#get) * * [getDevices](#getdevices) * * [remove](#remove) * * [select](#select) * * [getSelected](#getselected) * * [Device]: device.html * * @module Devices */ var evAll = 'device'; var evPfx = "".concat(evAll, ":"); var evSelect = "".concat(evPfx, "select"); var evSelectBefore = "".concat(evSelect, ":before"); var evUpdate = "".concat(evPfx, "update"); var evAdd = "".concat(evPfx, "add"); var evAddBefore = "".concat(evAdd, ":before"); var evRemove = "".concat(evPfx, "remove"); var evRemoveBefore = "".concat(evRemove, ":before"); var chnSel = 'change:device'; var deviceEvents = { all: evAll, select: evSelect, update: evUpdate, add: evAdd, remove: evRemove, removeBefore: evRemoveBefore, }; var DeviceManager = /** @class */ (function (_super) { device_manager_extends(DeviceManager, _super); function DeviceManager(em) { var _a; var _this = _super.call(this, em, 'DeviceManager', new model_Devices(), deviceEvents, device_manager_config_config) || this; _this.Device = model_Device; _this.Devices = model_Devices; _this.storageKey = ''; _this.devices = _this.all; (_a = _this.config.devices) === null || _a === void 0 ? void 0 : _a.forEach(function (device) { return _this.add(device, { silent: true }); }); _this.select(_this.config.default || _this.devices.at(0)); em.on(chnSel, _this._onSelect, _this); return _this; } DeviceManager.prototype._onSelect = function (m, deviceId, opts) { var _a = this, em = _a.em, events = _a.events; var prevId = m.previous('device'); var newDevice = this.get(deviceId); var ev = events.select; em.trigger(ev, newDevice, this.get(prevId)); this.__catchAllEvent(ev, newDevice, opts); }; /** * Add new device * @param {Object} props Device properties * @returns {[Device]} Added device * @example * const device1 = deviceManager.add({ * // Without an explicit ID, the `name` will be taken. In case of missing `name`, a random ID will be created. * id: 'tablet', * name: 'Tablet', * width: '900px', // This width will be applied on the canvas frame and for the CSS media * }); * const device2 = deviceManager.add({ * id: 'tablet2', * name: 'Tablet 2', * width: '800px', // This width will be applied on the canvas frame * widthMedia: '810px', // This width that will be used for the CSS media * height: '600px', // Height will be applied on the canvas frame * }); */ DeviceManager.prototype.add = function (props, options) { if (options === void 0) { options = {}; } var result; var opts = options; // Support old API if ((0,index_all.isString)(props)) { var width = options; opts = arguments[2] || {}; result = device_manager_assign(device_manager_assign({}, opts), { id: props, name: opts.name || props, width: width }); } else { result = props; } if (!result.id) { result.id = result.name || this._createId(); } return this.devices.add(result, opts); }; /** * Return device by ID * @param {String} id ID of the device * @returns {[Device]|null} * @example * const device = deviceManager.get('Tablet'); * console.log(JSON.stringify(device)); * // {name: 'Tablet', width: '900px'} */ DeviceManager.prototype.get = function (id) { // Support old API var byName = this.getAll().filter(function (d) { return d.get('name') === id; })[0]; return byName || this.devices.get(id) || null; }; /** * Remove device * @param {String|[Device]} device Device or device id * @returns {[Device]} Removed device * @example * const removed = deviceManager.remove('device-id'); * // or by passing the Device * const device = deviceManager.get('device-id'); * deviceManager.remove(device); */ DeviceManager.prototype.remove = function (device, opts) { if (opts === void 0) { opts = {}; } return this.__remove(device, opts); }; /** * Return all devices * @returns {Array<[Device]>} * @example * const devices = deviceManager.getDevices(); * console.log(JSON.stringify(devices)); * // [{name: 'Desktop', width: ''}, ...] */ DeviceManager.prototype.getDevices = function () { return this.devices.models; }; /** * Change the selected device. This will update the frame in the canvas * @param {String|[Device]} device Device or device id * @example * deviceManager.select('some-id'); * // or by passing the page * const device = deviceManager.get('some-id'); * deviceManager.select(device); */ DeviceManager.prototype.select = function (device, opts) { if (opts === void 0) { opts = {}; } var md = (0,index_all.isString)(device) ? this.get(device) : device; md && this.em.set('device', md.get('id'), opts); return this; }; /** * Get the selected device * @returns {[Device]} * @example * const selected = deviceManager.getSelected(); */ DeviceManager.prototype.getSelected = function () { return this.get(this.em.get('device')); }; DeviceManager.prototype.getAll = function () { return this.devices; }; DeviceManager.prototype.render = function () { var _a; var em = this.em; (_a = this.view) === null || _a === void 0 ? void 0 : _a.remove(); this.view = new view_DevicesView({ collection: this.devices, config: device_manager_assign({ em: em }, this.config), }); return this.view.render().el; }; DeviceManager.prototype.destroy = function () { this.__destroy(); }; return DeviceManager; }(ItemManagerModule)); /* harmony default export */ const device_manager = (DeviceManager); ;// CONCATENATED MODULE: ./src/abstract/ModuleCollection.ts var ModuleCollection_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ModuleCollection = /** @class */ (function (_super) { ModuleCollection_extends(ModuleCollection, _super); function ModuleCollection(module, models, modelConstructor) { return _super.call(this, models, { module: module, modelConstructor: modelConstructor }) || this; } ModuleCollection.prototype.add = function (model, options) { var _this = this; var _a; //Note: the undefined case needed because backbonejs not handle the reset() correctly var models = (0,index_all.isArray)(model) ? model : !(0,index_all.isUndefined)(model) ? [model] : undefined; models = (_a = models === null || models === void 0 ? void 0 : models.map(function (m) { return (m instanceof _this.newModel ? m : new _this.newModel(_this.module, m)); })) !== null && _a !== void 0 ? _a : [undefined]; return _super.prototype.add.call(this, (0,index_all.isArray)(model) ? models : models[0], options); }; ModuleCollection.prototype.preinitialize = function (models, options) { this.newModel = options.modelConstructor; this.module = options.module; }; return ModuleCollection; }(common/* Collection */.FE)); /* harmony default export */ const abstract_ModuleCollection = (ModuleCollection); ;// CONCATENATED MODULE: ./src/canvas/model/Frame.ts var Frame_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var Frame_assign = ( false) || function () { Frame_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return Frame_assign.apply(this, arguments); }; var Frame_spreadArray = ( false) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var keyAutoW = '__aw'; var keyAutoH = '__ah'; var getDimension = function (frame, type) { var _a; var dim = frame.get(type); var viewDim = (_a = frame.view) === null || _a === void 0 ? void 0 : _a.el[type === 'width' ? 'offsetWidth' : 'offsetHeight']; if ((0,index_all.isNumber)(dim)) { return dim; } else if ((0,index_all.isString)(dim) && dim.endsWith('px')) { return parseFloat(dim); } else if (viewDim) { return viewDim; } else { return 0; } }; /** * @property {Object|String} component Wrapper component definition. You can also pass an HTML string as components of the default wrapper component. * @property {String} [width=''] Width of the frame. By default, the canvas width will be taken. * @property {String} [height=''] Height of the frame. By default, the canvas height will be taken. * @property {Number} [x=0] Horizontal position of the frame in the canvas. * @property {Number} [y=0] Vertical position of the frame in the canvas. * */ var Frame = /** @class */ (function (_super) { Frame_extends(Frame, _super); /** * @hideconstructor */ function Frame(module, attr) { var _this = _super.call(this, module, attr) || this; var em = _this.em; var _a = _this.attributes, styles = _a.styles, component = _a.component; var domc = em.Components; var conf = domc.getConfig(); var allRules = em.Css.getAll(); var idMap = {}; var modOpts = { em: em, config: conf, frame: _this, idMap: idMap }; if (!(0,mixins.isComponent)(component)) { var wrp = (0,mixins.isObject)(component) ? component : { components: component }; !wrp.type && (wrp.type = 'wrapper'); var Wrapper = domc.getType('wrapper').model; _this.set('component', new Wrapper(wrp, modOpts)); } if (!styles) { _this.set('styles', allRules); } else if (!(0,mixins.isObject)(styles)) { // Avoid losing styles on remapped components var idMapKeys = Object.keys(idMap); if (idMapKeys.length && Array.isArray(styles)) { styles.forEach(function (style) { var sel = style.selectors; if (sel && sel.length == 1) { var sSel = sel[0]; var idSel = sSel.name && sSel.type === 2 && sSel; if (idSel && idMap[idSel.name]) { idSel.name = idMap[idSel.name]; } else if ((0,index_all.isString)(sSel) && sSel[0] === '#') { var prevId = sSel.substring(1); if (prevId && idMap[prevId]) { sel[0] = "#".concat(idMap[prevId]); } } } }); } allRules.add(styles); _this.set('styles', allRules); } !attr.width && _this.set(keyAutoW, 1); !attr.height && _this.set(keyAutoH, 1); !_this.id && _this.set('id', (0,mixins.createId)()); return _this; } Frame.prototype.defaults = function () { return { x: 0, y: 0, changesCount: 0, attributes: {}, width: null, height: null, head: [], component: '', styles: '', refFrame: null, _undo: true, _undoexc: ['changesCount'], }; }; Object.defineProperty(Frame.prototype, "width", { get: function () { return getDimension(this, 'width'); }, enumerable: false, configurable: true }); Object.defineProperty(Frame.prototype, "height", { get: function () { return getDimension(this, 'height'); }, enumerable: false, configurable: true }); Object.defineProperty(Frame.prototype, "head", { get: function () { return this.get('head'); }, enumerable: false, configurable: true }); Object.defineProperty(Frame.prototype, "refFrame", { get: function () { return this.get('refFrame'); }, enumerable: false, configurable: true }); Object.defineProperty(Frame.prototype, "root", { get: function () { var refFrame = this.refFrame; return (refFrame === null || refFrame === void 0 ? void 0 : refFrame.getComponent()) || this.getComponent(); }, enumerable: false, configurable: true }); Frame.prototype.initRefs = function () { var refFrame = this.refFrame; if ((0,index_all.isString)(refFrame)) { var frame = this.module.framesById[refFrame]; frame && this.set({ refFrame: frame }, { silent: true }); } }; Frame.prototype.getBoxRect = function () { var _a = this.attributes, x = _a.x, y = _a.y; var _b = this, width = _b.width, height = _b.height; return { x: x, y: y, width: width, height: height, }; }; Frame.prototype.onRemove = function () { !this.refFrame && this.getComponent().remove({ root: 1 }); }; Frame.prototype.changesUp = function (opt) { if (opt === void 0) { opt = {}; } if (opt.temporary || opt.noCount || opt.avoidStore) { return; } this.set('changesCount', this.get('changesCount') + 1); }; Frame.prototype.getComponent = function () { return this.get('component'); }; Frame.prototype.getStyles = function () { return this.get('styles'); }; Frame.prototype.disable = function () { this.trigger('disable'); }; Frame.prototype.remove = function () { var _a; (_a = this.view) === null || _a === void 0 ? void 0 : _a.remove(); this.view = undefined; var coll = this.collection; return coll && coll.remove(this); }; Frame.prototype.getHead = function () { return Frame_spreadArray([], this.head, true); }; Frame.prototype.setHead = function (value) { return this.set('head', Frame_spreadArray([], value, true)); }; Frame.prototype.addHeadItem = function (item) { this.head.push(item); }; Frame.prototype.getHeadByAttr = function (attr, value, tag) { return this.head.filter(function (item) { return item.attributes && item.attributes[attr] == value && (!tag || tag === item.tag); })[0]; }; Frame.prototype.removeHeadByAttr = function (attr, value, tag) { var item = this.getHeadByAttr(attr, value, tag); var index = this.head.indexOf(item); if (index >= 0) { this.head.splice(index, 1); } }; Frame.prototype.addLink = function (href) { var tag = 'link'; !this.getHeadByAttr('href', href, tag) && this.addHeadItem({ tag: tag, attributes: { href: href, rel: 'stylesheet', }, }); }; Frame.prototype.removeLink = function (href) { this.removeHeadByAttr('href', href, 'link'); }; Frame.prototype.addScript = function (src) { var tag = 'script'; !this.getHeadByAttr('src', src, tag) && this.addHeadItem({ tag: tag, attributes: { src: src }, }); }; Frame.prototype.removeScript = function (src) { this.removeHeadByAttr('src', src, 'script'); }; Frame.prototype.getPage = function () { var _a; return (_a = this.collection) === null || _a === void 0 ? void 0 : _a.page; }; Frame.prototype._emitUpdated = function (data) { if (data === void 0) { data = {}; } this.em.trigger('frame:updated', Frame_assign({ frame: this }, data)); }; Frame.prototype.hasAutoHeight = function () { var height = this.attributes.height; if (height === 'auto' || this.config.infiniteCanvas) { return true; } return false; }; Frame.prototype.toJSON = function (opts) { if (opts === void 0) { opts = {}; } var obj = ModuleModel/* default */.Z.prototype.toJSON.call(this, opts); var defaults = (0,index_all.result)(this, 'defaults'); if (opts.fromUndo) delete obj.component; delete obj.styles; delete obj.changesCount; obj[keyAutoW] && delete obj.width; obj[keyAutoH] && delete obj.height; if (obj.refFrame) { obj.refFrame = obj.refFrame.id; delete obj.component; } // Remove private keys (0,index_all.forEach)(obj, function (value, key) { key.indexOf('_') === 0 && delete obj[key]; }); (0,index_all.forEach)(defaults, function (value, key) { if (obj[key] === value) delete obj[key]; }); (0,index_all.forEach)(['attributes', 'head'], function (prop) { if ((0,index_all.isEmpty)(obj[prop])) delete obj[prop]; }); return obj; }; return Frame; }(ModuleModel/* default */.Z)); /* harmony default export */ const model_Frame = (Frame); ;// CONCATENATED MODULE: ./src/canvas/model/Frames.ts var Frames_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var Frames = /** @class */ (function (_super) { Frames_extends(Frames, _super); function Frames(module, models) { if (models === void 0) { models = []; } var _this = _super.call(this, module, models, model_Frame) || this; _this.loadedItems = 0; _this.itemsToLoad = 0; (0,index_all.bindAll)(_this, 'itemLoaded'); _this.on('add', _this.onAdd); _this.on('reset', _this.onReset); _this.on('remove', _this.onRemove); _this.forEach(function (frame) { return _this.onAdd(frame); }); return _this; } Frames.prototype.onAdd = function (frame) { this.module.framesById[frame.id] = frame; }; Frames.prototype.onReset = function (m, opts) { var _this = this; var prev = (opts === null || opts === void 0 ? void 0 : opts.previousModels) || []; prev.map(function (p) { return _this.onRemove(p); }); }; Frames.prototype.onRemove = function (frame) { frame.onRemove(); delete this.module.framesById[frame.id]; }; Frames.prototype.initRefs = function () { this.forEach(function (frame) { return frame.initRefs(); }); }; Frames.prototype.itemLoaded = function () { this.loadedItems++; if (this.loadedItems >= this.itemsToLoad) { this.trigger('loaded:all'); this.listenToLoadItems(false); } }; Frames.prototype.listenToLoad = function () { this.loadedItems = 0; this.itemsToLoad = this.length; this.listenToLoadItems(true); }; Frames.prototype.listenToLoadItems = function (on) { var _this = this; this.forEach(function (item) { return item[on ? 'on' : 'off']('loaded', _this.itemLoaded); }); }; return Frames; }(abstract_ModuleCollection)); /* harmony default export */ const model_Frames = (Frames); ;// CONCATENATED MODULE: ./src/pages/model/Page.ts var Page_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var Page = /** @class */ (function (_super) { Page_extends(Page, _super); function Page(props, opts) { if (opts === void 0) { opts = {}; } var _this = _super.call(this, props, opts) || this; var em = opts.em; var defFrame = {}; _this.em = em; if (!props.frames) { defFrame.component = props.component; defFrame.styles = props.styles; ['component', 'styles'].map(function (i) { return _this.unset(i); }); } var frms = props.frames || [defFrame]; var frames = new model_Frames(em.Canvas, frms); frames.page = _this; _this.set('frames', frames); !_this.getId() && _this.set('id', em === null || em === void 0 ? void 0 : em.Pages._createId()); em === null || em === void 0 ? void 0 : em.UndoManager.add(frames); return _this; } Page.prototype.defaults = function () { return { name: '', frames: [], _undo: true, }; }; Page.prototype.onRemove = function () { this.getFrames().reset(); }; Page.prototype.getFrames = function () { return this.get('frames'); }; /** * Get page id * @returns {String} */ Page.prototype.getId = function () { return this.id; }; /** * Get page name * @returns {String} */ Page.prototype.getName = function () { return this.get('name'); }; /** * Update page name * @param {String} name New page name * @example * page.setName('New name'); */ Page.prototype.setName = function (name) { return this.set({ name: name }); }; /** * Get all frames * @returns {Array<Frame>} * @example * const arrayOfFrames = page.getAllFrames(); */ Page.prototype.getAllFrames = function () { return this.getFrames().models || []; }; /** * Get the first frame of the page (identified always as the main one) * @returns {Frame} * @example * const mainFrame = page.getMainFrame(); */ Page.prototype.getMainFrame = function () { return this.getFrames().at(0); }; /** * Get the root component (usually is the `wrapper` component) from the main frame * @returns {Component} * @example * const rootComponent = page.getMainComponent(); * console.log(rootComponent.toHTML()); */ Page.prototype.getMainComponent = function () { var frame = this.getMainFrame(); return frame === null || frame === void 0 ? void 0 : frame.getComponent(); }; Page.prototype.toJSON = function (opts) { if (opts === void 0) { opts = {}; } var obj = common/* Model */.Hn.prototype.toJSON.call(this, opts); var defaults = (0,index_all.result)(this, 'defaults'); // Remove private keys (0,index_all.forEach)(obj, function (value, key) { key.indexOf('_') === 0 && delete obj[key]; }); (0,index_all.forEach)(defaults, function (value, key) { if (obj[key] === value) delete obj[key]; }); return obj; }; return Page; }(common/* Model */.Hn)); /* harmony default export */ const model_Page = (Page); ;// CONCATENATED MODULE: ./src/pages/model/Pages.ts var Pages_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var Pages_assign = ( false) || function () { Pages_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return Pages_assign.apply(this, arguments); }; var Pages = /** @class */ (function (_super) { Pages_extends(Pages, _super); function Pages(models, em) { var _this = _super.call(this, models) || this; _this.on('reset', _this.onReset); _this.on('remove', _this.onRemove); // @ts-ignore We need to inject `em` for pages created on reset from the Storage load _this.model = function (props, opts) { if (opts === void 0) { opts = {}; } return new model_Page(props, Pages_assign(Pages_assign({}, opts), { em: em })); }; return _this; } Pages.prototype.onReset = function (m, opts) { var _this = this; var _a; (_a = opts === null || opts === void 0 ? void 0 : opts.previousModels) === null || _a === void 0 ? void 0 : _a.map(function (p) { return _this.onRemove(p); }); }; Pages.prototype.onRemove = function (removed) { removed === null || removed === void 0 ? void 0 : removed.onRemove(); }; return Pages; }(common/* Collection */.FE)); /* harmony default export */ const model_Pages = (Pages); ;// CONCATENATED MODULE: ./src/pages/index.ts /** * You can customize the initial state of the module from the editor initialization * ```js * const editor = grapesjs.init({ * .... * pageManager: { * pages: [ * { * id: 'page-id', * styles: `.my-class { color: red }`, // or a JSON of styles * component: '<div class="my-class">My element</div>', // or a JSON of components * } * ] * }, * }) * ``` * * Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance * * ```js * const pageManager = editor.Pages; * ``` * * ## Available Events * * `page:add` - Added new page. The page is passed as an argument to the callback * * `page:remove` - Page removed. The page is passed as an argument to the callback * * `page:select` - New page selected. The newly selected page and the previous one, are passed as arguments to the callback * * `page:update` - Page updated. The updated page and the object containing changes are passed as arguments to the callback * * `page` - Catch-all event for all the events mentioned above. An object containing all the available data about the triggered event is passed as an argument to the callback * * ## Methods * * [add](#add) * * [get](#get) * * [getAll](#getall) * * [getAllWrappers](#getallwrappers) * * [getMain](#getmain) * * [remove](#remove) * * [select](#select) * * [getSelected](#getselected) * * [Page]: page.html * [Component]: component.html * * @module Pages */ var pages_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var pages_spreadArray = ( false) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var pages_evAll = 'page'; var pages_evPfx = "".concat(pages_evAll, ":"); var evPageSelect = "".concat(pages_evPfx, "select"); var evPageSelectBefore = "".concat(evPageSelect, ":before"); var evPageUpdate = "".concat(pages_evPfx, "update"); var evPageAdd = "".concat(pages_evPfx, "add"); var evPageAddBefore = "".concat(evPageAdd, ":before"); var evPageRemove = "".concat(pages_evPfx, "remove"); var evPageRemoveBefore = "".concat(evPageRemove, ":before"); var pages_chnSel = 'change:selected'; var typeMain = 'main'; var pageEvents = { all: pages_evAll, select: evPageSelect, selectBefore: evPageSelectBefore, update: evPageUpdate, add: evPageAdd, addBefore: evPageAddBefore, remove: evPageRemove, removeBefore: evPageRemoveBefore, }; var PageManager = /** @class */ (function (_super) { pages_extends(PageManager, _super); /** * Get all pages * @name getAll * @function * @returns {Array<[Page]>} * @example * const arrayOfPages = pageManager.getAll(); */ /** * Initialize module * @hideconstructor * @param {Object} config Configurations */ function PageManager(em) { var _this = _super.call(this, em, 'PageManager', new model_Pages([], em), pageEvents) || this; _this.storageKey = 'pages'; (0,index_all.bindAll)(_this, '_onPageChange'); var model = new ModuleModel/* default */.Z({ _undo: true }); _this.model = model; _this.pages.on('reset', function (coll) { return coll.at(0) && _this.select(coll.at(0)); }); _this.pages.on('all', _this.__onChange, _this); model.on(pages_chnSel, _this._onPageChange); return _this; } Object.defineProperty(PageManager.prototype, "pages", { get: function () { return this.all; }, enumerable: false, configurable: true }); PageManager.prototype.getAll = function () { // this avoids issues during the TS build (some getAll are inconsistent) return pages_spreadArray([], this.all.models, true); }; PageManager.prototype.__onChange = function (event, page, coll, opts) { var options = opts || coll; this.em.trigger(pages_evAll, { event: event, page: page, options: options }); }; PageManager.prototype.onLoad = function () { var _a; var _b = this, pages = _b.pages, config = _b.config, em = _b.em; var opt = { silent: true }; var configPages = ((_a = config.pages) === null || _a === void 0 ? void 0 : _a.map(function (page) { return new model_Page(page, { em: em, config: config }); })) || []; pages.add(configPages, opt); var mainPage = !pages.length ? this.add({ type: typeMain }, opt) : this.getMain(); mainPage && this.select(mainPage, opt); }; PageManager.prototype._onPageChange = function (m, page, opts) { var em = this.em; var lm = em.Layers; var mainComp = page.getMainComponent(); lm && mainComp && lm.setRoot(mainComp); em.trigger(evPageSelect, page, m.previous('selected')); this.__onChange(pages_chnSel, page, opts); }; PageManager.prototype.postLoad = function () { var _a = this, em = _a.em, model = _a.model, pages = _a.pages; var um = em.UndoManager; um.add(model); um.add(pages); pages.on('add remove reset change', function (m, c, o) { return em.changesUp(o || c); }); }; /** * Add new page * @param {Object} props Page properties * @param {Object} [opts] Options * @returns {[Page]} * @example * const newPage = pageManager.add({ * id: 'new-page-id', // without an explicit ID, a random one will be created * styles: `.my-class { color: red }`, // or a JSON of styles * component: '<div class="my-class">My element</div>', // or a JSON of components * }); */ PageManager.prototype.add = function (props, opts) { var _this = this; if (opts === void 0) { opts = {}; } var em = this.em; props.id = props.id || this._createId(); var add = function () { var page = _this.pages.add(new model_Page(props, { em: _this.em, config: _this.config }), opts); opts.select && _this.select(page); return page; }; !opts.silent && em.trigger(evPageAddBefore, props, add, opts); return !opts.abort && add(); }; /** * Remove page * @param {String|[Page]} page Page or page id * @returns {[Page]} Removed Page * @example * const removedPage = pageManager.remove('page-id'); * // or by passing the page * const somePage = pageManager.get('page-id'); * pageManager.remove(somePage); */ PageManager.prototype.remove = function (page, opts) { var _this = this; if (opts === void 0) { opts = {}; } var em = this.em; var pg = (0,index_all.isString)(page) ? this.get(page) : page; var rm = function () { pg && _this.pages.remove(pg, opts); return pg; }; !opts.silent && em.trigger(evPageRemoveBefore, pg, rm, opts); return !opts.abort && rm(); }; /** * Get page by id * @param {String} id Page id * @returns {[Page]} * @example * const somePage = pageManager.get('page-id'); */ PageManager.prototype.get = function (id) { return this.pages.filter(function (p) { return p.get(p.idAttribute) === id; })[0]; }; /** * Get main page (the first one available) * @returns {[Page]} * @example * const mainPage = pageManager.getMain(); */ PageManager.prototype.getMain = function () { var pages = this.pages; return pages.filter(function (p) { return p.get('type') === typeMain; })[0] || pages.at(0); }; /** * Get wrapper components (aka body) from all pages and frames. * @returns {Array<[Component]>} * @example * const wrappers = pageManager.getAllWrappers(); * // Get all `image` components from the project * const allImages = wrappers.map(wrp => wrp.findType('image')).flat(); */ PageManager.prototype.getAllWrappers = function () { var pages = this.getAll(); return (0,index_all.unique)((0,index_all.flatten)(pages.map(function (page) { return page.getAllFrames().map(function (frame) { return frame.getComponent(); }); }))); }; /** * Change the selected page. This will switch the page rendered in canvas * @param {String|[Page]} page Page or page id * @returns {this} * @example * pageManager.select('page-id'); * // or by passing the page * const somePage = pageManager.get('page-id'); * pageManager.select(somePage); */ PageManager.prototype.select = function (page, opts) { if (opts === void 0) { opts = {}; } var pg = (0,index_all.isString)(page) ? this.get(page) : page; if (pg) { this.em.trigger(evPageSelectBefore, pg, opts); this.model.set('selected', pg, opts); } return this; }; /** * Get the selected page * @returns {[Page]} * @example * const selectedPage = pageManager.getSelected(); */ PageManager.prototype.getSelected = function () { return this.model.get('selected'); }; PageManager.prototype.destroy = function () { var _this = this; this.pages.off().reset(); this.model.stopListening(); this.model.clear({ silent: true }); //@ts-ignore ['selected', 'model'].map(function (i) { return (_this[i] = 0); }); }; PageManager.prototype.store = function () { return this.getProjectData(); }; PageManager.prototype.load = function (data) { var result = this.loadProjectData(data, { all: this.pages, reset: true }); this.pages.forEach(function (page) { return page.getFrames().initRefs(); }); return result; }; PageManager.prototype._createId = function () { var pages = this.getAll(); var len = pages.length + 16; var pagesMap = this.getAllMap(); var id; do { id = (0,mixins.createId)(len); } while (pagesMap[id]); return id; }; return PageManager; }(ItemManagerModule)); /* harmony default export */ const pages = (PageManager); ;// CONCATENATED MODULE: ./src/canvas/model/Canvas.ts var Canvas_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var Canvas = /** @class */ (function (_super) { Canvas_extends(Canvas, _super); function Canvas(module) { var _this = this; var em = module.em, config = module.config; var scripts = config.scripts, styles = config.styles; _this = _super.call(this, module, { scripts: scripts, styles: styles }) || this; _this.set('frames', new model_Frames(module)); _this.on('change:zoom', _this.onZoomChange); _this.on('change:x change:y', _this.onCoordsChange); _this.on('change:pointer change:pointerScreen', _this.onPointerChange); _this.listenTo(em, "change:device ".concat(evUpdate), _this.updateDevice); _this.listenTo(em, evPageSelect, _this._pageUpdated); return _this; } Canvas.prototype.defaults = function () { return { frame: '', frames: [], rulers: false, zoom: 100, x: 0, y: 0, // Scripts to apply on all frames scripts: [], // Styles to apply on all frames styles: [], pointer: common/* DEFAULT_COORDS */.pH, pointerScreen: common/* DEFAULT_COORDS */.pH, }; }; Object.defineProperty(Canvas.prototype, "frames", { get: function () { return this.get('frames'); }, enumerable: false, configurable: true }); Canvas.prototype.init = function () { var em = this.em; var mainPage = em.Pages.getMain(); this.set('frames', mainPage.getFrames()); this.updateDevice({ frame: mainPage.getMainFrame() }); }; Canvas.prototype._pageUpdated = function (page, prev) { var em = this.em; em.setSelected(); em.get('readyCanvas') && em.stopDefault(); // We have to stop before changing current frames prev === null || prev === void 0 ? void 0 : prev.getFrames().map(function (frame) { return frame.disable(); }); this.set('frames', page.getFrames()); this.updateDevice({ frame: page.getMainFrame() }); }; Canvas.prototype.updateDevice = function (opts) { if (opts === void 0) { opts = {}; } var em = this.em; var device = em.getDeviceModel(); var model = opts.frame || em.getCurrentFrameModel(); if (model && device) { var _a = device.attributes, width = _a.width, height = _a.height; model.set({ width: width, height: height }, { noUndo: 1 }); } }; Canvas.prototype.onZoomChange = function () { var _a = this, em = _a.em, module = _a.module; var zoom = this.get('zoom'); zoom < 1 && this.set('zoom', 1); em.trigger(module.events.zoom); }; Canvas.prototype.onCoordsChange = function () { var _a = this, em = _a.em, module = _a.module; em.trigger(module.events.coords); }; Canvas.prototype.onPointerChange = function () { var _a = this, em = _a.em, module = _a.module; em.trigger(module.events.pointer); }; Canvas.prototype.getPointerCoords = function (type) { if (type === void 0) { type = common/* CoordinatesTypes */.vA.World; } var _a = this.attributes, pointer = _a.pointer, pointerScreen = _a.pointerScreen; return type === common/* CoordinatesTypes */.vA.World ? pointer : pointerScreen; }; return Canvas; }(ModuleModel/* default */.Z)); /* harmony default export */ const model_Canvas = (Canvas); // EXTERNAL MODULE: ./src/canvas/model/CanvasSpot.ts var CanvasSpot = __nested_webpack_require_911993__(675); ;// CONCATENATED MODULE: ./src/canvas/model/CanvasSpots.ts var CanvasSpots_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var CanvasSpots = /** @class */ (function (_super) { CanvasSpots_extends(CanvasSpots, _super); function CanvasSpots(module, models) { if (models === void 0) { models = []; } var _this = _super.call(this, module, models, CanvasSpot/* default */.Z) || this; _this.on('add', _this.onAdd); _this.on('change', _this.onChange); _this.on('remove', _this.onRemove); var em = _this.em; _this.refreshDbn = (0,index_all.debounce)(function () { return _this.refresh(); }, 0); var evToRefreshDbn = 'component:resize styleable:change component:input component:update frame:updated undo redo'; _this.listenTo(em, evToRefreshDbn, function () { return _this.refreshDbn(); }); return _this; } Object.defineProperty(CanvasSpots.prototype, "em", { get: function () { return this.module.em; }, enumerable: false, configurable: true }); Object.defineProperty(CanvasSpots.prototype, "events", { get: function () { return this.module.events; }, enumerable: false, configurable: true }); CanvasSpots.prototype.refresh = function () { var _a = this, em = _a.em, events = _a.events; em.trigger(events.spot); }; CanvasSpots.prototype.onAdd = function (spot) { this.__trgEvent(this.events.spotAdd, { spot: spot }); }; CanvasSpots.prototype.onChange = function (spot) { this.__trgEvent(this.events.spotUpdate, { spot: spot }); }; CanvasSpots.prototype.onRemove = function (spot) { this.__trgEvent(this.events.spotRemove, { spot: spot }); }; CanvasSpots.prototype.__trgEvent = function (event, props) { var module = this.module; var em = module.em; em.trigger(event, props); this.refreshDbn(); }; return CanvasSpots; }(abstract_ModuleCollection)); /* harmony default export */ const model_CanvasSpots = (CanvasSpots); ;// CONCATENATED MODULE: ./src/canvas/types.ts /**{START_EVENTS}*/ var CanvasEvents; (function (CanvasEvents) { /** * @event `canvas:dragenter` Something is dragged inside the canvas, `DataTransfer` instance passed as an argument. */ CanvasEvents["dragEnter"] = "canvas:dragenter"; /** * @event `canvas:dragover` Something is dragging on the canvas, `DataTransfer` instance passed as an argument. */ CanvasEvents["dragOver"] = "canvas:dragover"; /** * @event `canvas:dragend` When a drag operation is ended, `DataTransfer` instance passed as an argument. */ CanvasEvents["dragEnd"] = "canvas:dragend"; /** * @event `canvas:dragdata` On any dataTransfer parse, `DataTransfer` instance and the `result` are passed as arguments. * By changing `result.content` you're able to customize what is dropped. */ CanvasEvents["dragData"] = "canvas:dragdata"; /** * @event `canvas:drop` Something is dropped in canvas, `DataTransfer` instance and the dropped model are passed as arguments. */ CanvasEvents["drop"] = "canvas:drop"; /** * @event `canvas:spot` Spots updated. * @example * editor.on('canvas:spot', () => { * console.log('Spots', editor.Canvas.getSpots()); * }); */ CanvasEvents["spot"] = "canvas:spot"; /** * @event `canvas:spot:add` New canvas spot added. * @example * editor.on('canvas:spot:add', ({ spot }) => { * console.log('Spot added', spot); * }); */ CanvasEvents["spotAdd"] = "canvas:spot:add"; /** * @event `canvas:spot:update` Canvas spot updated. * @example * editor.on('canvas:spot:update', ({ spot }) => { * console.log('Spot updated', spot); * }); */ CanvasEvents["spotUpdate"] = "canvas:spot:update"; /** * @event `canvas:spot:remove` Canvas spot removed. * @example * editor.on('canvas:spot:remove', ({ spot }) => { * console.log('Spot removed', spot); * }); */ CanvasEvents["spotRemove"] = "canvas:spot:remove"; /** * @event `canvas:coords` Canvas coordinates updated. * @example * editor.on('canvas:coords', () => { * console.log('Canvas coordinates updated:', editor.Canvas.getCoords()); * }); */ CanvasEvents["coords"] = "canvas:coords"; /** * @event `canvas:zoom` Canvas zoom updated. * @example * editor.on('canvas:zoom', () => { * console.log('Canvas zoom updated:', editor.Canvas.getZoom()); * }); */ CanvasEvents["zoom"] = "canvas:zoom"; /** * @event `canvas:pointer` Canvas pointer updated. * @example * editor.on('canvas:pointer', () => { * console.log('Canvas pointer updated:', editor.Canvas.getPointer()); * }); */ CanvasEvents["pointer"] = "canvas:pointer"; })(CanvasEvents || (CanvasEvents = {})); /**{END_EVENTS}*/ // need this to avoid the TS documentation generator to break /* harmony default export */ const types = ((/* unused pure expression or super */ null && (0))); ;// CONCATENATED MODULE: ./src/abstract/ModuleView.ts var ModuleView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); // type TCollection<TItem extends ModuleModel | ModuleCollection> = TItem extends ModuleCollection ? TItem : unknown; var ModuleView = /** @class */ (function (_super) { ModuleView_extends(ModuleView, _super); function ModuleView() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(ModuleView.prototype, "pfx", { get: function () { return this.ppfx + this.config.stylePrefix || ''; }, enumerable: false, configurable: true }); Object.defineProperty(ModuleView.prototype, "ppfx", { get: function () { return this.em.config.stylePrefix || ''; }, enumerable: false, configurable: true }); Object.defineProperty(ModuleView.prototype, "module", { get: function () { var _a, _b; return (_b = (_a = this.model) === null || _a === void 0 ? void 0 : _a.module) !== null && _b !== void 0 ? _b : this.collection.module; }, enumerable: false, configurable: true }); Object.defineProperty(ModuleView.prototype, "em", { get: function () { return this.module.em; }, enumerable: false, configurable: true }); Object.defineProperty(ModuleView.prototype, "config", { get: function () { return this.module.config; }, enumerable: false, configurable: true }); ModuleView.prototype.preinitialize = function (options) { this.className = ''; }; return ModuleView; }(common/* View */.G7)); /* harmony default export */ const abstract_ModuleView = (ModuleView); // EXTERNAL MODULE: ./src/utils/dom.ts var dom = __nested_webpack_require_911993__(491); ;// CONCATENATED MODULE: ./src/abstract/ModuleDomainViews.ts var ModuleDomainViews_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ModuleDomainViews = /** @class */ (function (_super) { ModuleDomainViews_extends(ModuleDomainViews, _super); function ModuleDomainViews(opts, autoAdd) { if (opts === void 0) { opts = {}; } if (autoAdd === void 0) { autoAdd = false; } var _this = _super.call(this, opts) || this; // Defines the View per type _this.itemsView = ''; _this.itemType = 'type'; _this.reuseView = false; _this.viewCollection = []; autoAdd && _this.listenTo(_this.collection, 'add', _this.addTo); return _this; } /** * Add new model to the collection * @param {ModuleModel} model * @private * */ ModuleDomainViews.prototype.addTo = function (model) { this.add(model); }; ModuleDomainViews.prototype.itemViewNotFound = function (type) { /*const { em, ns } = this; const warn = `${ns ? `[${ns}]: ` : ''}'${type}' type not found`; em?.logWarning(warn);*/ }; /** * Render new model inside the view * @param {ModuleModel} model * @param {Object} fragment Fragment collection * @private * */ ModuleDomainViews.prototype.add = function (model, fragment) { var _a = this, reuseView = _a.reuseView, viewCollection = _a.viewCollection; var frag = fragment || null; var typeField = model.get(this.itemType); var view; //@ts-ignore if (model.view && reuseView) { //@ts-ignore view = model.view; } else { view = this.renderView(model, typeField); } viewCollection.push(view); var rendered = view.render().el; if (frag) frag.appendChild(rendered); else this.$el.append(rendered); }; ModuleDomainViews.prototype.render = function () { var _this = this; var frag = document.createDocumentFragment(); this.clearItems(); this.$el.empty(); if (this.collection.length) this.collection.each(function (model) { return _this.add(model, frag); }); this.$el.append(frag); this.onRender(); return this; }; ModuleDomainViews.prototype.onRender = function () { }; ModuleDomainViews.prototype.onRemoveBefore = function (items, opts) { }; ModuleDomainViews.prototype.onRemove = function (items, opts) { }; ModuleDomainViews.prototype.remove = function (opts) { if (opts === void 0) { opts = {}; } var viewCollection = this.viewCollection; this.onRemoveBefore(viewCollection, opts); this.clearItems(); common/* View */.G7.prototype.remove.apply(this, opts); this.onRemove(viewCollection, opts); return this; }; ModuleDomainViews.prototype.clearItems = function () { var items = this.viewCollection || []; // TODO Traits do not update the target anymore // items.forEach(item => item.remove()); // this.items = []; }; return ModuleDomainViews; }(abstract_ModuleView)); /* harmony default export */ const abstract_ModuleDomainViews = (ModuleDomainViews); ;// CONCATENATED MODULE: ./src/css_composer/view/CssRuleView.ts var CssRuleView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var CssRuleView = /** @class */ (function (_super) { CssRuleView_extends(CssRuleView, _super); function CssRuleView(o) { if (o === void 0) { o = {}; } var _this = _super.call(this, o) || this; _this.config = o.config || {}; var model = _this.model; _this.listenTo(model, 'change', _this.render); _this.listenTo(model, 'destroy remove', _this.remove); _this.listenTo(model.get('selectors'), 'change', _this.render); return _this; } // @ts-ignore CssRuleView.prototype.tagName = function () { return 'style'; }; CssRuleView.prototype.render = function () { var _a = this, model = _a.model, el = _a.el; var important = model.get('important'); el.innerHTML = model.toCSS({ important: important }); return this; }; return CssRuleView; }(common/* View */.G7)); /* harmony default export */ const view_CssRuleView = (CssRuleView); ;// CONCATENATED MODULE: ./src/css_composer/view/CssGroupRuleView.ts var CssGroupRuleView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var CssGroupRuleView = /** @class */ (function (_super) { CssGroupRuleView_extends(CssGroupRuleView, _super); function CssGroupRuleView() { return _super !== null && _super.apply(this, arguments) || this; } CssGroupRuleView.prototype._createElement = function () { return document.createTextNode(''); }; CssGroupRuleView.prototype.render = function () { var model = this.model; var important = model.get('important'); this.el.textContent = model.getDeclaration({ important: important }); return this; }; return CssGroupRuleView; }(view_CssRuleView)); /* harmony default export */ const view_CssGroupRuleView = (CssGroupRuleView); ;// CONCATENATED MODULE: ./src/css_composer/view/CssRulesView.ts var CssRulesView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var getBlockId = function (pfx, order) { return "".concat(pfx).concat(order ? "-".concat(parseFloat(order)) : ''); }; var CssRulesView = /** @class */ (function (_super) { CssRulesView_extends(CssRulesView, _super); function CssRulesView(o) { var _this = _super.call(this, o) || this; (0,index_all.bindAll)(_this, 'sortRules'); var config = o.config || {}; _this.atRules = {}; _this.config = config; _this.em = config.em; _this.pfx = config.stylePrefix || ''; _this.className = _this.pfx + 'rules'; var coll = _this.collection; _this.listenTo(coll, 'add', _this.addTo); _this.listenTo(coll, 'reset', _this.render); return _this; } /** * Add to collection * @param {Object} model * @private * */ CssRulesView.prototype.addTo = function (model) { this.addToCollection(model); }; /** * Add new object to collection * @param {Object} model * @param {Object} fragmentEl * @return {Object} * @private * */ CssRulesView.prototype.addToCollection = function (model, fragmentEl) { // If the render is not yet started if (!this.renderStarted) { return; } var fragment = fragmentEl || null; var config = this.config; var opts = { model: model, config: config }; var rendered, view; // I have to render keyframes of the same name together // Unfortunately at the moment I didn't find the way of appending them // if not staticly, via appendData if (model.get('atRuleType') === 'keyframes') { var atRule = model.getAtRule(); var atRuleEl = this.atRules[atRule]; if (!atRuleEl) { var styleEl = document.createElement('style'); atRuleEl = document.createTextNode(''); styleEl.appendChild(document.createTextNode("".concat(atRule, "{"))); styleEl.appendChild(atRuleEl); styleEl.appendChild(document.createTextNode('}')); this.atRules[atRule] = atRuleEl; rendered = styleEl; } view = new view_CssGroupRuleView(opts); atRuleEl.appendData(view.render().el.textContent); } else { view = new view_CssRuleView(opts); rendered = view.render().el; } var clsName = this.className; var mediaText = model.get('mediaText'); var defaultBlockId = getBlockId(clsName); var blockId = defaultBlockId; // If the rule contains a media query it might have a different container // for it (eg. rules created with Device Manager) if (mediaText) { blockId = getBlockId(clsName, this.getMediaWidth(mediaText)); } if (rendered) { var container = fragment || this.el; var contRules = void 0; // Try to find a specific container for the rule (if it // containes a media query), otherwise get the default one try { contRules = container.querySelector("#".concat(blockId)); } catch (e) { } if (!contRules) { contRules = container.querySelector("#".concat(defaultBlockId)); } contRules === null || contRules === void 0 ? void 0 : contRules.appendChild(rendered); } return rendered; }; CssRulesView.prototype.getMediaWidth = function (mediaText) { return mediaText && mediaText.replace("(".concat(this.em.getConfig().mediaCondition, ": "), '').replace(')', ''); }; CssRulesView.prototype.sortRules = function (a, b) { var em = this.em; var isMobFirst = (em.getConfig().mediaCondition || '').indexOf('min-width') !== -1; if (!isMobFirst) return 0; var left = isMobFirst ? a : b; var right = isMobFirst ? b : a; return left - right; }; CssRulesView.prototype.render = function () { var _this = this; this.renderStarted = true; this.atRules = {}; var _a = this, em = _a.em, $el = _a.$el, collection = _a.collection; var cls = this.className; var frag = document.createDocumentFragment(); $el.empty(); // Create devices related DOM structure, ensure also to have a default container var prs = em.Devices.getAll().pluck('priority').sort(this.sortRules); prs.every(function (pr) { return pr; }) && prs.unshift(0); prs.forEach(function (pr) { return frag.appendChild((0,dom/* createEl */.ut)('div', { id: getBlockId(cls, pr) })); }); collection.each(function (model) { return _this.addToCollection(model, frag); }); $el.append(frag); $el.attr('class', cls); return this; }; return CssRulesView; }(common/* View */.G7)); /* harmony default export */ const view_CssRulesView = (CssRulesView); ;// CONCATENATED MODULE: ./src/utils/Droppable.ts var Droppable_assign = ( false) || function () { Droppable_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return Droppable_assign.apply(this, arguments); }; /** * This class makes the canvas droppable */ var Droppable = /** @class */ (function () { function Droppable(em, rootEl) { var _this = this; this.em = em; this.canvas = em.Canvas; var el = rootEl || this.canvas.getFrames().map(function (frame) { return frame.getComponent().getEl(); }); var els = Array.isArray(el) ? el : [el]; this.el = els[0]; this.counter = 0; (0,index_all.bindAll)(this, 'handleDragEnter', 'handleDragOver', 'handleDrop', 'handleDragLeave'); els.forEach(function (el) { return _this.toggleEffects(el, true); }); } Droppable.prototype.toggleEffects = function (el, enable) { var methods = { on: dom.on, off: dom/* off */.S1 }; var method = enable ? 'on' : 'off'; methods[method](el, 'dragenter', this.handleDragEnter); methods[method](el, 'dragover', this.handleDragOver); methods[method](el, 'drop', this.handleDrop); methods[method](el, 'dragleave', this.handleDragLeave); }; Droppable.prototype.__customTglEff = function (enable) { var _a; var method = enable ? dom.on : dom/* off */.S1; var doc = this.el.ownerDocument; var frameEl = (_a = doc.defaultView) === null || _a === void 0 ? void 0 : _a.frameElement; this.sortOpts = enable ? { onStart: function (_a) { var sorter = _a.sorter; (0,dom.on)(frameEl, 'pointermove', sorter.onMove); }, onEnd: function (_a) { var sorter = _a.sorter; (0,dom/* off */.S1)(frameEl, 'pointermove', sorter.onMove); }, customTarget: function (_a) { var event = _a.event; return doc.elementFromPoint(event.clientX, event.clientY); }, } : null; method(frameEl, 'pointerenter', this.handleDragEnter); method(frameEl, 'pointermove', this.handleDragOver); method(document, 'pointerup', this.handleDrop); method(frameEl, 'pointerout', this.handleDragLeave); // Test with touch devices (seems like frameEl is not capturing pointer events). // on/off(document, 'pointermove', sorter.onMove); // for the sorter // enable && this.handleDragEnter({}); // no way to use pointerenter/pointerout }; Droppable.prototype.startCustom = function () { this.__customTglEff(true); }; Droppable.prototype.endCustom = function (cancel) { this.over ? this.endDrop(cancel) : this.__customTglEff(false); }; /** * This function is expected to be always executed at the end of d&d. */ Droppable.prototype.endDrop = function (cancel, ev) { var _a = this, em = _a.em, dragStop = _a.dragStop; this.counter = 0; dragStop && dragStop(cancel || !this.over); this.__customTglEff(false); em.trigger('canvas:dragend', ev); }; Droppable.prototype.handleDragLeave = function (ev) { this.updateCounter(-1, ev); }; Droppable.prototype.updateCounter = function (value, ev) { this.counter += value; this.counter === 0 && this.endDrop(true, ev); }; Droppable.prototype.handleDragEnter = function (ev) { var _this = this; var _a = this, em = _a.em, canvas = _a.canvas; var dt = ev.dataTransfer; var dragContentOrigin = em.get('dragContent'); if (!dragContentOrigin && !canvas.getConfig().allowExternalDrop) { return; } this.updateCounter(1, ev); if (this.over) return; this.over = true; var utils = em.Utils; // For security reason I can't read the drag data on dragenter, but // as I need it for the Sorter context I will use `dragContent` or just // any not empty element var content = dragContentOrigin || '<br>'; var dragStop; var dragContent; em.stopDefault(); // Select the right drag provider if (em.inAbsoluteMode()) { var wrapper_1 = em.Components.getWrapper(); var target_1 = wrapper_1.append({})[0]; var dragger_1 = em.Commands.run('core:component-drag', { event: ev, guidesInfo: 1, center: 1, target: target_1, onEnd: function (ev, dragger, _a) { var cancelled = _a.cancelled; var comp; if (!cancelled) { comp = wrapper_1.append(content)[0]; var canvasOffset = canvas.getOffset(); var _b = target_1.getStyle(), top_1 = _b.top, left = _b.left, position = _b.position; var scroll_1 = (0,dom/* getDocumentScroll */.GX)(ev.target); var postLeft = parseInt("".concat(parseFloat(left) + scroll_1.x - canvasOffset.left), 10); var posTop = parseInt("".concat(parseFloat(top_1) + scroll_1.y - canvasOffset.top), 10); comp.addStyle({ left: postLeft + 'px', top: posTop + 'px', position: position, }); } _this.handleDragEnd(comp, dt); target_1.remove(); }, }); dragStop = function (cancel) { return dragger_1.stop(ev, { cancel: cancel }); }; dragContent = function (cnt) { return (content = cnt); }; } else { var sorter_1 = new utils.Sorter(Droppable_assign({ // @ts-ignore em: em, wmargin: 1, nested: 1, canvasRelative: 1, direction: 'a', container: this.el, placer: canvas.getPlacerEl(), containerSel: '*', itemSel: '*', pfx: 'gjs-', onEndMove: function (model) { return _this.handleDragEnd(model, dt); }, document: this.el.ownerDocument }, (this.sortOpts || {}))); sorter_1.setDropContent(content); sorter_1.startSort(); this.sorter = sorter_1; dragStop = function (cancel) { cancel && (sorter_1.moved = false); sorter_1.endMove(); }; dragContent = function (content) { return sorter_1.setDropContent(content); }; } this.dragStop = dragStop; this.dragContent = dragContent; em.trigger('canvas:dragenter', dt, content); }; Droppable.prototype.handleDragEnd = function (model, dt) { var em = this.em; this.over = false; if (model) { em.set('dragResult', model); em.trigger('canvas:drop', dt, model); } em.runDefault({ preserveSelected: 1 }); }; /** * Always need to have this handler active for enabling the drop * @param {Event} ev */ Droppable.prototype.handleDragOver = function (ev) { ev.preventDefault(); this.em.trigger('canvas:dragover', ev); }; /** * WARNING: This function might fail to run on drop, for example, when the * drop, accidentally, happens on some external element (DOM not inside the iframe) */ Droppable.prototype.handleDrop = function (ev) { ev.preventDefault(); var dragContent = this.dragContent; var dt = ev.dataTransfer; var content = this.getContentByData(dt).content; ev.target.style.border = ''; content && dragContent && dragContent(content); this.endDrop(!content, ev); }; Droppable.prototype.getContentByData = function (dt) { var em = this.em; var types = dt && dt.types; var files = (dt && dt.files) || []; var dragContent = em.get('dragContent'); var content = dt && dt.getData('text'); if (files.length) { content = []; for (var i = 0; i < files.length; i++) { var file = files[i]; var type = file.type.split('/')[0]; if (type == 'image') { content.push({ type: type, file: file, attributes: { alt: file.name }, }); } } } else if (dragContent) { content = dragContent; } else if ((0,index_all.indexOf)(types, 'text/html') >= 0) { content = dt && dt.getData('text/html').replace(/<\/?meta[^>]*>/g, ''); } else if ((0,index_all.indexOf)(types, 'text/uri-list') >= 0) { content = { type: 'link', attributes: { href: content }, content: content, }; } else if ((0,index_all.indexOf)(types, 'text/json') >= 0) { var json = dt && dt.getData('text/json'); json && (content = JSON.parse(json)); } else if (types.length === 1 && types[0] === 'text/plain') { // Avoid dropping non-selectable and non-editable text nodes inside the editor content = "<div>".concat(content, "</div>"); } var result = { content: content }; em.trigger('canvas:dragdata', dt, result); return result; }; return Droppable; }()); /* harmony default export */ const utils_Droppable = (Droppable); ;// CONCATENATED MODULE: ./src/canvas/view/FrameView.ts var FrameView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var FrameView_assign = ( false) || function () { FrameView_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return FrameView_assign.apply(this, arguments); }; var FrameView_spreadArray = ( false) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var FrameView = /** @class */ (function (_super) { FrameView_extends(FrameView, _super); function FrameView(model, view) { var _this = _super.call(this, { model: model }) || this; _this.dragging = false; _this.loaded = false; _this.lastMaxHeight = 0; _this.tools = {}; (0,index_all.bindAll)(_this, 'updateClientY', 'stopAutoscroll', 'autoscroll', '_emitUpdate'); var el = _this.el; //@ts-ignore _this.module._config = FrameView_assign(FrameView_assign({}, (_this.config || {})), { //@ts-ignore frameView: _this }); _this.frameWrapView = view; _this.showGlobalTools = (0,index_all.debounce)(_this.showGlobalTools.bind(_this), 50); var cvModel = _this.getCanvasModel(); _this.listenTo(model, 'change:head', _this.updateHead); _this.listenTo(cvModel, 'change:styles', _this.renderStyles); model.view = _this; (0,mixins.setViewEl)(el, _this); return _this; } Object.defineProperty(FrameView.prototype, "tagName", { /** @ts-ignore */ get: function () { return 'iframe'; }, enumerable: false, configurable: true }); Object.defineProperty(FrameView.prototype, "attributes", { /** @ts-ignore */ get: function () { return { allowfullscreen: 'allowfullscreen' }; }, enumerable: false, configurable: true }); FrameView.prototype.getBoxRect = function () { var _a = this, el = _a.el, module = _a.module; var canvasView = module.getCanvasView(); var coords = module.getCoords(); var frameRect = el.getBoundingClientRect(); var canvasRect = canvasView.getCanvasOffset(); var vwDelta = canvasView.getViewportDelta(); var zoomM = module.getZoomMultiplier(); var x = (frameRect.x - canvasRect.left - vwDelta.x - coords.x) * zoomM; var y = (frameRect.y - canvasRect.top - vwDelta.y - coords.y) * zoomM; var width = frameRect.width * zoomM; var height = frameRect.height * zoomM; return { x: x, y: y, width: width, height: height, }; }; /** * Update `<head>` content of the frame */ FrameView.prototype.updateHead = function () { var model = this.model; var headEl = this.getHead(); var toRemove = []; var toAdd = []; var current = model.head; var prev = model.previous('head'); var attrStr = function (attr) { if (attr === void 0) { attr = {}; } return Object.keys(attr) .sort() .map(function (i) { return "[".concat(i, "=\"").concat(attr[i], "\"]"); }) .join(''); }; var find = function (items, stack, res) { items.forEach(function (item) { var tag = item.tag, attributes = item.attributes; var has = stack.some(function (s) { return s.tag === tag && attrStr(s.attributes) === attrStr(attributes); }); !has && res.push(item); }); }; find(current, prev, toAdd); find(prev, current, toRemove); toRemove.forEach(function (stl) { var _a; var el = headEl.querySelector("".concat(stl.tag).concat(attrStr(stl.attributes))); (_a = el === null || el === void 0 ? void 0 : el.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(el); }); (0,dom/* appendVNodes */.SJ)(headEl, toAdd); }; FrameView.prototype.getEl = function () { return this.el; }; FrameView.prototype.getCanvasModel = function () { return this.em.Canvas.getModel(); }; FrameView.prototype.getWindow = function () { return this.getEl().contentWindow; }; FrameView.prototype.getDoc = function () { return this.getEl().contentDocument; }; FrameView.prototype.getHead = function () { return this.getDoc().querySelector('head'); }; FrameView.prototype.getBody = function () { return this.getDoc().querySelector('body'); }; FrameView.prototype.getWrapper = function () { return this.getBody().querySelector('[data-gjs-type=wrapper]'); }; FrameView.prototype.getJsContainer = function () { if (!this.jsContainer) { this.jsContainer = (0,dom/* createEl */.ut)('div', { class: "".concat(this.ppfx, "js-cont") }); } return this.jsContainer; }; FrameView.prototype.getToolsEl = function () { var _a; return (_a = this.frameWrapView) === null || _a === void 0 ? void 0 : _a.elTools; }; FrameView.prototype.getGlobalToolsEl = function () { return this.em.Canvas.getGlobalToolsEl(); }; FrameView.prototype.getHighlighter = function () { return this._getTool('[data-hl]'); }; FrameView.prototype.getBadgeEl = function () { return this._getTool('[data-badge]'); }; FrameView.prototype.getOffsetViewerEl = function () { return this._getTool('[data-offset]'); }; FrameView.prototype.getRect = function () { if (!this.rect) { this.rect = this.el.getBoundingClientRect(); } return this.rect; }; /** * Get rect data, not affected by the canvas zoom */ FrameView.prototype.getOffsetRect = function () { var el = this.el; var _a = this.getBody(), scrollTop = _a.scrollTop, scrollLeft = _a.scrollLeft; var height = el.offsetHeight; var width = el.offsetWidth; return { top: el.offsetTop, left: el.offsetLeft, height: height, width: width, scrollTop: scrollTop, scrollLeft: scrollLeft, scrollBottom: scrollTop + height, scrollRight: scrollLeft + width, }; }; FrameView.prototype._getTool = function (name) { var tools = this.tools; var toolsEl = this.getToolsEl(); if (!tools[name]) { tools[name] = toolsEl.querySelector(name); } return tools[name]; }; FrameView.prototype.remove = function () { var _a; var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } this._toggleEffects(false); this.tools = {}; (_a = this.wrapper) === null || _a === void 0 ? void 0 : _a.remove(); abstract_ModuleView.prototype.remove.apply(this, args); return this; }; FrameView.prototype.startAutoscroll = function () { var _this = this; this.lastMaxHeight = this.getWrapper().offsetHeight - this.el.offsetHeight; // By detaching those from the stack avoid browsers lags // Noticeable with "fast" drag of blocks setTimeout(function () { _this._toggleAutoscrollFx(true); requestAnimationFrame(_this.autoscroll); }, 0); }; FrameView.prototype.autoscroll = function () { if (this.dragging) { var lastClientY = this.lastClientY; var canvas = this.em.Canvas; var win = this.getWindow(); var actualTop = win.pageYOffset; var clientY = lastClientY || 0; var limitTop = canvas.getConfig().autoscrollLimit; var limitBottom = this.getRect().height - limitTop; var nextTop = actualTop; if (clientY < limitTop) { nextTop -= limitTop - clientY; } if (clientY > limitBottom) { nextTop += clientY - limitBottom; } if (!(0,index_all.isUndefined)(lastClientY) && // Fixes #3134 nextTop !== actualTop && nextTop > 0 && nextTop < this.lastMaxHeight) { var toolsEl = this.getGlobalToolsEl(); toolsEl.style.opacity = '0'; this.showGlobalTools(); win.scrollTo(0, nextTop); canvas.spots.refreshDbn(); } requestAnimationFrame(this.autoscroll); } }; FrameView.prototype.updateClientY = function (ev) { ev.preventDefault(); this.lastClientY = (0,dom/* getPointerEvent */.VB)(ev).clientY * this.em.getZoomDecimal(); }; FrameView.prototype.showGlobalTools = function () { this.getGlobalToolsEl().style.opacity = ''; }; FrameView.prototype.stopAutoscroll = function () { this.dragging && this._toggleAutoscrollFx(false); }; FrameView.prototype._toggleAutoscrollFx = function (enable) { this.dragging = enable; var win = this.getWindow(); var method = enable ? 'on' : 'off'; var mt = { on: dom.on, off: dom/* off */.S1 }; mt[method](win, 'mousemove dragover', this.updateClientY); mt[method](win, 'mouseup', this.stopAutoscroll); }; FrameView.prototype.render = function () { var _a = this, $el = _a.$el, ppfx = _a.ppfx, em = _a.em; $el.attr({ class: "".concat(ppfx, "frame") }); this.renderScripts(); em.trigger('frame:render', this); return this; }; FrameView.prototype.renderScripts = function () { var _this = this; var _a = this, el = _a.el, model = _a.model, em = _a.em; var evLoad = 'frame:load'; var evOpts = { el: el, model: model, view: this }; var canvas = this.getCanvasModel(); var appendScript = function (scripts) { var _a; if (scripts.length > 0) { var src = scripts.shift(); var scriptEl = (0,dom/* createEl */.ut)('script', FrameView_assign({ type: 'text/javascript' }, ((0,index_all.isString)(src) ? { src: src } : src))); scriptEl.onerror = scriptEl.onload = appendScript.bind(null, scripts); (_a = el.contentDocument) === null || _a === void 0 ? void 0 : _a.head.appendChild(scriptEl); } else { _this.renderBody(); em && em.trigger(evLoad, evOpts); } }; el.onload = function () { var frameContent = _this.config.frameContent; if (frameContent) { var doc = _this.getDoc(); doc.open(); doc.write(frameContent); doc.close(); } em && em.trigger("".concat(evLoad, ":before"), evOpts); appendScript(FrameView_spreadArray([], canvas.get('scripts'), true)); }; }; FrameView.prototype.renderStyles = function (opts) { if (opts === void 0) { opts = {}; } var head = this.getHead(); var canvas = this.getCanvasModel(); var normalize = function (stls) { return stls.map(function (href) { return ({ tag: 'link', attributes: FrameView_assign({ rel: 'stylesheet' }, ((0,index_all.isString)(href) ? { href: href } : href)), }); }); }; var prevStyles = normalize(opts.prev || canvas.previous('styles')); var styles = normalize(canvas.get('styles')); var toRemove = []; var toAdd = []; var find = function (items, stack, res) { items.forEach(function (item) { var href = item.attributes.href; var has = stack.some(function (s) { return s.attributes.href === href; }); !has && res.push(item); }); }; find(styles, prevStyles, toAdd); find(prevStyles, styles, toRemove); toRemove.forEach(function (stl) { var _a; var el = head.querySelector("link[href=\"".concat(stl.attributes.href, "\"]")); (_a = el === null || el === void 0 ? void 0 : el.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(el); }); (0,dom/* appendVNodes */.SJ)(head, toAdd); }; FrameView.prototype.renderBody = function () { var _this = this; var _a, _b; var _c = this, config = _c.config, em = _c.em, model = _c.model, ppfx = _c.ppfx; var doc = this.getDoc(); var body = this.getBody(); var win = this.getWindow(); var hasAutoHeight = model.hasAutoHeight(); var conf = em.config; //@ts-ignore This could be used inside component-related scripts to check if the // script is executed inside the editor. win._isEditor = true; this.renderStyles({ prev: [] }); var colorWarn = '#ffca6f'; (0,dom/* append */.R3)(body, "<style>\n ".concat(conf.baseCss || config.frameStyle || '', "\n\n ").concat(hasAutoHeight ? 'body { overflow: hidden }' : '', "\n\n [data-gjs-type=\"wrapper\"] {\n ").concat(!hasAutoHeight ? 'min-height: 100vh;' : '', "\n padding-top: 0.001em;\n }\n\n .").concat(ppfx, "dashed *[data-gjs-highlightable] {\n outline: 1px dashed rgba(170,170,170,0.7);\n outline-offset: -2px;\n }\n\n .").concat(ppfx, "selected {\n outline: 2px solid #3b97e3 !important;\n outline-offset: -2px;\n }\n\n .").concat(ppfx, "selected-parent {\n outline: 2px solid ").concat(colorWarn, " !important\n }\n\n .").concat(ppfx, "no-select {\n user-select: none;\n -webkit-user-select:none;\n -moz-user-select: none;\n }\n\n .").concat(ppfx, "freezed {\n opacity: 0.5;\n pointer-events: none;\n }\n\n .").concat(ppfx, "no-pointer {\n pointer-events: none;\n }\n\n .").concat(ppfx, "plh-image {\n background: #f5f5f5;\n border: none;\n height: 100px;\n width: 100px;\n display: block;\n outline: 3px solid #ffca6f;\n cursor: pointer;\n outline-offset: -2px\n }\n\n .").concat(ppfx, "grabbing {\n cursor: grabbing;\n cursor: -webkit-grabbing;\n }\n\n .").concat(ppfx, "is__grabbing {\n overflow-x: hidden;\n }\n\n .").concat(ppfx, "is__grabbing,\n .").concat(ppfx, "is__grabbing * {\n cursor: grabbing !important;\n }\n\n ").concat(conf.canvasCss || '', "\n ").concat(conf.protectedCss || '', "\n </style>")); var root = model.root; var view = em.Components.getType('wrapper').view; this.wrapper = new view({ model: root, config: FrameView_assign(FrameView_assign({}, root.config), { em: em, frameView: this }), }).render(); (0,dom/* append */.R3)(body, (_a = this.wrapper) === null || _a === void 0 ? void 0 : _a.el); (0,dom/* append */.R3)(body, new view_CssRulesView({ collection: model.getStyles(), //@ts-ignore config: FrameView_assign(FrameView_assign({}, em.Css.getConfig()), { frameView: this }), }).render().el); (0,dom/* append */.R3)(body, this.getJsContainer()); // em.trigger('loaded'); // I need to manage only the first one maybe //this.updateOffset(); // TOFIX (check if I need it) // Avoid some default behaviours //@ts-ignore (0,dom.on)(body, 'click', function (ev) { var _a; return ev && ((_a = ev.target) === null || _a === void 0 ? void 0 : _a.tagName) == 'A' && ev.preventDefault(); }); (0,dom.on)(body, 'submit', function (ev) { return ev && ev.preventDefault(); }); // When the iframe is focused the event dispatcher is not the same so // I need to delegate all events to the parent document [ { event: 'keydown keyup keypress', class: 'KeyboardEvent' }, { event: 'mousedown mousemove mouseup', class: 'MouseEvent' }, { event: 'pointerdown pointermove pointerup', class: 'PointerEvent' }, { event: 'wheel', class: 'WheelEvent', opts: { passive: !config.infiniteCanvas } }, ].forEach(function (obj) { return obj.event.split(' ').forEach(function (event) { doc.addEventListener(event, function (ev) { return _this.el.dispatchEvent((0,dom/* createCustomEvent */.t3)(ev, obj.class)); }, obj.opts); }); }); this._toggleEffects(true); if ((0,mixins.hasDnd)(em)) { this.droppable = new utils_Droppable(em, (_b = this.wrapper) === null || _b === void 0 ? void 0 : _b.el); } this.loaded = true; model.trigger('loaded'); }; FrameView.prototype._toggleEffects = function (enable) { var method = enable ? dom.on : dom/* off */.S1; var win = this.getWindow(); win && method(win, "".concat(dom/* motionsEv */.G1, " resize"), this._emitUpdate); }; FrameView.prototype._emitUpdate = function () { this.model._emitUpdated(); }; return FrameView; }(abstract_ModuleView)); /* harmony default export */ const view_FrameView = (FrameView); // EXTERNAL MODULE: ./src/utils/Dragger.ts var Dragger = __nested_webpack_require_911993__(668); ;// CONCATENATED MODULE: ./src/canvas/view/FrameWrapView.ts var FrameWrapView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var FrameWrapView_assign = ( false) || function () { FrameWrapView_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return FrameWrapView_assign.apply(this, arguments); }; var FrameWrapView = /** @class */ (function (_super) { FrameWrapView_extends(FrameWrapView, _super); function FrameWrapView(model, canvasView) { var _this = _super.call(this, { model: model }) || this; (0,index_all.bindAll)(_this, 'onScroll', 'frameLoaded', 'updateOffset', 'remove', 'startDrag'); var config = FrameWrapView_assign(FrameWrapView_assign({}, model.config), { frameWrapView: _this }); _this.cv = canvasView; _this.frame = new view_FrameView(model, _this); _this.classAnim = "".concat(_this.ppfx, "frame-wrapper--anim"); _this.updateOffset = (0,index_all.debounce)(_this.updateOffset.bind(_this), 0); _this.updateSize = (0,index_all.debounce)(_this.updateSize.bind(_this), 0); _this.listenTo(model, 'loaded', _this.frameLoaded); _this.listenTo(model, 'change:x change:y', _this.updatePos); _this.listenTo(model, 'change:width change:height', _this.updateSize); _this.listenTo(model, 'destroy remove', _this.remove); _this.updatePos(); _this.setupDragger(); return _this; } FrameWrapView.prototype.events = function () { return { 'click [data-action-remove]': 'remove', 'mousedown [data-action-move]': 'startDrag', }; }; FrameWrapView.prototype.setupDragger = function () { var _this = this; var _a = this, module = _a.module, model = _a.model; var dragX, dragY, zoom; var toggleEffects = function (on) { module.toggleFramesEvents(on); }; this.dragger = new Dragger/* default */.Z({ onStart: function () { var _a = model.attributes, x = _a.x, y = _a.y; zoom = _this.em.getZoomMultiplier(); dragX = x; dragY = y; toggleEffects(false); }, onEnd: function () { return toggleEffects(true); }, setPosition: function (posOpts) { model.set({ x: dragX + posOpts.x * zoom, y: dragY + posOpts.y * zoom, }); }, }); }; FrameWrapView.prototype.startDrag = function (ev) { var _a; ev && ((_a = this.dragger) === null || _a === void 0 ? void 0 : _a.start(ev)); }; FrameWrapView.prototype.__clear = function (opts) { var frame = this.frame; frame && frame.remove(opts); (0,dom/* removeEl */.L_)(this.elTools); }; FrameWrapView.prototype.remove = function (opts) { var _this = this; this.__clear(opts); abstract_ModuleView.prototype.remove.apply(this, opts); //@ts-ignore ['frame', 'dragger', 'cv', 'elTools'].forEach(function (i) { return (_this[i] = 0); }); return this; }; FrameWrapView.prototype.updateOffset = function () { var _a; var _b = this, em = _b.em, $el = _b.$el, frame = _b.frame; if (!em || em.destroyed) return; em.runDefault({ preserveSelected: 1 }); $el.removeClass(this.classAnim); (_a = frame === null || frame === void 0 ? void 0 : frame.model) === null || _a === void 0 ? void 0 : _a._emitUpdated(); }; FrameWrapView.prototype.updatePos = function (md) { var _a = this, model = _a.model, el = _a.el; var _b = model.attributes, x = _b.x, y = _b.y; var style = el.style; this.frame.rect = undefined; style.left = isNaN(x) ? x : "".concat(x, "px"); style.top = isNaN(y) ? y : "".concat(y, "px"); md && this.updateOffset(); }; FrameWrapView.prototype.updateSize = function () { this.updateDim(); }; /** * Update dimensions of the frame * @private */ FrameWrapView.prototype.updateDim = function () { var _a = this, em = _a.em, el = _a.el, $el = _a.$el, model = _a.model, classAnim = _a.classAnim, frame = _a.frame; if (!frame) return; frame.rect = undefined; $el.addClass(classAnim); var _b = this.__handleSize(), noChanges = _b.noChanges, width = _b.width, height = _b.height; // Set width and height from DOM (should be done only once) if ((0,index_all.isNull)(width) || (0,index_all.isNull)(height)) { model.set(FrameWrapView_assign(FrameWrapView_assign({}, (!width ? { width: el.offsetWidth } : {})), (!height ? { height: el.offsetHeight } : {})), { silent: 1 }); } // Prevent fixed highlighting box which appears when on // component hover during the animation em.stopDefault({ preserveSelected: 1 }); noChanges ? this.updateOffset() : setTimeout(this.updateOffset, 350); }; FrameWrapView.prototype.onScroll = function () { var _a = this, frame = _a.frame, em = _a.em; em.trigger('frame:scroll', { frame: frame, body: frame.getBody(), target: frame.getWindow(), }); }; FrameWrapView.prototype.frameLoaded = function () { var _a = this, frame = _a.frame, config = _a.config; frame.getWindow().onscroll = this.onScroll; this.updateDim(); }; FrameWrapView.prototype.__handleSize = function () { var _a, _b; var un = 'px'; var _c = this, model = _c.model, el = _c.el; var style = el.style; var _d = model.attributes, width = _d.width, height = _d.height; var currW = style.width || ''; var currH = style.height || ''; var newW = width || ''; var newH = height || ''; var noChanges = currW == newW && currH == newH; var newWidth = (0,index_all.isNumber)(newW) ? "".concat(newW).concat(un) : newW; var newHeight = (0,index_all.isNumber)(newH) ? "".concat(newH).concat(un) : newH; style.width = newWidth; if (model.hasAutoHeight()) { var iframe = this.frame.el; if (iframe.contentDocument // this doesn't work always // && !this.sizeObserver ) { var contentDocument_1 = iframe.contentDocument; var observer = new ResizeObserver(function () { style.height = "".concat(contentDocument_1.body.scrollHeight, "px"); }); observer.observe(contentDocument_1.body); (_a = this.sizeObserver) === null || _a === void 0 ? void 0 : _a.disconnect(); this.sizeObserver = observer; } } else { style.height = newHeight; (_b = this.sizeObserver) === null || _b === void 0 ? void 0 : _b.disconnect(); delete this.sizeObserver; } return { noChanges: noChanges, width: width, height: height, newW: newW, newH: newH }; }; FrameWrapView.prototype.render = function () { var _a = this, frame = _a.frame, $el = _a.$el, ppfx = _a.ppfx, cv = _a.cv, model = _a.model, el = _a.el; var onRender = model.attributes.onRender; this.__clear(); this.__handleSize(); frame.render(); $el .empty() .attr({ class: "".concat(ppfx, "frame-wrapper") }) .append("\n <div class=\"".concat(ppfx, "frame-wrapper__top gjs-two-color\" data-frame-top>\n <div class=\"").concat(ppfx, "frame-wrapper__name\" data-action-move>\n ").concat(model.get('name') || '', "\n </div>\n <div class=\"").concat(ppfx, "frame-wrapper__top-r\">\n <div class=\"").concat(ppfx, "frame-wrapper__icon\" data-action-remove style=\"display: none\">\n <svg viewBox=\"0 0 24 24\"><path d=\"M19 4h-3.5l-1-1h-5l-1 1H5v2h14M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12z\"></path></svg>\n </div>\n </div>\n </div>\n <div class=\"").concat(ppfx, "frame-wrapper__right\" data-frame-right></div>\n <div class=\"").concat(ppfx, "frame-wrapper__left\" data-frame-left></div>\n <div class=\"").concat(ppfx, "frame-wrapper__bottom\" data-frame-bottom></div>\n ")) .append(frame.el); var elTools = (0,dom/* createEl */.ut)('div', { class: "".concat(ppfx, "tools"), style: 'pointer-events:none; display: none', }, "\n <div class=\"".concat(ppfx, "highlighter\" data-hl></div>\n <div class=\"").concat(ppfx, "badge\" data-badge></div>\n <div class=\"").concat(ppfx, "placeholder\">\n <div class=\"").concat(ppfx, "placeholder-int\"></div>\n </div>\n <div class=\"").concat(ppfx, "ghost\"></div>\n <div class=\"").concat(ppfx, "toolbar\" style=\"pointer-events:all\"></div>\n <div class=\"").concat(ppfx, "resizer\"></div>\n <div class=\"").concat(ppfx, "offset-v\" data-offset>\n <div class=\"gjs-marginName\" data-offset-m>\n <div class=\"gjs-margin-v-el gjs-margin-v-top\" data-offset-m-t></div>\n <div class=\"gjs-margin-v-el gjs-margin-v-bottom\" data-offset-m-b></div>\n <div class=\"gjs-margin-v-el gjs-margin-v-left\" data-offset-m-l></div>\n <div class=\"gjs-margin-v-el gjs-margin-v-right\" data-offset-m-r></div>\n </div>\n <div class=\"gjs-paddingName\" data-offset-m>\n <div class=\"gjs-padding-v-el gjs-padding-v-top\" data-offset-p-t></div>\n <div class=\"gjs-padding-v-el gjs-padding-v-bottom\" data-offset-p-b></div>\n <div class=\"gjs-padding-v-el gjs-padding-v-left\" data-offset-p-l></div>\n <div class=\"gjs-padding-v-el gjs-padding-v-right\" data-offset-p-r></div>\n </div>\n </div>\n <div class=\"").concat(ppfx, "offset-fixed-v\"></div>\n ")); this.elTools = elTools; var twrp = cv === null || cv === void 0 ? void 0 : cv.toolsWrapper; twrp && twrp.appendChild(elTools); // TODO remove on frame remove onRender && onRender({ el: el, elTop: el.querySelector('[data-frame-top]'), elRight: el.querySelector('[data-frame-right]'), elBottom: el.querySelector('[data-frame-bottom]'), elLeft: el.querySelector('[data-frame-left]'), frame: model, frameWrapperView: this, remove: this.remove, startDrag: this.startDrag, }); return this; }; return FrameWrapView; }(abstract_ModuleView)); /* harmony default export */ const view_FrameWrapView = (FrameWrapView); ;// CONCATENATED MODULE: ./src/canvas/view/FramesView.ts var FramesView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var FramesView = /** @class */ (function (_super) { FramesView_extends(FramesView, _super); function FramesView(opts, config) { if (opts === void 0) { opts = {}; } var _this = _super.call(this, opts, true) || this; _this.listenTo(_this.collection, 'reset', _this.render); _this.canvasView = config.canvasView; _this._module = config.module; return _this; } FramesView.prototype.onRemoveBefore = function (items, opts) { if (opts === void 0) { opts = {}; } items.forEach(function (item) { return item.remove(opts); }); }; FramesView.prototype.onRender = function () { var _a = this, $el = _a.$el, ppfx = _a.ppfx; $el.attr({ class: "".concat(ppfx, "frames") }); }; FramesView.prototype.clearItems = function () { var items = this.viewCollection || []; items.forEach(function (item) { return item.remove(); }); this.viewCollection = []; }; FramesView.prototype.renderView = function (item, type) { return new view_FrameWrapView(item, this.canvasView); }; return FramesView; }(abstract_ModuleDomainViews)); /* harmony default export */ const view_FramesView = (FramesView); ;// CONCATENATED MODULE: ./src/canvas/view/CanvasView.ts var CanvasView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var CanvasView_assign = ( false) || function () { CanvasView_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return CanvasView_assign.apply(this, arguments); }; var CanvasView = /** @class */ (function (_super) { CanvasView_extends(CanvasView, _super); function CanvasView(model) { var _this = _super.call(this, { model: model }) || this; _this.ready = false; (0,index_all.bindAll)(_this, 'clearOff', 'onKeyPress', 'onWheel', 'onPointer'); var _a = _this, em = _a.em, pfx = _a.pfx, ppfx = _a.ppfx; var events = _this.module.events; _this.className = "".concat(pfx, "canvas ").concat(ppfx, "no-touch-actions").concat(!em.config.customUI ? " ".concat(pfx, "canvas-bg") : ''); _this.clsUnscale = "".concat(pfx, "unscale"); _this._initFrames(); _this.listenTo(em, 'change:canvasOffset', _this.clearOff); _this.listenTo(em, 'component:selected', _this.checkSelected); _this.listenTo(em, "".concat(events.coords, " ").concat(events.zoom), _this.updateFrames); _this.listenTo(model, 'change:frames', _this._onFramesUpdate); _this.toggleListeners(true); return _this; } CanvasView.prototype.template = function () { var pfx = this.pfx; return "\n <div class=\"".concat(pfx, "canvas__frames\" data-frames>\n <div class=\"").concat(pfx, "canvas__spots\" data-spots></div>\n </div>\n <div id=\"").concat(pfx, "tools\" class=\"").concat(pfx, "canvas__tools\" data-tools></div>\n <style data-canvas-style></style>\n "); }; CanvasView.prototype._onFramesUpdate = function () { this._initFrames(); this._renderFrames(); }; CanvasView.prototype._initFrames = function () { var _a = this, frames = _a.frames, model = _a.model, config = _a.config, em = _a.em; var collection = model.frames; em.set('readyCanvas', 0); collection.once('loaded:all', function () { return em.set('readyCanvas', 1); }); frames === null || frames === void 0 ? void 0 : frames.remove(); this.frames = new view_FramesView({ collection: collection }, CanvasView_assign(CanvasView_assign({}, config), { canvasView: this })); }; CanvasView.prototype.checkSelected = function (component, opts) { var _a; if (opts === void 0) { opts = {}; } var scroll = opts.scroll; var currFrame = this.em.getCurrentFrame(); scroll && ((_a = component.views) === null || _a === void 0 ? void 0 : _a.forEach(function (view) { view.frameView === currFrame && view.scrollIntoView(scroll); })); }; CanvasView.prototype.remove = function () { var _a; var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } (_a = this.frames) === null || _a === void 0 ? void 0 : _a.remove(); //@ts-ignore this.frames = undefined; abstract_ModuleView.prototype.remove.apply(this, args); this.toggleListeners(false); return this; }; CanvasView.prototype.preventDefault = function (ev) { var _a; if (ev) { ev.preventDefault(); (_a = ev._parentEvent) === null || _a === void 0 ? void 0 : _a.preventDefault(); } }; CanvasView.prototype.toggleListeners = function (enable) { var _a = this, el = _a.el, config = _a.config; var fn = enable ? dom.on : dom/* off */.S1; fn(document, 'keypress', this.onKeyPress); fn(window, 'scroll resize', this.clearOff); fn(el, 'wheel', this.onWheel, { passive: !config.infiniteCanvas }); fn(el, 'pointermove', this.onPointer); }; CanvasView.prototype.screenToWorld = function (x, y) { var module = this.module; var coords = module.getCoords(); var zoom = module.getZoomMultiplier(); var vwDelta = this.getViewportDelta(); return { x: (x - coords.x - vwDelta.x) * zoom, y: (y - coords.y - vwDelta.y) * zoom, }; }; CanvasView.prototype.onPointer = function (ev) { if (!this.config.infiniteCanvas) return; var canvasRect = this.getCanvasOffset(); var docScroll = (0,dom/* getDocumentScroll */.GX)(); var screenCoords = { x: ev.clientX - canvasRect.left + docScroll.x, y: ev.clientY - canvasRect.top + docScroll.y, }; if (ev._parentEvent) { // with _parentEvent means was triggered from the iframe var frameRect = ev.target.getBoundingClientRect(); var zoom = this.module.getZoomDecimal(); screenCoords.x = frameRect.left - canvasRect.left + docScroll.x + ev.clientX * zoom; screenCoords.y = frameRect.top - canvasRect.top + docScroll.y + ev.clientY * zoom; } this.model.set({ pointerScreen: screenCoords, pointer: this.screenToWorld(screenCoords.x, screenCoords.y), }); }; CanvasView.prototype.onKeyPress = function (ev) { var em = this.em; var key = (0,dom/* getKeyChar */.sN)(ev); if (key === ' ' && em.getZoomDecimal() !== 1 && !em.Canvas.isInputFocused()) { this.preventDefault(ev); em.Editor.runCommand('core:canvas-move'); } }; CanvasView.prototype.onWheel = function (ev) { var _a = this, module = _a.module, config = _a.config; if (config.infiniteCanvas) { this.preventDefault(ev); var deltaX = ev.deltaX, deltaY = ev.deltaY; var zoom = module.getZoomDecimal(); var isZooming = (0,dom/* hasModifierKey */.Vb)(ev); var coords = module.getCoords(); if (isZooming) { var newZoom = zoom - deltaY * zoom * 0.01; module.setZoom(newZoom * 100); // Update coordinates based on pointer var pointer = this.model.getPointerCoords(common/* CoordinatesTypes */.vA.Screen); var canvasRect = this.getCanvasOffset(); var pointerX = pointer.x - canvasRect.width / 2; var pointerY = pointer.y - canvasRect.height / 2; var zoomDelta = newZoom / zoom; var x = pointerX - (pointerX - coords.x) * zoomDelta; var y = pointerY - (pointerY - coords.y) * zoomDelta; module.setCoords(x, y); } else { this.onPointer(ev); module.setCoords(coords.x - deltaX, coords.y - deltaY); } } }; CanvasView.prototype.updateFrames = function (ev) { var em = this.em; var toolsWrpEl = this.toolsWrapper; var defOpts = { preserveSelected: 1 }; this.updateFramesArea(); this.clearOff(); toolsWrpEl.style.display = 'none'; em.trigger('canvas:update', ev); this.timerZoom && clearTimeout(this.timerZoom); this.timerZoom = setTimeout(function () { em.stopDefault(defOpts); em.runDefault(defOpts); toolsWrpEl.style.display = ''; }, 300); }; CanvasView.prototype.updateFramesArea = function () { var _a = this, framesArea = _a.framesArea, model = _a.model, module = _a.module, cvStyle = _a.cvStyle, clsUnscale = _a.clsUnscale; var mpl = module.getZoomMultiplier(); if (framesArea) { var _b = model.attributes, x = _b.x, y = _b.y; var zoomDc = module.getZoomDecimal(); framesArea.style.transform = "scale(".concat(zoomDc, ") translate(").concat(x * mpl, "px, ").concat(y * mpl, "px)"); } if (cvStyle) { cvStyle.innerHTML = "\n .".concat(clsUnscale, " { scale: ").concat(mpl, " }\n "); } }; CanvasView.prototype.fitViewport = function (opts) { var _a, _b; if (opts === void 0) { opts = {}; } var _c = this, em = _c.em, module = _c.module, model = _c.model; var canvasRect = this.getCanvasOffset(); var el = opts.el; var elFrame = el && ((_a = (0,mixins.getComponentView)(el)) === null || _a === void 0 ? void 0 : _a.frameView); var frame = elFrame ? elFrame.model : opts.frame || em.getCurrentFrameModel() || model.frames.at(0); var _d = frame.attributes, x = _d.x, y = _d.y; var boxRect = { x: x !== null && x !== void 0 ? x : 0, y: y !== null && y !== void 0 ? y : 0, width: frame.width, height: frame.height, }; if (el) { var elRect = this.getElBoxRect(el); boxRect.x = boxRect.x + elRect.x; boxRect.y = boxRect.y + elRect.y; boxRect.width = elRect.width; boxRect.height = elRect.height; } var noHeight = opts.ignoreHeight; var gap = (_b = opts.gap) !== null && _b !== void 0 ? _b : 0; var gapIsNum = (0,index_all.isNumber)(gap); var gapX = gapIsNum ? gap : gap.x; var gapY = gapIsNum ? gap : gap.y; var boxWidth = boxRect.width + gapX * 2; var boxHeight = boxRect.height + gapY * 2; var canvasWidth = canvasRect.width; var canvasHeight = canvasRect.height; var widthRatio = canvasWidth / boxWidth; var heightRatio = canvasHeight / boxHeight; var zoomRatio = noHeight ? widthRatio : Math.min(widthRatio, heightRatio); var zoom = zoomRatio * 100; module.setZoom(zoom); // check for the frame witdh is necessary as we're centering the frame via CSS var coordX = -boxRect.x + (frame.width >= canvasWidth ? canvasWidth / 2 - boxWidth / 2 : -gapX); var coordY = -boxRect.y + canvasHeight / 2 - boxHeight / 2; var coords = { x: (coordX + gapX) * zoomRatio, y: (coordY + gapY) * zoomRatio, }; if (noHeight) { var zoomMltp = module.getZoomMultiplier(); var canvasWorldHeight = canvasHeight * zoomMltp; var canvasHeightDiff = canvasWorldHeight - canvasHeight; var yDelta = canvasHeightDiff / 2; coords.y = (-boxRect.y + gapY) * zoomRatio - yDelta / zoomMltp; } module.setCoords(coords.x, coords.y); }; /** * Checks if the element is visible in the canvas's viewport * @param {HTMLElement} el * @return {Boolean} */ CanvasView.prototype.isElInViewport = function (el) { var elem = (0,mixins.getElement)(el); var rect = (0,dom/* getElRect */.Ut)(elem); var frameRect = this.getFrameOffset(elem); var rTop = rect.top; var rLeft = rect.left; return rTop >= 0 && rLeft >= 0 && rTop <= frameRect.height && rLeft <= frameRect.width; }; /** * Get the offset of the element * @param {HTMLElement} el * @return { {top: number, left: number, width: number, height: number} } */ CanvasView.prototype.offset = function (el, opts) { if (opts === void 0) { opts = {}; } var noScroll = opts.noScroll; var rect = (0,dom/* getElRect */.Ut)(el); var scroll = noScroll ? { x: 0, y: 0 } : (0,dom/* getDocumentScroll */.GX)(el); return { top: rect.top + scroll.y, left: rect.left + scroll.x, width: rect.width, height: rect.height, }; }; CanvasView.prototype.getRectToScreen = function (boxRect) { var _a, _b, _c, _d; var zoom = this.module.getZoomDecimal(); var coords = this.module.getCoords(); var vwDelta = this.getViewportDelta(); var x = ((_a = boxRect.x) !== null && _a !== void 0 ? _a : 0) * zoom + coords.x + vwDelta.x || 0; var y = ((_b = boxRect.y) !== null && _b !== void 0 ? _b : 0) * zoom + coords.y + vwDelta.y || 0; return { x: x, y: y, width: ((_c = boxRect.width) !== null && _c !== void 0 ? _c : 0) * zoom, height: ((_d = boxRect.height) !== null && _d !== void 0 ? _d : 0) * zoom, }; }; CanvasView.prototype.getElBoxRect = function (el, opts) { var _a, _b, _c; if (opts === void 0) { opts = {}; } var module = this.module; var _d = (0,dom/* getElRect */.Ut)(el), width = _d.width, height = _d.height, left = _d.left, top = _d.top; var frameView = (_a = (0,mixins.getComponentView)(el)) === null || _a === void 0 ? void 0 : _a.frameView; var frameRect = frameView === null || frameView === void 0 ? void 0 : frameView.getBoxRect(); var zoomMlt = module.getZoomMultiplier(); var frameX = (_b = frameRect === null || frameRect === void 0 ? void 0 : frameRect.x) !== null && _b !== void 0 ? _b : 0; var frameY = (_c = frameRect === null || frameRect === void 0 ? void 0 : frameRect.y) !== null && _c !== void 0 ? _c : 0; var canvasEl = this.el; var docScroll = (0,dom/* getDocumentScroll */.GX)(); var xWithFrame = left + frameX + (canvasEl.scrollLeft + docScroll.x) * zoomMlt; var yWithFrame = top + frameY + (canvasEl.scrollTop + docScroll.y) * zoomMlt; var boxRect = { x: xWithFrame, y: yWithFrame, width: width, height: height, }; if (opts.local) { boxRect.x = left; boxRect.y = top; } return opts.toScreen ? this.getRectToScreen(boxRect) : boxRect; }; CanvasView.prototype.getViewportRect = function (opts) { if (opts === void 0) { opts = {}; } var _a = this.getCanvasOffset(), top = _a.top, left = _a.left, width = _a.width, height = _a.height; var module = this.module; if (opts.toWorld) { var zoom = module.getZoomMultiplier(); var coords = module.getCoords(); var vwDelta = this.getViewportDelta(); var x = -coords.x - vwDelta.x || 0; var y = -coords.y - vwDelta.y || 0; return { x: x * zoom, y: y * zoom, width: width * zoom, height: height * zoom, }; } else { return { x: left, y: top, width: width, height: height, }; } }; CanvasView.prototype.getViewportDelta = function (opts) { if (opts === void 0) { opts = {}; } var zoom = this.module.getZoomMultiplier(); var _a = this.getCanvasOffset(), width = _a.width, height = _a.height; var worldWidth = width * zoom; var worldHeight = height * zoom; var widthDelta = worldWidth - width; var heightDelta = worldHeight - height; return { x: widthDelta / 2 / zoom, y: heightDelta / 2 / zoom, }; }; /** * Cleare cached offsets * @private */ CanvasView.prototype.clearOff = function () { this.frmOff = undefined; this.cvsOff = undefined; }; /** * Return frame offset * @return { {top: number, left: number, width: number, height: number} } * @public */ CanvasView.prototype.getFrameOffset = function (el) { var _a; if (!this.frmOff || el) { var frame = (_a = this.frame) === null || _a === void 0 ? void 0 : _a.el; var winEl = el === null || el === void 0 ? void 0 : el.ownerDocument.defaultView; var frEl = winEl ? winEl.frameElement : frame; this.frmOff = this.offset(frEl || frame); } return this.frmOff; }; /** * Return canvas offset * @return { {top: number, left: number, width: number, height: number} } * @public */ CanvasView.prototype.getCanvasOffset = function () { if (!this.cvsOff) this.cvsOff = this.offset(this.el); return this.cvsOff; }; /** * Returns element's rect info * @param {HTMLElement} el * @param {object} opts * @return { {top: number, left: number, width: number, height: number, zoom: number, rect: any} } * @public */ CanvasView.prototype.getElementPos = function (el, opts) { if (opts === void 0) { opts = {}; } var zoom = this.module.getZoomDecimal(); var frameOffset = this.getFrameOffset(el); var canvasEl = this.el; var canvasOffset = this.getCanvasOffset(); var elRect = this.offset(el, opts); var frameTop = opts.avoidFrameOffset ? 0 : frameOffset.top; var frameLeft = opts.avoidFrameOffset ? 0 : frameOffset.left; var elTop = opts.avoidFrameZoom ? elRect.top : elRect.top * zoom; var elLeft = opts.avoidFrameZoom ? elRect.left : elRect.left * zoom; var top = opts.avoidFrameOffset ? elTop : elTop + frameTop - canvasOffset.top + canvasEl.scrollTop; var left = opts.avoidFrameOffset ? elLeft : elLeft + frameLeft - canvasOffset.left + canvasEl.scrollLeft; var height = opts.avoidFrameZoom ? elRect.height : elRect.height * zoom; var width = opts.avoidFrameZoom ? elRect.width : elRect.width * zoom; return { top: top, left: left, height: height, width: width, zoom: zoom, rect: elRect }; }; /** * Returns element's offsets like margins and paddings * @param {HTMLElement} el * @return { MarginPaddingOffsets } * @public */ CanvasView.prototype.getElementOffsets = function (el) { if (!el || (0,dom/* isTextNode */.BM)(el)) return {}; var result = {}; var styles = window.getComputedStyle(el); var zoom = this.module.getZoomDecimal(); var marginPaddingOffsets = [ 'marginTop', 'marginRight', 'marginBottom', 'marginLeft', 'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft', ]; marginPaddingOffsets.forEach(function (offset) { result[offset] = parseFloat(styles[offset]) * zoom; }); return result; }; /** * Returns position data of the canvas element * @return { {top: number, left: number, width: number, height: number} } obj Position object * @public */ CanvasView.prototype.getPosition = function (opts) { var _a; if (opts === void 0) { opts = {}; } var doc = (_a = this.frame) === null || _a === void 0 ? void 0 : _a.el.contentDocument; if (!doc) { return { top: 0, left: 0, width: 0, height: 0, }; } var bEl = doc.body; var zoom = this.module.getZoomDecimal(); var fo = this.getFrameOffset(); var co = this.getCanvasOffset(); var noScroll = opts.noScroll; return { top: fo.top + (noScroll ? 0 : bEl.scrollTop) * zoom - co.top, left: fo.left + (noScroll ? 0 : bEl.scrollLeft) * zoom - co.left, width: co.width, height: co.height, }; }; /** * Update javascript of a specific component passed by its View * @param {ModuleView} view Component's View * @private */ //TODO change type after the ComponentView was updated to ts CanvasView.prototype.updateScript = function (view) { var model = view.model; var id = model.getId(); if (!view.scriptContainer) { view.scriptContainer = (0,dom/* createEl */.ut)('div', { 'data-id': id }); var jsEl = this.getJsContainer(); jsEl === null || jsEl === void 0 ? void 0 : jsEl.appendChild(view.scriptContainer); } view.el.id = id; view.scriptContainer.innerHTML = ''; // In editor, I make use of setTimeout as during the append process of elements // those will not be available immediately, therefore 'item' variable var script = document.createElement('script'); var scriptFn = model.getScriptString(); var scriptFnStr = model.get('script-props') ? scriptFn : "function(){\n".concat(scriptFn, "\n;}"); var scriptProps = JSON.stringify(model.__getScriptProps()); script.innerHTML = "\n setTimeout(function() {\n var item = document.getElementById('".concat(id, "');\n if (!item) return;\n (").concat(scriptFnStr, ".bind(item))(").concat(scriptProps, ")\n }, 1);"); // #873 // Adding setTimeout will make js components work on init of the editor setTimeout(function () { var scr = view.scriptContainer; scr === null || scr === void 0 ? void 0 : scr.appendChild(script); }, 0); }; /** * Get javascript container * @private */ CanvasView.prototype.getJsContainer = function (view) { var frameView = this.getFrameView(view); return frameView === null || frameView === void 0 ? void 0 : frameView.getJsContainer(); }; CanvasView.prototype.getFrameView = function (view) { return (view === null || view === void 0 ? void 0 : view.frameView) || this.em.getCurrentFrame(); }; CanvasView.prototype._renderFrames = function () { if (!this.ready) return; var _a = this, model = _a.model, frames = _a.frames, em = _a.em, framesArea = _a.framesArea; var frms = model.frames; frms.listenToLoad(); frames.render(); var mainFrame = frms.at(0); var currFrame = mainFrame === null || mainFrame === void 0 ? void 0 : mainFrame.view; em.setCurrentFrame(currFrame); framesArea === null || framesArea === void 0 ? void 0 : framesArea.appendChild(frames.el); this.frame = currFrame; this.updateFramesArea(); }; CanvasView.prototype.renderFrames = function () { this._renderFrames(); }; CanvasView.prototype.render = function () { var _a = this, el = _a.el, $el = _a.$el, ppfx = _a.ppfx, config = _a.config, em = _a.em; $el.html(this.template()); var $frames = $el.find('[data-frames]'); this.framesArea = $frames.get(0); var toolsWrp = $el.find('[data-tools]'); this.toolsWrapper = toolsWrp.get(0); toolsWrp.append("\n <div class=\"".concat(ppfx, "tools ").concat(ppfx, "tools-gl\" style=\"pointer-events:none\">\n <div class=\"").concat(ppfx, "placeholder\">\n <div class=\"").concat(ppfx, "placeholder-int\"></div>\n </div>\n </div>\n <div id=\"").concat(ppfx, "tools\" style=\"pointer-events:none\">\n ").concat(config.extHl ? "<div class=\"".concat(ppfx, "highlighter-sel\"></div>") : '', "\n <div class=\"").concat(ppfx, "badge\"></div>\n <div class=\"").concat(ppfx, "ghost\"></div>\n <div class=\"").concat(ppfx, "toolbar\" style=\"pointer-events:all\"></div>\n <div class=\"").concat(ppfx, "resizer\"></div>\n <div class=\"").concat(ppfx, "offset-v\"></div>\n <div class=\"").concat(ppfx, "offset-fixed-v\"></div>\n </div>\n ")); this.toolsEl = el.querySelector("#".concat(ppfx, "tools")); this.hlEl = el.querySelector(".".concat(ppfx, "highlighter")); this.badgeEl = el.querySelector(".".concat(ppfx, "badge")); this.placerEl = el.querySelector(".".concat(ppfx, "placeholder")); this.ghostEl = el.querySelector(".".concat(ppfx, "ghost")); this.toolbarEl = el.querySelector(".".concat(ppfx, "toolbar")); this.resizerEl = el.querySelector(".".concat(ppfx, "resizer")); this.offsetEl = el.querySelector(".".concat(ppfx, "offset-v")); this.fixedOffsetEl = el.querySelector(".".concat(ppfx, "offset-fixed-v")); this.toolsGlobEl = el.querySelector(".".concat(ppfx, "tools-gl")); this.spotsEl = el.querySelector('[data-spots]'); this.cvStyle = el.querySelector('[data-canvas-style]'); this.el.className = (0,mixins.getUiClass)(em, this.className); this.ready = true; this._renderFrames(); return this; }; return CanvasView; }(abstract_ModuleView)); /* harmony default export */ const view_CanvasView = (CanvasView); ;// CONCATENATED MODULE: ./src/canvas/index.ts /** * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/GrapesJS/grapesjs/blob/master/src/canvas/config/config.ts) * ```js * const editor = grapesjs.init({ * canvas: { * // options * } * }) * ``` * * Once the editor is instantiated you can use its API and listen to its events. Before using these methods, you should get the module from the instance. * * ```js * // Listen to events * editor.on('canvas:drop', () => { ... }); * * // Use the API * const canvas = editor.Canvas; * canvas.setCoords(...); * ``` * * {REPLACE_EVENTS} * * [Component]: component.html * [Frame]: frame.html * [CanvasSpot]: canvas_spot.html * * @module Canvas */ var canvas_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var canvas_assign = ( false) || function () { canvas_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return canvas_assign.apply(this, arguments); }; var canvas_spreadArray = ( false) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var CanvasModule = /** @class */ (function (_super) { canvas_extends(CanvasModule, _super); /** * Initialize module. Automatically called with a new instance of the editor * @param {Object} config Configurations * @private */ function CanvasModule(em) { var _this = _super.call(this, em, 'Canvas', canvas_config_config) || this; _this.events = CanvasEvents; _this.framesById = {}; _this.canvas = new model_Canvas(_this); _this.spots = new model_CanvasSpots(_this); _this.model = _this.canvas; _this.startAutoscroll = _this.startAutoscroll.bind(_this); _this.stopAutoscroll = _this.stopAutoscroll.bind(_this); return _this; } /** * Get configuration object * @name getConfig * @function * @return {Object} */ /** * Used inside RTE * @private */ CanvasModule.prototype.getCanvasView = function () { return this.canvasView; }; CanvasModule.prototype.postLoad = function () { this.model.init(); }; CanvasModule.prototype.getModel = function () { return this.canvas; }; /** * Get the canvas element * @returns {HTMLElement} */ CanvasModule.prototype.getElement = function () { return this.getCanvasView().el; }; CanvasModule.prototype.getFrame = function (index) { return this.getFrames()[index || 0]; }; /** * Get the main frame element of the canvas * @returns {HTMLIFrameElement} */ CanvasModule.prototype.getFrameEl = function () { var frame = (this.canvasView || {}).frame; return frame === null || frame === void 0 ? void 0 : frame.el; }; CanvasModule.prototype.getFramesEl = function () { var _a; return (_a = this.canvasView) === null || _a === void 0 ? void 0 : _a.framesArea; }; /** * Get the main frame window instance * @returns {Window} */ CanvasModule.prototype.getWindow = function () { var frame = (this.canvasView || {}).frame; return frame === null || frame === void 0 ? void 0 : frame.getWindow(); }; /** * Get the main frame document element * @returns {HTMLDocument} */ CanvasModule.prototype.getDocument = function () { var frame = this.getFrameEl(); return frame === null || frame === void 0 ? void 0 : frame.contentDocument; }; /** * Get the main frame body element * @return {HTMLBodyElement} */ CanvasModule.prototype.getBody = function () { var doc = this.getDocument(); return doc === null || doc === void 0 ? void 0 : doc.body; }; CanvasModule.prototype._getLocalEl = function (globalEl, compView, method) { var result = globalEl; var frameView = compView === null || compView === void 0 ? void 0 : compView.frameView; result = frameView ? frameView[method]() : result; return result; }; /** * Returns element containing all global canvas tools * @returns {HTMLElement} * @private */ CanvasModule.prototype.getGlobalToolsEl = function () { var _a; return (_a = this.canvasView) === null || _a === void 0 ? void 0 : _a.toolsGlobEl; }; /** * Returns element containing all canvas tools * @returns {HTMLElement} * @private */ CanvasModule.prototype.getToolsEl = function (compView) { return this._getLocalEl(this.getCanvasView().toolsEl, compView, 'getToolsEl'); }; /** * Returns highlighter element * @returns {HTMLElement} * @private */ CanvasModule.prototype.getHighlighter = function (compView) { return this._getLocalEl(this.getCanvasView().hlEl, compView, 'getHighlighter'); }; /** * Returns badge element * @returns {HTMLElement} * @private */ CanvasModule.prototype.getBadgeEl = function (compView) { return this._getLocalEl(this.getCanvasView().badgeEl, compView, 'getBadgeEl'); }; /** * Returns placer element * @returns {HTMLElement} * @private */ CanvasModule.prototype.getPlacerEl = function () { return this.getCanvasView().placerEl; }; /** * Returns ghost element * @returns {HTMLElement} * @private */ CanvasModule.prototype.getGhostEl = function () { return this.getCanvasView().ghostEl; }; /** * Returns toolbar element * @returns {HTMLElement} * @private */ CanvasModule.prototype.getToolbarEl = function () { return this.getCanvasView().toolbarEl; }; /** * Returns resizer element * @returns {HTMLElement} * @private */ CanvasModule.prototype.getResizerEl = function () { return this.getCanvasView().resizerEl; }; /** * Returns offset viewer element * @returns {HTMLElement} * @private */ CanvasModule.prototype.getOffsetViewerEl = function (compView) { return this._getLocalEl(this.getCanvasView().offsetEl, compView, 'getOffsetViewerEl'); }; /** * Returns fixed offset viewer element * @returns {HTMLElement} * @private */ CanvasModule.prototype.getFixedOffsetViewerEl = function () { return this.getCanvasView().fixedOffsetEl; }; CanvasModule.prototype.getSpotsEl = function () { var _a; return (_a = this.canvasView) === null || _a === void 0 ? void 0 : _a.spotsEl; }; CanvasModule.prototype.render = function () { var _a; (_a = this.canvasView) === null || _a === void 0 ? void 0 : _a.remove(); this.canvasView = new view_CanvasView(this.canvas); return this.canvasView.render().el; }; /** * Get frame position * @returns {Object} * @private */ CanvasModule.prototype.getOffset = function () { var frameOff = this.offset(this.getFrameEl()); var canvasOff = this.offset(this.getElement()); return { top: frameOff.top - canvasOff.top, left: frameOff.left - canvasOff.left, }; }; /** * Get the offset of the passed component element * @param {HTMLElement} el * @returns {Object} * @private */ CanvasModule.prototype.offset = function (el) { return this.getCanvasView().offset(el); }; /** * Set custom badge naming strategy * @param {Function} f * @example * canvas.setCustomBadgeLabel(function(component){ * return component.getName(); * }); */ CanvasModule.prototype.setCustomBadgeLabel = function (f) { //@ts-ignore this.config.customBadgeLabel = f; }; /** * Get element position relative to the canvas * @param {HTMLElement} el * @returns {Object} * @private */ CanvasModule.prototype.getElementPos = function (el, opts) { return this.getCanvasView().getElementPos(el, opts); }; /** * Returns element's offsets like margins and paddings * @param {HTMLElement} el * @returns {Object} * @private */ CanvasModule.prototype.getElementOffsets = function (el) { return this.getCanvasView().getElementOffsets(el); }; /** * Get canvas rectangular data * @returns {Object} */ CanvasModule.prototype.getRect = function () { var _a; var _b = (_a = this.getCanvasView().getPosition()) !== null && _a !== void 0 ? _a : {}, _c = _b.top, top = _c === void 0 ? 0 : _c, _d = _b.left, left = _d === void 0 ? 0 : _d; return canvas_assign(canvas_assign({}, this.getCanvasView().getCanvasOffset()), { topScroll: top, leftScroll: left }); }; /** * This method comes handy when you need to attach something like toolbars * to elements inside the canvas, dealing with all relative position, * offsets, etc. and returning as result the object with positions which are * viewable by the user (when the canvas is scrolled the top edge of the element * is not viewable by the user anymore so the new top edge is the one of the canvas) * * The target should be visible before being passed here as invisible elements * return empty string as width * @param {HTMLElement} target The target in this case could be the toolbar * @param {HTMLElement} element The element on which I'd attach the toolbar * @param {Object} options Custom options * @param {Boolean} options.toRight Set to true if you want the toolbar attached to the right * @return {Object} * @private */ CanvasModule.prototype.getTargetToElementDim = function (target, element, options) { if (options === void 0) { options = {}; } var opts = options || {}; var canvasPos = this.getCanvasView().getPosition(); if (!canvasPos) return; var pos = opts.elPos || this.getCanvasView().getElementPos(element); var toRight = options.toRight || 0; var targetHeight = opts.targetHeight || target.offsetHeight; var targetWidth = opts.targetWidth || target.offsetWidth; var eventToTrigger = opts.event || null; var elTop = pos.top - targetHeight; var elLeft = pos.left; elLeft += toRight ? pos.width : 0; elLeft = toRight ? elLeft - targetWidth : elLeft; var leftPos = elLeft < canvasPos.left ? canvasPos.left : elLeft; var topPos = elTop < canvasPos.top ? canvasPos.top : elTop; topPos = topPos > pos.top + pos.height ? pos.top + pos.height : topPos; var result = { top: topPos, left: leftPos, elementTop: pos.top, elementLeft: pos.left, elementWidth: pos.width, elementHeight: pos.height, targetWidth: target.offsetWidth, targetHeight: target.offsetHeight, canvasTop: canvasPos.top, canvasLeft: canvasPos.left, canvasWidth: canvasPos.width, canvasHeight: canvasPos.height, }; // In this way I can catch data and also change the position strategy if (eventToTrigger && this.em) { this.em.trigger(eventToTrigger, result); } return result; }; CanvasModule.prototype.canvasRectOffset = function (el, pos, opts) { var _this = this; if (opts === void 0) { opts = {}; } var getFrameElFromDoc = function (doc) { var defaultView = doc.defaultView; return defaultView === null || defaultView === void 0 ? void 0 : defaultView.frameElement; }; var rectOff = function (el, top, pos) { if (top === void 0) { top = 1; } var zoom = _this.em.getZoomDecimal(); var side = top ? 'top' : 'left'; var doc = el.ownerDocument; var _a = opts.offset ? getFrameElFromDoc(doc) : {}, _b = _a.offsetTop, offsetTop = _b === void 0 ? 0 : _b, _c = _a.offsetLeft, offsetLeft = _c === void 0 ? 0 : _c; var _d = doc.body || {}, _e = _d.scrollTop, scrollTop = _e === void 0 ? 0 : _e, _f = _d.scrollLeft, scrollLeft = _f === void 0 ? 0 : _f; var scroll = top ? scrollTop : scrollLeft; var offset = top ? offsetTop : offsetLeft; return pos[side] - (scroll - offset) * zoom; }; return { top: rectOff(el, 1, pos), left: rectOff(el, 0, pos), }; }; /** * * @param {HTMLElement} el The component element in the canvas * @param {HTMLElement} targetEl The target element to position (eg. toolbar) * @param {Object} opts * @private */ CanvasModule.prototype.getTargetToElementFixed = function (el, targetEl, opts) { if (opts === void 0) { opts = {}; } var elRect = opts.pos || this.getElementPos(el, { noScroll: true }); var canvasOffset = opts.canvasOff || this.canvasRectOffset(el, elRect); var targetHeight = targetEl.offsetHeight || 0; var targetWidth = targetEl.offsetWidth || 0; var elRight = elRect.left + elRect.width; var canvasView = this.getCanvasView(); var canvasRect = canvasView.getPosition(); var frameOffset = canvasView.getFrameOffset(el); var event = opts.event; var top = -targetHeight; var left = !(0,index_all.isUndefined)(opts.left) ? opts.left : elRect.width - targetWidth; left = elRect.left < -left ? -elRect.left : left; left = elRight > canvasRect.width ? left - (elRight - canvasRect.width) : left; // Check when the target top edge reaches the top of the viewable canvas if (canvasOffset.top < targetHeight) { var fullHeight = elRect.height + targetHeight; var elIsShort = fullHeight < frameOffset.height; // Scroll with the window if the top edge is reached and the // element is bigger than the canvas if (elIsShort) { top = top + fullHeight; } else { top = -canvasOffset.top < elRect.height ? -canvasOffset.top : elRect.height; } } var result = { top: top, left: left, canvasOffsetTop: canvasOffset.top, canvasOffsetLeft: canvasOffset.left, elRect: elRect, canvasOffset: canvasOffset, canvasRect: canvasRect, targetWidth: targetWidth, targetHeight: targetHeight, }; // In this way I can catch data and also change the position strategy event && this.em.trigger(event, result); return result; }; /** * Instead of simply returning e.clientX and e.clientY this function * calculates also the offset based on the canvas. This is helpful when you * need to get X and Y position while moving between the editor area and * canvas area, which is in the iframe * @param {Event} e * @return {Object} * @private */ CanvasModule.prototype.getMouseRelativePos = function (e, opts) { if (opts === void 0) { opts = {}; } var addTop = 0; var addLeft = 0; var subWinOffset = opts.subWinOffset; var doc = e.target.ownerDocument; var win = doc.defaultView || doc.parentWindow; var frame = win.frameElement; var yOffset = subWinOffset ? win.pageYOffset : 0; var xOffset = subWinOffset ? win.pageXOffset : 0; if (frame) { var frameRect = frame.getBoundingClientRect(); addTop = frameRect.top || 0; addLeft = frameRect.left || 0; } return { y: e.clientY + addTop - yOffset, x: e.clientX + addLeft - xOffset, }; }; /** * X and Y mouse position relative to the canvas * @param {Event} ev * @return {Object} * @private */ CanvasModule.prototype.getMouseRelativeCanvas = function (ev, opts) { var _a; var zoom = this.getZoomDecimal(); var _b = (_a = this.getCanvasView().getPosition(opts)) !== null && _a !== void 0 ? _a : {}, _c = _b.top, top = _c === void 0 ? 0 : _c, _d = _b.left, left = _d === void 0 ? 0 : _d; return { y: ev.clientY * zoom + top, x: ev.clientX * zoom + left, }; }; /** * Check if the canvas is focused * @returns {Boolean} */ CanvasModule.prototype.hasFocus = function () { return this.getDocument().hasFocus(); }; /** * Detects if some input is focused (input elements, text components, etc.) * @return {Boolean} * @private */ CanvasModule.prototype.isInputFocused = function () { var doc = this.getDocument(); var frame = this.getFrameEl(); var toIgnore = canvas_spreadArray(['body'], this.config.notTextable, true); var docActive = frame && document.activeElement === frame; var focused = docActive ? doc && doc.activeElement : document.activeElement; return focused && !toIgnore.some(function (item) { return focused.matches(item); }); }; /** * Scroll canvas to the element if it's not visible. The scrolling is * executed via `scrollIntoView` API and options of this method are * passed to it. For instance, you can scroll smoothly by using * `{ behavior: 'smooth' }`. * @param {HTMLElement|[Component]} el * @param {Object} [opts={}] Options, same as options for `scrollIntoView` * @param {Boolean} [opts.force=false] Force the scroll, even if the element is already visible * @example * const selected = editor.getSelected(); * // Scroll smoothly (this behavior can be polyfilled) * canvas.scrollTo(selected, { behavior: 'smooth' }); * // Force the scroll, even if the element is alredy visible * canvas.scrollTo(selected, { force: true }); */ CanvasModule.prototype.scrollTo = function (el, opts) { if (opts === void 0) { opts = {}; } var elem = (0,mixins.getElement)(el); var view = elem && (0,mixins.getViewEl)(elem); view && view.scrollIntoView(opts); }; /** * Start autoscroll * @private */ CanvasModule.prototype.startAutoscroll = function (frame) { var fr = (frame && frame.view) || this.em.getCurrentFrame(); fr && fr.startAutoscroll(); }; /** * Stop autoscroll * @private */ CanvasModule.prototype.stopAutoscroll = function (frame) { var fr = (frame && frame.view) || this.em.getCurrentFrame(); fr && fr.stopAutoscroll(); }; /** * Set canvas zoom value * @param {Number} value The zoom value, from 0 to 100 * @returns {this} * @example * canvas.setZoom(50); // set zoom to 50% */ CanvasModule.prototype.setZoom = function (value) { this.canvas.set('zoom', typeof value === 'string' ? parseFloat(value) : value); return this; }; /** * Get canvas zoom value * @returns {Number} * @example * canvas.setZoom(50); // set zoom to 50% * const zoom = canvas.getZoom(); // 50 */ CanvasModule.prototype.getZoom = function () { return parseFloat(this.canvas.get('zoom')); }; /** * Set canvas position coordinates * @param {Number} x Horizontal position * @param {Number} y Vertical position * @returns {this} * @example * canvas.setCoords(100, 100); */ CanvasModule.prototype.setCoords = function (x, y, opts) { var _a; if (opts === void 0) { opts = {}; } var hasX = x || x === 0; var hasY = y || y === 0; var coords = { x: this.canvas.get('x'), y: this.canvas.get('y'), }; if (hasX) coords.x = parseFloat("".concat(x)); if (hasY) coords.y = parseFloat("".concat(y)); if (opts.toWorld) { var delta = (_a = this.canvasView) === null || _a === void 0 ? void 0 : _a.getViewportDelta(); if (delta) { if (hasX) coords.x = coords.x - delta.x; if (hasY) coords.y = coords.y - delta.y; } } this.canvas.set(coords); return this; }; /** * Get canvas position coordinates * @returns {Object} Object containing coordinates * @example * canvas.setCoords(100, 100); * const coords = canvas.getCoords(); * // { x: 100, y: 100 } */ CanvasModule.prototype.getCoords = function () { var _a = this.canvas.attributes, x = _a.x, y = _a.y; return { x: x, y: y }; }; /** * Get canvas pointer position coordinates. * @returns {Object} Object containing pointer coordinates * @private * @example * const worldPointer = canvas.getPointer(); * const screenPointer = canvas.getPointer(true); */ CanvasModule.prototype.getPointer = function (screen) { var _a = this.canvas.attributes, pointer = _a.pointer, pointerScreen = _a.pointerScreen; return screen ? pointerScreen : pointer; }; CanvasModule.prototype.getZoomDecimal = function () { return this.getZoom() / 100; }; CanvasModule.prototype.getZoomMultiplier = function () { var zoom = this.getZoomDecimal(); return zoom ? 1 / zoom : 1; }; CanvasModule.prototype.fitViewport = function (opts) { var _a; (_a = this.canvasView) === null || _a === void 0 ? void 0 : _a.fitViewport(opts); }; CanvasModule.prototype.toggleFramesEvents = function (on) { var style = this.getFramesEl().style; style.pointerEvents = on ? '' : 'none'; }; CanvasModule.prototype.getFrames = function () { return this.canvas.frames.map(function (item) { return item; }); }; /** * Add new frame to the canvas * @param {Object} props Frame properties * @returns {[Frame]} * @private * @example * canvas.addFrame({ * name: 'Mobile home page', * x: 100, // Position in canvas * y: 100, * width: 500, // Frame dimensions * height: 600, * // device: 'DEVICE-ID', * components: [ * '<h1 class="testh">Title frame</h1>', * '<p class="testp">Paragraph frame</p>', * ], * styles: ` * .testh { color: red; } * .testp { color: blue; } * `, * }); */ CanvasModule.prototype.addFrame = function (props, opts) { if (props === void 0) { props = {}; } if (opts === void 0) { opts = {}; } return this.canvas.frames.add(new model_Frame(this, canvas_assign({}, props)), opts); }; /** * Get the last created Component from a drag & drop to the canvas. * @returns {[Component]|undefined} */ CanvasModule.prototype.getLastDragResult = function () { return this.em.get('dragResult'); }; /** * Add or update canvas spot. * @param {Object} props Canvas spot properties. * @param opts * @returns {[CanvasSpot]} * @example * // Add new canvas spot * const spot = canvas.addSpot({ * type: 'select', // 'select' is one of the built-in spots * component: editor.getSelected(), * }); * * // Add custom canvas spot * const spot = canvas.addSpot({ * type: 'my-custom-spot', * component: editor.getSelected(), * }); * // Update the same spot by reusing its ID * canvas.addSpot({ * id: spot.id, * component: anotherComponent, * }); */ CanvasModule.prototype.addSpot = function (props, opts) { var _a; if (opts === void 0) { opts = {}; } var spotProps = props; var spots = this.getSpots(spotProps); if (spots.length) { var spot_1 = spots[0]; spot_1.set(spotProps); return spot_1; } var cmpView = spotProps.componentView || ((_a = spotProps.component) === null || _a === void 0 ? void 0 : _a.view); var spot = new CanvasSpot/* default */.Z(this, canvas_assign(canvas_assign({}, spotProps), { id: spotProps.id || "cs_".concat(spotProps.type, "_").concat(cmpView === null || cmpView === void 0 ? void 0 : cmpView.cid), type: spotProps.type || '' })); this.spots.add(spot, opts); return spot; }; /** * Get canvas spots. * @param {Object} [spotProps] Canvas spot properties for filtering the result. With no properties, all available spots will be returned. * @returns {[CanvasSpot][]} * @example * canvas.addSpot({ type: 'select', component: cmp1 }); * canvas.addSpot({ type: 'select', component: cmp2 }); * canvas.addSpot({ type: 'target', component: cmp3 }); * * // Get all spots * const allSpots = canvas.getSpots(); * allSpots.length; // 3 * * // Get all 'select' spots * const allSelectSpots = canvas.getSpots({ type: 'select' }); * allSelectSpots.length; // 2 */ CanvasModule.prototype.getSpots = function (spotProps) { if (spotProps === void 0) { spotProps = {}; } return this.spots.where(spotProps.id ? { id: spotProps.id } : spotProps); }; /** * Remove canvas spots. * @param {Object|[CanvasSpot][]} [spotProps] Canvas spot properties for filtering spots to remove or an array of spots to remove. With no properties, all available spots will be removed. * @returns {[CanvasSpot][]} * @example * canvas.addSpot({ type: 'select', component: cmp1 }); * canvas.addSpot({ type: 'select', component: cmp2 }); * canvas.addSpot({ type: 'target', component: cmp3 }); * * // Remove all 'select' spots * canvas.removeSpots({ type: 'select' }); * * // Remove spots by an array of canvas spots * const filteredSpots = canvas.getSpots().filter(spot => myCustomCondition); * canvas.removeSpots(filteredSpots); * * // Remove all spots * canvas.removeSpots(); */ CanvasModule.prototype.removeSpots = function (spotProps) { if (spotProps === void 0) { spotProps = {}; } var spots = (0,index_all.isArray)(spotProps) ? spotProps : this.getSpots(spotProps); var removed = this.spots.remove(spots); return removed; }; /** * Check if the built-in canvas spot has a declared custom rendering. * @param {String} type Built-in canvas spot type * @returns {Boolean} * @example * grapesjs.init({ * // ... * canvas: { * // avoid rendering the built-in 'target' canvas spot * customSpots: { target: true } * } * }); * // ... * canvas.hasCustomSpot('select'); // false * canvas.hasCustomSpot('target'); // true */ CanvasModule.prototype.hasCustomSpot = function (type) { var customSpots = this.config.customSpots; if (customSpots === true || (customSpots && type && customSpots[type])) { return true; } return false; }; /** * Transform a box rect from the world coordinate system to the screen one. * @param {Object} boxRect * @returns {Object} */ CanvasModule.prototype.getWorldRectToScreen = function (boxRect) { var _a; return (_a = this.canvasView) === null || _a === void 0 ? void 0 : _a.getRectToScreen(boxRect); }; CanvasModule.prototype.refreshSpots = function () { this.spots.refresh(); }; CanvasModule.prototype.destroy = function () { var _this = this; var _a; this.canvas.stopListening(); (_a = this.canvasView) === null || _a === void 0 ? void 0 : _a.remove(); //[this.canvas, this.canvasView].forEach(i => (i = {})); //@ts-ignore ['model', 'droppable'].forEach(function (i) { return (_this[i] = {}); }); }; return CanvasModule; }(abstract_Module)); /* harmony default export */ const canvas = (CanvasModule); ;// CONCATENATED MODULE: ./src/dom_components/config/config.ts /* harmony default export */ const dom_components_config_config = ({ stylePrefix: 'comp-', components: [], draggableComponents: true, disableTextInnerChilds: false, processor: undefined, voidElements: [ 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'menuitem', 'meta', 'param', 'source', 'track', 'wbr', ], }); ;// CONCATENATED MODULE: ./src/parser/model/BrowserParserHtml.ts var htmlType = 'text/html'; var defaultType = htmlType; // 'application/xml'; /* harmony default export */ const BrowserParserHtml = (function (str, config) { if (config === void 0) { config = {}; } var parser = new DOMParser(); var mimeType = config.htmlType || defaultType; var toHTML = mimeType === htmlType; var strF = toHTML ? str : "<div>".concat(str, "</div>"); var doc = parser.parseFromString(strF, mimeType); var res; if (toHTML) { // Replicate the old parser in order to avoid breaking changes var head = doc.head, body_1 = doc.body; // Move all scripts at the bottom of the page var scripts = head.querySelectorAll('script'); (0,index_all.each)(scripts, function (node) { return body_1.appendChild(node); }); // Move inside body all head children var hEls_1 = []; (0,index_all.each)(head.children, function (n) { return hEls_1.push(n); }); (0,index_all.each)(hEls_1, function (node, i) { return body_1.insertBefore(node, body_1.children[i]); }); res = body_1; } else { res = doc.firstChild; } return res; }); /** * POC, custom html parser specs * Parse an HTML string to an array of nodes * example * parse(`<div class="mycls" data-test>Hello</div><span>World <b>example</b></span>`) * // result * [ * { * tagName: 'div', * attributes: { class: 'mycls', 'data-test': '' }, * childNodes: ['Hello'], * },{ * tagName: 'span', * childNodes: [ * 'World ', * { * tagName: 'b', * childNodes: ['example'], * } * ], * } * ] * export const parseNodes = nodes => { const result = []; for (let i = 0; i < nodes.length; i++) { result.push(parseNode(nodes[i])); } return result; }; export const parseAttributes = attrs => { const result = {}; for (let j = 0; j < attrs.length; j++) { const attr = attrs[j]; const nodeName = attr.nodeName; const nodeValue = attr.nodeValue; result[nodeName] = nodeValue; } return result; }; export const parseNode = el => { // Return the string of the textnode element if (el.nodeType === 3) { return el.nodeValue; } const tagName = node.tagName ? node.tagName.toLowerCase() : ''; const attrs = el.attributes || []; const nodes = el.childNodes || []; return { ...(tagName && { tagName }), ...(attrs.length && { attributes: parseAttributes(attrs) }), ...(nodes.length && { childNodes: parseNodes(nodes) }) }; }; export default (str, config = {}) => { const result = []; const el = document.createElement('div'); el.innerHTML = str; const nodes = el.childNodes; const len = nodes.length; for (let i = 0; i < len; i++) { result.push(parseNode(nodes[i])); } return result; }; */ ;// CONCATENATED MODULE: ./src/parser/model/ParserHtml.ts var ParserHtml_assign = ( false) || function () { ParserHtml_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return ParserHtml_assign.apply(this, arguments); }; var modelAttrStart = 'data-gjs-'; var ParserHtml_event = 'parse:html'; var ParserHtml = function (em, config) { if (config === void 0) { config = {}; } return { compTypes: '', modelAttrStart: modelAttrStart, getPropAttribute: function (attrName, attrValue) { var name = attrName.replace(this.modelAttrStart, ''); var valueLen = (attrValue === null || attrValue === void 0 ? void 0 : attrValue.length) || 0; var firstChar = attrValue === null || attrValue === void 0 ? void 0 : attrValue.substring(0, 1); var lastChar = attrValue === null || attrValue === void 0 ? void 0 : attrValue.substring(valueLen - 1); var value = attrValue === 'true' ? true : attrValue === 'false' ? false : attrValue; // Try to parse JSON where it's possible // I can get false positive here (eg. a selector '[data-attr]') // so put it under try/catch and let fail silently try { value = (firstChar == '{' && lastChar == '}') || (firstChar == '[' && lastChar == ']') ? JSON.parse(value) : value; } catch (e) { } return { name: name, value: value, }; }, /** * Extract component props from an attribute object * @param {Object} attr * @returns {Object} An object containing props and attributes without them */ splitPropsFromAttr: function (attr) { var _this = this; if (attr === void 0) { attr = {}; } var props = {}; var attrs = {}; (0,index_all.each)(attr, function (value, key) { if (key.indexOf(_this.modelAttrStart) === 0) { var propsResult = _this.getPropAttribute(key, value); props[propsResult.name] = propsResult.value; } else { attrs[key] = value; } }); return { props: props, attrs: attrs, }; }, /** * Parse style string to object * @param {string} str * @return {Object} * @example * var stl = ParserHtml.parseStyle('color:black; width:100px; test:value;'); * console.log(stl); * // {color: 'black', width: '100px', test: 'value'} */ parseStyle: function (str) { var result = {}; while (str.indexOf('/*') >= 0) { var start = str.indexOf('/*'); var end = str.indexOf('*/') + 2; str = str.replace(str.slice(start, end), ''); } var decls = str.split(';'); for (var i = 0, len = decls.length; i < len; i++) { var decl = decls[i].trim(); if (!decl) continue; var prop = decl.split(':'); var key = prop[0].trim(); var value = prop.slice(1).join(':').trim(); // Support multiple values for the same key if (result[key]) { if (!(0,index_all.isArray)(result[key])) { result[key] = [result[key]]; } result[key].push(value); } else { result[key] = value; } } return result; }, /** * Parse class string to array * @param {string} str * @return {Array<string>} * @example * var res = ParserHtml.parseClass('test1 test2 test3'); * console.log(res); * // ['test1', 'test2', 'test3'] */ parseClass: function (str) { var result = []; var cls = str.split(' '); for (var i = 0, len = cls.length; i < len; i++) { var cl = cls[i].trim(); if (!cl) continue; result.push(cl); } return result; }, /** * Get data from the node element * @param {HTMLElement} el DOM element to traverse * @return {Array<Object>} */ parseNode: function (el, opts) { if (opts === void 0) { opts = {}; } var result = []; var nodes = el.childNodes; for (var i = 0, len = nodes.length; i < len; i++) { var node = nodes[i]; var attrs = node.attributes || []; var attrsLen = attrs.length; var nodePrev = result[result.length - 1]; var nodeChild = node.childNodes.length; var ct = this.compTypes; var model = {}; // TODO use component properties // Start with understanding what kind of component it is if (ct) { var obj = ''; var type = node.getAttribute && node.getAttribute("".concat(this.modelAttrStart, "type")); // If the type is already defined, use it if (type) { model = { type: type }; } else { // Iterate over all available Component Types and // the first with a valid result will be that component for (var it_1 = 0; it_1 < ct.length; it_1++) { var compType = ct[it_1]; // @ts-ignore obj = compType.model.isComponent(node, opts); if (obj) { if (typeof obj !== 'object') { // @ts-ignore obj = { type: compType.id }; } break; } } model = obj; } } // Set tag name if not yet done if (!model.tagName) { var tag = node.tagName || ''; var ns = node.namespaceURI || ''; model.tagName = tag && ns === 'http://www.w3.org/1999/xhtml' ? tag.toLowerCase() : tag; } if (attrsLen) { model.attributes = {}; } // Parse attributes for (var j = 0; j < attrsLen; j++) { var nodeName = attrs[j].nodeName; var nodeValue = attrs[j].nodeValue; // Isolate attributes if (nodeName == 'style') { model.style = this.parseStyle(nodeValue); } else if (nodeName == 'class') { model.classes = this.parseClass(nodeValue); } else if (nodeName == 'contenteditable') { continue; } else if (nodeName.indexOf(this.modelAttrStart) === 0) { var propsResult = this.getPropAttribute(nodeName, nodeValue); model[propsResult.name] = propsResult.value; } else { // @ts-ignore Check for attributes from props (eg. required, disabled) if (nodeValue === '' && node[nodeName] === true) { nodeValue = true; } model.attributes[nodeName] = nodeValue; } } // Check for nested elements but avoid it if already provided if (nodeChild && !model.components) { // Avoid infinite nested text nodes var firstChild = node.childNodes[0]; // If there is only one child and it's a TEXTNODE // just make it content of the current node if (nodeChild === 1 && firstChild.nodeType === 3) { !model.type && (model.type = 'text'); model.components = { type: 'textnode', content: firstChild.nodeValue, }; } else { model.components = this.parseNode(node, ParserHtml_assign(ParserHtml_assign({}, opts), { inSvg: opts.inSvg || model.type === 'svg' })); } } // Check if it's a text node and if could be moved to the prevous model if (model.type == 'textnode') { if (nodePrev && nodePrev.type == 'textnode') { nodePrev.content += model.content; continue; } // Throw away empty nodes (keep spaces) if (!opts.keepEmptyTextNodes) { var content = node.nodeValue; if (content != ' ' && !content.trim()) { continue; } } } // Check for custom void elements (valid in XML) if (!nodeChild && "".concat(node.outerHTML).slice(-2) === '/>') { model.void = true; } // If all children are texts and there is some textnode the parent should // be text too otherwise I'm unable to edit texnodes var comps = model.components; if (!model.type && comps) { var allTxt = 1; var foundTextNode = 0; for (var ci = 0; ci < comps.length; ci++) { var comp = comps[ci]; var cType = comp.type; if (['text', 'textnode'].indexOf(cType) < 0 && config.textTags.indexOf(comp.tagName) < 0) { allTxt = 0; break; } if (cType == 'textnode') { foundTextNode = 1; } } if (allTxt && foundTextNode) { model.type = 'text'; } } // If tagName is still empty and is not a textnode, do not push it if (!model.tagName && model.type != 'textnode') { continue; } result.push(model); } return result; }, /** * Parse HTML string to a desired model object * @param {string} str HTML string * @param {ParserCss} parserCss In case there is style tags inside HTML * @return {Object} */ parse: function (str, parserCss, opts) { var _a; if (opts === void 0) { opts = {}; } var conf = (em === null || em === void 0 ? void 0 : em.get('Config')) || {}; var res = { html: [] }; var cf = ParserHtml_assign(ParserHtml_assign({}, config), opts); var options = ParserHtml_assign(ParserHtml_assign(ParserHtml_assign({}, config.optionsHtml), { // @ts-ignore Support previous `configParser.htmlType` option htmlType: ((_a = config.optionsHtml) === null || _a === void 0 ? void 0 : _a.htmlType) || config.htmlType }), opts); var el = (0,index_all.isFunction)(cf.parserHtml) ? cf.parserHtml(str, options) : BrowserParserHtml(str, options); var scripts = el.querySelectorAll('script'); var i = scripts.length; // Support previous `configMain.allowScripts` option var allowScripts = !(0,index_all.isUndefined)(conf.allowScripts) ? conf.allowScripts : options.allowScripts; // Remove script tags if (!allowScripts) { while (i--) scripts[i].parentNode.removeChild(scripts[i]); } // Remove unsafe attributes if (!options.allowUnsafeAttr) { this.__clearUnsafeAttr(el); } // Detach style tags and parse them if (parserCss) { var styles = el.querySelectorAll('style'); var j = styles.length; var styleStr = ''; while (j--) { styleStr = styles[j].innerHTML + styleStr; styles[j].parentNode.removeChild(styles[j]); } if (styleStr) res.css = parserCss.parse(styleStr); } em && em.trigger("".concat(ParserHtml_event, ":root"), { input: str, root: el }); var result = this.parseNode(el, cf); // I have to keep it otherwise it breaks the DomComponents.addComponent (returns always array) var resHtml = result.length === 1 && !cf.returnArray ? result[0] : result; res.html = resHtml; em && em.trigger(ParserHtml_event, { input: str, output: res }); return res; }, __clearUnsafeAttr: function (node) { var _this = this; var attrs = node.attributes || []; var nodes = node.childNodes || []; var toRemove = []; (0,index_all.each)(attrs, function (attr) { var name = attr.nodeName || ''; name.indexOf('on') === 0 && toRemove.push(name); }); toRemove.map(function (name) { return node.removeAttribute(name); }); (0,index_all.each)(nodes, function (node) { return _this.__clearUnsafeAttr(node); }); }, }; }; /* harmony default export */ const model_ParserHtml = (ParserHtml); ;// CONCATENATED MODULE: ./src/domain_abstract/model/StyleableModel.ts var StyleableModel_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var StyleableModel_assign = ( false) || function () { StyleableModel_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return StyleableModel_assign.apply(this, arguments); }; var parserHtml = model_ParserHtml(); var getLastStyleValue = function (value) { return (0,index_all.isArray)(value) ? value[value.length - 1] : value; }; var StyleableModel = /** @class */ (function (_super) { StyleableModel_extends(StyleableModel, _super); function StyleableModel() { return _super !== null && _super.apply(this, arguments) || this; } /** * Forward style string to `parseStyle` to be parse to an object * @param {string} str * @returns */ StyleableModel.prototype.parseStyle = function (str) { return parserHtml.parseStyle(str); }; /** * To trigger the style change event on models I have to * pass a new object instance * @param {Object} prop * @return {Object} */ StyleableModel.prototype.extendStyle = function (prop) { return StyleableModel_assign(StyleableModel_assign({}, this.getStyle()), prop); }; /** * Get style object * @return {Object} */ StyleableModel.prototype.getStyle = function (prop) { var style = this.get('style') || {}; var result = StyleableModel_assign({}, style); return prop && (0,index_all.isString)(prop) ? result[prop] : result; }; /** * Set new style object * @param {Object|string} prop * @param {Object} opts * @return {Object} Applied properties */ StyleableModel.prototype.setStyle = function (prop, opts) { var _this = this; if (prop === void 0) { prop = {}; } if (opts === void 0) { opts = {}; } if ((0,index_all.isString)(prop)) { prop = this.parseStyle(prop); } var propOrig = this.getStyle(opts); if (opts.partial || opts.avoidStore) { opts.avoidStore = true; prop.__p = true; } else { delete prop.__p; } var propNew = StyleableModel_assign({}, prop); var newStyle = StyleableModel_assign({}, propNew); // Remove empty style properties (0,index_all.keys)(newStyle).forEach(function (prop) { if (newStyle[prop] === '') { delete newStyle[prop]; } }); this.set('style', newStyle, opts); var diff = (0,mixins.shallowDiff)(propOrig, propNew); // Delete the property used for partial updates delete diff.__p; (0,index_all.keys)(diff).forEach(function (pr) { // @ts-ignore var em = _this.em; if (opts.noEvent) return; _this.trigger("change:style:".concat(pr)); if (em) { em.trigger('styleable:change', _this, pr, opts); em.trigger("styleable:change:".concat(pr), _this, pr, opts); } }); return propNew; }; /** * Add style property * @param {Object|string} prop * @param {string} value * @example * this.addStyle({color: 'red'}); * this.addStyle('color', 'blue'); */ StyleableModel.prototype.addStyle = function (prop, value, opts) { var _a; if (value === void 0) { value = ''; } if (opts === void 0) { opts = {}; } if (typeof prop == 'string') { prop = (_a = {}, _a[prop] = value, _a); } else { opts = value || {}; } prop = this.extendStyle(prop); this.setStyle(prop, opts); }; /** * Remove style property * @param {string} prop */ StyleableModel.prototype.removeStyle = function (prop) { var style = this.getStyle(); delete style[prop]; this.setStyle(style); }; /** * Returns string of style properties * @param {Object} [opts={}] Options * @return {String} */ StyleableModel.prototype.styleToString = function (opts) { if (opts === void 0) { opts = {}; } var result = []; var style = this.getStyle(opts); var imp = opts.important; var _loop_1 = function (prop) { var important = (0,index_all.isArray)(imp) ? imp.indexOf(prop) >= 0 : imp; var firstChars = prop.substring(0, 2); var isPrivate = firstChars === '__'; if (isPrivate) return "continue"; var value = style[prop]; var values = (0,index_all.isArray)(value) ? value : [value]; values.forEach(function (val) { var value = "".concat(val).concat(important ? ' !important' : ''); value && result.push("".concat(prop, ":").concat(value, ";")); }); }; for (var prop in style) { _loop_1(prop); } return result.join(''); }; StyleableModel.prototype.getSelectors = function () { return (this.get('selectors') || this.get('classes')); }; StyleableModel.prototype.getSelectorsString = function (opts) { // @ts-ignore return this.selectorsToString ? this.selectorsToString(opts) : this.getSelectors().getFullString(); }; return StyleableModel; }(common/* Model */.Hn)); /* harmony default export */ const model_StyleableModel = (StyleableModel); ;// CONCATENATED MODULE: ./src/dom_components/model/Components.ts var Components_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var Components_assign = ( false) || function () { Components_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return Components_assign.apply(this, arguments); }; var __rest = ( false) || 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 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; var Components_spreadArray = ( false) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var getComponentIds = function (cmp, res) { if (res === void 0) { res = []; } if (!cmp) return []; var cmps = ((0,index_all.isArray)(cmp) || (0,index_all.isFunction)(cmp.map) ? cmp : [cmp]); cmps.map(function (cmp) { res.push(cmp.getId()); getComponentIds(cmp.components().models, res); }); return res; }; var getComponentsFromDefs = function (items, all, opts) { if (all === void 0) { all = {}; } if (opts === void 0) { opts = {}; } opts.visitedCmps = opts.visitedCmps || {}; var visitedCmps = opts.visitedCmps; var itms = (0,index_all.isArray)(items) ? items : [items]; return itms.map(function (item) { var _a = item.attributes, attributes = _a === void 0 ? {} : _a, components = item.components, tagName = item.tagName; var id = attributes.id, draggable = attributes.draggable, restAttr = __rest(attributes, ["id", "draggable"]); var result = item; if (id) { // Detect components with the same ID if (!visitedCmps[id]) { visitedCmps[id] = []; // Update the component if exists already if (all[id]) { result = all[id]; tagName && result.set({ tagName: tagName }, Components_assign(Components_assign({}, opts), { silent: true })); (0,index_all.keys)(restAttr).length && result.addAttributes(restAttr, Components_assign({}, opts)); } } else { // Found another component with the same ID, treat it as a new component visitedCmps[id].push(result); id = model_Component.getNewId(all); result.attributes.id = id; } } if (components) { var newComponents = getComponentsFromDefs(components, all); if ((0,index_all.isFunction)(result.components)) { var cmps = result.components(); cmps.length > 0 && cmps.reset(newComponents, opts); } else { result.components = newComponents; } } return result; }); }; var Components = /** @class */ (function (_super) { Components_extends(Components, _super); function Components() { return _super !== null && _super.apply(this, arguments) || this; } Components.prototype.initialize = function (models, opt) { if (opt === void 0) { opt = {}; } this.opt = opt; this.listenTo(this, 'add', this.onAdd); this.listenTo(this, 'remove', this.removeChildren); this.listenTo(this, 'reset', this.resetChildren); var em = opt.em, config = opt.config; this.config = config; this.em = em; this.domc = opt.domc || (em === null || em === void 0 ? void 0 : em.Components); }; Components.prototype.resetChildren = function (models, opts) { var _this = this; if (opts === void 0) { opts = {}; } var coll = this; var prev = opts.previousModels || []; var toRemove = prev.filter(function (prev) { return !models.get(prev.cid); }); var newIds = getComponentIds(models); var idsToKeep = getComponentIds(prev).filter(function (pr) { return newIds.indexOf(pr) >= 0; }); opts.keepIds = (opts.keepIds || []).concat(idsToKeep); toRemove.forEach(function (md) { return _this.removeChildren(md, coll, opts); }); models.each(function (model) { return _this.onAdd(model); }); }; Components.prototype.resetFromString = function (input, opts) { var _a, _b; if (input === void 0) { input = ''; } if (opts === void 0) { opts = {}; } opts.keepIds = getComponentIds(this); var _c = this, domc = _c.domc, em = _c.em, parent = _c.parent; var cssc = em === null || em === void 0 ? void 0 : em.Css; var allByID = (domc === null || domc === void 0 ? void 0 : domc.allById()) || {}; var parsed = this.parseString(input, opts); var newCmps = getComponentsFromDefs(parsed, allByID, opts); var _d = opts.visitedCmps, visitedCmps = _d === void 0 ? {} : _d; // Clone styles for duplicated components Object.keys(visitedCmps).forEach(function (id) { var cmps = visitedCmps[id]; if (cmps.length) { // Get all available rules of the component var rulesToClone_1 = (cssc === null || cssc === void 0 ? void 0 : cssc.getRules("#".concat(id))) || []; if (rulesToClone_1.length) { cmps.forEach(function (cmp) { rulesToClone_1.forEach(function (rule) { var newRule = rule.clone(); // @ts-ignore newRule.set('selectors', ["#".concat(cmp.attributes.id)]); cssc.getAll().add(newRule); }); }); } } }); this.reset(newCmps, opts); em === null || em === void 0 ? void 0 : em.trigger('component:content', parent, opts, input); (_b = (_a = parent).__checkInnerChilds) === null || _b === void 0 ? void 0 : _b.call(_a); }; Components.prototype.removeChildren = function (removed, coll, opts) { var _this = this; if (opts === void 0) { opts = {}; } // Removing a parent component can cause this function // to be called with an already removed child element if (!removed) { return; } var _a = this, domc = _a.domc, em = _a.em; var isTemp = opts.temporary || opts.fromUndo; removed.prevColl = this; // This one is required for symbols if (!isTemp) { // Remove the component from the global list var id_1 = removed.getId(); var sels = em.Selectors.getAll(); var rules = em.Css.getAll(); var canRemoveStyle = (opts.keepIds || []).indexOf(id_1) < 0; var allByID = domc ? domc.allById() : {}; delete allByID[id_1]; // Remove all component related styles var rulesRemoved = (canRemoveStyle ? rules.remove(rules.filter(function (r) { return r.getSelectors().getFullString() === "#".concat(id_1); }), opts) : []); // Clean selectors sels.remove(rulesRemoved.map(function (rule) { return rule.getSelectors().at(0); })); if (!removed.opt.temporary) { em.Commands.run('core:component-style-clear', { target: removed, }); removed.removed(); removed.trigger('removed'); em.trigger('component:remove', removed); } var inner_1 = removed.components(); inner_1.forEach(function (it) { return _this.removeChildren(it, coll, opts); }); } // Remove stuff registered in DomComponents.handleChanges var inner = removed.components(); em.stopListening(inner); em.stopListening(removed); em.stopListening(removed.get('classes')); removed.__postRemove(); }; /** @ts-ignore */ Components.prototype.model = function (attrs, options) { var opt = options.collection.opt; var em = opt.em; var model; var df = em.Components.componentTypes; options.em = em; options.config = opt.config; options.componentTypes = df; options.domc = opt.domc; for (var it_1 = 0; it_1 < df.length; it_1++) { var dfId = df[it_1].id; if (dfId == attrs.type) { model = df[it_1].model; break; } } // If no model found, get the default one if (!model) { model = df[df.length - 1].model; em && attrs.type && em.logWarning("Component type '".concat(attrs.type, "' not found"), { attrs: attrs, options: options, }); } return new model(attrs, options); }; Components.prototype.parseString = function (value, opt) { if (opt === void 0) { opt = {}; } var _a = this, em = _a.em, domc = _a.domc; var cssc = em.Css; var parsed = em.Parser.parseHtml(value); // We need this to avoid duplicate IDs model_Component.checkId(parsed.html, parsed.css, domc.componentsById, opt); if (parsed.css && cssc && !opt.temporary) { var at = opt.at, optsToPass = __rest(opt, ["at"]); cssc.addCollection(parsed.css, Components_assign(Components_assign({}, optsToPass), { extend: 1 })); } return parsed.html; }; /** @ts-ignore */ Components.prototype.add = function (models, opt) { var _this = this; if (opt === void 0) { opt = {}; } opt.keepIds = Components_spreadArray(Components_spreadArray([], (opt.keepIds || []), true), getComponentIds(opt.previousModels), true); if ((0,index_all.isString)(models)) { models = this.parseString(models, opt); } else if ((0,index_all.isArray)(models)) { models = Components_spreadArray([], models, true); models.forEach(function (item, index) { if ((0,index_all.isString)(item)) { var nodes = _this.parseString(item, opt); models[index] = (0,index_all.isArray)(nodes) && !nodes.length ? null : nodes; } }); } var isMult = (0,index_all.isArray)(models); // @ts-ignore models = (isMult ? models : [models]).filter(Boolean).map(function (model) { return _this.processDef(model); }); // @ts-ignore models = isMult ? (0,index_all.flatten)(models, 1) : models[0]; var result = common/* Collection */.FE.prototype.add.apply(this, [models, opt]); this.__firstAdd = result; return result; }; /** * Process component definition. */ Components.prototype.processDef = function (mdl) { // Avoid processing Models if (mdl.cid && mdl.ccid) return mdl; var _a = this, em = _a.em, _b = _a.config, config = _b === void 0 ? {} : _b; var processor = config.processor; var model = mdl; if (processor) { model = Components_assign({}, model); // Avoid 'Cannot delete property ...' var modelPr = processor(model); if (modelPr) { (0,index_all.each)(model, function (val, key) { return delete model[key]; }); (0,index_all.extend)(model, modelPr); } } // React JSX preset if (model.$$typeof && typeof model.props == 'object') { model = Components_assign({}, model); model.props = Components_assign({}, model.props); var domc = em.Components; var parser = em.Parser; var parserHtml = parser.parserHtml; (0,index_all.each)(model, function (value, key) { if (!(0,index_all.includes)(['props', 'type'], key)) delete model[key]; }); var props = model.props; var comps = props.children; delete props.children; delete model.props; var res = parserHtml.splitPropsFromAttr(props); model.attributes = res.attrs; if (comps) { model.components = comps; } if (!model.type) { model.type = 'textnode'; } else if (!domc.getType(model.type)) { model.tagName = model.type; delete model.type; } (0,index_all.extend)(model, res.props); } return model; }; Components.prototype.onAdd = function (model, c, opts) { if (opts === void 0) { opts = {}; } var _a = this, domc = _a.domc, em = _a.em; var style = model.getStyle(); var avoidInline = em && em.getConfig().avoidInlineStyle; domc && domc.Component.ensureInList(model); // @ts-ignore if (!(0,index_all.isEmpty)(style) && !avoidInline && em && em.get && em.getConfig().forceClass && !opts.temporary) { var name_1 = model.cid; em.Css.setClassRule(name_1, style); model.setStyle({}); model.addClass(name_1); } model.__postAdd({ recursive: true }); // this.__onAddEnd(); }; return Components; }(common/* Collection */.FE)); /* harmony default export */ const model_Components = (Components); ;// CONCATENATED MODULE: ./src/selector_manager/model/Selector.ts var Selector_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var TYPE_CLASS = 1; var TYPE_ID = 2; /** * @typedef Selector * @property {String} name Selector name, eg. `my-class` * @property {String} label Selector label, eg. `My Class` * @property {Number} [type=1] Type of the selector. 1 (class) | 2 (id) * @property {Boolean} [active=true] If not active, it's not selectable by the Style Manager. * @property {Boolean} [private=false] If true, it can't be seen by the Style Manager, but it will be rendered in the canvas and in export code. * @property {Boolean} [protected=false] If true, it can't be removed from the attached component. */ var Selector = /** @class */ (function (_super) { Selector_extends(Selector, _super); /** * @hideconstructor */ function Selector(props, opts) { if (opts === void 0) { opts = {}; } var _this = _super.call(this, props, opts) || this; var _a = opts.config, config = _a === void 0 ? {} : _a; var name = _this.get('name'); var label = _this.get('label'); if (!name) { _this.set('name', label); } else if (!label) { _this.set('label', name); } var namePreEsc = _this.get('name'); var escapeName = config.escapeName; var nameEsc = escapeName ? escapeName(namePreEsc) : Selector.escapeName(namePreEsc); _this.set('name', nameEsc); _this.em = opts.em; return _this; } Selector.prototype.defaults = function () { return { name: '', label: '', type: TYPE_CLASS, active: true, private: false, protected: false, _undo: true, }; }; Selector.prototype.isId = function () { return this.get('type') === TYPE_ID; }; Selector.prototype.isClass = function () { return this.get('type') === TYPE_CLASS; }; Selector.prototype.getFullName = function (opts) { if (opts === void 0) { opts = {}; } var escape = opts.escape; var name = this.get('name'); var pfx = ''; switch (this.get('type')) { case TYPE_CLASS: pfx = '.'; break; case TYPE_ID: pfx = '#'; break; } return pfx + (escape ? escape(name) : name); }; /** * Get selector as a string. * @returns {String} * @example * // Given such selector: { name: 'my-selector', type: 2 } * console.log(selector.toString()); * // -> `#my-selector` */ Selector.prototype.toString = function () { return this.getFullName(); }; /** * Get selector label. * @returns {String} * @example * // Given such selector: { name: 'my-selector', label: 'My selector' } * console.log(selector.getLabel()); * // -> `My selector` */ Selector.prototype.getLabel = function () { return this.get('label'); }; /** * Update selector label. * @param {String} label New label * @example * // Given such selector: { name: 'my-selector', label: 'My selector' } * selector.setLabel('New Label') * console.log(selector.getLabel()); * // -> `New Label` */ Selector.prototype.setLabel = function (label) { return this.set('label', label); }; /** * Get selector active state. * @returns {Boolean} */ Selector.prototype.getActive = function () { return this.get('active'); }; /** * Update selector active state. * @param {Boolean} value New active state */ Selector.prototype.setActive = function (value) { return this.set('active', value); }; Selector.prototype.toJSON = function (opts) { if (opts === void 0) { opts = {}; } var em = this.em; var obj = common/* Model */.Hn.prototype.toJSON.call(this, [opts]); var defaults = (0,index_all.result)(this, 'defaults'); if (em && em.getConfig().avoidDefaults) { (0,index_all.forEach)(defaults, function (value, key) { if (obj[key] === value) { delete obj[key]; } }); if (obj.label === obj.name) { delete obj.label; } var objLen = (0,index_all.keys)(obj).length; if (objLen === 1 && obj.name) { obj = obj.name; } if (objLen === 2 && obj.name && obj.type) { obj = this.getFullName(); } } return obj; }; /** * Escape string * @param {string} name * @return {string} * @private */ Selector.escapeName = function (name) { return "".concat(name).trim().replace(/([^a-z0-9\w-\:@]+)/gi, '-'); }; // Type selectors: https://developer.mozilla.org/it/docs/Web/CSS/CSS_Selectors Selector.TYPE_CLASS = TYPE_CLASS; Selector.TYPE_ID = TYPE_ID; return Selector; }(common/* Model */.Hn)); /* harmony default export */ const model_Selector = (Selector); Selector.prototype.idAttribute = 'name'; ;// CONCATENATED MODULE: ./src/selector_manager/model/Selectors.ts var Selectors_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var combine = function (tail, curr) { return tail.reduce(function (acc, item, n) { return acc.concat(combine(tail.slice(n + 1), "".concat(curr).concat(item))); }, [curr]); }; var Selectors = /** @class */ (function (_super) { Selectors_extends(Selectors, _super); function Selectors() { return _super !== null && _super.apply(this, arguments) || this; } Selectors.prototype.modelId = function (attr) { return "".concat(attr.name, "_").concat(attr.type || model_Selector.TYPE_CLASS); }; Selectors.prototype.getStyleable = function () { return (0,index_all.filter)(this.models, function (item) { return item.get('active') && !item.get('private'); }); }; Selectors.prototype.getValid = function (_a) { var _b = _a === void 0 ? {} : _a, noDisabled = _b.noDisabled; return (0,index_all.filter)(this.models, function (item) { return !item.get('private'); }).filter(function (item) { return noDisabled ? item.get('active') : 1; }); }; Selectors.prototype.getFullString = function (collection, opts) { if (opts === void 0) { opts = {}; } var result = []; var coll = collection || this; coll.forEach(function (selector) { return result.push(selector.getFullName(opts)); }); opts.sort && result.sort(); return result.join('').trim(); }; Selectors.prototype.getFullName = function (opts) { if (opts === void 0) { opts = {}; } var combination = opts.combination, array = opts.array; var result = []; var sels = this.map(function (s) { return s.getFullName(opts); }).sort(); if (combination) { sels.forEach(function (sel, n) { result = result.concat(combine(sels.slice(n + 1), sel)); }); } else { result = sels; } return array ? result : combination ? result.join(',') : result.join(''); }; return Selectors; }(common/* Collection */.FE)); /* harmony default export */ const model_Selectors = (Selectors); Selectors.prototype.model = model_Selector; ;// CONCATENATED MODULE: ./src/trait_manager/model/Trait.ts var Trait_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var Trait_assign = ( false) || function () { Trait_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return Trait_assign.apply(this, arguments); }; /** * @typedef Trait * @property {String} id Trait id, eg. `my-trait-id`. * @property {String} type Trait type, defines how the trait should rendered. Possible values: `text` (default), `number`, `select`, `checkbox`, `color`, `button` * @property {String} label The trait label to show for the rendered trait. * @property {String} name The name of the trait used as a key for the attribute/property. By default, the name is used as attribute name or property in case `changeProp` in enabled. * @property {Boolean} changeProp If `true` the trait value is applied on component * */ var Trait = /** @class */ (function (_super) { Trait_extends(Trait, _super); function Trait(prop, em) { var _this = _super.call(this, prop) || this; var _a = _this.attributes, target = _a.target, name = _a.name; !_this.get('id') && _this.set('id', name); if (target) { _this.setTarget(target); } _this.em = em; return _this; } Trait.prototype.defaults = function () { return { type: 'text', label: '', name: '', unit: '', step: 1, value: '', default: '', placeholder: '', changeProp: false, options: [], }; }; Trait.prototype.setTarget = function (target) { if (target) { var _a = this.attributes, name_1 = _a.name, changeProp = _a.changeProp, initValue = _a.value; this.target = target; this.unset('target'); var targetEvent = changeProp ? "change:".concat(name_1) : "change:attributes:".concat(name_1); this.listenTo(target, targetEvent, this.targetUpdated); var value = initValue || this.getValue(); !(0,index_all.isUndefined)(value) && this.set({ value: value }, { silent: true }); } }; /** * Get the trait id. * @returns {String} */ Trait.prototype.getId = function () { return this.get('id'); }; /** * Get the trait type. * @returns {String} */ Trait.prototype.getType = function () { return this.get('type'); }; /** * Get the trait name. * @returns {String} */ Trait.prototype.getName = function () { return this.get('name'); }; /** * Get the trait label. * @param {Object} [opts={}] Options. * @param {Boolean} [opts.locale=true] Use the locale string from i18n module. * @returns {String} */ Trait.prototype.getLabel = function (opts) { var _a; if (opts === void 0) { opts = {}; } var _b = opts.locale, locale = _b === void 0 ? true : _b; var id = this.getId(); var name = this.get('label') || this.getName(); return (locale && ((_a = this.em) === null || _a === void 0 ? void 0 : _a.t("traitManager.traits.labels.".concat(id)))) || name; }; /** * Get the trait value. * The value is taken from component attributes by default or from properties if the trait has the `changeProp` enabled. * @returns {any} */ Trait.prototype.getValue = function () { return this.getTargetValue(); }; /** * Update the trait value. * The value is applied on component attributes by default or on properties if the trait has the `changeProp` enabled. * @param {any} value Value of the trait. * @param {Object} [opts={}] Options. * @param {Boolean} [opts.partial] If `true` the update won't be considered complete (not stored in UndoManager). */ Trait.prototype.setValue = function (value, opts) { var _this = this; var _a; if (opts === void 0) { opts = {}; } var valueOpts = {}; var setValue = this.get('setValue'); if (setValue) { setValue({ value: value, editor: (_a = this.em) === null || _a === void 0 ? void 0 : _a.getEditor(), trait: this, component: this.target, partial: !!opts.partial, emitUpdate: function () { return _this.targetUpdated(); }, }); return; } if (opts.partial) { valueOpts.avoidStore = true; } this.setTargetValue(value, valueOpts); if (opts.partial === false) { this.setTargetValue(''); this.setTargetValue(value); } }; /** * Get default value. */ Trait.prototype.getDefault = function () { return this.get('default'); }; /** * Get trait options. */ Trait.prototype.getOptions = function () { return this.get('options') || []; }; /** * Get current selected option or by id. * @param {String} [id] Option id. * @returns {Object | null} */ Trait.prototype.getOption = function (id) { var _this = this; var idSel = (0,mixins.isDef)(id) ? id : this.getValue(); return this.getOptions().filter(function (o) { return _this.getOptionId(o) === idSel; })[0]; }; /** * Get the option id from the option object. * @param {Object} option Option object * @returns {String} Option id */ Trait.prototype.getOptionId = function (option) { return option.id || option.value; }; /** * Get option label. * @param {String|Object} id Option id or the option object * @param {Object} [opts={}] Options * @param {Boolean} [opts.locale=true] Use the locale string from i18n module * @returns {String} Option label */ Trait.prototype.getOptionLabel = function (id, opts) { var _a; if (opts === void 0) { opts = {}; } var _b = opts.locale, locale = _b === void 0 ? true : _b; var option = ((0,index_all.isString)(id) ? this.getOption(id) : id); var optId = this.getOptionId(option); var label = option.label || option.name || optId; var propName = this.getName(); return (locale && ((_a = this.em) === null || _a === void 0 ? void 0 : _a.t("traitManager.traits.options.".concat(propName, ".").concat(optId)))) || label; }; Trait.prototype.props = function () { return this.attributes; }; Trait.prototype.targetUpdated = function () { var _a; var value = this.getTargetValue(); this.set({ value: value }, { fromTarget: 1 }); (_a = this.em) === null || _a === void 0 ? void 0 : _a.trigger('trait:update', { trait: this, component: this.target, }); }; Trait.prototype.getTargetValue = function () { var _a; var name = this.getName(); var target = this.target; var getValue = this.get('getValue'); var value; if (getValue) { value = getValue({ editor: (_a = this.em) === null || _a === void 0 ? void 0 : _a.getEditor(), trait: this, component: target, }); } else if (this.get('changeProp')) { value = target.get(name); } else { // @ts-ignore TODO update post component update value = target.getAttributes()[name]; } return !(0,index_all.isUndefined)(value) ? value : ''; }; Trait.prototype.setTargetValue = function (value, opts) { var _a; if (opts === void 0) { opts = {}; } var _b = this, target = _b.target, attributes = _b.attributes; var name = this.getName(); if ((0,index_all.isUndefined)(value)) return; var valueToSet = value; if (value === 'false') { valueToSet = false; } else if (value === 'true') { valueToSet = true; } if (this.getType() === 'checkbox') { var valueTrue = attributes.valueTrue, valueFalse = attributes.valueFalse; if (valueToSet && !(0,index_all.isUndefined)(valueTrue)) { valueToSet = valueTrue; } if (!valueToSet && !(0,index_all.isUndefined)(valueFalse)) { valueToSet = valueFalse; } } if (this.get('changeProp')) { target.set(name, valueToSet, opts); } else { target.addAttributes((_a = {}, _a[name] = valueToSet, _a), opts); } }; Trait.prototype.setValueFromInput = function (value, final, opts) { if (final === void 0) { final = true; } if (opts === void 0) { opts = {}; } var toSet = { value: value }; this.set(toSet, Trait_assign(Trait_assign({}, opts), { avoidStore: 1 })); // Have to trigger the change if (final) { this.set('value', '', opts); this.set(toSet, opts); } }; Trait.prototype.getInitValue = function () { var target = this.target; var name = this.getName(); var value; if (target) { var attrs = target.get('attributes'); value = this.get('changeProp') ? target.get(name) : attrs[name]; } return value || this.get('value') || this.get('default'); }; return Trait; }(common/* Model */.Hn)); /* harmony default export */ const model_Trait = (Trait); ;// CONCATENATED MODULE: ./src/trait_manager/model/TraitFactory.ts var TraitFactory = /** @class */ (function () { function TraitFactory(config) { if (config === void 0) { config = {}; } this.config = config; } /** * Build props object by their name */ TraitFactory.prototype.build = function (prop, em) { return (0,index_all.isString)(prop) ? this.buildFromString(prop, em) : new model_Trait(prop, em); }; TraitFactory.prototype.buildFromString = function (name, em) { var obj = { name: name, type: 'text', }; switch (name) { case 'target': obj.type = 'select'; obj.default = false; obj.options = this.config.optionsTarget; break; } return new model_Trait(obj, em); }; return TraitFactory; }()); /* harmony default export */ const model_TraitFactory = (TraitFactory); ;// CONCATENATED MODULE: ./src/trait_manager/model/Traits.ts var Traits_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var Traits = /** @class */ (function (_super) { Traits_extends(Traits, _super); function Traits(coll, options) { var _a; var _this = _super.call(this, coll) || this; _this.em = options.em; _this.listenTo(_this, 'add', _this.handleAdd); _this.listenTo(_this, 'reset', _this.handleReset); var tm = (_a = _this.em) === null || _a === void 0 ? void 0 : _a.Traits; var tmOpts = tm === null || tm === void 0 ? void 0 : tm.getConfig(); _this.tf = new model_TraitFactory(tmOpts); return _this; } Traits.prototype.handleReset = function (coll, _a) { var _b = _a === void 0 ? {} : _a, _c = _b.previousModels, previousModels = _c === void 0 ? [] : _c; previousModels.forEach(function (model) { return model.trigger('remove'); }); }; Traits.prototype.handleAdd = function (model) { model.em = this.em; var target = this.target; if (target) { model.target = target; } }; Traits.prototype.setTarget = function (target) { this.target = target; this.models.forEach(function (trait) { return trait.setTarget(target); }); }; Traits.prototype.add = function (models, opt) { if (models == undefined) { return undefined; } var _a = this, target = _a.target, em = _a.em; if ((0,index_all.isArray)(models)) { var traits = []; for (var i = 0, len = models.length; i < len; i++) { var trait_1 = models[i]; traits[i] = trait_1 instanceof model_Trait ? trait_1 : this.tf.build(trait_1, em); traits[i].setTarget(target); } return _super.prototype.add.call(this, traits, opt); } var trait = models instanceof model_Trait ? models : this.tf.build(models, em); trait.setTarget(target); return _super.prototype.add.call(this, trait, opt); }; return Traits; }(common/* Collection */.FE)); /* harmony default export */ const model_Traits = (Traits); ;// CONCATENATED MODULE: ./src/dom_components/model/Component.ts var Component_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var Component_assign = ( false) || function () { Component_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return Component_assign.apply(this, arguments); }; var Component_rest = ( false) || 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 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; var Component_spreadArray = ( false) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var escapeRegExp = function (str) { return str.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&'); }; var avoidInline = function (em) { return !!(em === null || em === void 0 ? void 0 : em.getConfig().avoidInlineStyle); }; var eventDrag = 'component:drag'; var keySymbols = '__symbols'; var keySymbol = '__symbol'; var keySymbolOvrd = '__symbol_ovrd'; var keyUpdate = 'component:update'; var keyUpdateInside = "".concat(keyUpdate, "-inside"); /** * The Component object represents a single node of our template structure, so when you update its properties the changes are * immediately reflected on the canvas and in the code to export (indeed, when you ask to export the code we just go through all * the tree of nodes). * An example on how to update properties: * ```js * component.set({ * tagName: 'span', * attributes: { ... }, * removable: false, * }); * component.get('tagName'); * // -> 'span' * ``` * * [Component]: component.html * * @property {String} [type=''] Component type, eg. `text`, `image`, `video`, etc. * @property {String} [tagName='div'] HTML tag of the component, eg. `span`. Default: `div` * @property {Object} [attributes={}] Key-value object of the component's attributes, eg. `{ title: 'Hello' }` Default: `{}` * @property {String} [name=''] Name of the component. Will be used, for example, in Layers and badges * @property {Boolean} [removable=true] When `true` the component is removable from the canvas, default: `true` * @property {Boolean|String|Function} [draggable=true] Indicates if it's possible to drag the component inside others. * You can also specify a query string to indentify elements, * eg. `'.some-class[title=Hello], [data-gjs-type=column]'` means you can drag the component only inside elements * containing `some-class` class and `Hello` title, and `column` components. In the case of a function, target and destination components are passed as arguments, return a Boolean to indicate if the drag is possible. Default: `true` * @property {Boolean|String|Function} [droppable=true] Indicates if it's possible to drop other components inside. You can use * a query string as with `draggable`. In the case of a function, target and destination components are passed as arguments, return a Boolean to indicate if the drop is possible. Default: `true` * @property {Boolean} [badgable=true] Set to false if you don't want to see the badge (with the name) over the component. Default: `true` * @property {Boolean|Array<String>} [stylable=true] True if it's possible to style the component. * You can also indicate an array of CSS properties which is possible to style, eg. `['color', 'width']`, all other properties * will be hidden from the style manager. Default: `true` * @property {Array<String>} [stylable-require=[]] Indicate an array of style properties to show up which has been marked as `toRequire`. Default: `[]` * @property {Array<String>} [unstylable=[]] Indicate an array of style properties which should be hidden from the style manager. Default: `[]` * @property {Boolean} [highlightable=true] It can be highlighted with 'dotted' borders if true. Default: `true` * @property {Boolean} [copyable=true] True if it's possible to clone the component. Default: `true` * @property {Boolean} [resizable=false] Indicates if it's possible to resize the component. It's also possible to pass an object as [options for the Resizer](https://github.com/GrapesJS/grapesjs/blob/master/src/utils/Resizer.js). Default: `false` * @property {Boolean} [editable=false] Allow to edit the content of the component (used on Text components). Default: `false` * @property {Boolean} [layerable=true] Set to `false` if you need to hide the component inside Layers. Default: `true` * @property {Boolean} [selectable=true] Allow component to be selected when clicked. Default: `true` * @property {Boolean} [hoverable=true] Shows a highlight outline when hovering on the element if `true`. Default: `true` * @property {Boolean} [locked=false] Disable the selection of the component and its children in the canvas. Default: `false` * @property {Boolean} [void=false] This property is used by the HTML exporter as void elements don't have closing tags, eg. `<br/>`, `<hr/>`, etc. Default: `false` * @property {Object} [style={}] Component default style, eg. `{ width: '100px', height: '100px', 'background-color': 'red' }` * @property {String} [styles=''] Component related styles, eg. `.my-component-class { color: red }` * @property {String} [content=''] Content of the component (not escaped) which will be appended before children rendering. Default: `''` * @property {String} [icon=''] Component's icon, this string will be inserted before the name (in Layers and badge), eg. it can be an HTML string '<i class="fa fa-square-o"></i>'. Default: `''` * @property {String|Function} [script=''] Component's javascript. More about it [here](/modules/Components-js.html). Default: `''` * @property {String|Function} [script-export=''] You can specify javascript available only in export functions (eg. when you get the HTML). * If this property is defined it will overwrite the `script` one (in export functions). Default: `''` * @property {Array<Object|String>} [traits=''] Component's traits. More about it [here](/modules/Traits.html). Default: `['id', 'title']` * @property {Array<String>} [propagate=[]] Indicates an array of properties which will be inhereted by all NEW appended children. * For example if you create a component likes this: `{ removable: false, draggable: false, propagate: ['removable', 'draggable'] }` * and append some new component inside, the new added component will get the exact same properties indicated in the `propagate` array (and the `propagate` property itself). Default: `[]` * @property {Array<Object>} [toolbar=null] Set an array of items to show up inside the toolbar when the component is selected (move, clone, delete). * Eg. `toolbar: [ { attributes: {class: 'fa fa-arrows'}, command: 'tlb-move' }, ... ]`. * By default, when `toolbar` property is falsy the editor will add automatically commands `core:component-exit` (select parent component, added if there is one), `tlb-move` (added if `draggable`) , `tlb-clone` (added if `copyable`), `tlb-delete` (added if `removable`). * @property {Collection<Component>} [components=null] Children components. Default: `null` * * @module docsjs.Component */ var Component = /** @class */ (function (_super) { Component_extends(Component, _super); function Component() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(Component.prototype, "defaults", { /** * @private * @ts-ignore */ get: function () { var _a; return _a = { tagName: 'div', type: '', name: '', removable: true, draggable: true, droppable: true, badgable: true, stylable: true, 'stylable-require': '', 'style-signature': '', unstylable: '', highlightable: true, copyable: true, resizable: false, editable: false, layerable: true, selectable: true, hoverable: true, locked: false, void: false, state: '', status: '', content: '', icon: '', style: '', styles: '', classes: '', script: '', 'script-props': '', 'script-export': '', attributes: {}, traits: ['id', 'title'], propagate: '', dmode: '', toolbar: null }, _a[keySymbol] = 0, _a[keySymbols] = 0, _a[keySymbolOvrd] = 0, _a._undo = true, _a._undoexc = ['status', 'open'], _a; }, enumerable: false, configurable: true }); Object.defineProperty(Component.prototype, "classes", { get: function () { return this.get('classes'); }, enumerable: false, configurable: true }); Object.defineProperty(Component.prototype, "traits", { get: function () { return this.get('traits'); }, enumerable: false, configurable: true }); Object.defineProperty(Component.prototype, "content", { get: function () { var _a; return (_a = this.get('content')) !== null && _a !== void 0 ? _a : ''; }, enumerable: false, configurable: true }); Object.defineProperty(Component.prototype, "toolbar", { get: function () { return this.get('toolbar') || []; }, enumerable: false, configurable: true }); Object.defineProperty(Component.prototype, "resizable", { get: function () { return this.get('resizable'); }, enumerable: false, configurable: true }); /** * Hook method, called once the model is created */ Component.prototype.init = function () { }; /** * Hook method, called when the model has been updated (eg. updated some model's property) * @param {String} property Property name, if triggered after some property update * @param {*} value Property value, if triggered after some property update * @param {*} previous Property previous value, if triggered after some property update */ Component.prototype.updated = function (property, value, previous) { }; /** * Hook method, called once the model has been removed */ Component.prototype.removed = function () { }; Component.prototype.initialize = function (props, opt) { var _this = this; if (props === void 0) { props = {}; } if (opt === void 0) { opt = {}; } (0,index_all.bindAll)(this, '__upSymbProps', '__upSymbCls', '__upSymbComps'); var em = opt.em; // Propagate properties from parent if indicated var parent = this.parent(); var parentAttr = parent === null || parent === void 0 ? void 0 : parent.attributes; var propagate = this.get('propagate'); propagate && this.set('propagate', (0,index_all.isArray)(propagate) ? propagate : [propagate]); if (parentAttr && parentAttr.propagate && !propagate) { var newAttr_1 = {}; var toPropagate = parentAttr.propagate; toPropagate.forEach(function (prop) { return (newAttr_1[prop] = parent.get(prop)); }); newAttr_1.propagate = toPropagate; this.set(Component_assign(Component_assign({}, newAttr_1), props)); } // Check void elements if (opt && opt.config && opt.config.voidElements.indexOf(this.get('tagName')) >= 0) { this.set('void', true); } opt.em = em; this.opt = opt; this.em = em; this.frame = opt.frame; this.config = opt.config || {}; this.set('attributes', Component_assign(Component_assign({}, ((0,index_all.result)(this, 'defaults').attributes || {})), (this.get('attributes') || {}))); this.ccid = Component.createId(this, opt); this.initClasses(); this.initComponents(); this.initTraits(); this.initToolbar(); this.initScriptProps(); this.listenTo(this, 'change:script', this.scriptUpdated); this.listenTo(this, 'change:tagName', this.tagUpdated); this.listenTo(this, 'change:attributes', this.attrUpdated); this.listenTo(this, 'change:attributes:id', this._idUpdated); this.on('change:toolbar', this.__emitUpdateTlb); this.on('change', this.__onChange); this.on(keyUpdateInside, this.__propToParent); this.set('status', ''); this.views = []; // Register global updates for collection properties ['classes', 'traits', 'components'].forEach(function (name) { var events = "add remove ".concat(name !== 'components' ? 'change' : ''); _this.listenTo(_this.get(name), events.trim(), function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return _this.emitUpdate.apply(_this, Component_spreadArray([name], args, false)); }); }); if (!opt.temporary) { // Add component styles var cssc = em && em.Css; var _a = this.attributes, styles = _a.styles, type = _a.type; if (styles && cssc) { cssc.addCollection(styles, { avoidUpdateStyle: true }, { group: "cmp:".concat(type) }); } this.__postAdd(); this.init(); this.__isSymbolOrInst() && this.__initSymb(); em && em.trigger('component:create', this); } }; Component.prototype.__postAdd = function (opts) { if (opts === void 0) { opts = {}; } var em = this.em; var um = em === null || em === void 0 ? void 0 : em.UndoManager; var comps = this.components(); if (um && !this.__hasUm) { um.add(comps); um.add(this.getSelectors()); this.__hasUm = true; } opts.recursive && comps.map(function (c) { return c.__postAdd(opts); }); }; Component.prototype.__postRemove = function () { var em = this.em; var um = em === null || em === void 0 ? void 0 : em.get('UndoManager'); if (um) { um.remove(this.components()); um.remove(this.getSelectors()); delete this.__hasUm; } }; Component.prototype.__onChange = function (m, opts) { var _this = this; var changed = this.changedAttributes() || {}; (0,index_all.keys)(changed).forEach(function (prop) { return _this.emitUpdate(prop); }); ['status', 'open', 'toolbar', 'traits'].forEach(function (name) { return delete changed[name]; }); // Propagate component prop changes if (!(0,mixins.isEmptyObj)(changed)) { this.__changesUp(opts); this.__propSelfToParent({ component: this, changed: changed, options: opts }); } }; Component.prototype.__changesUp = function (opts) { var _a = this, em = _a.em, frame = _a.frame; [frame, em].forEach(function (md) { return md && md.changesUp(opts); }); }; Component.prototype.__propSelfToParent = function (props) { this.trigger(keyUpdate, props); this.__propToParent(props); }; Component.prototype.__propToParent = function (props) { var parent = this.parent(); parent && parent.trigger(keyUpdateInside, props); }; Component.prototype.__emitUpdateTlb = function () { this.emitUpdate('toolbar'); }; /** * Check component's type * @param {string} type Component type * @return {Boolean} * @example * component.is('image') * // -> false */ Component.prototype.is = function (type) { return !!(this.get('type') == type); }; /** * Return all the propeties * @returns {Object} */ Component.prototype.props = function () { return this.attributes; }; /** * Get the index of the component in the parent collection. * @return {Number} */ Component.prototype.index = function () { var collection = this.collection; return collection ? collection.indexOf(this) : 0; }; /** * Change the drag mode of the component. * To get more about this feature read: https://github.com/GrapesJS/grapesjs/issues/1936 * @param {String} value Drag mode, options: `'absolute'` | `'translate'` | `''` * @returns {this} */ Component.prototype.setDragMode = function (value) { return this.set('dmode', value); }; /** * Get the drag mode of the component. * @returns {String} Drag mode value, options: `'absolute'` | `'translate'` | `''` */ Component.prototype.getDragMode = function () { return this.get('dmode') || ''; }; /** * Find inner components by query string. * **ATTENTION**: this method works only with already rendered component * @param {String} query Query string * @return {Array} Array of components * @example * component.find('div > .class'); * // -> [Component, Component, ...] */ Component.prototype.find = function (query) { var _a; var result = []; var $els = (_a = this.view) === null || _a === void 0 ? void 0 : _a.$el.find(query); $els === null || $els === void 0 ? void 0 : $els.each(function (i) { var $el = $els.eq(i); var model = $el.data('model'); model && result.push(model); }); return result; }; /** * Find all inner components by component type. * The advantage of this method over `find` is that you can use it * also before rendering the component * @param {String} type Component type * @returns {Array<Component>} * @example * const allImages = component.findType('image'); * console.log(allImages[0]) // prints the first found component */ Component.prototype.findType = function (type) { var result = []; var find = function (components) { return components.forEach(function (item) { item.is(type) && result.push(item); find(item.components()); }); }; find(this.components()); return result; }; /** * Find the closest parent component by query string. * **ATTENTION**: this method works only with already rendered component * @param {string} query Query string * @return {Component} * @example * component.closest('div.some-class'); * // -> Component */ Component.prototype.closest = function (query) { var _a; var result = (_a = this.view) === null || _a === void 0 ? void 0 : _a.$el.closest(query); return (result === null || result === void 0 ? void 0 : result.length) ? result.data('model') : undefined; }; /** * Find the closest parent component by its type. * The advantage of this method over `closest` is that you can use it * also before rendering the component * @param {String} type Component type * @returns {Component} Found component, otherwise `undefined` * @example * const Section = component.closestType('section'); * console.log(Section); */ Component.prototype.closestType = function (type) { var parent = this.parent(); while (parent && !parent.is(type)) { parent = parent.parent(); } return parent; }; /** * The method returns a Boolean value indicating whether the passed * component is a descendant of a given component * @param {Component} component Component to check * @returns {Boolean} */ Component.prototype.contains = function (component) { var result = !1; if (!component) return result; var contains = function (components) { !result && components.forEach(function (item) { if (item === component) result = !0; !result && contains(item.components()); }); }; contains(this.components()); return result; }; /** * Once the tag is updated I have to rerender the element * @private */ Component.prototype.tagUpdated = function () { this.trigger('rerender'); }; /** * Replace a component with another one * @param {String|Component} el Component or HTML string * @return {Component|Array<Component>} New added component/s * @example * component.replaceWith('<div>Some new content</div>'); * // -> Component */ Component.prototype.replaceWith = function (el) { var coll = this.collection; var at = coll.indexOf(this); coll.remove(this); return coll.add(el, { at: at }); }; /** * Emit changes for each updated attribute * @private */ Component.prototype.attrUpdated = function (m, v, opts) { var _this = this; if (opts === void 0) { opts = {}; } var attrs = this.get('attributes'); // Handle classes var classes = attrs.class; classes && this.setClass(classes); delete attrs.class; // Handle style var style = attrs.style; style && this.setStyle(style); delete attrs.style; var attrPrev = Component_assign({}, this.previous('attributes')); var diff = (0,mixins.shallowDiff)(attrPrev, this.get('attributes')); (0,index_all.keys)(diff).forEach(function (pr) { return _this.trigger("change:attributes:".concat(pr), _this, diff[pr], opts); }); }; /** * Update attributes of the component * @param {Object} attrs Key value attributes * @param {Object} options Options for the model update * @return {this} * @example * component.setAttributes({ id: 'test', 'data-key': 'value' }); */ Component.prototype.setAttributes = function (attrs, opts) { if (opts === void 0) { opts = {}; } this.set('attributes', Component_assign({}, attrs), opts); return this; }; /** * Add attributes to the component * @param {Object} attrs Key value attributes * @param {Object} options Options for the model update * @return {this} * @example * component.addAttributes({ 'data-key': 'value' }); */ Component.prototype.addAttributes = function (attrs, opts) { if (opts === void 0) { opts = {}; } return this.setAttributes(Component_assign(Component_assign({}, this.getAttributes({ noClass: true })), attrs), opts); }; /** * Remove attributes from the component * @param {String|Array<String>} attrs Array of attributes to remove * @param {Object} options Options for the model update * @return {this} * @example * component.removeAttributes('some-attr'); * component.removeAttributes(['some-attr1', 'some-attr2']); */ Component.prototype.removeAttributes = function (attrs, opts) { if (attrs === void 0) { attrs = []; } if (opts === void 0) { opts = {}; } var attrArr = Array.isArray(attrs) ? attrs : [attrs]; var compAttr = this.getAttributes(); attrArr.map(function (i) { return delete compAttr[i]; }); return this.setAttributes(compAttr, opts); }; /** * Get the style of the component * @return {Object} */ Component.prototype.getStyle = function (options, optsAdd) { if (options === void 0) { options = {}; } if (optsAdd === void 0) { optsAdd = {}; } var em = this.em; var prop = (0,index_all.isString)(options) ? options : ''; var opts = prop ? optsAdd : options; if (avoidInline(em) && !opts.inline) { var state = em.get('state'); var cc = em.Css; var rule = cc.getIdRule(this.getId(), Component_assign({ state: state }, opts)); this.rule = rule; if (rule) { return rule.getStyle(prop); } } return _super.prototype.getStyle.call(this, prop); }; /** * Set the style on the component * @param {Object} prop Key value style object * @return {Object} * @example * component.setStyle({ color: 'red' }); */ Component.prototype.setStyle = function (prop, opts) { var _this = this; if (prop === void 0) { prop = {}; } if (opts === void 0) { opts = {}; } var _a = this, opt = _a.opt, em = _a.em; if (avoidInline(em) && !opt.temporary && !opts.inline) { var style = this.get('style') || {}; prop = (0,index_all.isString)(prop) ? this.parseStyle(prop) : prop; prop = Component_assign(Component_assign({}, prop), style); var state = em.get('state'); var cc = em.Css; var propOrig = this.getStyle(opts); this.rule = cc.setIdRule(this.getId(), prop, Component_assign({ state: state }, opts)); var diff = (0,mixins.shallowDiff)(propOrig, prop); this.set('style', '', { silent: true }); (0,index_all.keys)(diff).forEach(function (pr) { return _this.trigger("change:style:".concat(pr)); }); } else { prop = _super.prototype.setStyle.apply(this, arguments); } return prop; }; /** * Return all component's attributes * @return {Object} */ Component.prototype.getAttributes = function (opts) { if (opts === void 0) { opts = {}; } var em = this.em; var classes = []; var attributes = Component_assign({}, this.get('attributes')); var sm = em === null || em === void 0 ? void 0 : em.Selectors; var id = this.getId(); // Add classes if (opts.noClass) { delete attributes.class; } else { this.classes.forEach(function (cls) { return classes.push((0,index_all.isString)(cls) ? cls : cls.get('name')); }); classes.length && (attributes.class = classes.join(' ')); } // Add style if (!opts.noStyle) { var style = this.get('style'); if ((0,mixins.isObject)(style) && !(0,mixins.isEmptyObj)(style)) { attributes.style = this.styleToString({ inline: 1 }); } } // Check if we need an ID on the component if (!(0,index_all.has)(attributes, 'id')) { var addId = false; // If we don't rely on inline styling we have to check // for the ID selector if (avoidInline(em) || !(0,index_all.isEmpty)(this.getStyle())) { addId = !!(sm === null || sm === void 0 ? void 0 : sm.get(id, sm.Selector.TYPE_ID)); } // Symbols should always have an id if (this.__getSymbol() || this.__getSymbols()) { addId = true; } if (addId) { attributes.id = id; } } return attributes; }; /** * Add classes * @param {Array<String>|String} classes Array or string of classes * @return {Array} Array of added selectors * @example * model.addClass('class1'); * model.addClass('class1 class2'); * model.addClass(['class1', 'class2']); * // -> [SelectorObject, ...] */ Component.prototype.addClass = function (classes) { var added = this.em.Selectors.addClass(classes); return this.classes.add(added); }; /** * Set classes (resets current collection) * @param {Array<String>|String} classes Array or string of classes * @return {Array} Array of added selectors * @example * model.setClass('class1'); * model.setClass('class1 class2'); * model.setClass(['class1', 'class2']); * // -> [SelectorObject, ...] */ Component.prototype.setClass = function (classes) { this.classes.reset(); return this.addClass(classes); }; /** * Remove classes * @param {Array<String>|String} classes Array or string of classes * @return {Array} Array of removed selectors * @example * model.removeClass('class1'); * model.removeClass('class1 class2'); * model.removeClass(['class1', 'class2']); * // -> [SelectorObject, ...] */ Component.prototype.removeClass = function (classes) { var removed = []; classes = (0,index_all.isArray)(classes) ? classes : [classes]; var selectors = this.classes; var type = model_Selector.TYPE_CLASS; classes.forEach(function (classe) { var classes = classe.split(' '); classes.forEach(function (name) { var selector = selectors.where({ name: name, type: type })[0]; selector && removed.push(selectors.remove(selector)); }); }); return removed; }; /** * Returns component's classes as an array of strings * @return {Array} */ Component.prototype.getClasses = function () { var attr = this.getAttributes(); var classStr = attr.class; return classStr ? classStr.split(' ') : []; }; Component.prototype.__logSymbol = function (type, toUp, opts) { if (opts === void 0) { opts = {}; } var symbol = this.__getSymbol(); var symbols = this.__getSymbols(); if (!symbol && !symbols) return; this.em.log(type, { model: this, toUp: toUp, context: 'symbols', opts: opts }); }; Component.prototype.__initSymb = function () { if (this.__symbReady) return; this.on('change', this.__upSymbProps); this.__symbReady = true; }; Component.prototype.__isSymbol = function () { return (0,index_all.isArray)(this.get(keySymbols)); }; Component.prototype.__isSymbolOrInst = function () { return !!(this.__isSymbol() || this.get(keySymbol)); }; Component.prototype.__isSymbolTop = function () { var parent = this.parent(); var symb = this.__isSymbolOrInst(); return symb && (!parent || (parent && !parent.__isSymbol() && !parent.__getSymbol())); }; Component.prototype.__isSymbolNested = function () { if (!this.__isSymbolOrInst() || this.__isSymbolTop()) return false; var symbTopSelf = (this.__isSymbol() ? this : this.__getSymbol()).__getSymbTop(); var symbTop = this.__getSymbTop(); var symbTopMain = symbTop.__isSymbol() ? symbTop : symbTop.__getSymbol(); return symbTopMain !== symbTopSelf; }; Component.prototype.__getAllById = function () { var em = this.em; return em ? em.Components.allById() : {}; }; Component.prototype.__getSymbol = function () { var symb = this.get(keySymbol); if (symb && (0,index_all.isString)(symb)) { var ref = this.__getAllById()[symb]; if (ref) { symb = ref; this.set(keySymbol, ref); } else { symb = 0; } } return symb; }; Component.prototype.__getSymbols = function () { var _this = this; var symbs = this.get(keySymbols); if (symbs && (0,index_all.isArray)(symbs)) { symbs.forEach(function (symb, idx) { if (symb && (0,index_all.isString)(symb)) { symbs[idx] = _this.__getAllById()[symb]; } }); symbs = symbs.filter(function (symb) { return symb && !(0,index_all.isString)(symb); }); } return symbs; }; Component.prototype.__isSymbOvrd = function (prop) { if (prop === void 0) { prop = ''; } var ovrd = this.get(keySymbolOvrd); var prp = prop.split(':')[0]; var props = prop !== prp ? [prop, prp] : [prop]; return ovrd === true || ((0,index_all.isArray)(ovrd) && props.some(function (p) { return ovrd.indexOf(p) >= 0; })); }; Component.prototype.__getSymbToUp = function (opts) { var _this = this; if (opts === void 0) { opts = {}; } var result = []; var changed = opts.changed; if (opts.fromInstance || opts.noPropagate || opts.fromUndo || // Avoid updating others if the current component has override (changed && this.__isSymbOvrd(changed))) { return result; } var symbols = this.__getSymbols() || []; var symbol = this.__getSymbol(); var all = symbol ? Component_spreadArray([symbol], (symbol.__getSymbols() || []), true) : symbols; result = all .filter(function (s) { return s !== _this; }) // Avoid updating those with override .filter(function (s) { return !(changed && s.__isSymbOvrd(changed)); }); return result; }; Component.prototype.__getSymbTop = function (opts) { var result = this; var parent = this.parent(opts); while (parent && (parent.__isSymbol() || parent.__getSymbol())) { result = parent; parent = parent.parent(opts); } return result; }; Component.prototype.__upSymbProps = function (m, opts) { var _this = this; if (opts === void 0) { opts = {}; } var changed = this.changedAttributes() || {}; var attrs = changed.attributes || {}; delete changed.status; delete changed.open; delete changed[keySymbols]; delete changed[keySymbol]; delete changed[keySymbolOvrd]; delete changed.attributes; delete attrs.id; if (!(0,mixins.isEmptyObj)(attrs)) changed.attributes = attrs; if (!(0,mixins.isEmptyObj)(changed)) { var toUp = this.__getSymbToUp(opts); // Avoid propagating overrides to other symbols (0,index_all.keys)(changed).map(function (prop) { if (_this.__isSymbOvrd(prop)) delete changed[prop]; }); this.__logSymbol('props', toUp, { opts: opts, changed: changed }); toUp.forEach(function (child) { var propsChanged = Component_assign({}, changed); // Avoid updating those with override (0,index_all.keys)(propsChanged).map(function (prop) { if (child.__isSymbOvrd(prop)) delete propsChanged[prop]; }); child.set(propsChanged, Component_assign({ fromInstance: _this }, opts)); }); } }; Component.prototype.__upSymbCls = function (m, c, opts) { var _this = this; if (opts === void 0) { opts = {}; } var toUp = this.__getSymbToUp(opts); this.__logSymbol('classes', toUp, { opts: opts }); toUp.forEach(function (child) { // @ts-ignore This will propagate the change up to __upSymbProps child.set('classes', _this.get('classes'), { fromInstance: _this }); }); this.__changesUp(opts); }; Component.prototype.__upSymbComps = function (m, c, o) { var _this = this; var optUp = o || c || {}; var fromInstance = optUp.fromInstance, fromUndo = optUp.fromUndo; var toUpOpts = { fromInstance: fromInstance, fromUndo: fromUndo }; var isTemp = m.opt.temporary; // Reset if (!o) { var toUp = this.__getSymbToUp(Component_assign(Component_assign({}, toUpOpts), { changed: 'components:reset' })); // @ts-ignore var cmps_1 = m.models; this.__logSymbol('reset', toUp, { components: cmps_1 }); toUp.forEach(function (symb) { var newMods = cmps_1.map(function (mod) { return mod.clone({ symbol: true }); }); // @ts-ignore symb.components().reset(newMods, Component_assign({ fromInstance: _this }, c)); }); // Add } else if (o.add) { var addedInstances_1 = []; var isMainSymb_1 = !!this.__getSymbols(); var toUp = this.__getSymbToUp(Component_assign(Component_assign({}, toUpOpts), { changed: 'components:add' })); if (toUp.length) { var addSymb = m.__getSymbol(); addedInstances_1 = (addSymb ? addSymb.__getSymbols() : m.__getSymbols()) || []; addedInstances_1 = Component_spreadArray([], addedInstances_1, true); addedInstances_1.push(addSymb ? addSymb : m); } !isTemp && this.__logSymbol('add', toUp, { opts: o, addedInstances: addedInstances_1.map(function (c) { return c.cid; }), added: m.cid, }); // Here, before appending a new symbol, I have to ensure there are no previously // created symbols (eg. used mainly when drag components around) toUp.forEach(function (symb) { var symbTop = symb.__getSymbTop(); var symbPrev = addedInstances_1.filter(function (addedInst) { var addedTop = addedInst.__getSymbTop({ prev: 1 }); return symbTop && addedTop && addedTop === symbTop; })[0]; var toAppend = symbPrev || m.clone({ symbol: true, symbolInv: isMainSymb_1 }); symb.append(toAppend, Component_assign({ fromInstance: _this }, o)); }); // Remove } else { // Remove instance reference from the symbol var symb = m.__getSymbol(); symb && !o.temporary && symb.set(keySymbols, symb.__getSymbols().filter(function (i) { return i !== m; })); // Propagate remove only if the component is an inner symbol if (!m.__isSymbolTop()) { var changed_1 = 'components:remove'; var index_1 = o.index; var parent_1 = m.parent(); var opts_1 = Component_assign({ fromInstance: m }, o); var isSymbNested = m.__isSymbolNested(); var toUpFn = function (symb) { var symbPrnt = symb.parent(); symbPrnt && !symbPrnt.__isSymbOvrd(changed_1) && symb.remove(opts_1); }; // Check if the parent allows the removing var toUp = !(parent_1 === null || parent_1 === void 0 ? void 0 : parent_1.__isSymbOvrd(changed_1)) ? m.__getSymbToUp(toUpOpts) : []; if (isSymbNested) { toUp = parent_1 === null || parent_1 === void 0 ? void 0 : parent_1.__getSymbToUp(Component_assign(Component_assign({}, toUpOpts), { changed: changed_1 })); toUpFn = function (symb) { var toRemove = symb.components().at(index_1); toRemove && toRemove.remove(Component_assign({ fromInstance: parent_1 }, opts_1)); }; } !isTemp && this.__logSymbol('remove', toUp, { opts: o, removed: m.cid, isSymbNested: isSymbNested, }); toUp.forEach(toUpFn); } } this.__changesUp(optUp); }; Component.prototype.initClasses = function (m, c, opts) { if (opts === void 0) { opts = {}; } var event = 'change:classes'; var _a = this.get('attributes') || {}, attrCls = _a.class, restAttr = Component_rest(_a, ["class"]); var toListen = [this, event, this.initClasses]; var cls = this.get('classes') || attrCls || []; var clsArr = (0,index_all.isString)(cls) ? cls.split(' ') : cls; this.stopListening.apply(this, toListen); var classes = this.normalizeClasses(clsArr); var selectors = new model_Selectors([]); this.set('classes', selectors, opts); selectors.add(classes); selectors.on('add remove reset', this.__upSymbCls); // Clear attributes from classes attrCls && classes.length && this.set('attributes', restAttr); // @ts-ignore this.listenTo.apply(this, toListen); return this; }; Component.prototype.initComponents = function () { var event = 'change:components'; var toListen = [this, event, this.initComponents]; this.stopListening.apply(this, toListen); // Have to add components after the init, otherwise the parent // is not visible var comps = new model_Components([], this.opt); comps.parent = this; var components = this.get('components'); var addChild = !this.opt.avoidChildren; this.set('components', comps); addChild && components && comps.add((0,index_all.isFunction)(components) ? components(this) : components, this.opt); comps.on('add remove reset', this.__upSymbComps); // @ts-ignore this.listenTo.apply(this, toListen); return this; }; Component.prototype.initTraits = function (changed) { var em = this.em; var event = 'change:traits'; this.off(event, this.initTraits); this.__loadTraits(); var attrs = Component_assign({}, this.get('attributes')); var traits = this.traits; traits.each(function (trait) { if (!trait.get('changeProp')) { var name_1 = trait.get('name'); var value = trait.getInitValue(); if (name_1 && value) attrs[name_1] = value; } }); traits.length && this.set('attributes', attrs); this.on(event, this.initTraits); changed && em && em.trigger('component:toggled'); return this; }; Component.prototype.initScriptProps = function () { if (this.opt.temporary) return; var prop = 'script-props'; var toListen = ["change:".concat(prop), this.initScriptProps]; this.off.apply(this, toListen); var prevProps = this.previous(prop) || []; var newProps = this.get(prop) || []; var prevPropsEv = prevProps.map(function (e) { return "change:".concat(e); }).join(' '); var newPropsEv = newProps.map(function (e) { return "change:".concat(e); }).join(' '); prevPropsEv && this.off(prevPropsEv, this.__scriptPropsChange); newPropsEv && this.on(newPropsEv, this.__scriptPropsChange); // @ts-ignore this.on.apply(this, toListen); }; Component.prototype.__scriptPropsChange = function (m, v, opts) { if (opts === void 0) { opts = {}; } if (opts.avoidStore) return; this.trigger('rerender'); }; /** * Add new component children * @param {Component|String} components Component to add * @param {Object} [opts={}] Options for the append action * @return {Array} Array of appended components * @example * someComponent.get('components').length // -> 0 * const videoComponent = someComponent.append('<video></video><div></div>')[0]; * // This will add 2 components (`video` and `div`) to your `someComponent` * someComponent.get('components').length // -> 2 * // You can pass components directly * otherComponent.append(otherComponent2); * otherComponent.append([otherComponent3, otherComponent4]); * // append at specific index (eg. at the beginning) * someComponent.append(otherComponent, { at: 0 }); */ Component.prototype.append = function (components, opts) { if (opts === void 0) { opts = {}; } var compArr = (0,index_all.isArray)(components) ? Component_spreadArray([], components, true) : [components]; var toAppend = compArr.map(function (comp) { if ((0,index_all.isString)(comp)) { return comp; } else { // I have to remove components from the old container before adding them to a new one comp.collection && comp.collection.remove(comp, { temporary: true }); return comp; } }); var result = this.components().add(toAppend, opts); return (0,index_all.isArray)(result) ? result : [result]; }; /** * Set new collection if `components` are provided, otherwise the * current collection is returned * @param {Component|Component[]|String} [components] Component Definitions or HTML string * @param {Object} [opts={}] Options, same as in `Component.append()` * @returns {Collection|Array<[Component]>} * @example * // Set new collection * component.components('<span></span><div></div>'); * // Get current collection * const collection = component.components(); * console.log(collection.length); * // -> 2 */ Component.prototype.components = function (components, opts) { if (opts === void 0) { opts = {}; } var coll = this.get('components'); if ((0,index_all.isUndefined)(components)) { return coll; } else { coll.reset(undefined, opts); return components ? this.append(components, opts) : []; } }; /** * If exists, returns the child component at specific index. * @param {Number} index Index of the component to return * @returns {[Component]|null} * @example * // Return first child * component.getChildAt(0); * // Return second child * component.getChildAt(1); */ Component.prototype.getChildAt = function (index) { return this.components().at(index || 0) || undefined; }; /** * If exists, returns the last child component. * @returns {[Component]|null} * @example * const lastChild = component.getLastChild(); */ Component.prototype.getLastChild = function () { var children = this.components(); return children.at(children.length - 1) || null; }; /** * Remove all inner components * * @return {this} */ Component.prototype.empty = function (opts) { if (opts === void 0) { opts = {}; } this.components().reset(undefined, opts); return this; }; /** * Get the parent component, if exists * @return {Component|null} * @example * component.parent(); * // -> Component */ Component.prototype.parent = function (opts) { if (opts === void 0) { opts = {}; } var coll = this.collection || (opts.prev && this.prevColl); return coll ? coll.parent : undefined; }; /** * Return all parents of the component. * @returns {Array<Component>} */ Component.prototype.parents = function () { var parent = this.parent(); return parent ? [parent].concat(parent.parents()) : []; }; /** * Script updated * @private */ Component.prototype.scriptUpdated = function () { this.set('scriptUpdated', 1); }; /** * Init toolbar * @private */ Component.prototype.initToolbar = function () { var em = this.em; var model = this; var ppfx = (em && em.getConfig().stylePrefix) || ''; if (!model.get('toolbar') && em) { var tb = []; model.collection && tb.push({ label: em.getIcon('arrowUp'), command: function (ed) { return ed.runCommand('core:component-exit', { force: 1 }); }, }); model.get('draggable') && tb.push({ attributes: { class: "".concat(ppfx, "no-touch-actions"), draggable: true }, label: em.getIcon('move'), command: 'tlb-move', }); model.get('copyable') && tb.push({ label: em.getIcon('copy'), command: 'tlb-clone', }); model.get('removable') && tb.push({ label: em.getIcon('delete'), command: 'tlb-delete', }); model.set('toolbar', tb); } }; Component.prototype.__loadTraits = function (tr, opts) { if (opts === void 0) { opts = {}; } var traitsI = tr || this.traits; if (!(traitsI instanceof model_Traits)) { traitsI = ((0,index_all.isFunction)(traitsI) ? traitsI(this) : traitsI); var traits = new model_Traits([], this.opt); traits.setTarget(this); if (traitsI.length) { traitsI.forEach(function (tr) { return tr.attributes && delete tr.attributes.value; }); traits.add(traitsI); } this.set({ traits: traits }, opts); } return this; }; /** * Get traits. * @returns {Array<Trait>} * @example * const traits = component.getTraits(); * console.log(traits); * // [Trait, Trait, Trait, ...] */ Component.prototype.getTraits = function () { this.__loadTraits(); return Component_spreadArray([], this.traits.models, true); }; /** * Replace current collection of traits with a new one. * @param {Array<Object>} traits Array of trait definitions * @returns {Array<Trait>} * @example * const traits = component.setTraits([{ type: 'checkbox', name: 'disabled'}, ...]); * console.log(traits); * // [Trait, ...] */ Component.prototype.setTraits = function (traits) { var tr = (0,index_all.isArray)(traits) ? traits : [traits]; // @ts-ignore this.set({ traits: tr }); return this.getTraits(); }; /** * Get the trait by id/name. * @param {String} id The `id` or `name` of the trait * @return {Trait|null} Trait getModelToStyle * @example * const traitTitle = component.getTrait('title'); * traitTitle && traitTitle.set('label', 'New label'); */ Component.prototype.getTrait = function (id) { return (this.getTraits().filter(function (trait) { return trait.get('id') === id || trait.get('name') === id; })[0] || null); }; /** * Update a trait. * @param {String} id The `id` or `name` of the trait * @param {Object} props Object with the props to update * @return {this} * @example * component.updateTrait('title', { * type: 'select', * options: [ 'Option 1', 'Option 2' ], * }); */ Component.prototype.updateTrait = function (id, props) { var _a; var trait = this.getTrait(id); trait && trait.set(props); (_a = this.em) === null || _a === void 0 ? void 0 : _a.trigger('component:toggled'); return this; }; /** * Get the trait position index by id/name. Useful in case you want to * replace some trait, at runtime, with something else. * @param {String} id The `id` or `name` of the trait * @return {Number} Index position of the current trait * @example * const traitTitle = component.getTraitIndex('title'); * console.log(traitTitle); // 1 */ Component.prototype.getTraitIndex = function (id) { var trait = this.getTrait(id); return trait ? this.traits.indexOf(trait) : -1; }; /** * Remove trait/s by id/s. * @param {String|Array<String>} id The `id`/`name` of the trait (or an array) * @return {Array<Trait>} Array of removed traits * @example * component.removeTrait('title'); * component.removeTrait(['title', 'id']); */ Component.prototype.removeTrait = function (id) { var _this = this; var _a; var ids = (0,index_all.isArray)(id) ? id : [id]; var toRemove = ids.map(function (id) { return _this.getTrait(id); }); var traits = this.traits; var removed = toRemove.length ? traits.remove(toRemove) : []; (_a = this.em) === null || _a === void 0 ? void 0 : _a.trigger('component:toggled'); return (0,index_all.isArray)(removed) ? removed : [removed]; }; /** * Add new trait/s. * @param {String|Object|Array<String|Object>} trait Trait to add (or an array of traits) * @param {Options} opts Options for the add * @return {Array<Trait>} Array of added traits * @example * component.addTrait('title', { at: 1 }); // Add title trait (`at` option is the position index) * component.addTrait({ * type: 'checkbox', * name: 'disabled', * }); * component.addTrait(['title', {...}, ...]); */ Component.prototype.addTrait = function (trait, opts) { var _a; if (opts === void 0) { opts = {}; } this.__loadTraits(); var added = this.traits.add(trait, opts); (_a = this.em) === null || _a === void 0 ? void 0 : _a.trigger('component:toggled'); return (0,index_all.isArray)(added) ? added : [added]; }; /** * Normalize input classes from array to array of objects * @param {Array} arr * @return {Array} * @private */ Component.prototype.normalizeClasses = function (arr) { var res = []; var em = this.em; var clm = em === null || em === void 0 ? void 0 : em.Selectors; if (!clm) return []; // @ts-ignore if (arr.models) return Component_spreadArray([], arr.models, true); arr.forEach(function (val) { return res.push(clm.add(val)); }); return res; }; /** * Override original clone method * @private */ Component.prototype.clone = function (opt) { if (opt === void 0) { opt = {}; } var em = this.em; var attr = Component_assign({}, this.attributes); var opts = Component_assign({}, this.opt); var id = this.getId(); var cssc = em === null || em === void 0 ? void 0 : em.Css; attr.attributes = Component_assign({}, attr.attributes); delete attr.attributes.id; // @ts-ignore attr.components = []; // @ts-ignore attr.classes = []; // @ts-ignore attr.traits = []; if (this.__isSymbolTop()) { opt.symbol = true; } this.get('components').each(function (md, i) { // @ts-ignore attr.components[i] = md.clone(Component_assign(Component_assign({}, opt), { _inner: 1 })); }); this.get('traits').each(function (md, i) { // @ts-ignore attr.traits[i] = md.clone(); }); this.get('classes').each(function (md, i) { // @ts-ignore attr.classes[i] = md.get('name'); }); attr.status = ''; // @ts-ignore opts.collection = null; // @ts-ignore var cloned = new this.constructor(attr, opts); // Clone component specific rules var newId = "#".concat(cloned.getId()); var rulesToClone = cssc ? cssc.getRules("#".concat(id)) : []; rulesToClone.forEach(function (rule) { var newRule = rule.clone(); // @ts-ignore newRule.set('selectors', [newId]); cssc.getAll().add(newRule); }); // Symbols // If I clone an inner symbol, I have to reset it cloned.set(keySymbols, 0); var symbol = this.__getSymbol(); var symbols = this.__getSymbols(); if (!opt.symbol && (symbol || symbols)) { cloned.set(keySymbol, 0); cloned.set(keySymbols, 0); } else if (symbol) { // Contains already a reference to a symbol symbol.set(keySymbols, Component_spreadArray(Component_spreadArray([], symbol.__getSymbols(), true), [cloned], false)); cloned.__initSymb(); } else if (opt.symbol) { // Request to create a symbol if (this.__isSymbol()) { // Already a symbol, cloned should be an instance this.set(keySymbols, Component_spreadArray(Component_spreadArray([], symbols, true), [cloned], false)); cloned.set(keySymbol, this); cloned.__initSymb(); } else if (opt.symbolInv) { // Inverted, cloned is the instance, the origin is the main symbol this.set(keySymbols, [cloned]); cloned.set(keySymbol, this); [this, cloned].map(function (i) { return i.__initSymb(); }); } else { // Cloned becomes the main symbol cloned.set(keySymbols, [this]); [this, cloned].map(function (i) { return i.__initSymb(); }); this.set(keySymbol, cloned); } } var event = 'component:clone'; em && em.trigger(event, cloned); this.trigger(event, cloned); return cloned; }; /** * Get the name of the component. * @param {Object} [opts={}] Options * @param {Boolean} [opts.noCustom] Avoid custom name assigned to the component. * @returns {String} * */ Component.prototype.getName = function (opts) { if (opts === void 0) { opts = {}; } var em = this.em; var _a = this.attributes, type = _a.type, tagName = _a.tagName, name = _a.name; var defName = type || tagName; var nameTag = !type ? tagName : ''; var i18nPfx = 'domComponents.names.'; var i18nName = name && (em === null || em === void 0 ? void 0 : em.t("".concat(i18nPfx).concat(name))); var i18nNameTag = nameTag && (em === null || em === void 0 ? void 0 : em.t("".concat(i18nPfx).concat(nameTag))); var i18nDefName = em && (em.t("".concat(i18nPfx).concat(type)) || em.t("".concat(i18nPfx).concat(tagName))); var customName = this.get('custom-name'); return ((!opts.noCustom ? customName : '') || // Used in Layers (when the user changes the name) i18nName || // Use local component `name` key (eg. `domComponents.names.myComponentName`) name || // Use component `name` key i18nNameTag || // Use local component `tagName` key (eg. `domComponents.names.div`) (0,mixins.capitalize)(nameTag) || // Use component `tagName` key i18nDefName || // Use local component `type` key (eg. `domComponents.names.image`) (0,mixins.capitalize)(defName) // Use component `type` key ); }; /** * Get the icon string * @return {String} */ Component.prototype.getIcon = function () { var icon = this.get('icon'); return icon ? icon + ' ' : ''; }; /** * Return HTML string of the component * @param {Object} [opts={}] Options * @param {String} [opts.tag] Custom tagName * @param {Object|Function} [opts.attributes=null] You can pass an object of custom attributes to replace with the current ones or you can even pass a function to generate attributes dynamically. * @param {Boolean} [opts.withProps] Include component properties as `data-gjs-*` attributes. This allows you to have re-importable HTML. * @param {Boolean} [opts.altQuoteAttr] In case the attribute value contains a `"` char, instead of escaping it (`attr="value ""`), the attribute will be quoted using single quotes (`attr='value "'`). * @return {String} HTML string * @example * // Simple HTML return * component.set({ tagName: 'span' }); * component.setAttributes({ title: 'Hello' }); * component.toHTML(); * // -> <span title="Hello"></span> * * // Custom attributes * component.toHTML({ attributes: { 'data-test': 'Hello' } }); * // -> <span data-test="Hello"></span> * * // Custom dynamic attributes * component.toHTML({ * attributes(component, attributes) { * if (component.get('tagName') == 'span') { * attributes.title = 'Custom attribute'; * } * return attributes; * }, * }); * // -> <span title="Custom attribute"></span> */ Component.prototype.toHTML = function (opts) { if (opts === void 0) { opts = {}; } var model = this; var attrs = []; var customTag = opts.tag; var tag = customTag || model.get('tagName'); var sTag = model.get('void'); var customAttr = opts.attributes; var attributes = this.getAttrToHTML(); delete opts.tag; // Get custom attributes if requested if (customAttr) { if ((0,index_all.isFunction)(customAttr)) { attributes = customAttr(model, attributes) || {}; } else if ((0,mixins.isObject)(customAttr)) { attributes = customAttr; } } if (opts.withProps) { var props = this.toJSON(); (0,index_all.forEach)(props, function (value, key) { var skipProps = ['classes', 'attributes', 'components']; if (key[0] !== '_' && skipProps.indexOf(key) < 0) { attributes["data-gjs-".concat(key)] = (0,index_all.isArray)(value) || (0,mixins.isObject)(value) ? JSON.stringify(value) : value; } }); } for (var attr in attributes) { var val = attributes[attr]; if (!(0,index_all.isUndefined)(val) && val !== null) { if ((0,index_all.isBoolean)(val)) { val && attrs.push(attr); } else { var valueRes = ''; if (opts.altQuoteAttr && (0,index_all.isString)(val) && val.indexOf('"') >= 0) { valueRes = "'".concat(val.replace(/'/g, '''), "'"); } else { var value = (0,index_all.isString)(val) ? val.replace(/"/g, '"') : val; valueRes = "\"".concat(value, "\""); } attrs.push("".concat(attr, "=").concat(valueRes)); } } } var attrString = attrs.length ? " ".concat(attrs.join(' ')) : ''; var inner = model.getInnerHTML(opts); var code = "<".concat(tag).concat(attrString).concat(sTag ? '/' : '', ">").concat(inner); !sTag && (code += "</".concat(tag, ">")); return code; }; /** * Get inner HTML of the component * @param {Object} [opts={}] Same options of `toHTML` * @returns {String} HTML string */ Component.prototype.getInnerHTML = function (opts) { return this.__innerHTML(opts); }; Component.prototype.__innerHTML = function (opts) { if (opts === void 0) { opts = {}; } var cmps = this.components(); return !cmps.length ? this.content : cmps.map(function (c) { return c.toHTML(opts); }).join(''); }; /** * Returns object of attributes for HTML * @return {Object} * @private */ Component.prototype.getAttrToHTML = function () { var attrs = this.getAttributes(); if (avoidInline(this.em)) { delete attrs.style; } return attrs; }; /** * Return a shallow copy of the model's attributes for JSON * stringification. * @return {Object} * @private */ Component.prototype.toJSON = function (opts) { if (opts === void 0) { opts = {}; } var obj = backbone.Model.prototype.toJSON.call(this, opts); obj.attributes = this.getAttributes(); delete obj.attributes.class; delete obj.toolbar; delete obj.traits; delete obj.status; delete obj.open; // used in Layers delete obj._undoexc; if (!opts.fromUndo) { var symbol = obj[keySymbol]; var symbols = obj[keySymbols]; if (symbols && (0,index_all.isArray)(symbols)) { obj[keySymbols] = symbols.filter(function (i) { return i; }).map(function (i) { return (i.getId ? i.getId() : i); }); } if (symbol && !(0,index_all.isString)(symbol)) { obj[keySymbol] = symbol.getId(); } } if (this.em.getConfig().avoidDefaults) { this.getChangedProps(obj); } return obj; }; /** * Return an object containing only changed props */ Component.prototype.getChangedProps = function (res) { var obj = res || backbone.Model.prototype.toJSON.apply(this); var defaults = (0,index_all.result)(this, 'defaults'); (0,index_all.forEach)(defaults, function (value, key) { if (['type'].indexOf(key) === -1 && obj[key] === value) { delete obj[key]; } }); if ((0,index_all.isEmpty)(obj.type)) { delete obj.type; } (0,index_all.forEach)(['attributes', 'style'], function (prop) { if ((0,index_all.isEmpty)(defaults[prop]) && (0,index_all.isEmpty)(obj[prop])) { delete obj[prop]; } }); (0,index_all.forEach)(['classes', 'components'], function (prop) { if (!obj[prop] || ((0,index_all.isEmpty)(defaults[prop]) && !obj[prop].length)) { delete obj[prop]; } }); return obj; }; /** * Return the component id * @return {String} */ Component.prototype.getId = function () { var attrs = this.get('attributes') || {}; return attrs.id || this.ccid || this.cid; }; /** * Set new id on the component * @param {String} id * @return {this} */ Component.prototype.setId = function (id, opts) { var attrs = Component_assign({}, this.get('attributes')); attrs.id = id; this.set('attributes', attrs, opts); return this; }; /** * Get the DOM element of the component. * This works only if the component is already rendered * @param {Frame} frame Specific frame from which taking the element * @return {HTMLElement} */ Component.prototype.getEl = function (frame) { var view = this.getView(frame); return view && view.el; }; /** * Get the View of the component. * This works only if the component is already rendered * @param {Frame} frame Get View of a specific frame * @return {ComponentView} */ Component.prototype.getView = function (frame) { var _a = this, view = _a.view, views = _a.views, em = _a.em; var frm = frame || (em === null || em === void 0 ? void 0 : em.getCurrentFrameModel()); if (frm) { view = views.filter(function (view) { return view.frameView === frm.view; })[0]; } return view; }; Component.prototype.getCurrentView = function () { var frameView = this.em.getCurrentFrame(); var frame = frameView === null || frameView === void 0 ? void 0 : frameView.model; return this.getView(frame); }; Component.prototype.__getScriptProps = function () { var modelProps = this.props(); var scrProps = this.get('script-props') || []; return scrProps.reduce(function (acc, prop) { acc[prop] = modelProps[prop]; return acc; }, {}); }; /** * Return script in string format, cleans 'function() {..' from scripts * if it's a function * @param {string|Function} script * @return {string} * @private */ Component.prototype.getScriptString = function (script) { var _this = this; var scr = script || this.get('script') || ''; if (!scr) { return scr; } if (this.get('script-props')) { scr = scr.toString().trim(); } else { // Deprecated // Need to convert script functions to strings if ((0,index_all.isFunction)(scr)) { var scrStr = scr.toString().trim(); scrStr = scrStr.slice(scrStr.indexOf('{') + 1, scrStr.lastIndexOf('}')); scr = scrStr.trim(); } var config = this.em.getConfig(); var tagVarStart = escapeRegExp(config.tagVarStart || '{[ '); var tagVarEnd = escapeRegExp(config.tagVarEnd || ' ]}'); var reg = new RegExp("".concat(tagVarStart, "([\\w\\d-]*)").concat(tagVarEnd), 'g'); scr = scr.replace(reg, function (match, v) { // If at least one match is found I have to track this change for a // better optimization inside JS generator _this.scriptUpdated(); var result = _this.attributes[v] || ''; return (0,index_all.isArray)(result) || typeof result == 'object' ? JSON.stringify(result) : result; }); } return scr; }; Component.prototype.emitUpdate = function (property) { var _a; var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } var em = this.em; var event = keyUpdate + (property ? ":".concat(property) : ''); var item = property && this.get(property); // @ts-ignore property && this.updated.apply(this, Component_spreadArray([property, item, property && this.previous(property)], args, false)); this.trigger.apply(this, Component_spreadArray([event], args, false)); em && em.trigger.apply(em, Component_spreadArray([event, this], args, false)); ['components', 'classes'].indexOf(property) >= 0 && this.__propSelfToParent({ component: this, changed: (_a = {}, _a[property] = item, _a), options: args[2] || args[1] || {}, }); }; /** * Execute callback function on itself and all inner components * @param {Function} clb Callback function, the model is passed as an argument * @return {this} * @example * component.onAll(component => { * // do something with component * }) */ Component.prototype.onAll = function (clb) { if ((0,index_all.isFunction)(clb)) { clb(this); this.components().forEach(function (model) { return model.onAll(clb); }); } return this; }; /** * Execute a callback function on all inner child components. * @param {Function} clb Callback function, the child component is passed as an argument * @example * component.forEachChild(child => { * console.log(child) * }) */ Component.prototype.forEachChild = function (clb) { if ((0,index_all.isFunction)(clb)) { this.components().forEach(function (child) { clb(child); child.forEachChild(clb); }); } }; /** * Remove the component * @return {this} */ Component.prototype.remove = function (opts) { var _this = this; if (opts === void 0) { opts = {}; } var em = this.em; var coll = this.collection; var remove = function () { coll && coll.remove(_this, Component_assign(Component_assign({}, opts), { action: 'remove-component' })); // Component without parent if (!coll) { _this.components('', opts); _this.components().removeChildren(_this, undefined, opts); } }; var rmOpts = Component_assign({}, opts); [this, em].map(function (i) { return i.trigger('component:remove:before', _this, remove, rmOpts); }); !rmOpts.abort && remove(); return this; }; /** * Move the component to another destination component * @param {Component} component Destination component (so the current one will be appended as a child) * @param {Object} opts Options for the append action * @returns {this} * @example * // Move the selected component on top of the wrapper * const dest = editor.getWrapper(); * editor.getSelected().move(dest, { at: 0 }); */ Component.prototype.move = function (component, opts) { if (opts === void 0) { opts = {}; } if (component) { var at = opts.at; var index = this.index(); var sameParent = component === this.parent(); var sameIndex = index === at || index === at - 1; if (!sameParent || !sameIndex) { if (sameParent && at && at > index) { opts.at = at - 1; } this.remove({ temporary: 1 }); component.append(this, opts); this.emitUpdate(); } } return this; }; /** * Check if the component is an instance of some component type. * @param {String} type Component type * @returns {Boolean} * @example * // Add a new component type by extending an existing one * editor.Components.addType('text-ext', { extend: 'text' }); * // Append a new component somewhere * const newTextExt = editor.getSelected().append({ type: 'text-ext' })[0]; * newTextExt.isInstanceOf('text-ext'); // true * newTextExt.isInstanceOf('text'); // true */ Component.prototype.isInstanceOf = function (type) { var _a, _b; var cmp = (_b = (_a = this.em) === null || _a === void 0 ? void 0 : _a.Components.getType(type)) === null || _b === void 0 ? void 0 : _b.model; if (!cmp) return false; return this instanceof cmp; }; /** * Check if the component is a child of some other component (or component type) * @param {[Component]|String} component Component parent to check. In case a string is passed, * the check will be performed on the component type. * @returns {Boolean} * @example * const newTextComponent = editor.getSelected().append({ * type: 'text', * components: 'My text <b>here</b>', * })[0]; * const innerComponent = newTextComponent.find('b')[0]; * innerComponent.isChildOf(newTextComponent); // true * innerComponent.isChildOf('text'); // true */ Component.prototype.isChildOf = function (component) { var byType = (0,index_all.isString)(component); var parent = this.parent(); while (parent) { if (byType) { if (parent.isInstanceOf(component)) { return true; } } else { if (parent === component) { return true; } } parent = parent.parent(); } return false; }; /** * Reset id of the component and any of its style rule * @param {Object} [opts={}] Options * @return {this} * @private */ Component.prototype.resetId = function (opts) { if (opts === void 0) { opts = {}; } var em = this.em; var oldId = this.getId(); if (!oldId) return this; var newId = Component.createId(this); this.setId(newId); var rule = em === null || em === void 0 ? void 0 : em.Css.getIdRule(oldId); var selector = rule === null || rule === void 0 ? void 0 : rule.get('selectors').at(0); selector === null || selector === void 0 ? void 0 : selector.set('name', newId); return this; }; Component.prototype._getStyleRule = function (_a) { var _b = _a === void 0 ? {} : _a, id = _b.id; var em = this.em; var idS = id || this.getId(); return em === null || em === void 0 ? void 0 : em.Css.getIdRule(idS); }; Component.prototype._getStyleSelector = function (opts) { var rule = this._getStyleRule(opts); return rule === null || rule === void 0 ? void 0 : rule.get('selectors').at(0); }; Component.prototype._idUpdated = function (m, v, opts) { if (opts === void 0) { opts = {}; } if (opts.idUpdate) return; var ccid = this.ccid; var id = (this.get('attributes') || {}).id; var idPrev = (this.previous('attributes') || {}).id || ccid; var list = Component.getList(this); // If the ID already exists I need to rollback to the old one if (list[id] || (!id && idPrev)) { return this.setId(idPrev, { idUpdate: true }); } // Remove the old ID reference and add the new one delete list[idPrev]; list[id] = this; this.ccid = id; // Update the style selector name var selector = this._getStyleSelector({ id: idPrev }); selector && selector.set({ name: id, label: id }); }; Component.getDefaults = function () { return (0,index_all.result)(this.prototype, 'defaults'); }; Component.isComponent = function (el) { return { tagName: (0,mixins.toLowerCase)(el.tagName) }; }; Component.ensureInList = function (model) { var list = Component.getList(model); var id = model.getId(); var current = list[id]; if (!current) { // Insert in list list[id] = model; } else if (current !== model) { // Create new ID var nextId = Component.getIncrementId(id, list); model.setId(nextId); list[nextId] = model; } model.components().forEach(function (i) { return Component.ensureInList(i); }); }; Component.createId = function (model, opts) { if (opts === void 0) { opts = {}; } var list = Component.getList(model); var _a = opts.idMap, idMap = _a === void 0 ? {} : _a; var id = model.get('attributes').id; var nextId; if (id) { nextId = Component.getIncrementId(id, list, opts); model.setId(nextId); if (id !== nextId) idMap[id] = nextId; } else { nextId = Component.getNewId(list); } list[nextId] = model; return nextId; }; Component.getNewId = function (list) { var count = Object.keys(list).length; // Testing 1000000 components with `+ 2` returns 0 collisions var ilen = count.toString().length + 2; var uid = (Math.random() + 1.1).toString(36).slice(-ilen); var newId = "i".concat(uid); while (list[newId]) { newId = Component.getNewId(list); } return newId; }; Component.getIncrementId = function (id, list, opts) { if (opts === void 0) { opts = {}; } var _a = opts.keepIds, keepIds = _a === void 0 ? [] : _a; var counter = 1; var newId = id; if (keepIds.indexOf(id) < 0) { while (list[newId]) { counter++; newId = "".concat(id, "-").concat(counter); } } return newId; }; Component.getList = function (model) { var _a = model.opt, opt = _a === void 0 ? {} : _a; // @ts-ignore var domc = opt.domc, em = opt.em; var dm = domc || (em === null || em === void 0 ? void 0 : em.Components); return dm ? dm.componentsById : {}; }; Component.checkId = function (components, styles, list, opts) { if (styles === void 0) { styles = []; } if (list === void 0) { list = {}; } if (opts === void 0) { opts = {}; } var comps = (0,index_all.isArray)(components) ? components : [components]; var _a = opts.keepIds, keepIds = _a === void 0 ? [] : _a; comps.forEach(function (comp) { comp.attributes; var _a = comp.attributes, attributes = _a === void 0 ? {} : _a, components = comp.components; var id = attributes.id; // Check if we have collisions with current components if (id && list[id] && keepIds.indexOf(id) < 0) { var newId_1 = Component.getIncrementId(id, list); attributes.id = newId_1; // Update passed styles (0,index_all.isArray)(styles) && styles.forEach(function (style) { var selectors = style.selectors; selectors.forEach(function (sel, idx) { if (sel === "#".concat(id)) selectors[idx] = "#".concat(newId_1); }); }); } components && Component.checkId(components, styles, list, opts); }); }; return Component; }(model_StyleableModel)); /* harmony default export */ const model_Component = (Component); ;// CONCATENATED MODULE: ./src/dom_components/model/ComponentTextNode.ts var ComponentTextNode_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ComponentTextNode_assign = ( false) || function () { ComponentTextNode_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return ComponentTextNode_assign.apply(this, arguments); }; var ComponentTextNode = /** @class */ (function (_super) { ComponentTextNode_extends(ComponentTextNode, _super); function ComponentTextNode() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(ComponentTextNode.prototype, "defaults", { get: function () { return ComponentTextNode_assign(ComponentTextNode_assign({}, _super.prototype.defaults), { tagName: '', droppable: false, layerable: false, selectable: false, editable: true }); }, enumerable: false, configurable: true }); ComponentTextNode.prototype.toHTML = function () { var content = this.content; var parent = this.parent(); return (parent === null || parent === void 0 ? void 0 : parent.is('script')) ? content : this.__escapeContent(content); }; ComponentTextNode.prototype.__escapeContent = function (content) { return (0,mixins.escapeNodeContent)(content); }; ComponentTextNode.isComponent = function (el) { var _a; if (el.nodeType === 3) { return { type: 'textnode', content: (_a = el.textContent) !== null && _a !== void 0 ? _a : '', }; } }; return ComponentTextNode; }(model_Component)); /* harmony default export */ const model_ComponentTextNode = (ComponentTextNode); ;// CONCATENATED MODULE: ./src/dom_components/model/ComponentComment.ts var ComponentComment_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ComponentComment_assign = ( false) || function () { ComponentComment_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return ComponentComment_assign.apply(this, arguments); }; var ComponentComment = /** @class */ (function (_super) { ComponentComment_extends(ComponentComment, _super); function ComponentComment() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(ComponentComment.prototype, "defaults", { get: function () { // @ts-ignore return ComponentComment_assign({}, _super.prototype.defaults); }, enumerable: false, configurable: true }); ComponentComment.prototype.toHTML = function () { return "<!--".concat(this.content, "-->"); }; ComponentComment.isComponent = function (el) { var _a; if (el.nodeType == 8) { return { tagName: 'NULL', type: 'comment', content: (_a = el.textContent) !== null && _a !== void 0 ? _a : '', }; } }; return ComponentComment; }(model_ComponentTextNode)); /* harmony default export */ const model_ComponentComment = (ComponentComment); ;// CONCATENATED MODULE: ./src/dom_components/model/ComponentFrame.ts var ComponentFrame_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ComponentFrame_assign = ( false) || function () { ComponentFrame_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return ComponentFrame_assign.apply(this, arguments); }; var type = 'iframe'; var ComponentFrame = /** @class */ (function (_super) { ComponentFrame_extends(ComponentFrame, _super); function ComponentFrame() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(ComponentFrame.prototype, "defaults", { get: function () { return ComponentFrame_assign(ComponentFrame_assign({}, _super.prototype.defaults), { type: type, tagName: type, droppable: false, resizable: true, traits: ['id', 'title', 'src'], attributes: { frameborder: '0' } }); }, enumerable: false, configurable: true }); ComponentFrame.isComponent = function (el) { return (0,mixins.toLowerCase)(el.tagName) === type; }; return ComponentFrame; }(model_Component)); /* harmony default export */ const model_ComponentFrame = (ComponentFrame); // ComponentFrame.isComponent = el => toLowerCase(el.tagName) === type; ;// CONCATENATED MODULE: ./src/dom_components/model/ComponentImage.ts var ComponentImage_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ComponentImage_assign = ( false) || function () { ComponentImage_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return ComponentImage_assign.apply(this, arguments); }; var svgAttrs = 'xmlns="http://www.w3.org/2000/svg" width="100" viewBox="0 0 24 24" style="fill: rgba(0,0,0,0.15); transform: scale(0.75)"'; var ComponentImage = /** @class */ (function (_super) { ComponentImage_extends(ComponentImage, _super); function ComponentImage() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(ComponentImage.prototype, "defaults", { get: function () { return ComponentImage_assign(ComponentImage_assign({}, _super.prototype.defaults), { type: 'image', tagName: 'img', void: true, droppable: 0, editable: 1, highlightable: 0, resizable: { ratioDefault: 1 }, traits: ['alt'], src: "<svg ".concat(svgAttrs, ">\n <path d=\"M8.5 13.5l2.5 3 3.5-4.5 4.5 6H5m16 1V5a2 2 0 0 0-2-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2z\"></path>\n </svg>"), // Fallback image in case the src can't be loaded // If you use SVG, xmlns="http://www.w3.org/2000/svg" is required fallback: "<svg ".concat(svgAttrs, ">\n <path d=\"M2.28 3L1 4.27l2 2V19c0 1.1.9 2 2 2h12.73l2 2L21 21.72 2.28 3m2.55 0L21 19.17V5a2 2 0 0 0-2-2H4.83M8.5 13.5l2.5 3 1-1.25L14.73 18H5l3.5-4.5z\"></path>\n </svg>"), // File to load asynchronously once the model is rendered file: '' }); }, enumerable: false, configurable: true }); ComponentImage.prototype.initialize = function (props, opts) { _super.prototype.initialize.call(this, props, opts); var src = this.get('attributes').src; if (src && (0,mixins.buildBase64UrlFromSvg)((0,index_all.result)(this, 'defaults').src) !== src) { this.set('src', src, { silent: true }); } }; ComponentImage.prototype.initToolbar = function () { _super.prototype.initToolbar.call(this); var em = this.em; if (em) { var cmd = em.Commands; var cmdName = 'image-editor'; // Add Image Editor button only if the default command exists if (cmd.has(cmdName)) { var hasButtonBool = false; var tb = this.get('toolbar'); for (var i = 0; i < tb.length; i++) { if (tb[i].command === 'image-editor') { hasButtonBool = true; break; } } if (!hasButtonBool) { tb.push({ attributes: { class: 'fa fa-pencil' }, command: cmdName, }); this.set('toolbar', tb); } } } }; /** * Returns object of attributes for HTML * @return {Object} * @private */ ComponentImage.prototype.getAttrToHTML = function () { var attr = _super.prototype.getAttrToHTML.call(this); var src = this.getSrcResult(); if (src) attr.src = src; return attr; }; ComponentImage.prototype.getSrcResult = function (opt) { if (opt === void 0) { opt = {}; } var src = this.get(opt.fallback ? 'fallback' : 'src') || ''; var result = src; if (src && src.substr(0, 4) === '<svg') { result = (0,mixins.buildBase64UrlFromSvg)(src); } return result; }; ComponentImage.prototype.isDefaultSrc = function () { var src = this.get('src'); var srcDef = (0,index_all.result)(this, 'defaults').src; return src === srcDef || src === (0,mixins.buildBase64UrlFromSvg)(srcDef); }; /** * Return a shallow copy of the model's attributes for JSON * stringification. * @return {Object} * @private */ ComponentImage.prototype.toJSON = function (opts) { var obj = _super.prototype.toJSON.call(this, opts); var attributes = obj.attributes; if (attributes && obj.src === attributes.src) { delete obj.src; } return obj; }; /** * Parse uri * @param {string} uri * @return {object} * @private */ ComponentImage.prototype.parseUri = function (uri) { var result = {}; var getQueryObject = function (search) { if (search === void 0) { search = ''; } var query = {}; var qrs = search.substring(1).split('&'); for (var i = 0; i < qrs.length; i++) { var pair = qrs[i].split('='); var name_1 = decodeURIComponent(pair[0]); if (name_1) query[name_1] = decodeURIComponent(pair[1] || ''); } return query; }; if ((0,mixins.hasWin)()) { result = document.createElement('a'); result.href = uri; } else if (typeof URL !== 'undefined') { try { result = new URL(uri); } catch (e) { } } return { hostname: result.hostname || '', pathname: result.pathname || '', protocol: result.protocol || '', search: result.search || '', hash: result.hash || '', port: result.port || '', query: getQueryObject(result.search), }; }; ComponentImage.isComponent = function (el) { return (0,mixins.toLowerCase)(el.tagName) === 'img'; }; return ComponentImage; }(model_Component)); /* harmony default export */ const model_ComponentImage = (ComponentImage); ;// CONCATENATED MODULE: ./src/dom_components/model/ComponentText.ts var ComponentText_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ComponentText_assign = ( false) || function () { ComponentText_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return ComponentText_assign.apply(this, arguments); }; var ComponentText = /** @class */ (function (_super) { ComponentText_extends(ComponentText, _super); function ComponentText() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(ComponentText.prototype, "defaults", { get: function () { return ComponentText_assign(ComponentText_assign({}, _super.prototype.defaults), { type: 'text', droppable: false, editable: true }); }, enumerable: false, configurable: true }); ComponentText.prototype.initialize = function (props, opts) { _super.prototype.initialize.call(this, props, opts); this.__checkInnerChilds(); }; ComponentText.prototype.__checkInnerChilds = function () { var disableTextInnerChilds = this.em.Components.config.disableTextInnerChilds; if (disableTextInnerChilds) { var disableChild_1 = function (child) { if (!child.isInstanceOf('textnode')) { child.set({ locked: true, layerable: false, }); } }; if ((0,index_all.isFunction)(disableTextInnerChilds)) { this.forEachChild(function (child) { disableTextInnerChilds(child) && disableChild_1(child); }); } else { this.forEachChild(disableChild_1); } } }; return ComponentText; }(model_Component)); /* harmony default export */ const model_ComponentText = (ComponentText); ;// CONCATENATED MODULE: ./src/dom_components/model/ComponentLabel.ts var ComponentLabel_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ComponentLabel_assign = ( false) || function () { ComponentLabel_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return ComponentLabel_assign.apply(this, arguments); }; var ComponentLabel_type = 'label'; var ComponentLabel = /** @class */ (function (_super) { ComponentLabel_extends(ComponentLabel, _super); function ComponentLabel() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(ComponentLabel.prototype, "defaults", { get: function () { return ComponentLabel_assign(ComponentLabel_assign({}, _super.prototype.defaults), { type: ComponentLabel_type, tagName: ComponentLabel_type, traits: ['id', 'title', 'for'] }); }, enumerable: false, configurable: true }); ComponentLabel.isComponent = function (el) { return (0,mixins.toLowerCase)(el.tagName) === ComponentLabel_type; }; return ComponentLabel; }(model_ComponentText)); /* harmony default export */ const model_ComponentLabel = (ComponentLabel); ;// CONCATENATED MODULE: ./src/dom_components/model/ComponentLink.ts var ComponentLink_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ComponentLink_assign = ( false) || function () { ComponentLink_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return ComponentLink_assign.apply(this, arguments); }; var ComponentLink_type = 'link'; var ComponentLink = /** @class */ (function (_super) { ComponentLink_extends(ComponentLink, _super); function ComponentLink() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(ComponentLink.prototype, "defaults", { get: function () { return ComponentLink_assign(ComponentLink_assign({}, _super.prototype.defaults), { type: ComponentLink_type, tagName: 'a', traits: ['title', 'href', 'target'] }); }, enumerable: false, configurable: true }); ComponentLink.isComponent = function (el, opts) { if (opts === void 0) { opts = {}; } var result; if ((0,mixins.toLowerCase)(el.tagName) === 'a') { var textTags_1 = opts.textTags || []; result = { type: ComponentLink_type, editable: false }; // The link is editable only if, at least, one of its // children is a text node (not empty one) var children = el.childNodes; var len = children.length; if (!len) delete result.editable; (0,index_all.forEach)(children, function (child) { var tagName = child.tagName; if ((child.nodeType == 3 && child.textContent.trim() !== '') || (tagName && textTags_1.indexOf((0,mixins.toLowerCase)(tagName)) >= 0)) { delete result.editable; } }); } return result; }; return ComponentLink; }(model_ComponentText)); /* harmony default export */ const model_ComponentLink = (ComponentLink); ;// CONCATENATED MODULE: ./src/dom_components/model/ComponentMap.ts var ComponentMap_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ComponentMap_assign = ( false) || function () { ComponentMap_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return ComponentMap_assign.apply(this, arguments); }; var ComponentMap = /** @class */ (function (_super) { ComponentMap_extends(ComponentMap, _super); function ComponentMap() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(ComponentMap.prototype, "defaults", { /** @ts-ignore */ get: function () { // @ts-ignore var defs = _super.prototype.defaults; return ComponentMap_assign(ComponentMap_assign({}, defs), { type: 'map', src: '', void: false, mapUrl: 'https://maps.google.com/maps', tagName: 'iframe', mapType: 'q', address: '', zoom: '1', attributes: { frameborder: 0 }, // @ts-ignore toolbar: defs.toolbar, traits: [ { label: 'Address', name: 'address', placeholder: 'eg. London, UK', changeProp: 1, }, { type: 'select', label: 'Map type', name: 'mapType', changeProp: 1, options: [ { value: 'q', name: 'Roadmap' }, { value: 'w', name: 'Satellite' }, ], }, { label: 'Zoom', name: 'zoom', type: 'range', min: '1', max: '20', changeProp: 1, }, ] }); }, enumerable: false, configurable: true }); ComponentMap.prototype.initialize = function (props, opts) { if (this.get('src')) this.parseFromSrc(); else this.updateSrc(); _super.prototype.initialize.call(this, props, opts); this.listenTo(this, 'change:address change:zoom change:mapType', this.updateSrc); }; ComponentMap.prototype.updateSrc = function () { this.set('src', this.getMapUrl()); }; /** * Returns url of the map * @return {string} * @private */ ComponentMap.prototype.getMapUrl = function () { var addr = this.get('address'); var zoom = this.get('zoom'); var type = this.get('mapType'); addr = addr ? '&q=' + addr : ''; zoom = zoom ? '&z=' + zoom : ''; type = type ? '&t=' + type : ''; var result = this.get('mapUrl') + '?' + addr + zoom + type; result += '&output=embed'; return result; }; /** * Set attributes by src string * @private */ ComponentMap.prototype.parseFromSrc = function () { var uri = this.parseUri(this.get('src')); var qr = uri.query; if (qr.q) this.set('address', qr.q); if (qr.z) this.set('zoom', qr.z); if (qr.t) this.set('mapType', qr.t); }; ComponentMap.isComponent = function (el) { if ((0,mixins.toLowerCase)(el.tagName) == 'iframe' && /maps\.google\.com/.test(el.src)) { return { type: 'map', src: el.src }; } }; return ComponentMap; }(model_ComponentImage)); /* harmony default export */ const model_ComponentMap = (ComponentMap); ;// CONCATENATED MODULE: ./src/dom_components/model/ComponentScript.ts var ComponentScript_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ComponentScript_assign = ( false) || function () { ComponentScript_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return ComponentScript_assign.apply(this, arguments); }; var ComponentScript_type = 'script'; var ComponentScript = /** @class */ (function (_super) { ComponentScript_extends(ComponentScript, _super); function ComponentScript() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(ComponentScript.prototype, "defaults", { get: function () { return ComponentScript_assign(ComponentScript_assign({}, _super.prototype.defaults), { type: ComponentScript_type, tagName: ComponentScript_type, droppable: false, draggable: false, layerable: false }); }, enumerable: false, configurable: true }); ComponentScript.isComponent = function (el) { if ((0,mixins.toLowerCase)(el.tagName) == ComponentScript_type) { var result = { type: ComponentScript_type }; if (el.src) { result.src = el.src; result.onload = el.onload; } return result; } }; return ComponentScript; }(model_Component)); /* harmony default export */ const model_ComponentScript = (ComponentScript); ;// CONCATENATED MODULE: ./src/dom_components/model/ComponentSvg.ts var ComponentSvg_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ComponentSvg_assign = ( false) || function () { ComponentSvg_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return ComponentSvg_assign.apply(this, arguments); }; var ComponentSvg_type = 'svg'; var ComponentSvg = /** @class */ (function (_super) { ComponentSvg_extends(ComponentSvg, _super); function ComponentSvg() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(ComponentSvg.prototype, "defaults", { get: function () { return ComponentSvg_assign(ComponentSvg_assign({}, _super.prototype.defaults), { type: ComponentSvg_type, tagName: ComponentSvg_type, highlightable: false, resizable: { ratioDefault: true } }); }, enumerable: false, configurable: true }); ComponentSvg.prototype.getName = function () { var name = this.get('tagName'); var customName = this.get('custom-name'); name = name.charAt(0).toUpperCase() + name.slice(1); return customName || name; }; ComponentSvg.isComponent = function (el) { return (0,mixins.toLowerCase)(el.tagName) === ComponentSvg_type; }; return ComponentSvg; }(model_Component)); /* harmony default export */ const model_ComponentSvg = (ComponentSvg); ;// CONCATENATED MODULE: ./src/dom_components/model/ComponentSvgIn.ts var ComponentSvgIn_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ComponentSvgIn_assign = ( false) || function () { ComponentSvgIn_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return ComponentSvgIn_assign.apply(this, arguments); }; /** * Component for inner SVG elements */ var ComponentSvgIn = /** @class */ (function (_super) { ComponentSvgIn_extends(ComponentSvgIn, _super); function ComponentSvgIn() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(ComponentSvgIn.prototype, "defaults", { get: function () { return ComponentSvgIn_assign(ComponentSvgIn_assign({}, _super.prototype.defaults), { selectable: false, hoverable: false, layerable: false }); }, enumerable: false, configurable: true }); ComponentSvgIn.isComponent = function (el, opts) { if (opts === void 0) { opts = {}; } return !!opts.inSvg; }; return ComponentSvgIn; }(model_ComponentSvg)); /* harmony default export */ const model_ComponentSvgIn = (ComponentSvgIn); ;// CONCATENATED MODULE: ./src/dom_components/model/ComponentTable.ts var ComponentTable_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ComponentTable_assign = ( false) || function () { ComponentTable_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return ComponentTable_assign.apply(this, arguments); }; var ComponentTable_type = 'table'; var ComponentTable = /** @class */ (function (_super) { ComponentTable_extends(ComponentTable, _super); function ComponentTable() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(ComponentTable.prototype, "defaults", { get: function () { return ComponentTable_assign(ComponentTable_assign({}, _super.prototype.defaults), { type: ComponentTable_type, tagName: ComponentTable_type, droppable: ['tbody', 'thead', 'tfoot'] }); }, enumerable: false, configurable: true }); ComponentTable.prototype.initialize = function (props, opts) { _super.prototype.initialize.call(this, props, opts); var components = this.get('components'); !components.length && components.add({ type: 'tbody' }); }; ComponentTable.isComponent = function (el) { return (0,mixins.toLowerCase)(el.tagName) === ComponentTable_type; }; return ComponentTable; }(model_Component)); /* harmony default export */ const model_ComponentTable = (ComponentTable); ;// CONCATENATED MODULE: ./src/dom_components/model/ComponentTableBody.ts var ComponentTableBody_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ComponentTableBody_assign = ( false) || function () { ComponentTableBody_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return ComponentTableBody_assign.apply(this, arguments); }; var ComponentTableBody_type = 'tbody'; var ComponentTableBody = /** @class */ (function (_super) { ComponentTableBody_extends(ComponentTableBody, _super); function ComponentTableBody() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(ComponentTableBody.prototype, "defaults", { get: function () { return ComponentTableBody_assign(ComponentTableBody_assign({}, _super.prototype.defaults), { type: ComponentTableBody_type, tagName: ComponentTableBody_type, draggable: ['table'], droppable: ['tr'], columns: 1, rows: 1 }); }, enumerable: false, configurable: true }); ComponentTableBody.prototype.initialize = function (props, opts) { _super.prototype.initialize.call(this, props, opts); var components = this.get('components'); var columns = this.get('columns'); var rows = this.get('rows'); // Init components if empty if (!components.length) { var rowsToAdd = []; while (rows--) { var columnsToAdd = []; var clm = columns; while (clm--) { columnsToAdd.push({ type: 'cell', classes: ['cell'], }); } rowsToAdd.push({ type: 'row', classes: ['row'], components: columnsToAdd, }); } components.add(rowsToAdd); } }; ComponentTableBody.isComponent = function (el) { return (0,mixins.toLowerCase)(el.tagName) === ComponentTableBody_type; }; return ComponentTableBody; }(model_Component)); /* harmony default export */ const model_ComponentTableBody = (ComponentTableBody); ;// CONCATENATED MODULE: ./src/dom_components/model/ComponentTableCell.ts var ComponentTableCell_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ComponentTableCell_assign = ( false) || function () { ComponentTableCell_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return ComponentTableCell_assign.apply(this, arguments); }; var ComponentTableCell = /** @class */ (function (_super) { ComponentTableCell_extends(ComponentTableCell, _super); function ComponentTableCell() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(ComponentTableCell.prototype, "defaults", { get: function () { return ComponentTableCell_assign(ComponentTableCell_assign({}, _super.prototype.defaults), { type: 'cell', tagName: 'td', draggable: ['tr'] }); }, enumerable: false, configurable: true }); ComponentTableCell.isComponent = function (el) { return ['td', 'th'].indexOf((0,mixins.toLowerCase)(el.tagName)) >= 0; }; return ComponentTableCell; }(model_Component)); /* harmony default export */ const model_ComponentTableCell = (ComponentTableCell); ;// CONCATENATED MODULE: ./src/dom_components/model/ComponentTableFoot.ts var ComponentTableFoot_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ComponentTableFoot_assign = ( false) || function () { ComponentTableFoot_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return ComponentTableFoot_assign.apply(this, arguments); }; var ComponentTableFoot_type = 'tfoot'; var ComponentTableFoot = /** @class */ (function (_super) { ComponentTableFoot_extends(ComponentTableFoot, _super); function ComponentTableFoot() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(ComponentTableFoot.prototype, "defaults", { get: function () { return ComponentTableFoot_assign(ComponentTableFoot_assign({}, _super.prototype.defaults), { type: ComponentTableFoot_type, tagName: ComponentTableFoot_type }); }, enumerable: false, configurable: true }); ComponentTableFoot.isComponent = function (el) { return (0,mixins.toLowerCase)(el.tagName) === ComponentTableFoot_type; }; return ComponentTableFoot; }(model_ComponentTableBody)); /* harmony default export */ const model_ComponentTableFoot = (ComponentTableFoot); ;// CONCATENATED MODULE: ./src/dom_components/model/ComponentTableHead.ts var ComponentTableHead_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ComponentTableHead_assign = ( false) || function () { ComponentTableHead_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return ComponentTableHead_assign.apply(this, arguments); }; var ComponentTableHead_type = 'thead'; var ComponentTableHead = /** @class */ (function (_super) { ComponentTableHead_extends(ComponentTableHead, _super); function ComponentTableHead() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(ComponentTableHead.prototype, "defaults", { get: function () { return ComponentTableHead_assign(ComponentTableHead_assign({}, _super.prototype.defaults), { type: ComponentTableHead_type, tagName: ComponentTableHead_type }); }, enumerable: false, configurable: true }); ComponentTableHead.isComponent = function (el) { return (0,mixins.toLowerCase)(el.tagName) === ComponentTableHead_type; }; return ComponentTableHead; }(model_ComponentTableBody)); /* harmony default export */ const model_ComponentTableHead = (ComponentTableHead); ;// CONCATENATED MODULE: ./src/dom_components/model/ComponentTableRow.ts var ComponentTableRow_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ComponentTableRow_assign = ( false) || function () { ComponentTableRow_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return ComponentTableRow_assign.apply(this, arguments); }; var tagName = 'tr'; var ComponentTableRow = /** @class */ (function (_super) { ComponentTableRow_extends(ComponentTableRow, _super); function ComponentTableRow() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(ComponentTableRow.prototype, "defaults", { get: function () { return ComponentTableRow_assign(ComponentTableRow_assign({}, _super.prototype.defaults), { tagName: tagName, draggable: ['thead', 'tbody', 'tfoot'], droppable: ['th', 'td'] }); }, enumerable: false, configurable: true }); ComponentTableRow.isComponent = function (el) { return (0,mixins.toLowerCase)(el.tagName) === tagName; }; return ComponentTableRow; }(model_Component)); /* harmony default export */ const model_ComponentTableRow = (ComponentTableRow); ;// CONCATENATED MODULE: ./src/dom_components/model/ComponentVideo.ts var ComponentVideo_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ComponentVideo_assign = ( false) || function () { ComponentVideo_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return ComponentVideo_assign.apply(this, arguments); }; var ComponentVideo_type = 'video'; var yt = 'yt'; var vi = 'vi'; var ytnc = 'ytnc'; var defProvider = 'so'; var hasParam = function (value) { return value && value !== '0'; }; var ComponentVideo = /** @class */ (function (_super) { ComponentVideo_extends(ComponentVideo, _super); function ComponentVideo() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(ComponentVideo.prototype, "defaults", { get: function () { return ComponentVideo_assign(ComponentVideo_assign({}, _super.prototype.defaults), { type: ComponentVideo_type, tagName: ComponentVideo_type, videoId: '', void: false, provider: defProvider, ytUrl: 'https://www.youtube.com/embed/', ytncUrl: 'https://www.youtube-nocookie.com/embed/', viUrl: 'https://player.vimeo.com/video/', loop: false, poster: '', muted: 0, autoplay: false, controls: true, color: '', list: '', rel: 1, modestbranding: 0, sources: [], attributes: { allowfullscreen: 'allowfullscreen' } }); }, enumerable: false, configurable: true }); ComponentVideo.prototype.initialize = function (props, opts) { this.em = opts.em; if (this.get('src')) this.parseFromSrc(); this.updatePropsFromAttr(); this.updateTraits(); this.on('change:provider', this.updateTraits); this.on('change:videoId change:provider', this.updateSrc); _super.prototype.initialize.call(this, props, opts); }; ComponentVideo.prototype.updatePropsFromAttr = function () { if (this.get('provider') === defProvider) { var _a = this.get('attributes'), controls = _a.controls, autoplay = _a.autoplay, loop = _a.loop; var toUp = {}; if ((0,mixins.isDef)(controls)) toUp.controls = !!controls; if ((0,mixins.isDef)(autoplay)) toUp.autoplay = !!autoplay; if ((0,mixins.isDef)(loop)) toUp.loop = !!loop; if (!(0,mixins.isEmptyObj)(toUp)) { this.set(toUp); } } }; /** * Update traits by provider * @private */ ComponentVideo.prototype.updateTraits = function () { var em = this.em; var prov = this.get('provider'); var tagName = 'iframe'; var traits; switch (prov) { case yt: case ytnc: traits = this.getYoutubeTraits(); break; case vi: traits = this.getVimeoTraits(); break; default: tagName = 'video'; traits = this.getSourceTraits(); } this.set({ tagName: tagName }, { silent: true }); // avoid break in view // @ts-ignore this.set({ traits: traits }); em.get('ready') && em.trigger('component:toggled'); }; /** * Set attributes by src string */ ComponentVideo.prototype.parseFromSrc = function () { var prov = this.get('provider'); var uri = this.parseUri(this.get('src')); var qr = uri.query; switch (prov) { case yt: case ytnc: case vi: this.set('videoId', uri.pathname.split('/').pop()); qr.list && this.set('list', qr.list); hasParam(qr.autoplay) && this.set('autoplay', true); hasParam(qr.loop) && this.set('loop', true); parseInt(qr.controls) === 0 && this.set('controls', false); hasParam(qr.color) && this.set('color', qr.color); qr.rel === '0' && this.set('rel', 0); qr.modestbranding === '1' && this.set('modestbranding', 1); break; default: } }; /** * Update src on change of video ID * @private */ ComponentVideo.prototype.updateSrc = function () { var prov = this.get('provider'); var src = ''; switch (prov) { case yt: src = this.getYoutubeSrc(); break; case ytnc: src = this.getYoutubeNoCookieSrc(); break; case vi: src = this.getVimeoSrc(); break; } this.set({ src: src }); }; /** * Returns object of attributes for HTML * @return {Object} * @private */ ComponentVideo.prototype.getAttrToHTML = function () { var attr = _super.prototype.getAttrToHTML.call(this); var prov = this.get('provider'); switch (prov) { case yt: case ytnc: case vi: break; default: attr.loop = !!this.get('loop'); attr.autoplay = !!this.get('autoplay'); attr.controls = !!this.get('controls'); } return attr; }; // Listen provider change and switch traits, in TraitView listen traits change /** * Return the provider trait * @return {Object} * @private */ ComponentVideo.prototype.getProviderTrait = function () { return { type: 'select', label: 'Provider', name: 'provider', changeProp: true, options: [ { value: 'so', name: 'HTML5 Source' }, { value: yt, name: 'Youtube' }, { value: ytnc, name: 'Youtube (no cookie)' }, { value: vi, name: 'Vimeo' }, ], }; }; /** * Return traits for the source provider * @return {Array<Object>} * @private */ ComponentVideo.prototype.getSourceTraits = function () { return [ this.getProviderTrait(), { label: 'Source', name: 'src', placeholder: 'eg. ./media/video.mp4', changeProp: true, }, { label: 'Poster', name: 'poster', placeholder: 'eg. ./media/image.jpg', }, this.getAutoplayTrait(), this.getLoopTrait(), this.getControlsTrait(), ]; }; /** * Return traits for the source provider * @return {Array<Object>} * @private */ ComponentVideo.prototype.getYoutubeTraits = function () { return [ this.getProviderTrait(), { label: 'Video ID', name: 'videoId', placeholder: 'eg. jNQXAC9IVRw', changeProp: true, }, this.getAutoplayTrait(), this.getLoopTrait(), this.getControlsTrait(), { type: 'checkbox', label: 'Related', name: 'rel', changeProp: true, }, { type: 'checkbox', label: 'Modest', name: 'modestbranding', changeProp: true, }, ]; }; /** * Return traits for the source provider * @return {Array<Object>} * @private */ ComponentVideo.prototype.getVimeoTraits = function () { return [ this.getProviderTrait(), { label: 'Video ID', name: 'videoId', placeholder: 'eg. 123456789', changeProp: true, }, { label: 'Color', name: 'color', placeholder: 'eg. FF0000', changeProp: true, }, this.getAutoplayTrait(), this.getLoopTrait(), ]; }; /** * Return object trait * @return {Object} * @private */ ComponentVideo.prototype.getAutoplayTrait = function () { return { type: 'checkbox', label: 'Autoplay', name: 'autoplay', changeProp: true, }; }; /** * Return object trait * @return {Object} * @private */ ComponentVideo.prototype.getLoopTrait = function () { return { type: 'checkbox', label: 'Loop', name: 'loop', changeProp: true, }; }; /** * Return object trait * @return {Object} * @private */ ComponentVideo.prototype.getControlsTrait = function () { return { type: 'checkbox', label: 'Controls', name: 'controls', changeProp: true, }; }; /** * Returns url to youtube video * @return {string} * @private */ ComponentVideo.prototype.getYoutubeSrc = function () { var id = this.get('videoId'); var url = this.get('ytUrl'); var list = this.get('list'); url += id + (id.indexOf('?') < 0 ? '?' : ''); url += list ? "&list=".concat(list) : ''; url += this.get('autoplay') ? '&autoplay=1&muted=1' : ''; url += !this.get('controls') ? '&controls=0&showinfo=0' : ''; // Loop works only with playlist enabled // https://stackoverflow.com/questions/25779966/youtube-iframe-loop-doesnt-work url += this.get('loop') ? "&loop=1&playlist=".concat(id) : ''; url += this.get('rel') ? '' : '&rel=0'; url += this.get('modestbranding') ? '&modestbranding=1' : ''; return url; }; /** * Returns url to youtube no cookie video * @return {string} * @private */ ComponentVideo.prototype.getYoutubeNoCookieSrc = function () { var url = this.getYoutubeSrc(); url = url.replace(this.get('ytUrl'), this.get('ytncUrl')); return url; }; /** * Returns url to vimeo video * @return {string} * @private */ ComponentVideo.prototype.getVimeoSrc = function () { var url = this.get('viUrl'); url += this.get('videoId') + '?'; url += this.get('autoplay') ? '&autoplay=1&muted=1' : ''; url += this.get('loop') ? '&loop=1' : ''; url += !this.get('controls') ? '&title=0&portrait=0&badge=0' : ''; url += this.get('color') ? '&color=' + this.get('color') : ''; return url; }; ComponentVideo.isComponent = function (el) { var tagName = el.tagName, src = el.src; var isYtProv = /youtube\.com\/embed/.test(src); var isYtncProv = /youtube-nocookie\.com\/embed/.test(src); var isViProv = /player\.vimeo\.com\/video/.test(src); var isExtProv = isYtProv || isYtncProv || isViProv; if ((0,mixins.toLowerCase)(tagName) == ComponentVideo_type || ((0,mixins.toLowerCase)(tagName) == 'iframe' && isExtProv)) { var result = { type: 'video' }; if (src) result.src = src; if (isExtProv) { if (isYtProv) result.provider = yt; else if (isYtncProv) result.provider = ytnc; else if (isViProv) result.provider = vi; } return result; } }; return ComponentVideo; }(model_ComponentImage)); /* harmony default export */ const model_ComponentVideo = (ComponentVideo); ;// CONCATENATED MODULE: ./src/dom_components/model/ComponentWrapper.ts var ComponentWrapper_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ComponentWrapper_assign = ( false) || function () { ComponentWrapper_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return ComponentWrapper_assign.apply(this, arguments); }; var ComponentWrapper = /** @class */ (function (_super) { ComponentWrapper_extends(ComponentWrapper, _super); function ComponentWrapper() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(ComponentWrapper.prototype, "defaults", { get: function () { return ComponentWrapper_assign(ComponentWrapper_assign({}, _super.prototype.defaults), { tagName: 'body', removable: false, copyable: false, draggable: false, components: [], traits: [], stylable: [ 'background', 'background-color', 'background-image', 'background-repeat', 'background-attachment', 'background-position', 'background-size', ] }); }, enumerable: false, configurable: true }); ComponentWrapper.prototype.__postAdd = function () { var _a; var um = (_a = this.em) === null || _a === void 0 ? void 0 : _a.UndoManager; !this.__hasUm && (um === null || um === void 0 ? void 0 : um.add(this)); return _super.prototype.__postAdd.call(this); }; ComponentWrapper.prototype.__postRemove = function () { var _a; var um = (_a = this.em) === null || _a === void 0 ? void 0 : _a.UndoManager; um === null || um === void 0 ? void 0 : um.remove(this); return _super.prototype.__postRemove.call(this); }; ComponentWrapper.isComponent = function () { return false; }; return ComponentWrapper; }(model_Component)); /* harmony default export */ const model_ComponentWrapper = (ComponentWrapper); ;// CONCATENATED MODULE: ./src/dom_components/view/ComponentsView.ts var ComponentsView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ComponentsView = /** @class */ (function (_super) { ComponentsView_extends(ComponentsView, _super); function ComponentsView() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.compView = view_ComponentView; return _this; } ComponentsView.prototype.initialize = function (o) { this.opts = o || {}; this.config = o.config || {}; // @ts-ignore this.em = this.config.em; var coll = this.collection; this.listenTo(coll, 'add', this.addTo); this.listenTo(coll, 'reset', this.resetChildren); this.listenTo(coll, 'remove', this.removeChildren); }; ComponentsView.prototype.removeChildren = function (removed, coll, opts) { var _this = this; if (opts === void 0) { opts = {}; } removed.views.forEach(function (view) { if (!view) return; var childrenView = view.childrenView, scriptContainer = view.scriptContainer; childrenView && childrenView.stopListening(); (0,dom/* removeEl */.L_)(scriptContainer); view.remove.apply(view); }); var inner = removed.components(); inner.forEach(function (it) { return _this.removeChildren(it, coll, opts); }); }; /** * Add to collection * @param {Model} model * @param {Collection} coll * @param {Object} opts * @private * */ ComponentsView.prototype.addTo = function (model, coll, opts) { if (coll === void 0) { coll = {}; } if (opts === void 0) { opts = {}; } var em = this.em; var i = this.collection.indexOf(model); this.addToCollection(model, null, i); if (em && !opts.temporary) { var triggerAdd_1 = function (model) { em.trigger('component:add', model); model.components().forEach(function (comp) { return triggerAdd_1(comp); }); }; triggerAdd_1(model); } }; /** * Add new object to collection * @param {Object} Model * @param {Object} Fragment collection * @param {Integer} Index of append * * @return {Object} Object rendered * @private * */ ComponentsView.prototype.addToCollection = function (model, fragmentEl, index) { // if (!this.compView) this.compView = require('./ComponentView').default; var _a = this, config = _a.config, opts = _a.opts, em = _a.em; var fragment = fragmentEl || null; var frameView = config.frameView; var sameFrameView = (frameView === null || frameView === void 0 ? void 0 : frameView.model) && model.getView(frameView.model); var dt = opts.componentTypes || (em === null || em === void 0 ? void 0 : em.Components.getTypes()); var type = model.get('type') || 'default'; var viewObject = this.compView; for (var it_1 = 0; it_1 < dt.length; it_1++) { if (dt[it_1].id == type) { viewObject = dt[it_1].view; break; } } var view = sameFrameView || new viewObject({ model: model, // @ts-ignore config: config, componentTypes: dt, }); var rendered; try { // Avoid breaking on DOM rendering (eg. invalid attribute name) rendered = view.render().el; } catch (error) { rendered = document.createTextNode(''); em.logError(error); } if (fragment) { fragment.appendChild(rendered); } else { var parent_1 = this.parentEl; var children = parent_1.childNodes; if (!(0,index_all.isUndefined)(index)) { var lastIndex = children.length == index; // If the added model is the last of collection // need to change the logic of append if (lastIndex) { index--; } // In case the added is new in the collection index will be -1 if (lastIndex || !children.length) { parent_1.appendChild(rendered); } else { parent_1.insertBefore(rendered, children[index]); } } else { parent_1.appendChild(rendered); } } if (!model.opt.temporary) { em === null || em === void 0 ? void 0 : em.trigger('component:mount', model); } return rendered; }; ComponentsView.prototype.resetChildren = function (models, _a) { var _this = this; var _b = _a === void 0 ? {} : _a, _c = _b.previousModels, previousModels = _c === void 0 ? [] : _c; this.parentEl.innerHTML = ''; previousModels.forEach(function (md) { return _this.removeChildren(md, _this.collection); }); models.each(function (model) { return _this.addToCollection(model); }); }; ComponentsView.prototype.render = function (parent) { var _this = this; var el = this.el; var frag = document.createDocumentFragment(); this.parentEl = parent || this.el; this.collection.each(function (model) { return _this.addToCollection(model, frag); }); el.innerHTML = ''; el.appendChild(frag); return this; }; return ComponentsView; }(common/* View */.G7)); /* harmony default export */ const view_ComponentsView = (ComponentsView); ;// CONCATENATED MODULE: ./src/dom_components/view/ComponentView.ts var ComponentView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ComponentView_assign = ( false) || function () { ComponentView_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return ComponentView_assign.apply(this, arguments); }; var ComponentView = /** @class */ (function (_super) { ComponentView_extends(ComponentView, _super); function ComponentView() { return _super !== null && _super.apply(this, arguments) || this; } /** @ts-ignore */ ComponentView.prototype.className = function () { return this.getClasses(); }; /** @ts-ignore */ ComponentView.prototype.tagName = function () { return this.model.get('tagName'); }; ComponentView.prototype.initialize = function (opt) { if (opt === void 0) { opt = {}; } var model = this.model; var config = opt.config || {}; var em = config.em; var modelOpt = model.opt || {}; var _a = this, $el = _a.$el, el = _a.el; this.opts = opt; this.modelOpt = modelOpt; this.config = config; this.em = em; this.pfx = config.stylePrefix || ''; this.ppfx = config.pStylePrefix || ''; this.attr = model.get('attributes'); this.classe = this.attr.class || []; this.listenTo(model, 'change:style', this.updateStyle); this.listenTo(model, 'change:attributes', this.renderAttributes); this.listenTo(model, 'change:highlightable', this.updateHighlight); this.listenTo(model, 'change:status change:locked', this.updateStatus); this.listenTo(model, 'change:script rerender', this.reset); this.listenTo(model, 'change:content', this.updateContent); this.listenTo(model, 'change', this.handleChange); this.listenTo(model, 'active', this.onActive); this.listenTo(model, 'disable', this.onDisable); $el.data('model', model); (0,mixins.setViewEl)(el, this); model.view = this; this.frameView && model.views.push(this); this.initClasses(); this.initComponents({ avoidRender: true }); this.events = ComponentView_assign(ComponentView_assign({}, this.constructor.getEvents()), { dragstart: 'handleDragStart' }); this.delegateEvents(); !modelOpt.temporary && this.init(this._clbObj()); }; Object.defineProperty(ComponentView.prototype, "__cmpStyleOpts", { get: function () { return { state: '', mediaText: '' }; }, enumerable: false, configurable: true }); Object.defineProperty(ComponentView.prototype, "frameView", { get: function () { return this.opts.config.frameView; }, enumerable: false, configurable: true }); ComponentView.prototype.__isDraggable = function () { var _a = this, model = _a.model, config = _a.config; var draggable = model.attributes.draggable; return config.draggableComponents && draggable; }; ComponentView.prototype._clbObj = function () { var _a = this, em = _a.em, model = _a.model, el = _a.el; return { editor: em === null || em === void 0 ? void 0 : em.getEditor(), model: model, el: el, }; }; /** * Initialize callback */ ComponentView.prototype.init = function (opts) { }; /** * Remove callback */ ComponentView.prototype.removed = function (opts) { }; /** * On render callback */ ComponentView.prototype.onRender = function (opts) { }; /** * Callback executed when the `active` event is triggered on component */ ComponentView.prototype.onActive = function (ev) { }; /** * Callback executed when the `disable` event is triggered on component */ ComponentView.prototype.onDisable = function () { }; ComponentView.prototype.remove = function () { var _a; _super.prototype.remove.call(this); var _b = this, model = _b.model, $el = _b.$el; var views = model.views; var frame = this.frameView || {}; model.components().forEach(function (comp) { var view = comp.getView(frame.model); view === null || view === void 0 ? void 0 : view.remove(); }); (_a = this.childrenView) === null || _a === void 0 ? void 0 : _a.remove(); views.splice(views.indexOf(this), 1); this.removed(this._clbObj()); $el.data({ model: '', collection: '', view: '' }); // delete model.view; // Sorter relies on this property return this; }; ComponentView.prototype.handleDragStart = function (event) { if (!this.__isDraggable()) return false; event.stopPropagation(); event.preventDefault(); this.em.Commands.run('tlb-move', { target: this.model, event: event, }); }; ComponentView.prototype.initClasses = function () { var model = this.model; var classes = model.classes; var event = 'change:classes'; if (classes instanceof model_Selectors) { this.stopListening(model, event, this.initClasses); this.listenTo(model, event, this.initClasses); this.listenTo(classes, 'add remove change reset', this.updateClasses); classes.length && this.importClasses(); } }; ComponentView.prototype.initComponents = function (opts) { if (opts === void 0) { opts = {}; } var _a = this, model = _a.model, $el = _a.$el, childrenView = _a.childrenView; var event = 'change:components'; var comps = model.get('components'); var toListen = [model, event, this.initComponents]; if (comps instanceof model_Components) { $el.data('collection', comps); childrenView && childrenView.remove(); this.stopListening.apply(this, toListen); !opts.avoidRender && this.renderChildren(); // @ts-ignore this.listenTo.apply(this, toListen); } }; /** * Handle any property change * @private */ ComponentView.prototype.handleChange = function () { var model = this.model; var chgArr = (0,index_all.keys)(model.changed); if (chgArr.length === 1 && chgArr[0] === 'status') return; model.emitUpdate(); for (var prop in model.changed) { model.emitUpdate(prop); } }; /** * Import, if possible, classes inside main container * @private * */ ComponentView.prototype.importClasses = function () { var _a = this, em = _a.em, model = _a.model; var sm = em.Selectors; sm && model.classes.forEach(function (s) { return sm.add(s.get('name')); }); }; /** * Update item on status change * @param {Event} e * @private * */ ComponentView.prototype.updateStatus = function (opts) { if (opts === void 0) { opts = {}; } var _a = this, em = _a.em, el = _a.el, ppfx = _a.ppfx, model = _a.model; var canvas = em === null || em === void 0 ? void 0 : em.Canvas; var extHl = canvas === null || canvas === void 0 ? void 0 : canvas.config.extHl; var status = model.get('status'); var selectedCls = "".concat(ppfx, "selected"); var selectedParentCls = "".concat(selectedCls, "-parent"); var freezedCls = "".concat(ppfx, "freezed"); var hoveredCls = "".concat(ppfx, "hovered"); var noPointerCls = "".concat(ppfx, "no-pointer"); var toRemove = [selectedCls, selectedParentCls, freezedCls, hoveredCls, noPointerCls]; var selCls = extHl && !opts.noExtHl ? '' : selectedCls; this.$el.removeClass(toRemove.join(' ')); var actualCls = el.getAttribute('class') || ''; var cls = [actualCls]; var noCustomSpotSelect = !(canvas === null || canvas === void 0 ? void 0 : canvas.hasCustomSpot(CanvasSpot/* CanvasSpotBuiltInTypes */.q.Select)); var noCustomSpotTarget = !(canvas === null || canvas === void 0 ? void 0 : canvas.hasCustomSpot(CanvasSpot/* CanvasSpotBuiltInTypes */.q.Target)); switch (status) { case 'selected': noCustomSpotSelect && cls.push(selCls); break; case 'selected-parent': noCustomSpotTarget && cls.push(selectedParentCls); break; case 'freezed': cls.push(freezedCls); break; case 'freezed-selected': cls.push(freezedCls); noCustomSpotSelect && cls.push(selCls); break; case 'hovered': !opts.avoidHover && cls.push(hoveredCls); break; } model.get('locked') && cls.push(noPointerCls); var clsStr = cls.filter(Boolean).join(' '); clsStr && el.setAttribute('class', clsStr); }; /** * Update highlight attribute * @private * */ ComponentView.prototype.updateHighlight = function () { var model = this.model; var isTextable = model.get('textable'); var hl = model.get('highlightable') && (isTextable || !model.isChildOf('text')); this.setAttribute('data-gjs-highlightable', hl ? true : ''); }; /** * Update style attribute * @private * */ ComponentView.prototype.updateStyle = function (m, v, opts) { if (opts === void 0) { opts = {}; } var _a = this, model = _a.model, em = _a.em; if (avoidInline(em) && !opts.inline) { var styleOpts = this.__cmpStyleOpts; var style = model.getStyle(styleOpts); !(0,index_all.isEmpty)(style) && model.setStyle(style, styleOpts); } else { this.setAttribute('style', model.styleToString(opts)); } }; /** * Update classe attribute * @private * */ ComponentView.prototype.updateClasses = function () { var str = this.model.classes.pluck('name').join(' '); this.setAttribute('class', str); // Regenerate status class this.updateStatus(); this.onAttrUpdate(); }; /** * Update single attribute * @param {[type]} name [description] * @param {[type]} value [description] */ ComponentView.prototype.setAttribute = function (name, value) { var el = this.$el; value ? el.attr(name, value) : el.removeAttr(name); }; /** * Get classes from attributes. * This method is called before initialize * * @return {Array}|null * @private * */ ComponentView.prototype.getClasses = function () { return this.model.getClasses().join(' '); }; /** * Update attributes * @private * */ ComponentView.prototype.updateAttributes = function () { var attrs = []; var _a = this, model = _a.model, $el = _a.$el, el = _a.el; var _b = model.attributes, textable = _b.textable, type = _b.type; var defaultAttr = ComponentView_assign(ComponentView_assign({ id: model.getId(), 'data-gjs-type': type || 'default' }, (this.__isDraggable() && { draggable: true })), (textable && { contenteditable: 'false' })); // Remove all current attributes (0,index_all.each)(el.attributes, function (attr) { return attrs.push(attr.nodeName); }); attrs.forEach(function (attr) { return $el.removeAttr(attr); }); this.updateStyle(); this.updateHighlight(); var attr = ComponentView_assign(ComponentView_assign({}, defaultAttr), model.getAttributes()); // Remove all `false` attributes (0,index_all.keys)(attr).forEach(function (key) { return attr[key] === false && delete attr[key]; }); $el.attr(attr); }; /** * Update component content * @private * */ ComponentView.prototype.updateContent = function () { var content = this.model.content; var hasComps = this.model.components().length; this.getChildrenContainer().innerHTML = hasComps ? '' : content; }; /** * Prevent default helper * @param {Event} e * @private */ ComponentView.prototype.prevDef = function (e) { e.preventDefault(); }; /** * Render component's script * @private */ ComponentView.prototype.updateScript = function () { var _a = this, model = _a.model, em = _a.em; if (!model.get('script')) return; em === null || em === void 0 ? void 0 : em.Canvas.getCanvasView().updateScript(this); }; /** * Return children container * Differently from a simple component where children container is the * component itself * <my-comp> * <!-- * <child></child> ... * --> * </my-comp> * You could have the children container more deeper * <my-comp> * <div></div> * <div></div> * <div> * <div> * <!-- * <child></child> ... * --> * </div> * </div> * </my-comp> * @return HTMLElement * @private */ ComponentView.prototype.getChildrenContainer = function () { var container = this.el; if (typeof this.getChildrenSelector == 'function') { container = this.el.querySelector(this.getChildrenSelector()); } else if (typeof this.getTemplate == 'function') { // Need to find deepest first child } return container; }; /** * This returns rect informations not affected by the canvas zoom. * The method `getBoundingClientRect` doesn't work here and we * have to take in account offsetParent */ ComponentView.prototype.getOffsetRect = function () { var rect = { top: 0, left: 0, bottom: 0, right: 0 }; var target = this.el; var gtop = 0; var gleft = 0; var assignRect = function (el) { var offsetParent = el.offsetParent; if (offsetParent) { gtop += offsetParent.offsetTop; gleft += offsetParent.offsetLeft; assignRect(offsetParent); } else { rect.top = target.offsetTop + gtop; rect.left = target.offsetLeft + gleft; rect.bottom = rect.top + target.offsetHeight; rect.right = rect.left + target.offsetWidth; } }; assignRect(target); return rect; }; ComponentView.prototype.isInViewport = function () { var _a = this, el = _a.el, em = _a.em, frameView = _a.frameView; var canvasView = em.Canvas.getCanvasView(); var elRect = canvasView.getElBoxRect(el, { local: true }); var frameEl = frameView.el; var frameH = frameEl.clientHeight; var frameW = frameEl.clientWidth; var elTop = elRect.y; var elRight = elRect.x; var elBottom = elTop + elRect.height; var elLeft = elRight + elRect.width; var isTopInside = elTop >= 0 && elTop < frameH; var isBottomInside = elBottom > 0 && elBottom < frameH; var isLeftInside = elLeft >= 0 && elLeft < frameW; var isRightInside = elRight > 0 && elRight <= frameW; var partiallyIn = (isTopInside || isBottomInside) && (isLeftInside || isRightInside); return partiallyIn; }; ComponentView.prototype.scrollIntoView = function (opts) { var _a; if (opts === void 0) { opts = {}; } var isInViewport = this.isInViewport(); if (!isInViewport || opts.force) { var el = this.el; // PATCH: scrollIntoView won't work with multiple requests from iframes if (opts.behavior !== 'smooth') { var rect = this.getOffsetRect(); (_a = el.ownerDocument.defaultView) === null || _a === void 0 ? void 0 : _a.scrollTo(0, rect.top); } else { el.scrollIntoView(ComponentView_assign({ behavior: 'smooth', block: 'nearest' }, opts)); } } }; /** * Recreate the element of the view */ ComponentView.prototype.reset = function () { var el = this.el; // @ts-ignore this.el = ''; this._ensureElement(); this._setData(); (0,dom/* replaceWith */.dL)(el, this.el); this.render(); }; ComponentView.prototype._setData = function () { var model = this.model; var collection = model.components(); var view = this; this.$el.data({ model: model, collection: collection, view: view }); }; /** * Render children components * @private */ ComponentView.prototype.renderChildren = function () { this.updateContent(); var container = this.getChildrenContainer(); var view = this.childrenView || new view_ComponentsView({ // @ts-ignore collection: this.model.get('components'), config: this.config, componentTypes: this.opts.componentTypes, }); view.render(container); this.childrenView = view; var childNodes = Array.prototype.slice.call(view.el.childNodes); for (var i = 0, len = childNodes.length; i < len; i++) { container.appendChild(childNodes.shift()); } }; ComponentView.prototype.renderAttributes = function () { this.updateAttributes(); this.updateClasses(); }; ComponentView.prototype.onAttrUpdate = function () { }; ComponentView.prototype.render = function () { this.renderAttributes(); if (this.modelOpt.temporary) return this; this.renderChildren(); this.updateScript(); (0,mixins.setViewEl)(this.el, this); this.postRender(); return this; }; ComponentView.prototype.postRender = function () { if (!this.modelOpt.temporary) { this.onRender(this._clbObj()); } }; ComponentView.getEvents = function () { return (0,index_all.result)(this.prototype, 'events'); }; return ComponentView; }(common/* View */.G7)); /* harmony default export */ const view_ComponentView = (ComponentView); ;// CONCATENATED MODULE: ./src/dom_components/view/ComponentTextNodeView.ts var ComponentTextNodeView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ComponentTextNodeView = /** @class */ (function (_super) { ComponentTextNodeView_extends(ComponentTextNodeView, _super); function ComponentTextNodeView() { return _super !== null && _super.apply(this, arguments) || this; } // Clear methods used on Nodes with attributes ComponentTextNodeView.prototype._setAttributes = function () { }; ComponentTextNodeView.prototype.renderAttributes = function () { }; ComponentTextNodeView.prototype.updateStatus = function () { }; ComponentTextNodeView.prototype.updateClasses = function () { }; ComponentTextNodeView.prototype.setAttribute = function () { }; ComponentTextNodeView.prototype.updateAttributes = function () { }; ComponentTextNodeView.prototype.initClasses = function () { }; ComponentTextNodeView.prototype.initComponents = function () { }; ComponentTextNodeView.prototype.delegateEvents = function () { return this; }; ComponentTextNodeView.prototype._createElement = function () { return document.createTextNode(''); }; ComponentTextNodeView.prototype.render = function () { var _a = this, model = _a.model, el = _a.el; if (model.opt.temporary) return this; el.textContent = model.content; return this; }; return ComponentTextNodeView; }(view_ComponentView)); /* harmony default export */ const view_ComponentTextNodeView = (ComponentTextNodeView); ;// CONCATENATED MODULE: ./src/dom_components/view/ComponentCommentView.ts var ComponentCommentView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ComponentCommentView = /** @class */ (function (_super) { ComponentCommentView_extends(ComponentCommentView, _super); function ComponentCommentView() { return _super !== null && _super.apply(this, arguments) || this; } ComponentCommentView.prototype._createElement = function () { return document.createComment(this.model.content); }; return ComponentCommentView; }(view_ComponentTextNodeView)); /* harmony default export */ const view_ComponentCommentView = (ComponentCommentView); ;// CONCATENATED MODULE: ./src/dom_components/view/ComponentFrameView.ts var ComponentFrameView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ComponentFrameView = /** @class */ (function (_super) { ComponentFrameView_extends(ComponentFrameView, _super); function ComponentFrameView() { return _super !== null && _super.apply(this, arguments) || this; } ComponentFrameView.prototype.tagName = function () { return 'div'; }; ComponentFrameView.prototype.initialize = function (props) { _super.prototype.initialize.call(this, props); this.listenTo(this.model, 'change:attributes:src', this.updateSrc); }; ComponentFrameView.prototype.updateSrc = function () { var frame = (0,dom/* find */.sE)(this.el, 'iframe')[0]; frame && (0,dom/* attrUp */.FW)(frame, { src: this.__getSrc() }); }; ComponentFrameView.prototype.render = function () { _super.prototype.render.call(this); var frame = (0,dom/* createEl */.ut)('iframe', { class: "".concat(this.ppfx, "no-pointer"), style: 'width: 100%; height: 100%; border: none', src: this.__getSrc(), }); this.el.appendChild(frame); return this; }; ComponentFrameView.prototype.__getSrc = function () { return this.model.getAttributes().src || ''; }; return ComponentFrameView; }(view_ComponentView)); /* harmony default export */ const view_ComponentFrameView = (ComponentFrameView); ;// CONCATENATED MODULE: ./src/dom_components/view/ComponentImageView.ts var ComponentImageView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ComponentImageView = /** @class */ (function (_super) { ComponentImageView_extends(ComponentImageView, _super); function ComponentImageView() { return _super !== null && _super.apply(this, arguments) || this; } ComponentImageView.prototype.tagName = function () { return 'img'; }; ComponentImageView.prototype.events = function () { return { dblclick: 'onActive', click: 'initResize', error: 'onError', load: 'onLoad', dragstart: 'noDrag', }; }; ComponentImageView.prototype.initialize = function (props) { _super.prototype.initialize.call(this, props); this.listenTo(this.model, 'change:src', this.updateSrc); this.classEmpty = "".concat(this.ppfx, "plh-image"); this.fetchFile(); }; /** * Fetch file if exists */ ComponentImageView.prototype.fetchFile = function () { if (this.modelOpt.temporary) return; var _a = this, model = _a.model, em = _a.em; var file = model.get('file'); if (file && em) { var fu = em.Assets.FileUploader(); fu === null || fu === void 0 ? void 0 : fu.uploadFile({ // @ts-ignore dataTransfer: { files: [file] }, }, function (res) { var obj = res && res.data && res.data[0]; var src = obj && ((0,index_all.isString)(obj) ? obj : obj.src); src && model.set({ src: src }); }); model.set('file', ''); } }; /** * Update src attribute * @private * */ ComponentImageView.prototype.updateSrc = function () { var model = this.model; model.addAttributes({ src: model.getSrcResult() }); this.updateClasses(); }; ComponentImageView.prototype.updateClasses = function () { _super.prototype.updateClasses.call(this); var _a = this, el = _a.el, classEmpty = _a.classEmpty, model = _a.model; var srcExists = model.getSrcResult() && !model.isDefaultSrc(); var method = srcExists ? 'remove' : 'add'; el.classList[method](classEmpty); }; /** * Open dialog for image changing * @param {Object} e Event * @private * */ ComponentImageView.prototype.onActive = function (ev) { ev === null || ev === void 0 ? void 0 : ev.stopPropagation(); var _a = this, em = _a.em, model = _a.model; var am = em === null || em === void 0 ? void 0 : em.Assets; if (am && model.get('editable')) { am.open({ select: function (asset, complete) { model.set({ src: asset.getSrc() }); complete && am.close(); }, target: model, types: ['image'], accept: 'image/*', }); } }; ComponentImageView.prototype.onError = function () { var fallback = this.model.getSrcResult({ fallback: true }); if (fallback) { this.el.src = fallback; } }; ComponentImageView.prototype.onLoad = function () { // Used to update component tools box (eg. toolbar, resizer) once the image is loaded this.em.trigger('change:canvasOffset'); }; ComponentImageView.prototype.noDrag = function (ev) { ev.preventDefault(); return false; }; ComponentImageView.prototype.render = function () { this.renderAttributes(); if (this.modelOpt.temporary) return this; this.updateSrc(); var _a = this, $el = _a.$el, model = _a.model; var cls = $el.attr('class') || ''; !model.get('src') && $el.attr('class', "".concat(cls, " ").concat(this.classEmpty).trim()); this.postRender(); return this; }; return ComponentImageView; }(view_ComponentView)); /* harmony default export */ const view_ComponentImageView = (ComponentImageView); ;// CONCATENATED MODULE: ./src/dom_components/view/ComponentTextView.ts var ComponentTextView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ComponentTextView_assign = ( false) || function () { ComponentTextView_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return ComponentTextView_assign.apply(this, arguments); }; var __awaiter = ( false) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = ( false) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var ComponentTextView = /** @class */ (function (_super) { ComponentTextView_extends(ComponentTextView, _super); function ComponentTextView() { return _super !== null && _super.apply(this, arguments) || this; } ComponentTextView.prototype.events = function () { return { dblclick: 'onActive', input: 'onInput', }; }; ComponentTextView.prototype.initialize = function (props) { _super.prototype.initialize.call(this, props); (0,index_all.bindAll)(this, 'disableEditing', 'onDisable'); var model = this.model; var em = this.em; this.listenTo(model, 'focus', this.onActive); this.listenTo(model, 'change:content', this.updateContentText); this.listenTo(model, 'sync:content', this.syncContent); this.rte = em === null || em === void 0 ? void 0 : em.RichTextEditor; }; ComponentTextView.prototype.updateContentText = function (m, v, opts) { if (opts === void 0) { opts = {}; } !opts.fromDisable && this.disableEditing(); }; ComponentTextView.prototype.canActivate = function () { var _a = this, model = _a.model, rteEnabled = _a.rteEnabled, em = _a.em; var modelInEdit = em === null || em === void 0 ? void 0 : em.getEditing(); var sameInEdit = modelInEdit === model; var result = true; var isInnerText = false; var delegate; if (rteEnabled || !model.get('editable') || sameInEdit || (isInnerText = model.isChildOf('text'))) { result = false; // If the current is inner text, select the closest text if (isInnerText && !model.get('textable')) { var parent_1 = model.parent(); while (parent_1 && !parent_1.isInstanceOf('text')) { parent_1 = parent_1.parent(); } if (parent_1 && parent_1.get('editable')) { delegate = parent_1; } else { result = true; } } } return { result: result, delegate: delegate }; }; /** * Enable element content editing * @private * */ ComponentTextView.prototype.onActive = function (ev) { var _a, _b; return __awaiter(this, void 0, void 0, function () { var _c, rte, em, _d, result, delegate, _e, _f, err_1; return __generator(this, function (_g) { switch (_g.label) { case 0: _c = this, rte = _c.rte, em = _c.em; _d = this.canActivate(), result = _d.result, delegate = _d.delegate; // We place this before stopPropagation in case of nested // text components will not block the editing (#1394) if (!result) { if (delegate) { (_a = ev === null || ev === void 0 ? void 0 : ev.stopPropagation) === null || _a === void 0 ? void 0 : _a.call(ev); em.setSelected(delegate); delegate.trigger('active', ev); } return [2 /*return*/]; } (_b = ev === null || ev === void 0 ? void 0 : ev.stopPropagation) === null || _b === void 0 ? void 0 : _b.call(ev); _e = this; return [4 /*yield*/, this.getContent()]; case 1: _e.lastContent = _g.sent(); if (!rte) return [3 /*break*/, 5]; _g.label = 2; case 2: _g.trys.push([2, 4, , 5]); _f = this; return [4 /*yield*/, rte.enable(this, this.activeRte, { event: ev })]; case 3: _f.activeRte = _g.sent(); return [3 /*break*/, 5]; case 4: err_1 = _g.sent(); em.logError(err_1); return [3 /*break*/, 5]; case 5: this.toggleEvents(true); return [2 /*return*/]; } }); }); }; ComponentTextView.prototype.onDisable = function () { this.disableEditing(); }; /** * Disable element content editing * @private * */ ComponentTextView.prototype.disableEditing = function (opts) { if (opts === void 0) { opts = {}; } return __awaiter(this, void 0, void 0, function () { var _a, model, rte, activeRte, em, editable, err_2, _b; return __generator(this, function (_c) { switch (_c.label) { case 0: _a = this, model = _a.model, rte = _a.rte, activeRte = _a.activeRte, em = _a.em; editable = model && model.get('editable'); if (!rte) return [3 /*break*/, 8]; _c.label = 1; case 1: _c.trys.push([1, 3, , 4]); return [4 /*yield*/, rte.disable(this, activeRte)]; case 2: _c.sent(); return [3 /*break*/, 4]; case 3: err_2 = _c.sent(); em.logError(err_2); return [3 /*break*/, 4]; case 4: _b = editable; if (!_b) return [3 /*break*/, 6]; return [4 /*yield*/, this.getContent()]; case 5: _b = (_c.sent()) !== this.lastContent; _c.label = 6; case 6: if (!_b) return [3 /*break*/, 8]; return [4 /*yield*/, this.syncContent(opts)]; case 7: _c.sent(); this.lastContent = ''; _c.label = 8; case 8: this.toggleEvents(); return [2 /*return*/]; } }); }); }; /** * get content from RTE * @return string */ ComponentTextView.prototype.getContent = function () { return __awaiter(this, void 0, void 0, function () { var _a, rte, activeRte, result; return __generator(this, function (_b) { switch (_b.label) { case 0: _a = this, rte = _a.rte, activeRte = _a.activeRte; result = ''; if (!rte) return [3 /*break*/, 2]; return [4 /*yield*/, rte.getContent(this, activeRte)]; case 1: result = _b.sent(); _b.label = 2; case 2: return [2 /*return*/, result]; } }); }); }; /** * Merge content from the DOM to the model */ ComponentTextView.prototype.syncContent = function (opts) { if (opts === void 0) { opts = {}; } return __awaiter(this, void 0, void 0, function () { var _a, model, rte, rteEnabled, content, comps, contentOpt; return __generator(this, function (_b) { switch (_b.label) { case 0: _a = this, model = _a.model, rte = _a.rte, rteEnabled = _a.rteEnabled; if (!rteEnabled && !opts.force) return [2 /*return*/]; return [4 /*yield*/, this.getContent()]; case 1: content = _b.sent(); comps = model.components(); contentOpt = ComponentTextView_assign({ fromDisable: 1 }, opts); model.set('content', '', contentOpt); // If there is a custom RTE the content is just added staticly // inside 'content' if ((rte === null || rte === void 0 ? void 0 : rte.customRte) && !rte.customRte.parseContent) { comps.length && comps.reset(undefined, ComponentTextView_assign(ComponentTextView_assign({}, opts), { // @ts-ignore keepIds: getComponentIds(comps) })); model.set('content', content, contentOpt); } else { comps.resetFromString(content, opts); } return [2 /*return*/]; } }); }); }; ComponentTextView.prototype.insertComponent = function (content, opts) { var _a; if (opts === void 0) { opts = {}; } var _b = this, model = _b.model, el = _b.el; var doc = el.ownerDocument; var selection = doc.getSelection(); if (selection === null || selection === void 0 ? void 0 : selection.rangeCount) { var range = selection.getRangeAt(0); var textNode = range.startContainer; var offset_1 = range.startOffset; var textModel_1 = (0,mixins.getModel)(textNode); var newCmps_1 = []; if (textModel_1 && ((_a = textModel_1.is) === null || _a === void 0 ? void 0 : _a.call(textModel_1, 'textnode'))) { var cmps = textModel_1.collection; cmps.forEach(function (cmp) { if (cmp === textModel_1) { var type = 'textnode'; var cnt = cmp.content; newCmps_1.push({ type: type, content: cnt.slice(0, offset_1) }); newCmps_1.push(content); newCmps_1.push({ type: type, content: cnt.slice(offset_1) }); } else { newCmps_1.push(cmp); } }); var result = newCmps_1.filter(Boolean); var index = result.indexOf(content); cmps.reset(result, opts); return cmps.at(index); } } return model.append(content, opts); }; /** * Callback on input event * @param {Event} e */ ComponentTextView.prototype.onInput = function () { var em = this.em; var evPfx = 'component'; var ev = ["".concat(evPfx, ":update"), "".concat(evPfx, ":input")].join(' '); // Update toolbars em && em.trigger(ev, this.model); }; /** * Isolate disable propagation method * @param {Event} * @private * */ ComponentTextView.prototype.disablePropagation = function (e) { e.stopPropagation(); }; /** * Enable/Disable events * @param {Boolean} enable */ ComponentTextView.prototype.toggleEvents = function (enable) { var _a = this, em = _a.em, model = _a.model, $el = _a.$el; var mixins = { on: dom.on, off: dom/* off */.S1 }; var method = enable ? 'on' : 'off'; em.setEditing(enable ? this : false); this.rteEnabled = !!enable; // The ownerDocument is from the frame var elDocs = [this.el.ownerDocument, document]; mixins.off(elDocs, 'mousedown', this.onDisable); mixins[method](elDocs, 'mousedown', this.onDisable); em[method]('toolbar:run:before', this.onDisable); if (model) { model[method]('removed', this.onDisable); model.trigger("rte:".concat(enable ? 'enable' : 'disable')); } // @ts-ignore Avoid closing edit mode on component click $el === null || $el === void 0 ? void 0 : $el.off('mousedown', this.disablePropagation); // @ts-ignore $el && $el[method]('mousedown', this.disablePropagation); // Fixes #2210 but use this also as a replacement // of this fix: bd7b804f3b46eb45b4398304b2345ce870f232d2 if (this.config.draggableComponents) { var el = this.el; while (el) { el.draggable = enable ? !1 : !0; // Note: el.parentNode is sometimes null here el = el.parentNode; if (el && el.tagName == 'BODY') { // @ts-ignore el = 0; } } } }; return ComponentTextView; }(view_ComponentView)); /* harmony default export */ const view_ComponentTextView = (ComponentTextView); ;// CONCATENATED MODULE: ./src/dom_components/view/ComponentLinkView.ts var ComponentLinkView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ComponentLinkView = /** @class */ (function (_super) { ComponentLinkView_extends(ComponentLinkView, _super); function ComponentLinkView() { return _super !== null && _super.apply(this, arguments) || this; } ComponentLinkView.prototype.render = function () { _super.prototype.render.call(this); // I need capturing instead of bubbling as bubbled clicks from other // children will execute the link event this.el.addEventListener('click', this.prevDef, true); return this; }; return ComponentLinkView; }(view_ComponentTextView)); /* harmony default export */ const view_ComponentLinkView = (ComponentLinkView); ;// CONCATENATED MODULE: ./src/dom_components/view/ComponentLabelView.ts var ComponentLabelView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ComponentLabelView = /** @class */ (function (_super) { ComponentLabelView_extends(ComponentLabelView, _super); function ComponentLabelView() { return _super !== null && _super.apply(this, arguments) || this; } return ComponentLabelView; }(view_ComponentLinkView)); /* harmony default export */ const view_ComponentLabelView = (ComponentLabelView); ;// CONCATENATED MODULE: ./src/dom_components/view/ComponentMapView.ts var ComponentMapView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ComponentMapView = /** @class */ (function (_super) { ComponentMapView_extends(ComponentMapView, _super); function ComponentMapView() { return _super !== null && _super.apply(this, arguments) || this; } ComponentMapView.prototype.tagName = function () { return 'div'; }; ComponentMapView.prototype.events = function () { return {}; }; ComponentMapView.prototype.initialize = function (props) { _super.prototype.initialize.call(this, props); this.classEmpty = this.ppfx + 'plh-map'; }; /** * Update the map on the canvas * @private */ ComponentMapView.prototype.updateSrc = function () { this.getIframe().src = this.model.get('src'); }; ComponentMapView.prototype.getIframe = function () { if (!this.iframe) { var ifrm = document.createElement('iframe'); ifrm.src = this.model.get('src'); ifrm.frameBorder = '0'; ifrm.style.height = '100%'; ifrm.style.width = '100%'; ifrm.className = this.ppfx + 'no-pointer'; this.iframe = ifrm; } return this.iframe; }; ComponentMapView.prototype.render = function () { _super.prototype.render.call(this); this.updateClasses(); this.el.appendChild(this.getIframe()); return this; }; return ComponentMapView; }(view_ComponentImageView)); /* harmony default export */ const view_ComponentMapView = (ComponentMapView); ;// CONCATENATED MODULE: ./src/dom_components/view/ComponentScriptView.ts var ComponentScriptView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ComponentScriptView = /** @class */ (function (_super) { ComponentScriptView_extends(ComponentScriptView, _super); function ComponentScriptView() { return _super !== null && _super.apply(this, arguments) || this; } ComponentScriptView.prototype.tagName = function () { return 'script'; }; // @ts-ignore ComponentScriptView.prototype.events = function () { return {}; }; ComponentScriptView.prototype.render = function () { var _a = this, model = _a.model, em = _a.em; var src = model.get('src'); var scrCnt = em && em.get('scriptCount'); var scriptCount = scrCnt ? scrCnt : 0; var content = ''; // If it's an external script if (src) { var onload_1 = model.get('onload'); var svar = "script".concat(scriptCount); var svarNext = "script".concat(scriptCount + 1); var svarFn = "".concat(svar, "Start"); var svarNextFn = "".concat(svarNext, "Start"); // Load multiple external scripts in the correct order content = "\n var ".concat(svar, " = document.createElement('script');\n ").concat(svar, ".onload = function() {\n ").concat(onload_1 ? "".concat(onload_1, "();\n") : '', "\n typeof ").concat(svarNextFn, " == 'function' && ").concat(svarNextFn, "();\n };\n ").concat(svar, ".src = '").concat(src, "';\n function ").concat(svarFn, "() { document.body.appendChild(").concat(svar, "); };\n ").concat(!scriptCount ? "".concat(svarFn, "();") : '', "\n "); em && em.set('scriptCount', scriptCount + 1); } else { content = model.__innerHTML(); } this.el.innerHTML = content; this.postRender(); return this; }; return ComponentScriptView; }(view_ComponentImageView)); /* harmony default export */ const view_ComponentScriptView = (ComponentScriptView); ;// CONCATENATED MODULE: ./src/dom_components/view/ComponentSvgView.ts var ComponentSvgView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ComponentSvgView = /** @class */ (function (_super) { ComponentSvgView_extends(ComponentSvgView, _super); function ComponentSvgView() { return _super !== null && _super.apply(this, arguments) || this; } ComponentSvgView.prototype._createElement = function (tagName) { return document.createElementNS('http://www.w3.org/2000/svg', tagName); }; return ComponentSvgView; }(view_ComponentView)); /* harmony default export */ const view_ComponentSvgView = (ComponentSvgView); ;// CONCATENATED MODULE: ./src/dom_components/view/ComponentTableBodyView.ts var ComponentTableBodyView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ComponentTableBodyView = /** @class */ (function (_super) { ComponentTableBodyView_extends(ComponentTableBodyView, _super); function ComponentTableBodyView() { return _super !== null && _super.apply(this, arguments) || this; } return ComponentTableBodyView; }(view_ComponentView)); /* harmony default export */ const view_ComponentTableBodyView = (ComponentTableBodyView); ;// CONCATENATED MODULE: ./src/dom_components/view/ComponentTableCellView.ts var ComponentTableCellView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ComponentTableCellView = /** @class */ (function (_super) { ComponentTableCellView_extends(ComponentTableCellView, _super); function ComponentTableCellView() { return _super !== null && _super.apply(this, arguments) || this; } return ComponentTableCellView; }(view_ComponentView)); /* harmony default export */ const view_ComponentTableCellView = (ComponentTableCellView); ;// CONCATENATED MODULE: ./src/dom_components/view/ComponentTableFootView.ts var ComponentTableFootView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ComponentTableFootView = /** @class */ (function (_super) { ComponentTableFootView_extends(ComponentTableFootView, _super); function ComponentTableFootView() { return _super !== null && _super.apply(this, arguments) || this; } return ComponentTableFootView; }(view_ComponentView)); /* harmony default export */ const view_ComponentTableFootView = (ComponentTableFootView); ;// CONCATENATED MODULE: ./src/dom_components/view/ComponentTableHeadView.ts var ComponentTableHeadView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ComponentTableHeadView = /** @class */ (function (_super) { ComponentTableHeadView_extends(ComponentTableHeadView, _super); function ComponentTableHeadView() { return _super !== null && _super.apply(this, arguments) || this; } return ComponentTableHeadView; }(view_ComponentView)); /* harmony default export */ const view_ComponentTableHeadView = (ComponentTableHeadView); ;// CONCATENATED MODULE: ./src/dom_components/view/ComponentTableRowView.ts var ComponentTableRowView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ComponentTableRowView = /** @class */ (function (_super) { ComponentTableRowView_extends(ComponentTableRowView, _super); function ComponentTableRowView() { return _super !== null && _super.apply(this, arguments) || this; } return ComponentTableRowView; }(view_ComponentView)); /* harmony default export */ const view_ComponentTableRowView = (ComponentTableRowView); ;// CONCATENATED MODULE: ./src/dom_components/view/ComponentTableView.ts /* harmony default export */ const ComponentTableView = (view_ComponentView.extend({ events: {}, })); ;// CONCATENATED MODULE: ./src/dom_components/view/ComponentVideoView.ts var ComponentVideoView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ComponentVideoView = /** @class */ (function (_super) { ComponentVideoView_extends(ComponentVideoView, _super); function ComponentVideoView() { return _super !== null && _super.apply(this, arguments) || this; } ComponentVideoView.prototype.tagName = function () { return 'div'; }; // @ts-ignore ComponentVideoView.prototype.events = function () { return {}; }; ComponentVideoView.prototype.initialize = function () { // @ts-ignore view_ComponentView.prototype.initialize.apply(this, arguments); var model = this.model; var props = ['loop', 'autoplay', 'controls', 'color', 'rel', 'modestbranding', 'poster']; var events = props.map(function (p) { return "change:".concat(p); }).join(' '); this.listenTo(model, 'change:provider', this.updateProvider); this.listenTo(model, 'change:src', this.updateSrc); this.listenTo(model, events, this.updateVideo); }; /** * Rerender on update of the provider * @private */ ComponentVideoView.prototype.updateProvider = function () { var prov = this.model.get('provider'); this.el.innerHTML = ''; this.el.appendChild(this.renderByProvider(prov)); }; /** * Update the source of the video * @private */ ComponentVideoView.prototype.updateSrc = function () { var _a = this, model = _a.model, videoEl = _a.videoEl; if (!videoEl) return; var prov = model.get('provider'); var src = model.get('src'); switch (prov) { case 'yt': src = model.getYoutubeSrc(); break; case 'ytnc': src = model.getYoutubeNoCookieSrc(); break; case 'vi': src = model.getVimeoSrc(); break; } videoEl.src = src; }; /** * Update video parameters * @private */ ComponentVideoView.prototype.updateVideo = function () { var _a = this, model = _a.model, videoEl = _a.videoEl; var prov = model.get('provider'); switch (prov) { case 'yt': case 'ytnc': case 'vi': model.trigger('change:videoId'); break; default: { if (videoEl) { var el = videoEl; el.loop = model.get('loop'); el.autoplay = model.get('autoplay'); el.controls = model.get('controls'); el.poster = model.get('poster'); } } } }; ComponentVideoView.prototype.renderByProvider = function (prov) { var videoEl; switch (prov) { case 'yt': videoEl = this.renderYoutube(); break; case 'ytnc': videoEl = this.renderYoutubeNoCookie(); break; case 'vi': videoEl = this.renderVimeo(); break; default: videoEl = this.renderSource(); } this.videoEl = videoEl; return videoEl; }; ComponentVideoView.prototype.renderSource = function () { var el = document.createElement('video'); el.src = this.model.get('src'); this.initVideoEl(el); return el; }; ComponentVideoView.prototype.renderYoutube = function () { var el = document.createElement('iframe'); el.src = this.model.getYoutubeSrc(); el.frameBorder = '0'; el.setAttribute('allowfullscreen', 'true'); this.initVideoEl(el); return el; }; ComponentVideoView.prototype.renderYoutubeNoCookie = function () { var el = document.createElement('iframe'); el.src = this.model.getYoutubeNoCookieSrc(); el.frameBorder = '0'; el.setAttribute('allowfullscreen', 'true'); this.initVideoEl(el); return el; }; ComponentVideoView.prototype.renderVimeo = function () { var el = document.createElement('iframe'); el.src = this.model.getVimeoSrc(); el.frameBorder = '0'; el.setAttribute('allowfullscreen', 'true'); this.initVideoEl(el); return el; }; ComponentVideoView.prototype.initVideoEl = function (el) { el.className = this.ppfx + 'no-pointer'; el.style.height = '100%'; el.style.width = '100%'; }; ComponentVideoView.prototype.render = function () { view_ComponentView.prototype.render.apply(this); this.updateClasses(); var prov = this.model.get('provider'); this.el.appendChild(this.renderByProvider(prov)); this.updateVideo(); return this; }; return ComponentVideoView; }(view_ComponentImageView)); /* harmony default export */ const view_ComponentVideoView = (ComponentVideoView); ;// CONCATENATED MODULE: ./src/dom_components/view/ComponentWrapperView.ts var ComponentWrapperView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ComponentWrapperView = /** @class */ (function (_super) { ComponentWrapperView_extends(ComponentWrapperView, _super); function ComponentWrapperView() { return _super !== null && _super.apply(this, arguments) || this; } ComponentWrapperView.prototype.tagName = function () { return 'div'; }; return ComponentWrapperView; }(view_ComponentView)); /* harmony default export */ const view_ComponentWrapperView = (ComponentWrapperView); ;// CONCATENATED MODULE: ./src/dom_components/index.ts var dom_components_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var dom_components_assign = ( false) || function () { dom_components_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return dom_components_assign.apply(this, arguments); }; var dom_components_rest = ( false) || 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 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; /** * With this module is possible to manage components inside the canvas. You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/GrapesJS/grapesjs/blob/master/src/dom_components/config/config.ts) * ```js * const editor = grapesjs.init({ * domComponents: { * // options * } * }) * ``` * * Once the editor is instantiated you can use its API and listen to its events. Before using these methods, you should get the module from the instance. * * ```js * // Listen to events * editor.on('component:create', () => { ... }); * * // Use the API * const cmp = editor.Components; * cmp.addType(...); * ``` * * ## Available Events * * `component:create` - Component is created (only the model, is not yet mounted in the canvas), called after the init() method * * `component:mount` - Component is mounted to an element and rendered in canvas * * `component:add` - Triggered when a new component is added to the editor, the model is passed as an argument to the callback * * `component:remove` - Triggered when a component is removed, the model is passed as an argument to the callback * * `component:remove:before` - Triggered before the remove of the component, the model, remove function (if aborted via options, with this function you can complete the remove) and options (use options.abort = true to prevent remove), are passed as arguments to the callback * * `component:clone` - Triggered when a component is cloned, the new model is passed as an argument to the callback * * `component:update` - Triggered when a component is updated (moved, styled, etc.), the model is passed as an argument to the callback * * `component:update:{propertyName}` - Listen any property change, the model is passed as an argument to the callback * * `component:styleUpdate` - Triggered when the style of the component is updated, the model is passed as an argument to the callback * * `component:styleUpdate:{propertyName}` - Listen for a specific style property change, the model is passed as an argument to the callback * * `component:selected` - New component selected, the selected model is passed as an argument to the callback * * `component:deselected` - Component deselected, the deselected model is passed as an argument to the callback * * `component:toggled` - Component selection changed, toggled model is passed as an argument to the callback * * `component:type:add` - New component type added, the new type is passed as an argument to the callback * * `component:type:update` - Component type updated, the updated type is passed as an argument to the callback * * `component:drag:start` - Component drag started. Passed an object, to the callback, containing the `target` (component to drag), `parent` (parent of the component) and `index` (component index in the parent) * * `component:drag` - During component drag. Passed the same object as in `component:drag:start` event, but in this case, `parent` and `index` are updated by the current pointer * * `component:drag:end` - Component drag ended. Passed the same object as in `component:drag:start` event, but in this case, `parent` and `index` are updated by the final pointer * * `component:resize` - During component resize. * * ## Methods * * [getWrapper](#getwrapper) * * [getComponents](#getcomponents) * * [addComponent](#addcomponent) * * [clear](#clear) * * [addType](#addtype) * * [getType](#gettype) * * [getTypes](#gettypes) * * * [Component]: component.html * * @module Components */ /** @private */ var CanMoveReason; (function (CanMoveReason) { /** * Invalid source. This is a default value and should be ignored in case the `result` is true */ CanMoveReason[CanMoveReason["InvalidSource"] = 0] = "InvalidSource"; /** * Source doesn't accept target as destination. */ CanMoveReason[CanMoveReason["SourceReject"] = 1] = "SourceReject"; /** * Target doesn't accept source. */ CanMoveReason[CanMoveReason["TargetReject"] = 2] = "TargetReject"; })(CanMoveReason || (CanMoveReason = {})); var ComponentManager = /** @class */ (function (_super) { dom_components_extends(ComponentManager, _super); /** * Initialize module. Called on a new instance of the editor with configurations passed * inside 'domComponents' field * @param {Object} config Configurations * @private */ function ComponentManager(em) { var _this = _super.call(this, em, 'DomComponents', new model_Components(undefined, { em: em })) || this; _this.componentTypes = [ { id: 'cell', model: model_ComponentTableCell, view: view_ComponentTableCellView, }, { id: 'row', model: model_ComponentTableRow, view: view_ComponentTableRowView, }, { id: 'table', model: model_ComponentTable, view: ComponentTableView, }, { id: 'thead', model: model_ComponentTableHead, view: view_ComponentTableHeadView, }, { id: 'tbody', model: model_ComponentTableBody, view: view_ComponentTableBodyView, }, { id: 'tfoot', model: model_ComponentTableFoot, view: view_ComponentTableFootView, }, { id: 'map', model: model_ComponentMap, view: view_ComponentMapView, }, { id: 'link', model: model_ComponentLink, view: view_ComponentLinkView, }, { id: 'label', model: model_ComponentLabel, view: view_ComponentLabelView, }, { id: 'video', model: model_ComponentVideo, view: view_ComponentVideoView, }, { id: 'image', model: model_ComponentImage, view: view_ComponentImageView, }, { id: 'script', model: model_ComponentScript, view: view_ComponentScriptView, }, { id: 'svg-in', model: model_ComponentSvgIn, view: view_ComponentSvgView, }, { id: 'svg', model: model_ComponentSvg, view: view_ComponentSvgView, }, { id: 'iframe', model: model_ComponentFrame, view: view_ComponentFrameView, }, { id: 'comment', model: model_ComponentComment, view: view_ComponentCommentView, }, { id: 'textnode', model: model_ComponentTextNode, view: view_ComponentTextNodeView, }, { id: 'text', model: model_ComponentText, view: view_ComponentTextView, }, { id: 'wrapper', model: model_ComponentWrapper, view: view_ComponentWrapperView, }, { id: 'default', model: model_Component, view: view_ComponentView, }, ]; _this.componentsById = {}; _this.Component = model_Component; _this.Components = model_Components; _this.ComponentView = view_ComponentView; _this.ComponentsView = view_ComponentsView; /** * Name of the module * @type {String} * @private */ //name = "DomComponents"; _this.storageKey = 'components'; if (em) { //@ts-ignore _this.config.components = em.config.components || _this.config.components; } for (var name in dom_components_config_config) { //@ts-ignore if (!(name in _this.config)) _this.config[name] = dom_components_config_config[name]; } var ppfx = _this.config.pStylePrefix; if (ppfx) _this.config.stylePrefix = ppfx + _this.config.stylePrefix; // Load dependencies if (em) { em.get('Parser').compTypes = _this.componentTypes; em.on('change:componentHovered', _this.componentHovered, _this); var selected_1 = em.get('selected'); em.listenTo(selected_1, 'add', function (sel, c, opts) { return _this.selectAdd(selected_1.getComponent(sel), opts); }); em.listenTo(selected_1, 'remove', function (sel, c, opts) { return _this.selectRemove(selected_1.getComponent(sel), opts); }); } return _this; } ComponentManager.prototype.load = function (data) { var _this = this; return this.loadProjectData(data, { onResult: function (result) { var wrapper = _this.getWrapper(); if (!wrapper) { _this.em.Pages.add({}, { select: true }); wrapper = _this.getWrapper(); } if ((0,index_all.isArray)(result)) { result.length && wrapper.components(result); } else { var _a = result.components, components = _a === void 0 ? [] : _a, rest = dom_components_rest(result, ["components"]); wrapper.set(rest); //@ts-ignore wrapper.components(components); } }, }); }; ComponentManager.prototype.store = function () { return {}; }; /** * Returns the main wrapper. * @return {Object} * @private */ ComponentManager.prototype.getComponent = function () { var sel = this.em.Pages.getSelected(); var frame = sel === null || sel === void 0 ? void 0 : sel.getMainFrame(); return frame === null || frame === void 0 ? void 0 : frame.getComponent(); }; /** * Returns root component inside the canvas. Something like `<body>` inside HTML page * The wrapper doesn't differ from the original Component Model * @return {[Component]} Root Component * @example * // Change background of the wrapper and set some attribute * var wrapper = cmp.getWrapper(); * wrapper.set('style', {'background-color': 'red'}); * wrapper.set('attributes', {'title': 'Hello!'}); */ ComponentManager.prototype.getWrapper = function () { return this.getComponent(); }; /** * Returns wrapper's children collection. Once you have the collection you can * add other Components(Models) inside. Each component can have several nested * components inside and you can nest them as more as you wish. * @return {Components} Collection of components * @example * // Let's add some component * var wrapperChildren = cmp.getComponents(); * var comp1 = wrapperChildren.add({ * style: { 'background-color': 'red'} * }); * var comp2 = wrapperChildren.add({ * tagName: 'span', * attributes: { title: 'Hello!'} * }); * // Now let's add an other one inside first component * // First we have to get the collection inside. Each * // component has 'components' property * var comp1Children = comp1.get('components'); * // Procede as before. You could also add multiple objects * comp1Children.add([ * { style: { 'background-color': 'blue'}}, * { style: { height: '100px', width: '100px'}} * ]); * // Remove comp2 * wrapperChildren.remove(comp2); */ ComponentManager.prototype.getComponents = function () { var wrp = this.getWrapper(); return wrp === null || wrp === void 0 ? void 0 : wrp.components(); }; /** * Add new components to the wrapper's children. It's the same * as 'cmp.getComponents().add(...)' * @param {Object|[Component]|Array<Object>} component Component/s to add * @param {string} [component.tagName='div'] Tag name * @param {string} [component.type=''] Type of the component. Available: ''(default), 'text', 'image' * @param {boolean} [component.removable=true] If component is removable * @param {boolean} [component.draggable=true] If is possible to move the component around the structure * @param {boolean} [component.droppable=true] If is possible to drop inside other components * @param {boolean} [component.badgable=true] If the badge is visible when the component is selected * @param {boolean} [component.stylable=true] If is possible to style component * @param {boolean} [component.copyable=true] If is possible to copy&paste the component * @param {string} [component.content=''] String inside component * @param {Object} [component.style={}] Style object * @param {Object} [component.attributes={}] Attribute object * @param {Object} opt the options object to be used by the [Components.add]{@link getComponents} method * @return {[Component]|Array<[Component]>} Component/s added * @example * // Example of a new component with some extra property * var comp1 = cmp.addComponent({ * tagName: 'div', * removable: true, // Can't remove it * draggable: true, // Can't move it * copyable: true, // Disable copy/past * content: 'Content text', // Text inside component * style: { color: 'red'}, * attributes: { title: 'here' } * }); */ ComponentManager.prototype.addComponent = function (component, opt) { if (opt === void 0) { opt = {}; } return this.getComponents().add(component, opt); }; /** * Render and returns wrapper element with all components inside. * Once the wrapper is rendered, and it's what happens when you init the editor, * the all new components will be added automatically and property changes are all * updated immediately * @return {HTMLElement} * @private */ ComponentManager.prototype.render = function () { var _a; return (_a = this.componentView) === null || _a === void 0 ? void 0 : _a.render().el; }; /** * Remove all components * @return {this} */ ComponentManager.prototype.clear = function (opts) { if (opts === void 0) { opts = {}; } var components = this.getComponents(); //@ts-ignore components === null || components === void 0 ? void 0 : components.filter(Boolean).forEach(function (i) { return i.remove(opts); }); return this; }; /** * Set components * @param {Object|string} components HTML string or components model * @param {Object} opt the options object to be used by the {@link addComponent} method * @return {this} * @private */ ComponentManager.prototype.setComponents = function (components, opt) { if (opt === void 0) { opt = {}; } this.clear(opt).addComponent(components, opt); }; /** * Add new component type. * Read more about this in [Define New Component](https://grapesjs.com/docs/modules/Components.html#define-new-component) * @param {string} type Component ID * @param {Object} methods Component methods * @return {this} */ ComponentManager.prototype.addType = function (type, methods) { var em = this.em; var _a = methods.model, model = _a === void 0 ? {} : _a, _b = methods.view, view = _b === void 0 ? {} : _b, isComponent = methods.isComponent, extend = methods.extend, extendView = methods.extendView, _c = methods.extendFn, extendFn = _c === void 0 ? [] : _c, _d = methods.extendFnView, extendFnView = _d === void 0 ? [] : _d; var compType = this.getType(type); var extendType = this.getType(extend); var extendViewType = this.getType(extendView); var typeToExtend = extendType ? extendType : compType ? compType : this.getType('default'); var modelToExt = typeToExtend.model; var viewToExt = extendViewType ? extendViewType.view : typeToExtend.view; // Function for extending source object methods var getExtendedObj = function (fns, target, srcToExt) { return fns.reduce(function (res, next) { var fn = target[next]; var parentFn = srcToExt.prototype[next]; if (fn && parentFn) { res[next] = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } parentFn.bind(this).apply(void 0, args); fn.bind(this).apply(void 0, args); }; } return res; }, {}); }; // If the model/view is a simple object I need to extend it if (typeof model === 'object') { var modelDefaults_1 = { defaults: model.defaults }; delete model.defaults; methods.model = modelToExt.extend(dom_components_assign(dom_components_assign({}, model), getExtendedObj(extendFn, model, modelToExt)), { isComponent: compType && !extendType && !isComponent ? modelToExt.isComponent : isComponent || (function () { return 0; }), }); // Reassign the defaults getter to the model Object.defineProperty(methods.model.prototype, 'defaults', { get: function () { return (dom_components_assign(dom_components_assign({}, ((0,index_all.result)(modelToExt.prototype, 'defaults') || {})), ((0,index_all.result)(modelDefaults_1, 'defaults') || {}))); }, }); } if (typeof view === 'object') { methods.view = viewToExt.extend(dom_components_assign(dom_components_assign({}, view), getExtendedObj(extendFnView, view, viewToExt))); } if (compType) { compType.model = methods.model; compType.view = methods.view; } else { // @ts-ignore methods.id = type; this.componentTypes.unshift(methods); } var event = "component:type:".concat(compType ? 'update' : 'add'); em === null || em === void 0 ? void 0 : em.trigger(event, compType || methods); return this; }; ComponentManager.prototype.getType = function (type) { var df = this.componentTypes; for (var it = 0; it < df.length; it++) { var dfId = df[it].id; if (dfId == type) { return df[it]; } } return; }; /** * Remove component type * @param {string} type Component ID * @returns {Object|undefined} Removed component type, undefined otherwise */ ComponentManager.prototype.removeType = function (id) { var df = this.componentTypes; var type = this.getType(id); if (!type) return; var index = df.indexOf(type); df.splice(index, 1); return type; }; /** * Return the array of all types * @return {Array} */ ComponentManager.prototype.getTypes = function () { return this.componentTypes; }; ComponentManager.prototype.selectAdd = function (component, opts) { var _this = this; if (opts === void 0) { opts = {}; } if (component) { component.set({ status: 'selected', }); ['component:selected', 'component:toggled'].forEach(function (event) { return _this.em.trigger(event, component, opts); }); } }; ComponentManager.prototype.selectRemove = function (component, opts) { var _this = this; if (opts === void 0) { opts = {}; } if (component) { var em = this.em; component.set({ status: '', state: '', }); ['component:deselected', 'component:toggled'].forEach(function (event) { return _this.em.trigger(event, component, opts); }); } }; /** * Triggered when the component is hovered * @private */ ComponentManager.prototype.componentHovered = function () { var em = this.em; var model = em.get('componentHovered'); var previous = em.previous('componentHovered'); var state = 'hovered'; // Deselect the previous component previous && previous.get('status') == state && previous.set({ status: '', state: '', }); model && (0,index_all.isEmpty)(model.get('status')) && model.set('status', state); }; ComponentManager.prototype.getShallowWrapper = function () { var _a = this, shallow = _a.shallow, em = _a.em; if (!shallow && em) { var shallowEm = em.shallow; if (!shallowEm) return; var domc = shallowEm.Components; domc.componentTypes = this.componentTypes; shallow = domc.getWrapper(); if (shallow) { var events = [keyUpdate, keyUpdateInside].join(' '); shallow.on(events, (0,index_all.debounce)(function () { return shallow === null || shallow === void 0 ? void 0 : shallow.components(''); }, 100)); } this.shallow = shallow; } return shallow; }; /** * Check if the object is a [Component]. * @param {Object} obj * @returns {Boolean} * @example * cmp.isComponent(editor.getSelected()); // true * cmp.isComponent({}); // false */ ComponentManager.prototype.isComponent = function (obj) { return (0,mixins.isComponent)(obj); }; /** * Check if a component can be moved inside another one. * @param {[Component]} target The target component is the one that is supposed to receive the source one. * @param {[Component]|String} source The source can be another component, a component definition or an HTML string. * @param {Number} [index] Index position, if not specified, the check will be performed against appending the source to the target. * @returns {Object} Object containing the `result` (Boolean), `source`, `target` (as Components), and a `reason` (Number) with these meanings: * * `0` - Invalid source. This is a default value and should be ignored in case the `result` is true. * * `1` - Source doesn't accept target as destination. * * `2` - Target doesn't accept source. * @example * const rootComponent = editor.getWrapper(); * const someComponent = editor.getSelected(); * * // Check with two components * editor.Components.canMove(rootComponent, someComponent); * * // Check with component definition * editor.Components.canMove(rootComponent, { tagName: 'a', draggable: false }); * * // Check with HTML string * editor.Components.canMove(rootComponent, '<form>...</form>'); */ ComponentManager.prototype.canMove = function (target, source, index) { var result = { result: false, reason: CanMoveReason.InvalidSource, target: target, source: null, }; if (!source || !target) return result; var srcModel = (0,mixins.isComponent)(source) ? source : null; if (!srcModel) { var wrapper = this.getShallowWrapper(); srcModel = (wrapper === null || wrapper === void 0 ? void 0 : wrapper.append(source)[0]) || null; } result.source = srcModel; if (!srcModel) return result; // Check if the source is draggable in the target var draggable = srcModel.get('draggable'); if ((0,index_all.isFunction)(draggable)) { draggable = !!draggable(srcModel, target, index); } else { var el = target.getEl(); draggable = (0,index_all.isArray)(draggable) ? draggable.join(',') : draggable; draggable = (0,index_all.isString)(draggable) ? el === null || el === void 0 ? void 0 : el.matches(draggable) : draggable; } if (!draggable) return dom_components_assign(dom_components_assign({}, result), { reason: CanMoveReason.SourceReject }); // Check if the target accepts the source var droppable = target.get('droppable'); if ((0,index_all.isFunction)(droppable)) { droppable = !!droppable(srcModel, target, index); } else { if (droppable === false && target.isInstanceOf('text') && srcModel.get('textable')) { droppable = true; } else { var el = srcModel.getEl(); droppable = (0,index_all.isArray)(droppable) ? droppable.join(',') : droppable; droppable = (0,index_all.isString)(droppable) ? el === null || el === void 0 ? void 0 : el.matches(droppable) : droppable; } } // Ensure the target is not inside the source var isTargetInside = [target].concat(target.parents()).indexOf(srcModel) > -1; if (!droppable || isTargetInside) return dom_components_assign(dom_components_assign({}, result), { reason: CanMoveReason.TargetReject }); return dom_components_assign(dom_components_assign({}, result), { result: true }); }; ComponentManager.prototype.allById = function () { return this.componentsById; }; ComponentManager.prototype.getById = function (id) { return this.componentsById[id] || null; }; ComponentManager.prototype.destroy = function () { var _a; var all = this.allById(); Object.keys(all).forEach(function (id) { return all[id] && all[id].remove(); }); (_a = this.componentView) === null || _a === void 0 ? void 0 : _a.remove(); [this.em, this.componentsById, this.componentView].forEach(function (i) { return (i = {}); }); }; return ComponentManager; }(ItemManagerModule)); /* harmony default export */ const dom_components = (ComponentManager); ;// CONCATENATED MODULE: ./src/css_composer/config/config.ts var css_composer_config_config_config = { stylePrefix: 'css-', rules: [], }; /* harmony default export */ const css_composer_config_config = (css_composer_config_config_config); ;// CONCATENATED MODULE: ./src/code_manager/model/CssGenerator.ts var CssGenerator_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var maxValue = Number.MAX_VALUE; var getMediaLength = function (mediaQuery) { var length = /(-?\d*\.?\d+)\w{0,}/.exec(mediaQuery); return !length ? '' : length[0]; }; var CssGenerator = /** @class */ (function (_super) { CssGenerator_extends(CssGenerator, _super); function CssGenerator() { var _this = _super.call(this) || this; (0,index_all.bindAll)(_this, 'sortRules'); _this.compCls = []; _this.ids = []; return _this; } /** * Get CSS from a component * @param {Model} model * @return {String} */ CssGenerator.prototype.buildFromModel = function (model, opts) { var _this = this; if (opts === void 0) { opts = {}; } var code = ''; var em = this.em; var avoidInline = em && em.getConfig().avoidInlineStyle; var style = model.styleToString(); var classes = model.classes; this.ids.push("#".concat(model.getId())); // Let's know what classes I've found classes.forEach(function (model) { return _this.compCls.push(model.getFullName()); }); if (!avoidInline && style) { code = "#".concat(model.getId(), "{").concat(style, "}"); } var components = model.components(); components.forEach(function (model) { return (code += _this.buildFromModel(model, opts)); }); return code; }; CssGenerator.prototype.build = function (model, opts) { var _this = this; if (opts === void 0) { opts = {}; } var json = opts.json; var em = opts.em; var cssc = opts.cssc || (em === null || em === void 0 ? void 0 : em.Css); this.em = em; this.compCls = []; this.ids = []; this.model = model; var codeJson = []; var code = model ? this.buildFromModel(model, opts) : ''; var clearStyles = (0,index_all.isUndefined)(opts.clearStyles) && em ? em.getConfig().clearStyles : opts.clearStyles; if (cssc) { var rules = opts.rules || cssc.getAll(); var atRules_1 = {}; var dump_1 = []; if (opts.onlyMatched && model && (0,mixins.hasWin)()) { rules = this.matchedRules(model, rules); } rules.forEach(function (rule) { var atRule = rule.getAtRule(); if (atRule) { var mRules = atRules_1[atRule]; if (mRules) { mRules.push(rule); } else { atRules_1[atRule] = [rule]; } return; } var res = _this.buildFromRule(rule, dump_1, opts); if (json) { codeJson.push(res); } else { code += res; } }); this.sortMediaObject(atRules_1).forEach(function (item) { var rulesStr = ''; var atRule = item.key; var mRules = item.value; mRules.forEach(function (rule) { var ruleStr = _this.buildFromRule(rule, dump_1, opts); if (rule.get('singleAtRule')) { code += "".concat(atRule, "{").concat(ruleStr, "}"); } else { rulesStr += ruleStr; } json && codeJson.push(ruleStr); }); if (rulesStr) { code += "".concat(atRule, "{").concat(rulesStr, "}"); } }); // @ts-ignore em && clearStyles && rules.remove && rules.remove(dump_1); } return json ? codeJson.filter(function (r) { return r; }) : code; }; /** * Get CSS from the rule model * @param {Model} rule * @return {string} CSS string */ CssGenerator.prototype.buildFromRule = function (rule, dump, opts) { var _this = this; var _a; if (opts === void 0) { opts = {}; } var result = ''; var model = this.model; var selectorStrNoAdd = rule.selectorsToString({ skipAdd: 1 }); var selectorsAdd = rule.get('selectorsAdd'); var singleAtRule = rule.get('singleAtRule'); var found; // This will not render a rule if there is no its component (_a = rule.get('selectors')) === null || _a === void 0 ? void 0 : _a.forEach(function (selector) { var name = selector.getFullName(); if (_this.compCls.indexOf(name) >= 0 || _this.ids.indexOf(name) >= 0 || opts.keepUnusedStyles) { found = 1; } }); if ((selectorStrNoAdd && found) || selectorsAdd || singleAtRule || !model) { var block = rule.getDeclaration({ body: 1 }); block && (opts.json ? (result = rule) : (result += block)); } else { dump.push(rule); } return result; }; /** * Get matched rules of a component * @param {Component} component * @param {Array<CSSRule>} rules * @returns {Array<CSSRule>} */ CssGenerator.prototype.matchedRules = function (component, rules) { var _this = this; var el = component.getEl(); var result = []; rules.forEach(function (rule) { try { if (rule .selectorsToString() .split(',') .some(function (selector) { return el === null || el === void 0 ? void 0 : el.matches(_this.__cleanSelector(selector)); })) { result.push(rule); } } catch (err) { } }); component.components().forEach(function (component) { result = result.concat(_this.matchedRules(component, rules)); }); // Remove duplicates result = result.filter(function (rule, i) { return result.indexOf(rule) === i; }); return result; }; /** * Get the numeric length of the media query string * @param {String} mediaQuery Media query string * @return {Number} */ CssGenerator.prototype.getQueryLength = function (mediaQuery) { var length = /(-?\d*\.?\d+)\w{0,}/.exec(mediaQuery); if (!length) return maxValue; return parseFloat(length[1]); }; /** * Return a sorted array from media query object * @param {Object} items * @return {Array} */ CssGenerator.prototype.sortMediaObject = function (items) { var _this = this; if (items === void 0) { items = {}; } var itemsArr = []; (0,index_all.each)(items, function (value, key) { return itemsArr.push({ key: key, value: value }); }); return itemsArr.sort(function (a, b) { var isMobFirst = [a.key, b.key].every(function (mquery) { return mquery.indexOf('min-width') !== -1; }); var left = isMobFirst ? a.key : b.key; var right = isMobFirst ? b.key : a.key; return _this.getQueryLength(left) - _this.getQueryLength(right); }); }; CssGenerator.prototype.sortRules = function (a, b) { var getKey = function (rule) { return rule.get('mediaText') || ''; }; var isMobFirst = [getKey(a), getKey(b)].every(function (q) { return q.indexOf('min-width') !== -1; }); var left = isMobFirst ? getKey(a) : getKey(b); var right = isMobFirst ? getKey(b) : getKey(a); return this.getQueryLength(left) - this.getQueryLength(right); }; /** * Return passed selector without states * @param {String} selector * @returns {String} * @private */ CssGenerator.prototype.__cleanSelector = function (selector) { return selector .split(' ') .map(function (item) { return item.split(':')[0]; }) .join(' '); }; return CssGenerator; }(common/* Model */.Hn)); /* harmony default export */ const model_CssGenerator = (CssGenerator); ;// CONCATENATED MODULE: ./src/css_composer/model/CssRule.ts var CssRule_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var CssRule_assign = ( false) || function () { CssRule_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return CssRule_assign.apply(this, arguments); }; var CssRule_spreadArray = ( false) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; // @ts-ignore var CSS = ((0,mixins.hasWin)() ? window : {}).CSS; /** * @typedef CssRule * @property {Array<Selector>} selectors Array of selectors * @property {Object} style Object containing style definitions * @property {String} [selectorsAdd=''] Additional string css selectors * @property {String} [atRuleType=''] Type of at-rule, eg. `media`, 'font-face' * @property {String} [mediaText=''] At-rule value, eg. `(max-width: 1000px)` * @property {Boolean} [singleAtRule=false] This property is used only on at-rules, like 'page' or 'font-face', where the block containes only style declarations * @property {String} [state=''] State of the rule, eg: `hover`, `focused` * @property {Boolean|Array<String>} [important=false] If true, sets `!important` on all properties. You can also pass an array to specify properties on which use important * @property {Boolean} [stylable=true] Indicates if the rule is stylable from the editor * * [Device]: device.html * [State]: state.html * [Component]: component.html */ var CssRule = /** @class */ (function (_super) { CssRule_extends(CssRule, _super); function CssRule(props, opt) { if (opt === void 0) { opt = {}; } var _this = _super.call(this, props) || this; _this.config = props || {}; _this.opt = opt; _this.em = opt.em; _this.ensureSelectors(null, null, {}); _this.on('change', _this.__onChange); return _this; } CssRule.prototype.defaults = function () { return { selectors: [], selectorsAdd: '', style: {}, mediaText: '', state: '', stylable: true, atRuleType: '', singleAtRule: false, important: false, group: '', shallow: false, _undo: true, }; }; CssRule.prototype.__onChange = function (m, opts) { var em = this.em; var changed = this.changedAttributes(); changed && !(0,mixins.isEmptyObj)(changed) && (em === null || em === void 0 ? void 0 : em.changesUp(opts)); }; CssRule.prototype.clone = function () { var opts = CssRule_assign({}, this.opt); var attr = CssRule_assign({}, this.attributes); attr.selectors = this.get('selectors').map(function (s) { return s.clone(); }); // @ts-ignore return new this.constructor(attr, opts); }; CssRule.prototype.ensureSelectors = function (m, c, opts) { var em = this.em; var sm = em === null || em === void 0 ? void 0 : em.get('SelectorManager'); var toListen = [this, 'change:selectors', this.ensureSelectors]; var sels = this.getSelectors(); this.stopListening.apply(this, toListen); if (sels.models) { sels = CssRule_spreadArray([], sels.models, true); } sels = (0,index_all.isString)(sels) ? [sels] : sels; if (Array.isArray(sels)) { var res = sels.filter(function (i) { return i; }).map(function (i) { return (sm ? sm.add(i) : i); }); sels = new model_Selectors(res); } this.set('selectors', sels, opts); // @ts-ignore this.listenTo.apply(this, toListen); }; /** * Returns the at-rule statement when exists, eg. `@media (...)`, `@keyframes` * @returns {String} * @example * const cssRule = editor.Css.setRule('.class1', { color: 'red' }, { * atRuleType: 'media', * atRuleParams: '(min-width: 500px)' * }); * cssRule.getAtRule(); // "@media (min-width: 500px)" */ CssRule.prototype.getAtRule = function () { var type = this.get('atRuleType'); var condition = this.get('mediaText'); // Avoid breaks with the last condition var typeStr = type ? "@".concat(type) : condition ? '@media' : ''; return typeStr + (condition && typeStr ? " ".concat(condition) : ''); }; /** * Return selectors of the rule as a string * @param {Object} [opts] Options * @param {Boolean} [opts.skipState] Skip state from the result * @returns {String} * @example * const cssRule = editor.Css.setRule('.class1:hover', { color: 'red' }); * cssRule.selectorsToString(); // ".class1:hover" * cssRule.selectorsToString({ skipState: true }); // ".class1" */ CssRule.prototype.selectorsToString = function (opts) { if (opts === void 0) { opts = {}; } var result = []; var state = this.get('state'); var addSelector = this.get('selectorsAdd'); var selOpts = { escape: function (str) { return (CSS && CSS.escape ? CSS.escape(str) : str); }, }; // @ts-ignore var selectors = this.get('selectors').getFullString(0, selOpts); var stateStr = state && !opts.skipState ? ":".concat(state) : ''; selectors && result.push("".concat(selectors).concat(stateStr)); addSelector && !opts.skipAdd && result.push(addSelector); return result.join(', '); }; /** * Get declaration block (without the at-rule statement) * @param {Object} [opts={}] Options (same as in `selectorsToString`) * @returns {String} * @example * const cssRule = editor.Css.setRule('.class1', { color: 'red' }, { * atRuleType: 'media', * atRuleParams: '(min-width: 500px)' * }); * cssRule.getDeclaration() // ".class1{color:red;}" */ CssRule.prototype.getDeclaration = function (opts) { if (opts === void 0) { opts = {}; } var result = ''; var important = this.attributes.important; var selectors = this.selectorsToString(opts); var style = this.styleToString(CssRule_assign({ important: important }, opts)); var singleAtRule = this.get('singleAtRule'); if ((selectors || singleAtRule) && (style || opts.allowEmpty)) { result = singleAtRule ? style : "".concat(selectors, "{").concat(style, "}"); } return result; }; /** * Get the Device the rule is related to. * @returns {[Device]|null} * @example * const device = rule.getDevice(); * console.log(device?.getName()); */ CssRule.prototype.getDevice = function () { var em = this.em; var _a = this.attributes, atRuleType = _a.atRuleType, mediaText = _a.mediaText; var devices = (em === null || em === void 0 ? void 0 : em.get('DeviceManager').getDevices()) || []; var deviceDefault = devices.filter(function (d) { return d.getWidthMedia() === ''; })[0]; if (atRuleType !== 'media' || !mediaText) { return deviceDefault || null; } return devices.filter(function (d) { return d.getWidthMedia() === getMediaLength(mediaText); })[0] || null; }; /** * Get the State the rule is related to. * @returns {[State]|null} * @example * const state = rule.getState(); * console.log(state?.getLabel()); */ CssRule.prototype.getState = function () { var em = this.em; var stateValue = this.get('state'); var states = (em === null || em === void 0 ? void 0 : em.get('SelectorManager').getStates()) || []; return states.filter(function (s) { return s.getName() === stateValue; })[0] || null; }; /** * Returns the related Component (valid only for component-specific rules). * @returns {[Component]|null} * @example * const cmp = rule.getComponent(); * console.log(cmp?.toHTML()); */ CssRule.prototype.getComponent = function () { var _a; var sel = this.getSelectors(); var sngl = sel.length == 1 && sel.at(0); var cmpId = sngl && sngl.isId() && sngl.get('name'); return (cmpId && ((_a = this.em) === null || _a === void 0 ? void 0 : _a.Components.getById(cmpId))) || null; }; /** * Return the CSS string of the rule * @param {Object} [opts={}] Options (same as in `getDeclaration`) * @return {String} CSS string * @example * const cssRule = editor.Css.setRule('.class1', { color: 'red' }, { * atRuleType: 'media', * atRuleParams: '(min-width: 500px)' * }); * cssRule.toCSS() // "@media (min-width: 500px){.class1{color:red;}}" */ CssRule.prototype.toCSS = function (opts) { if (opts === void 0) { opts = {}; } var result = ''; var atRule = this.getAtRule(); var block = this.getDeclaration(opts); if (block || opts.allowEmpty) { result = block; } if (atRule && result) { result = "".concat(atRule, "{").concat(result, "}"); } return result; }; CssRule.prototype.toJSON = function () { var _a; var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var obj = common/* Model */.Hn.prototype.toJSON.apply(this, args); if ((_a = this.em) === null || _a === void 0 ? void 0 : _a.getConfig().avoidDefaults) { var defaults = this.defaults(); (0,index_all.forEach)(defaults, function (value, key) { if (obj[key] === value) { delete obj[key]; } }); // Delete the property used for partial updates delete obj.style.__p; if ((0,index_all.isEmpty)(obj.selectors)) delete obj.selectors; if ((0,index_all.isEmpty)(obj.style)) delete obj.style; } return obj; }; /** * Compare the actual model with parameters * @param {Object} selectors Collection of selectors * @param {String} state Css rule state * @param {String} width For which device this style is oriented * @param {Object} ruleProps Other rule props * @returns {Boolean} * @private */ CssRule.prototype.compare = function (selectors, state, width, ruleProps) { var _a; if (ruleProps === void 0) { ruleProps = {}; } var st = state || ''; var wd = width || ''; var selAdd = ruleProps.selectorsAdd || ''; var atRule = ruleProps.atRuleType || ''; var sel = !(0,index_all.isArray)(selectors) && !selectors.models ? [selectors] : selectors.models || selectors; // Fix atRuleType in case is not specified with width if (wd && !atRule) atRule = 'media'; var a1 = sel.map(function (model) { return model.getFullName(); }); var a2 = (_a = this.get('selectors')) === null || _a === void 0 ? void 0 : _a.map(function (model) { return model.getFullName(); }); // Check selectors var a1S = a1.slice().sort(); var a2S = a2.slice().sort(); if (a1.length !== a2.length || !a1S.every(function (v, i) { return v === a2S[i]; })) { return false; } // Check other properties if (this.get('state') !== st || this.get('mediaText') !== wd || this.get('selectorsAdd') !== selAdd || this.get('atRuleType') !== atRule) { return false; } return true; }; return CssRule; }(model_StyleableModel)); /* harmony default export */ const model_CssRule = (CssRule); ;// CONCATENATED MODULE: ./src/css_composer/model/CssRules.ts var CssRules_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var CssRules = /** @class */ (function (_super) { CssRules_extends(CssRules, _super); function CssRules(props, opt) { var _this = _super.call(this, props) || this; // Inject editor _this.editor = opt === null || opt === void 0 ? void 0 : opt.em; // This will put the listener post CssComposer.postLoad setTimeout(function () { _this.on('remove', _this.onRemove); _this.on('add', _this.onAdd); }); return _this; } CssRules.prototype.toJSON = function (opts) { var result = common/* Collection */.FE.prototype.toJSON.call(this, opts); return result.filter(function (rule) { return rule.style && !rule.shallow; }); }; CssRules.prototype.onAdd = function (model, c, o) { model.ensureSelectors(model, c, o); // required for undo }; CssRules.prototype.onRemove = function (removed) { var em = this.editor; em.stopListening(removed); em.UndoManager.remove(removed); }; /** @ts-ignore */ CssRules.prototype.add = function (models, opt) { if (opt === void 0) { opt = {}; } if (typeof models === 'string') { models = this.editor.get('Parser').parseCss(models); } opt.em = this.editor; return common/* Collection */.FE.prototype.add.apply(this, [models, opt]); }; return CssRules; }(common/* Collection */.FE)); /* harmony default export */ const model_CssRules = (CssRules); CssRules.prototype.model = model_CssRule; ;// CONCATENATED MODULE: ./src/css_composer/index.ts /** * This module manages CSS rules in the canvas. * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/GrapesJS/grapesjs/blob/master/src/css_composer/config/config.ts) * ```js * const editor = grapesjs.init({ * cssComposer: { * // options * } * }) * ``` * * Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance * * ```js * const css = editor.Css; * ``` * * * [addRules](#addrules) * * [setRule](#setrule) * * [getRule](#getrule) * * [getRules](#getrules) * * [remove](#remove) * * [clear](#clear) * * [CssRule]: css_rule.html * * @module Css */ var css_composer_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var css_composer_assign = ( false) || function () { css_composer_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return css_composer_assign.apply(this, arguments); }; var css_composer_spreadArray = ( false) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var CssComposer = /** @class */ (function (_super) { css_composer_extends(CssComposer, _super); /** * Initializes module. Automatically called with a new instance of the editor * @param {Object} config Configurations * @private */ function CssComposer(em) { var _this = _super.call(this, em, 'CssComposer', null, {}, css_composer_config_config) || this; _this.Selectors = model_Selectors; _this.storageKey = 'styles'; var config = _this.config; var ppfx = config.pStylePrefix; if (ppfx) config.stylePrefix = ppfx + config.stylePrefix; // @ts-ignore config.rules = _this.em.config.style || config.rules || ''; _this.rules = new model_CssRules([], config); return _this; } /** * On load callback * @private */ CssComposer.prototype.onLoad = function () { this.rules.add(this.config.rules, { silent: true }); }; /** * Do stuff after load * @param {Editor} em * @private */ CssComposer.prototype.postLoad = function () { var _a; var um = (_a = this.em) === null || _a === void 0 ? void 0 : _a.get('UndoManager'); um && um.add(this.getAll()); }; CssComposer.prototype.store = function () { return this.getProjectData(); }; CssComposer.prototype.load = function (data) { return this.loadProjectData(data, { // @ts-ignore Fix add() first in CssRules all: this.rules, }); }; /** * Add new rule to the collection, if not yet exists with the same selectors * @param {Array<Selector>} selectors Array of selectors * @param {String} state Css rule state * @param {String} width For which device this style is oriented * @param {Object} props Other props for the rule * @param {Object} opts Options for the add of new rule * @return {Model} * @private * @example * var sm = editor.SelectorManager; * var sel1 = sm.add('myClass1'); * var sel2 = sm.add('myClass2'); * var rule = cssComposer.add([sel1, sel2], 'hover'); * rule.set('style', { * width: '100px', * color: '#fff', * }); * */ CssComposer.prototype.add = function (selectors, state, width, opts, addOpts) { if (opts === void 0) { opts = {}; } if (addOpts === void 0) { addOpts = {}; } var s = state || ''; var w = width || ''; var opt = css_composer_assign({}, opts); var rule = this.get(selectors, s, w, opt); // do not create rules that were found before // unless this is a single at-rule, for which multiple declarations // make sense (e.g. multiple `@font-type`s) if (rule && rule.config && !rule.config.singleAtRule) { return rule; } else { opt.state = s; opt.mediaText = w; opt.selectors = []; // #4727: Prevent updating atRuleType if already defined if (w && !opt.atRuleType) { opt.atRuleType = 'media'; } rule = new model_CssRule(opt, this.config); // @ts-ignore rule.get('selectors').add(selectors, addOpts); this.rules.add(rule, addOpts); return rule; } }; /** * Get the rule * @param {String|Array<Selector>} selectors Array of selectors or selector string, eg `.myClass1.myClass2` * @param {String} state Css rule state, eg. 'hover' * @param {String} width Media rule value, eg. '(max-width: 992px)' * @param {Object} ruleProps Other rule props * @return {Model|null} * @private * @example * const sm = editor.SelectorManager; * const sel1 = sm.add('myClass1'); * const sel2 = sm.add('myClass2'); * const rule = cssComposer.get([sel1, sel2], 'hover', '(max-width: 992px)'); * // Update the style * rule.set('style', { * width: '300px', * color: '#000', * }); * */ CssComposer.prototype.get = function (selectors, state, width, ruleProps) { var slc = selectors; if ((0,index_all.isString)(selectors)) { var sm = this.em.Selectors; var singleSel = selectors.split(',')[0].trim(); var node = this.em.Parser.parserCss.checkNode({ selectors: singleSel })[0]; slc = sm.get(node.selectors); } return this.rules.find(function (rule) { return rule.compare(slc, state, width, ruleProps); }) || null; }; CssComposer.prototype.getAll = function () { return this.rules; }; /** * Add a raw collection of rule objects * This method overrides styles, in case, of already defined rule * @param {String|Array<Object>} data CSS string or an array of rule objects, eg. [{selectors: ['class1'], style: {....}}, ..] * @param {Object} opts Options * @param {Object} props Additional properties to add on rules * @return {Array<Model>} * @private */ CssComposer.prototype.addCollection = function (data, opts, props) { if (opts === void 0) { opts = {}; } if (props === void 0) { props = {}; } var em = this.em; var result = []; if ((0,index_all.isString)(data)) { data = em.Parser.parseCss(data); } var d = data instanceof Array ? data : [data]; for (var i = 0, l = d.length; i < l; i++) { var rule = (d[i] || {}); if (!rule.selectors) continue; var sm = em === null || em === void 0 ? void 0 : em.Selectors; if (!sm) console.warn('Selector Manager not found'); var sl = rule.selectors; var sels = sl instanceof Array ? sl : [sl]; var newSels = []; for (var j = 0, le = sels.length; j < le; j++) { // @ts-ignore var selec = sm.add(sels[j]); newSels.push(selec); } var modelExists = this.get(newSels, rule.state, rule.mediaText, rule); var model = this.add(newSels, rule.state, rule.mediaText, rule, opts); var updateStyle = !modelExists || !opts.avoidUpdateStyle; var style = rule.style || {}; (0,mixins.isObject)(props) && model.set(props, opts); if (updateStyle) { var styleUpdate = opts.extend ? css_composer_assign(css_composer_assign({}, model.get('style')), style) : style; model.set('style', styleUpdate, opts); } result.push(model); } return result; }; /** * Add CssRules via CSS string. * @param {String} css CSS string of rules to add. * @returns {Array<[CssRule]>} Array of rules * @example * const addedRules = css.addRules('.my-cls{ color: red } @media (max-width: 992px) { .my-cls{ color: darkred } }'); * // Check rules * console.log(addedRules.map(rule => rule.toCSS())); */ CssComposer.prototype.addRules = function (css) { return this.addCollection(css); }; /** * Add/update the CssRule. * @param {String} selectors Selector string, eg. `.myclass` * @param {Object} style Style properties and values. If the rule exists, styles will be replaced unless `addStyles` option is used. * @param {Object} [opts={}] Additional properties. * @param {String} [opts.atRuleType=''] At-rule type, eg. `media`. * @param {String} [opts.atRuleParams=''] At-rule parameters, eg. `(min-width: 500px)`. * @param {Boolean} [opts.addStyles=false] If the rule exists already, merge passed styles instead of replacing them. * @returns {[CssRule]} The new/updated CssRule. * @example * // Simple class-based rule * const rule = css.setRule('.class1.class2', { color: 'red' }); * console.log(rule.toCSS()) // output: .class1.class2 { color: red } * // With state and other mixed selector * const rule = css.setRule('.class1.class2:hover, div#myid', { color: 'red' }); * // output: .class1.class2:hover, div#myid { color: red } * // With media * const rule = css.setRule('.class1:hover', { color: 'red' }, { * atRuleType: 'media', * atRuleParams: '(min-width: 500px)', * }); * // output: `@media (min-width: 500px) { .class1:hover { color: red } }` * * // Update styles of existent rule * css.setRule('.class1', { color: 'red', background: 'red' }); * css.setRule('.class1', { color: 'blue' }, { addStyles: true }); * // output: .class1 { color: blue; background: red } */ CssComposer.prototype.setRule = function (selectors, style, opts) { if (style === void 0) { style = {}; } if (opts === void 0) { opts = {}; } var atRuleType = opts.atRuleType, atRuleParams = opts.atRuleParams; var node = this.em.Parser.parserCss.checkNode({ selectors: selectors, style: style, })[0]; var state = node.state, selectorsAdd = node.selectorsAdd; var sm = this.em.Selectors; var selector = sm.add(node.selectors); var rule = this.add(selector, state, atRuleParams, { selectorsAdd: selectorsAdd, atRule: atRuleType, }); if (opts.addStyles) { rule.addStyle(style, opts); } else { rule.setStyle(style, opts); } return rule; }; /** * Get the CssRule. * @param {String} selectors Selector string, eg. `.myclass:hover` * @param {Object} [opts={}] Additional properties * @param {String} [opts.atRuleType=''] At-rule type, eg. `media` * @param {String} [opts.atRuleParams=''] At-rule parameters, eg. '(min-width: 500px)' * @returns {[CssRule]} * @example * const rule = css.getRule('.myclass1:hover'); * const rule2 = css.getRule('.myclass1:hover, div#myid'); * const rule3 = css.getRule('.myclass1', { * atRuleType: 'media', * atRuleParams: '(min-width: 500px)', * }); */ CssComposer.prototype.getRule = function (selectors, opts) { if (opts === void 0) { opts = {}; } var em = this.em; var sm = em.Selectors; var node = em.Parser.parserCss.checkNode({ selectors: selectors })[0]; // @ts-ignore var selector = sm.get(node.selectors); var state = node.state, selectorsAdd = node.selectorsAdd; var atRuleType = opts.atRuleType, atRuleParams = opts.atRuleParams; return selector ? this.get(selector, state, atRuleParams, { selectorsAdd: selectorsAdd, atRuleType: atRuleType, }) : undefined; }; /** * Get all rules or filtered by a matching selector. * @param {String} [selector=''] Selector, eg. `.myclass` * @returns {Array<[CssRule]>} * @example * // Take all the component specific rules * const id = someComponent.getId(); * const rules = css.getRules(`#${id}`); * console.log(rules.map(rule => rule.toCSS())) * // All rules in the project * console.log(css.getRules()) */ CssComposer.prototype.getRules = function (selector) { var rules = this.getAll(); if (!selector) return css_composer_spreadArray([], rules.models, true); var optRuleSel = { sort: true }; var sels = (0,index_all.isString)(selector) ? selector.split(',').map(function (s) { return s.trim(); }) : selector; var result = rules.filter(function (r) { return sels.indexOf(r.getSelectors().getFullString(null, optRuleSel)) >= 0; }); return result; }; /** * Add/update the CSS rule with id selector * @param {string} name Id selector name, eg. 'my-id' * @param {Object} style Style properties and values * @param {Object} [opts={}] Custom options, like `state` and `mediaText` * @return {CssRule} The new/updated rule * @private * @example * const rule = css.setIdRule('myid', { color: 'red' }); * const ruleHover = css.setIdRule('myid', { color: 'blue' }, { state: 'hover' }); * // This will add current CSS: * // #myid { color: red } * // #myid:hover { color: blue } */ CssComposer.prototype.setIdRule = function (name, style, opts) { if (style === void 0) { style = {}; } if (opts === void 0) { opts = {}; } var _a = opts.addOpts, addOpts = _a === void 0 ? {} : _a, mediaText = opts.mediaText; var state = opts.state || ''; var media = !(0,index_all.isUndefined)(mediaText) ? mediaText : this.em.getCurrentMedia(); var sm = this.em.Selectors; var selector = sm.add({ name: name, type: model_Selector.TYPE_ID }, addOpts); var rule = this.add(selector, state, media, {}, addOpts); rule.setStyle(style, css_composer_assign(css_composer_assign({}, opts), addOpts)); return rule; }; /** * Get the CSS rule by id selector * @param {string} name Id selector name, eg. 'my-id' * @param {Object} [opts={}] Custom options, like `state` and `mediaText` * @return {CssRule} * @private * @example * const rule = css.getIdRule('myid'); * const ruleHover = css.setIdRule('myid', { state: 'hover' }); */ CssComposer.prototype.getIdRule = function (name, opts) { if (opts === void 0) { opts = {}; } var mediaText = opts.mediaText; var state = opts.state || ''; var media = !(0,index_all.isUndefined)(mediaText) ? mediaText : this.em.getCurrentMedia(); var selector = this.em.Selectors.get(name, model_Selector.TYPE_ID); return selector && this.get(selector, state, media); }; /** * Add/update the CSS rule with class selector * @param {string} name Class selector name, eg. 'my-class' * @param {Object} style Style properties and values * @param {Object} [opts={}] Custom options, like `state` and `mediaText` * @return {CssRule} The new/updated rule * @private * @example * const rule = css.setClassRule('myclass', { color: 'red' }); * const ruleHover = css.setClassRule('myclass', { color: 'blue' }, { state: 'hover' }); * // This will add current CSS: * // .myclass { color: red } * // .myclass:hover { color: blue } */ CssComposer.prototype.setClassRule = function (name, style, opts) { if (style === void 0) { style = {}; } if (opts === void 0) { opts = {}; } var state = opts.state || ''; var media = opts.mediaText || this.em.getCurrentMedia(); var sm = this.em.Selectors; var selector = sm.add({ name: name, type: model_Selector.TYPE_CLASS }); var rule = this.add(selector, state, media); rule.setStyle(style, opts); return rule; }; /** * Get the CSS rule by class selector * @param {string} name Class selector name, eg. 'my-class' * @param {Object} [opts={}] Custom options, like `state` and `mediaText` * @return {CssRule} * @private * @example * const rule = css.getClassRule('myclass'); * const ruleHover = css.getClassRule('myclass', { state: 'hover' }); */ CssComposer.prototype.getClassRule = function (name, opts) { if (opts === void 0) { opts = {}; } var state = opts.state || ''; var media = opts.mediaText || this.em.getCurrentMedia(); var selector = this.em.Selectors.get(name, model_Selector.TYPE_CLASS); return selector && this.get(selector, state, media); }; /** * Remove rule, by CssRule or matching selector (eg. the selector will match also at-rules like `@media`) * @param {String|[CssRule]|Array<[CssRule]>} rule CssRule or matching selector. * @return {Array<[CssRule]>} Removed rules * @example * // Remove by CssRule * const toRemove = css.getRules('.my-cls'); * css.remove(toRemove); * // Remove by selector * css.remove('.my-cls-2'); */ CssComposer.prototype.remove = function (rule, opts) { var toRemove = (0,index_all.isString)(rule) ? this.getRules(rule) : rule; var result = this.getAll().remove(toRemove, opts); return (0,index_all.isArray)(result) ? result : [result]; }; /** * Remove all rules * @return {this} */ CssComposer.prototype.clear = function (opts) { if (opts === void 0) { opts = {}; } this.getAll().reset([], opts); return this; }; CssComposer.prototype.getComponentRules = function (cmp, opts) { if (opts === void 0) { opts = {}; } var state = opts.state, mediaText = opts.mediaText, current = opts.current; if (current) { state = this.em.get('state') || ''; mediaText = this.em.getCurrentMedia(); } var id = cmp.getId(); var rules = this.getAll().filter(function (r) { if (!(0,index_all.isUndefined)(state) && r.get('state') !== state) return false; if (!(0,index_all.isUndefined)(mediaText) && r.get('mediaText') !== mediaText) return false; return r.getSelectorsString() === "#".concat(id); }); return rules; }; /** * Render the block of CSS rules * @return {HTMLElement} * @private */ CssComposer.prototype.render = function () { var _a; (_a = this.rulesView) === null || _a === void 0 ? void 0 : _a.remove(); this.rulesView = new view_CssRulesView({ collection: this.rules, config: this.config, }); return this.rulesView.render().el; }; CssComposer.prototype.destroy = function () { var _a; this.rules.reset(); this.rules.stopListening(); (_a = this.rulesView) === null || _a === void 0 ? void 0 : _a.remove(); }; return CssComposer; }(ItemManagerModule)); /* harmony default export */ const css_composer = (CssComposer); ;// CONCATENATED MODULE: ./src/block_manager/config/config.ts var block_manager_config_config_config = { appendTo: '', blocks: [], appendOnClick: false, custom: false, }; /* harmony default export */ const block_manager_config_config = (block_manager_config_config_config); ;// CONCATENATED MODULE: ./src/block_manager/model/Block.ts var Block_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); /** * @property {String} label Block label, eg. `My block` * @property {String|Object} content The content of the block. Might be an HTML string or a [Component Defintion](/modules/Components.html#component-definition) * @property {String} [media=''] HTML string for the media/icon of the block, eg. `<svg ...`, `<img ...`, etc. * @property {String} [category=''] Block category, eg. `Basic blocks` * @property {Boolean} [activate=false] If true, triggers the `active` event on the dropped component. * @property {Boolean} [select=false] If true, the dropped component will be selected. * @property {Boolean} [resetId=false] If true, all IDs of dropped components and their styles will be changed. * @property {Boolean} [disable=false] Disable the block from being interacted * @property {Function} [onClick] Custom behavior on click, eg. `(block, editor) => editor.getWrapper().append(block.get('content'))` * @property {Object} [attributes={}] Block attributes to apply in the view element * * @module docsjs.Block */ var Block = /** @class */ (function (_super) { Block_extends(Block, _super); function Block() { return _super !== null && _super.apply(this, arguments) || this; } Block.prototype.defaults = function () { return { label: '', content: '', media: '', category: '', activate: false, select: undefined, resetId: false, disable: false, onClick: undefined, attributes: {}, }; }; /** * Get block id * @returns {String} */ Block.prototype.getId = function () { return this.id; }; /** * Get block label * @returns {String} */ Block.prototype.getLabel = function () { return this.get('label'); }; /** * Get block media * @returns {String} */ Block.prototype.getMedia = function () { return this.get('media'); }; /** * Get block content * @returns {Object|String|Array<Object|String>} */ Block.prototype.getContent = function () { return this.get('content'); }; /** * Get block category label * @returns {String} */ Block.prototype.getCategoryLabel = function () { var ctg = this.get('category'); // @ts-ignore return (0,index_all.isFunction)(ctg === null || ctg === void 0 ? void 0 : ctg.get) ? ctg.get('label') : (ctg === null || ctg === void 0 ? void 0 : ctg.label) ? ctg === null || ctg === void 0 ? void 0 : ctg.label : ctg; }; return Block; }(common/* Model */.Hn)); /* harmony default export */ const model_Block = (Block); ;// CONCATENATED MODULE: ./src/block_manager/model/Blocks.ts var Blocks_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var Blocks = /** @class */ (function (_super) { Blocks_extends(Blocks, _super); function Blocks() { return _super !== null && _super.apply(this, arguments) || this; } return Blocks; }(common/* Collection */.FE)); /* harmony default export */ const model_Blocks = (Blocks); Blocks.prototype.model = model_Block; ;// CONCATENATED MODULE: ./src/block_manager/model/Category.ts var Category_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var Category = /** @class */ (function (_super) { Category_extends(Category, _super); function Category() { return _super !== null && _super.apply(this, arguments) || this; } Category.prototype.defaults = function () { return { id: '', label: '', open: true, attributes: {}, }; }; return Category; }(common/* Model */.Hn)); /* harmony default export */ const model_Category = (Category); ;// CONCATENATED MODULE: ./src/block_manager/model/Categories.ts var Categories_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var Categories = /** @class */ (function (_super) { Categories_extends(Categories, _super); function Categories() { return _super !== null && _super.apply(this, arguments) || this; } return Categories; }(common/* Collection */.FE)); /* harmony default export */ const model_Categories = (Categories); Categories.prototype.model = model_Category; ;// CONCATENATED MODULE: ./src/block_manager/types.ts /**{START_EVENTS}*/ var BlocksEvents; (function (BlocksEvents) { /** * @event `block:add` New block added to the collection. The [Block] is passed as an argument to the callback. * @example * editor.on('block:add', (block) => { ... }); */ BlocksEvents["add"] = "block:add"; /** * @event `block:remove` Block removed from the collection. The [Block] is passed as an argument to the callback. * @example * editor.on('block:remove', (block) => { ... }); */ BlocksEvents["remove"] = "block:remove"; /** * @event `block:remove:before` Event triggered before Block remove. * @example * editor.on('block:remove:before', (block, remove, opts) => { ... }); */ BlocksEvents["removeBefore"] = "block:remove:before"; /** * @event `block:update` Block updated. The [Block] and the object containing changes are passed as arguments to the callback. * @example * editor.on('block:update', (block, updatedProps) => { ... }); */ BlocksEvents["update"] = "block:update"; /** * @event `block:drag:start` Started dragging block. The [Block] is passed as an argument. * @example * editor.on('block:drag:start', (block) => { ... }); */ BlocksEvents["dragStart"] = "block:drag:start"; /** * @event `block:drag` The block is dragging. The [Block] is passed as an argument. * @example * editor.on('block:drag', (block) => { ... }); */ BlocksEvents["drag"] = "block:drag"; /** * @event `block:drag:stop` Dragging of the block is stopped. The dropped [Component] (if dropped successfully) and the [Block] are passed as arguments. * @example * editor.on('block:drag:stop', (component, block) => { ... }); */ BlocksEvents["dragEnd"] = "block:drag:stop"; /** * @event `block:custom` Event to use in case of [custom Block Manager UI](https://grapesjs.com/docs/modules/Blocks.html#customization). * @example * editor.on('block:custom', ({ container, blocks, ... }) => { ... }); */ BlocksEvents["custom"] = "block:custom"; /** * @event `block` Catch-all event for all the events mentioned above. An object containing all the available data about the triggered event is passed as an argument to the callback. * @example * editor.on('block', ({ event, model, ... }) => { ... }); */ BlocksEvents["all"] = "block"; })(BlocksEvents || (BlocksEvents = {})); /**{END_EVENTS}*/ ;// CONCATENATED MODULE: ./src/block_manager/view/BlockView.ts var BlockView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var BlockView = /** @class */ (function (_super) { BlockView_extends(BlockView, _super); function BlockView(o, config) { if (config === void 0) { config = {}; } var _this = _super.call(this, o) || this; var model = _this.model; _this.em = config.em; _this.config = config; _this.endDrag = _this.endDrag.bind(_this); _this.ppfx = config.pStylePrefix || ''; _this.listenTo(model, 'destroy remove', _this.remove); _this.listenTo(model, 'change', _this.render); return _this; } BlockView.prototype.events = function () { return { click: 'handleClick', mousedown: 'startDrag', dragstart: 'handleDragStart', drag: 'handleDrag', dragend: 'handleDragEnd', }; }; BlockView.prototype.__getModule = function () { return this.em.Blocks; }; BlockView.prototype.handleClick = function (ev) { var _a = this, config = _a.config, model = _a.model, em = _a.em; var onClick = model.get('onClick') || config.appendOnClick; em.trigger('block:click', model, ev); if (!onClick) { return; } else if ((0,index_all.isFunction)(onClick)) { return onClick(model, em === null || em === void 0 ? void 0 : em.getEditor(), { event: ev }); } var sorter = config.getSorter(); var content = model.get('content'); var selected = em.getSelected(); sorter.setDropContent(content); var target, valid, insertAt; // If there is a selected component, try first to append // the block inside, otherwise, try to place it as a next sibling if (selected) { valid = sorter.validTarget(selected.getEl(), content); if (valid.valid) { target = selected; } else { var parent_1 = selected.parent(); if (parent_1) { valid = sorter.validTarget(parent_1.getEl(), content); if (valid.valid) { target = parent_1; insertAt = parent_1.components().indexOf(selected) + 1; } } } } // If no target found yet, try to append the block to the wrapper if (!target) { var wrapper = em.getWrapper(); valid = sorter.validTarget(wrapper.getEl(), content); if (valid.valid) target = wrapper; } var result = target && target.append(content, { at: insertAt })[0]; result && em.setSelected(result, { scroll: 1 }); }; /** * Start block dragging * @private */ BlockView.prototype.startDrag = function (e) { var _a = this, config = _a.config, em = _a.em, model = _a.model; var disable = model.get('disable'); //Right or middel click if (e.button !== 0 || !config.getSorter || this.el.draggable || disable) return; em.refreshCanvas(); var sorter = config.getSorter(); sorter.__currentBlock = model; sorter.setDragHelper(this.el, e); sorter.setDropContent(this.model.get('content')); sorter.startSort(this.el); (0,dom.on)(document, 'mouseup', this.endDrag); }; BlockView.prototype.handleDragStart = function (ev) { this.__getModule().__startDrag(this.model, ev); }; BlockView.prototype.handleDrag = function (ev) { this.__getModule().__drag(ev); }; BlockView.prototype.handleDragEnd = function () { this.__getModule().__endDrag(); }; /** * Drop block * @private */ BlockView.prototype.endDrag = function () { (0,dom/* off */.S1)(document, 'mouseup', this.endDrag); var sorter = this.config.getSorter(); // After dropping the block in the canvas the mouseup event is not yet // triggerd on 'this.doc' and so clicking outside, the sorter, tries to move // things (throws false positives). As this method just need to drop away // the block helper I use the trick of 'moved = 0' to void those errors. sorter.moved = 0; sorter.endMove(); }; BlockView.prototype.render = function () { var _a; var _b = this, em = _b.em, el = _b.el, $el = _b.$el, ppfx = _b.ppfx, model = _b.model; var disable = model.get('disable'); var attr = model.get('attributes') || {}; var cls = attr.class || ''; var className = "".concat(ppfx, "block"); var label = (em && em.t("blockManager.labels.".concat(model.id))) || model.get('label'); // @ts-ignore deprecated var render = model.get('render'); var media = model.get('media'); var clsAdd = disable ? "".concat(className, "--disable") : "".concat(ppfx, "four-color-h"); $el.attr(attr); el.className = "".concat(cls, " ").concat(className, " ").concat(ppfx, "one-bg ").concat(clsAdd).trim(); el.innerHTML = "\n ".concat(media ? "<div class=\"".concat(className, "__media\">").concat(media, "</div>") : '', "\n <div class=\"").concat(className, "-label\">").concat(label, "</div>\n "); el.title = attr.title || ((_a = el.textContent) === null || _a === void 0 ? void 0 : _a.trim()); el.setAttribute('draggable', "".concat((0,mixins.hasDnd)(em) && !disable ? true : false)); // @ts-ignore var result = render && render({ el: el, model: model, className: className, prefix: ppfx }); if (result) el.innerHTML = result; return this; }; return BlockView; }(common/* View */.G7)); /* harmony default export */ const view_BlockView = (BlockView); ;// CONCATENATED MODULE: ./src/block_manager/view/CategoryView.ts var CategoryView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var CategoryView_makeTemplateObject = ( false) || function (cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; }; var CategoryView = /** @class */ (function (_super) { CategoryView_extends(CategoryView, _super); function CategoryView(o, config) { var _this = _super.call(this, o) || this; _this.config = config; var pfx = config.pStylePrefix || ''; _this.em = config.em; _this.pfx = pfx; _this.caretR = 'fa fa-caret-right'; _this.caretD = 'fa fa-caret-down'; _this.iconClass = "".concat(pfx, "caret-icon"); _this.activeClass = "".concat(pfx, "open"); _this.className = "".concat(pfx, "block-category"); _this.listenTo(_this.model, 'change:open', _this.updateVisibility); _this.model.view = _this; return _this; } CategoryView.prototype.events = function () { return { 'click [data-title]': 'toggle', }; }; CategoryView.prototype.template = function (_a) { var pfx = _a.pfx, label = _a.label; return html(CategoryView_templateObject_1 || (CategoryView_templateObject_1 = CategoryView_makeTemplateObject(["\n <div class=\"", "title\" data-title>\n <i class=\"", "caret-icon\"></i>\n ", "\n </div>\n <div class=\"", "blocks-c\"></div>\n "], ["\n <div class=\"", "title\" data-title>\n <i class=\"", "caret-icon\"></i>\n ", "\n </div>\n <div class=\"", "blocks-c\"></div>\n "])), pfx, pfx, label, pfx); }; /** @ts-ignore */ CategoryView.prototype.attributes = function () { return this.model.get('attributes') || {}; }; CategoryView.prototype.updateVisibility = function () { if (this.model.get('open')) this.open(); else this.close(); }; CategoryView.prototype.open = function () { this.$el.addClass(this.activeClass); this.getIconEl().className = "".concat(this.iconClass, " ").concat(this.caretD); this.getBlocksEl().style.display = ''; }; CategoryView.prototype.close = function () { this.$el.removeClass(this.activeClass); this.getIconEl().className = "".concat(this.iconClass, " ").concat(this.caretR); this.getBlocksEl().style.display = 'none'; }; CategoryView.prototype.toggle = function () { var model = this.model; model.set('open', !model.get('open')); }; CategoryView.prototype.getIconEl = function () { if (!this.iconEl) { this.iconEl = this.el.querySelector(".".concat(this.iconClass)); } return this.iconEl; }; CategoryView.prototype.getBlocksEl = function () { if (!this.blocksEl) { this.blocksEl = this.el.querySelector(".".concat(this.pfx, "blocks-c")); } return this.blocksEl; }; CategoryView.prototype.append = function (el) { this.getBlocksEl().appendChild(el); }; CategoryView.prototype.render = function () { var _a = this, em = _a.em, el = _a.el, $el = _a.$el, model = _a.model, pfx = _a.pfx; var label = em.t("blockManager.categories.".concat(model.id)) || model.get('label'); el.innerHTML = this.template({ pfx: pfx, label: label }); $el.addClass(this.className); $el.css({ order: model.get('order') }); this.updateVisibility(); return this; }; return CategoryView; }(common/* View */.G7)); /* harmony default export */ const view_CategoryView = (CategoryView); var CategoryView_templateObject_1; ;// CONCATENATED MODULE: ./src/block_manager/view/BlocksView.ts var BlocksView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var BlocksView_assign = ( false) || function () { BlocksView_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return BlocksView_assign.apply(this, arguments); }; var BlocksView = /** @class */ (function (_super) { BlocksView_extends(BlocksView, _super); function BlocksView(opts, config) { var _this = _super.call(this, opts) || this; (0,index_all.bindAll)(_this, 'getSorter', 'onDrag', 'onDrop', 'onMove'); _this.config = config || {}; _this.categories = opts.categories || ''; _this.renderedCategories = {}; var ppfx = _this.config.pStylePrefix || ''; _this.ppfx = ppfx; _this.noCatClass = "".concat(ppfx, "blocks-no-cat"); _this.blockContClass = "".concat(ppfx, "blocks-c"); _this.catsClass = "".concat(ppfx, "block-categories"); var coll = _this.collection; _this.listenTo(coll, 'add', _this.addTo); _this.listenTo(coll, 'reset', _this.render); _this.em = _this.config.em; if (_this.em) { _this.config.getSorter = _this.getSorter; } return _this; } BlocksView.prototype.__getModule = function () { return this.em.Blocks; }; BlocksView.prototype.updateConfig = function (opts) { if (opts === void 0) { opts = {}; } this.config = BlocksView_assign(BlocksView_assign({}, this.config), opts); }; /** * Get sorter * @private */ BlocksView.prototype.getSorter = function () { var em = this.em; if (!em) return; if (!this.sorter) { var utils = em.Utils; var canvas = em.Canvas; this.sorter = new utils.Sorter({ // @ts-ignore container: canvas.getBody(), placer: canvas.getPlacerEl(), containerSel: '*', itemSel: '*', pfx: this.ppfx, onStart: this.onDrag, onEndMove: this.onDrop, onMove: this.onMove, document: canvas.getFrameEl().contentDocument, direction: 'a', wmargin: 1, nested: 1, em: em, canvasRelative: 1, }); } return this.sorter; }; BlocksView.prototype.onDrag = function (ev) { this.em.stopDefault(); this.__getModule().__startDrag(this.sorter.__currentBlock, ev); }; BlocksView.prototype.onMove = function (ev) { this.__getModule().__drag(ev); }; BlocksView.prototype.onDrop = function (component) { this.em.runDefault(); this.__getModule().__endDrag({ component: component }); delete this.sorter.__currentBlock; }; /** * Add new model to the collection * @param {Model} model * @private * */ BlocksView.prototype.addTo = function (model) { this.add(model); }; /** * Render new model inside the view * @param {Model} model * @param {Object} fragment Fragment collection * @private * */ BlocksView.prototype.add = function (model, fragment) { var config = this.config; var view = new view_BlockView({ model: model, attributes: model.get('attributes'), }, config); var rendered = view.render().el; var category = model.get('category'); // Check for categories if (category && this.categories && !config.ignoreCategories) { if ((0,index_all.isString)(category)) { category = { id: category, label: category }; } else if ((0,index_all.isObject)(category) && !category.id) { category.id = category.label; } var catModel = this.categories.add(category); var catId = catModel.get('id'); var categories = this.getCategoriesEl(); var catView = this.renderedCategories[catId]; // @ts-ignore model.set('category', catModel, { silent: true }); if (!catView && categories) { catView = new view_CategoryView({ model: catModel }, config).render(); this.renderedCategories[catId] = catView; categories.appendChild(catView.el); } catView && catView.append(rendered); return; } fragment ? fragment.appendChild(rendered) : this.append(rendered); }; BlocksView.prototype.getCategoriesEl = function () { if (!this.catsEl) { this.catsEl = this.el.querySelector(".".concat(this.catsClass)); } return this.catsEl; }; BlocksView.prototype.getBlocksEl = function () { if (!this.blocksEl) { this.blocksEl = this.el.querySelector(".".concat(this.noCatClass, " .").concat(this.blockContClass)); } return this.blocksEl; }; BlocksView.prototype.append = function (el) { var blocks = this.getBlocksEl(); blocks && blocks.appendChild(el); }; BlocksView.prototype.render = function () { var _this = this; var ppfx = this.ppfx; var frag = document.createDocumentFragment(); delete this.catsEl; delete this.blocksEl; this.renderedCategories = {}; this.el.innerHTML = "\n <div class=\"".concat(this.catsClass, "\"></div>\n <div class=\"").concat(this.noCatClass, "\">\n <div class=\"").concat(this.blockContClass, "\"></div>\n </div>\n "); this.collection.each(function (model) { return _this.add(model, frag); }); this.append(frag); var cls = "".concat(this.blockContClass, "s ").concat(ppfx, "one-bg ").concat(ppfx, "two-color"); this.$el.addClass(cls); this.rendered = true; return this; }; return BlocksView; }(common/* View */.G7)); /* harmony default export */ const view_BlocksView = (BlocksView); ;// CONCATENATED MODULE: ./src/block_manager/index.ts var block_manager_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var block_manager_assign = ( false) || function () { block_manager_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return block_manager_assign.apply(this, arguments); }; /** * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/GrapesJS/grapesjs/blob/master/src/block_manager/config/config.ts) * ```js * const editor = grapesjs.init({ * blockManager: { * // options * } * }) * ``` * * Once the editor is instantiated you can use its API and listen to its events. Before using these methods, you should get the module from the instance. * * ```js * // Listen to events * editor.on('block:add', (block) => { ... }); * * // Use the API * const blockManager = editor.Blocks; * blockManager.add(...); * ``` * * {REPLACE_EVENTS} * * [Block]: block.html * [Component]: component.html * * @module Blocks */ var BlockManager = /** @class */ (function (_super) { block_manager_extends(BlockManager, _super); function BlockManager(em) { var _a; var _this = _super.call(this, em, 'BlockManager', new model_Blocks(((_a = em.config.blockManager) === null || _a === void 0 ? void 0 : _a.blocks) || []), BlocksEvents, block_manager_config_config) || this; _this.events = BlocksEvents; _this.Block = model_Block; _this.Blocks = model_Blocks; _this.Category = model_Category; _this.Categories = model_Categories; _this.storageKey = ''; // Global blocks collection _this.blocks = _this.all; _this.blocksVisible = new model_Blocks(_this.blocks.models); _this.categories = new model_Categories(); // Setup the sync between the global and public collections _this.blocks.on('add', function (model) { return _this.blocksVisible.add(model); }); _this.blocks.on('remove', function (model) { return _this.blocksVisible.remove(model); }); _this.blocks.on('reset', function (coll) { return _this.blocksVisible.reset(coll.models); }); _this.__onAllEvent = (0,index_all.debounce)(function () { return _this.__trgCustom(); }, 0); return _this; } /** * Get configuration object * @name getConfig * @function * @return {Object} */ BlockManager.prototype.__trgCustom = function () { this.em.trigger(this.events.custom, this.__customData()); }; BlockManager.prototype.__customData = function () { var _this = this; var bhv = this.__getBehaviour(); return { bm: this, blocks: this.getAll().models, container: bhv.container, dragStart: function (block, ev) { return _this.startDrag(block, ev); }, drag: function (ev) { return _this.__drag(ev); }, dragStop: function (cancel) { return _this.endDrag(cancel); }, }; }; BlockManager.prototype.__startDrag = function (block, ev) { var _a = this, em = _a.em, events = _a.events, blocks = _a.blocks; var content = block.getContent ? block.getContent() : block; this._dragBlock = block; em.set({ dragResult: null, dragContent: content }); [em, blocks].map(function (i) { return i.trigger(events.dragStart, block, ev); }); }; BlockManager.prototype.__drag = function (ev) { var _a = this, em = _a.em, events = _a.events, blocks = _a.blocks; var block = this._dragBlock; [em, blocks].map(function (i) { return i.trigger(events.drag, block, ev); }); }; BlockManager.prototype.__endDrag = function (opts) { if (opts === void 0) { opts = {}; } var _a = this, em = _a.em, events = _a.events, blocks = _a.blocks; var block = this._dragBlock; var cmp = opts.component || em.get('dragResult'); delete this._dragBlock; if (cmp && block) { var oldKey = 'activeOnRender'; var oldActive = cmp.get && cmp.get(oldKey); var toActive = block.get('activate') || oldActive; var toSelect = block.get('select'); var first = (0,index_all.isArray)(cmp) ? cmp[0] : cmp; if (toSelect || (toActive && toSelect !== false)) { em.setSelected(first); } if (toActive) { first.trigger('active'); oldActive && first.unset(oldKey); } if (block.get('resetId')) { first.onAll(function (cmp) { return cmp.resetId(); }); } } em.set({ dragResult: null, dragContent: null }); if (block) { [em, blocks].map(function (i) { return i.trigger(events.dragEnd, cmp, block); }); } }; BlockManager.prototype.__getFrameViews = function () { return this.em.Canvas.getFrames() .map(function (frame) { return frame.view; }) .filter(Boolean); }; BlockManager.prototype.__behaviour = function (opts) { if (opts === void 0) { opts = {}; } return (this._bhv = block_manager_assign(block_manager_assign({}, (this._bhv || {})), opts)); }; BlockManager.prototype.__getBehaviour = function () { return this._bhv || {}; }; BlockManager.prototype.startDrag = function (block, ev) { this.__startDrag(block, ev); this.__getFrameViews().forEach(function (fv) { var _a; return (_a = fv.droppable) === null || _a === void 0 ? void 0 : _a.startCustom(); }); }; BlockManager.prototype.endDrag = function (cancel) { this.__getFrameViews().forEach(function (fv) { var _a; return (_a = fv.droppable) === null || _a === void 0 ? void 0 : _a.endCustom(cancel); }); this.__endDrag(); }; BlockManager.prototype.postRender = function () { var _a = this, categories = _a.categories, config = _a.config, em = _a.em; var collection = this.blocksVisible; this.blocksView = new view_BlocksView({ collection: collection, categories: categories }, block_manager_assign(block_manager_assign({}, config), { em: em })); this.__appendTo(collection.models); this.__trgCustom(); }; /** * Add new block. * @param {String} id Block ID * @param {[Block]} props Block properties * @returns {[Block]} Added block * @example * blockManager.add('h1-block', { * label: 'Heading', * content: '<h1>Put your title here</h1>', * category: 'Basic', * attributes: { * title: 'Insert h1 block' * } * }); */ BlockManager.prototype.add = function (id, props, opts) { if (opts === void 0) { opts = {}; } var prp = props || {}; prp.id = id; return this.blocks.add(prp, opts); }; /** * Get the block by id. * @param {String} id Block id * @returns {[Block]} * @example * const block = blockManager.get('h1-block'); * console.log(JSON.stringify(block)); * // {label: 'Heading', content: '<h1>Put your ...', ...} */ BlockManager.prototype.get = function (id) { return this.blocks.get(id); }; /** * Return all blocks. * @returns {Collection<[Block]>} * @example * const blocks = blockManager.getAll(); * console.log(JSON.stringify(blocks)); * // [{label: 'Heading', content: '<h1>Put your ...'}, ...] */ BlockManager.prototype.getAll = function () { return this.blocks; }; /** * Return the visible collection, which containes blocks actually rendered * @returns {Collection<[Block]>} */ BlockManager.prototype.getAllVisible = function () { return this.blocksVisible; }; /** * Remove block. * @param {String|[Block]} block Block or block ID * @returns {[Block]} Removed block * @example * const removed = blockManager.remove('BLOCK_ID'); * // or by passing the Block * const block = blockManager.get('BLOCK_ID'); * blockManager.remove(block); */ BlockManager.prototype.remove = function (block, opts) { if (opts === void 0) { opts = {}; } return this.__remove(block, opts); }; /** * Get all available categories. * It's possible to add categories only within blocks via 'add()' method * @return {Array|Collection} */ BlockManager.prototype.getCategories = function () { return this.categories; }; /** * Return the Blocks container element * @return {HTMLElement} */ BlockManager.prototype.getContainer = function () { var _a; return (_a = this.blocksView) === null || _a === void 0 ? void 0 : _a.el; }; /** * Returns currently dragging block. * Updated when the drag starts and cleared once it's done. * @returns {[Block]|undefined} */ BlockManager.prototype.getDragBlock = function () { return this._dragBlock; }; /** * Render blocks * @param {Array} blocks Blocks to render, without the argument will render all global blocks * @param {Object} [opts={}] Options * @param {Boolean} [opts.external] Render blocks in a new container (HTMLElement will be returned) * @param {Boolean} [opts.ignoreCategories] Render blocks without categories * @return {HTMLElement} Rendered element * @example * // Render all blocks (inside the global collection) * blockManager.render(); * * // Render new set of blocks * const blocks = blockManager.getAll(); * const filtered = blocks.filter(block => block.get('category') == 'sections') * * blockManager.render(filtered); * // Or a new set from an array * blockManager.render([ * {label: 'Label text', content: '<div>Content</div>'} * ]); * * // Back to blocks from the global collection * blockManager.render(); * * // You can also render your blocks outside of the main block container * const newBlocksEl = blockManager.render(filtered, { external: true }); * document.getElementById('some-id').appendChild(newBlocksEl); */ BlockManager.prototype.render = function (blocks, opts) { if (opts === void 0) { opts = {}; } var _a = this, categories = _a.categories, config = _a.config, em = _a.em; var toRender = blocks || this.getAll().models; if (opts.external) { var collection = new model_Blocks(toRender); return new view_BlocksView({ collection: collection, categories: categories }, block_manager_assign(block_manager_assign({ em: em }, config), opts)).render().el; } if (this.blocksView) { this.blocksView.updateConfig(opts); this.blocksView.collection.reset(toRender); if (!this.blocksView.rendered) { this.blocksView.render(); this.blocksView.rendered = true; } } return this.getContainer(); }; BlockManager.prototype.destroy = function () { var _a; var colls = [this.blocks, this.blocksVisible, this.categories]; colls.map(function (c) { return c.stopListening(); }); colls.map(function (c) { return c.reset(); }); (_a = this.blocksView) === null || _a === void 0 ? void 0 : _a.remove(); }; return BlockManager; }(ItemManagerModule)); /* harmony default export */ const block_manager = (BlockManager); ;// CONCATENATED MODULE: ./src/selector_manager/config/config.ts var selector_manager_config_config_config = { stylePrefix: 'clm-', appendTo: '', selectors: [], states: [{ name: 'hover' }, { name: 'active' }, { name: 'nth-of-type(2n)' }], iconAdd: '<svg viewBox="0 0 24 24"><path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"></path></svg>', iconSync: '<svg viewBox="0 0 24 24"><path d="M12 18c-3.31 0-6-2.69-6-6 0-1 .25-1.97.7-2.8L5.24 7.74A7.93 7.93 0 0 0 4 12c0 4.42 3.58 8 8 8v3l4-4-4-4m0-11V1L8 5l4 4V6c3.31 0 6 2.69 6 6 0 1-.25 1.97-.7 2.8l1.46 1.46A7.93 7.93 0 0 0 20 12c0-4.42-3.58-8-8-8z"></path></svg>', iconTagOn: '<svg viewBox="0 0 24 24"><path d="M19 19H5V5h10V3H5c-1.11 0-2 .89-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2v-8h-2m-11.09-.92L6.5 11.5 11 16 21 6l-1.41-1.42L11 13.17l-3.09-3.09z"></path></svg>', iconTagOff: '<svg viewBox="0 0 24 24"><path d="M19 3H5c-1.11 0-2 .89-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5a2 2 0 0 0-2-2m0 2v14H5V5h14z"></path></svg>', iconTagRemove: '<svg viewBox="0 0 24 24"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12 19 6.41z"></path></svg>', componentFirst: false, custom: false, }; /* harmony default export */ const selector_manager_config_config = (selector_manager_config_config_config); ;// CONCATENATED MODULE: ./src/selector_manager/model/State.ts var State_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); /** * @typedef State * @property {String} name State name, eg. `hover`, `nth-of-type(2n)` * @property {String} label State label, eg. `Hover`, `Even/Odd` */ var State = /** @class */ (function (_super) { State_extends(State, _super); function State() { return _super !== null && _super.apply(this, arguments) || this; } State.prototype.defaults = function () { return { name: '', label: '', }; }; /** * Get state name * @returns {String} */ State.prototype.getName = function () { return this.get('name'); }; /** * Get state label. If label was not provided, the name will be returned. * @returns {String} */ State.prototype.getLabel = function () { return this.get('label') || this.getName(); }; return State; }(common/* Model */.Hn)); /* harmony default export */ const model_State = (State); State.prototype.idAttribute = 'name'; ;// CONCATENATED MODULE: ./src/selector_manager/view/ClassTagView.ts var ClassTagView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ClassTagView_makeTemplateObject = ( false) || function (cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; }; var inputProp = 'contentEditable'; var ClassTagView = /** @class */ (function (_super) { ClassTagView_extends(ClassTagView, _super); function ClassTagView(o) { if (o === void 0) { o = {}; } var _this = _super.call(this, o) || this; var config = o.config || {}; _this.config = config; _this.module = o.module; _this.coll = o.coll || null; _this.pfx = config.stylePrefix || ''; _this.ppfx = config.pStylePrefix || ''; _this.em = config.em; _this.listenTo(_this.model, 'change:active', _this.updateStatus); return _this; } ClassTagView.prototype.template = function () { var _a = this, pfx = _a.pfx, model = _a.model, config = _a.config; var label = model.get('label') || ''; return html(ClassTagView_templateObject_1 || (ClassTagView_templateObject_1 = ClassTagView_makeTemplateObject(["\n <span id=\"", "checkbox\" class=\"", "tag-status\" data-tag-status></span>\n <span id=\"", "tag-label\" data-tag-name>", "</span>\n <span id=\"", "close\" class=\"", "tag-close\" data-tag-remove> $", " </span>\n "], ["\n <span id=\"", "checkbox\" class=\"", "tag-status\" data-tag-status></span>\n <span id=\"", "tag-label\" data-tag-name>", "</span>\n <span id=\"", "close\" class=\"", "tag-close\" data-tag-remove> $", " </span>\n "])), pfx, pfx, pfx, label, pfx, pfx, config.iconTagRemove); }; ClassTagView.prototype.events = function () { return { 'click [data-tag-remove]': 'removeTag', 'click [data-tag-status]': 'changeStatus', 'dblclick [data-tag-name]': 'startEditTag', 'focusout [data-tag-name]': 'endEditTag', }; }; /** * Returns the element which containes the anme of the tag * @return {HTMLElement} */ ClassTagView.prototype.getInputEl = function () { if (!this.inputEl) { this.inputEl = this.el.querySelector('[data-tag-name]'); } return this.inputEl; }; /** * Start editing tag * @private */ ClassTagView.prototype.startEditTag = function () { var em = this.em; var inputEl = this.getInputEl(); inputEl; inputEl[inputProp] = 'true'; inputEl.focus(); em === null || em === void 0 ? void 0 : em.setEditing(true); }; /** * End editing tag. If the class typed already exists the * old one will be restored otherwise will be changed * @private */ ClassTagView.prototype.endEditTag = function () { var _a = this, model = _a.model, em = _a.em; var inputEl = this.getInputEl(); var label = inputEl.textContent || ''; var sm = em === null || em === void 0 ? void 0 : em.Selectors; inputEl[inputProp] = 'false'; em === null || em === void 0 ? void 0 : em.setEditing(false); if (sm && sm.rename(model, label) !== model) { inputEl.innerText = model.get('label'); } }; /** * Update status of the tag * @private */ ClassTagView.prototype.changeStatus = function () { var model = this.model; model.set('active', !model.get('active')); }; /** * Remove tag from the selected component * @param {Object} e * @private */ ClassTagView.prototype.removeTag = function () { this.module.removeSelected(this.model); }; /** * Update status of the checkbox * @private */ ClassTagView.prototype.updateStatus = function () { var _a = this, model = _a.model, $el = _a.$el, config = _a.config; var iconTagOn = config.iconTagOn, iconTagOff = config.iconTagOff; var $chk = $el.find('[data-tag-status]'); if (model.get('active')) { $chk.html(iconTagOn); $el.removeClass('opac50'); } else { $chk.html(iconTagOff); $el.addClass('opac50'); } }; ClassTagView.prototype.render = function () { var pfx = this.pfx; var ppfx = this.ppfx; this.$el.html(this.template()); this.$el.attr('class', "".concat(pfx, "tag ").concat(ppfx, "three-bg")); this.updateStatus(); return this; }; return ClassTagView; }(common/* View */.G7)); /* harmony default export */ const view_ClassTagView = (ClassTagView); var ClassTagView_templateObject_1; ;// CONCATENATED MODULE: ./src/selector_manager/view/ClassTagsView.ts var ClassTagsView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ClassTagsView_makeTemplateObject = ( false) || function (cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; }; var ClassTagsView = /** @class */ (function (_super) { ClassTagsView_extends(ClassTagsView, _super); function ClassTagsView(o) { if (o === void 0) { o = {}; } var _this = _super.call(this, o) || this; _this.config = o.config || {}; _this.pfx = _this.config.stylePrefix || ''; _this.ppfx = _this.config.pStylePrefix || ''; _this.className = _this.pfx + 'tags'; _this.stateInputId = _this.pfx + 'states'; _this.stateInputC = _this.pfx + 'input-c'; _this.states = _this.config.states || []; var em = _this.config.em; var coll = _this.collection; _this.target = em; var md = em.Selectors; _this.module = md; _this.em = em; _this.componentChanged = (0,index_all.debounce)(_this.componentChanged.bind(_this), 0); _this.checkSync = (0,index_all.debounce)(_this.checkSync.bind(_this), 0); var toList = 'component:toggled component:update:classes'; var toListCls = 'component:update:classes change:state'; _this.listenTo(em, toList, _this.componentChanged); _this.listenTo(em, 'styleManager:update', _this.componentChanged); _this.listenTo(em, toListCls, _this.__handleStateChange); _this.listenTo(em, 'styleable:change change:device', _this.checkSync); // component:styleUpdate _this.listenTo(coll, 'add', _this.addNew); _this.listenTo(coll, 'reset', _this.renderClasses); _this.listenTo(coll, 'remove', _this.tagRemoved); _this.listenTo(md.getAll(), md.events.state, (0,index_all.debounce)(function () { return _this.renderStates(); }, 0)); _this.delegateEvents(); return _this; } ClassTagsView.prototype.template = function (_a) { var labelInfo = _a.labelInfo, labelHead = _a.labelHead, iconSync = _a.iconSync, iconAdd = _a.iconAdd, pfx = _a.pfx, ppfx = _a.ppfx; return html(ClassTagsView_templateObject_1 || (ClassTagsView_templateObject_1 = ClassTagsView_makeTemplateObject([" <div id=\"", "up\" class=\"", "header\">\n <div id=\"", "label\" class=\"", "header-label\">", "</div>\n <div id=\"", "status-c\" class=\"", "header-status\">\n <span id=\"", "input-c\" data-states-c>\n <div class=\"", "field ", "select\">\n <span id=\"", "input-holder\">\n <select id=\"", "states\" data-states></select>\n </span>\n <div class=\"", "sel-arrow\">\n <div class=\"", "d-s-arrow\"></div>\n </div>\n </div>\n </span>\n </div>\n </div>\n <div id=\"", "tags-field\" class=\"", "field\">\n <div id=\"", "tags-c\" data-selectors></div>\n <input id=\"", "new\" data-input />\n <span id=\"", "add-tag\" class=\"", "tags-btn ", "tags-btn__add\" data-add> $", " </span>\n <span class=\"", "tags-btn ", "tags-btn__sync\" style=\"display: none\" data-sync-style> $", " </span>\n </div>\n <div class=\"", "sels-info\">\n <div class=\"", "label-sel\">", ":</div>\n <div class=\"", "sels\" data-selected></div>\n </div>"], [" <div id=\"", "up\" class=\"", "header\">\n <div id=\"", "label\" class=\"", "header-label\">", "</div>\n <div id=\"", "status-c\" class=\"", "header-status\">\n <span id=\"", "input-c\" data-states-c>\n <div class=\"", "field ", "select\">\n <span id=\"", "input-holder\">\n <select id=\"", "states\" data-states></select>\n </span>\n <div class=\"", "sel-arrow\">\n <div class=\"", "d-s-arrow\"></div>\n </div>\n </div>\n </span>\n </div>\n </div>\n <div id=\"", "tags-field\" class=\"", "field\">\n <div id=\"", "tags-c\" data-selectors></div>\n <input id=\"", "new\" data-input />\n <span id=\"", "add-tag\" class=\"", "tags-btn ", "tags-btn__add\" data-add> $", " </span>\n <span class=\"", "tags-btn ", "tags-btn__sync\" style=\"display: none\" data-sync-style> $", " </span>\n </div>\n <div class=\"", "sels-info\">\n <div class=\"", "label-sel\">", ":</div>\n <div class=\"", "sels\" data-selected></div>\n </div>"])), pfx, pfx, pfx, pfx, labelHead, pfx, pfx, pfx, ppfx, ppfx, ppfx, pfx, ppfx, ppfx, pfx, ppfx, pfx, pfx, pfx, pfx, pfx, iconAdd, pfx, pfx, iconSync, pfx, pfx, labelInfo, pfx); }; ClassTagsView.prototype.events = function () { return { 'change [data-states]': 'stateChanged', 'click [data-add]': 'startNewTag', 'focusout [data-input]': 'endNewTag', 'keyup [data-input]': 'onInputKeyUp', 'click [data-sync-style]': 'syncStyle', }; }; ClassTagsView.prototype.syncStyle = function () { var em = this.em; var target = this.getTarget(); var cssC = em.Css; var opts = { noDisabled: 1 }; var selectors = this.getCommonSelectors({ opts: opts }); var state = em.get('state'); var mediaText = em.getCurrentMedia(); var ruleComponents = []; var rule = cssC.get(selectors, state, mediaText) || cssC.add(selectors, state, mediaText); var style; this.getTargets().forEach(function (target) { var ruleComponent = cssC.getIdRule(target.getId(), { state: state, mediaText: mediaText, }); style = ruleComponent.getStyle(); ruleComponent.setStyle({}); ruleComponents.push(ruleComponent); }); style && rule.addStyle(style); em.trigger('component:toggled'); em.trigger('component:sync-style', { component: target, selectors: selectors, mediaText: mediaText, rule: rule, ruleComponents: ruleComponents, state: state, }); }; /** * Triggered when a tag is removed from collection * @param {Object} model Removed model * @private */ ClassTagsView.prototype.tagRemoved = function (model) { this.updateStateVis(); }; /** * Add new model * @param {Object} model * @private */ ClassTagsView.prototype.addNew = function (model) { this.addToClasses(model); }; /** * Start tag creation * @param {Object} e * @private */ ClassTagsView.prototype.startNewTag = function () { var _a, _b; (_a = this.$addBtn) === null || _a === void 0 ? void 0 : _a.css({ display: 'none' }); (_b = this.$input) === null || _b === void 0 ? void 0 : _b.show().focus(); }; /** * End tag creation * @param {Object} e * @private */ ClassTagsView.prototype.endNewTag = function () { var _a, _b; (_a = this.$addBtn) === null || _a === void 0 ? void 0 : _a.css({ display: '' }); (_b = this.$input) === null || _b === void 0 ? void 0 : _b.hide().val(''); }; /** * Checks what to do on keyup event * @param {Object} e * @private */ ClassTagsView.prototype.onInputKeyUp = function (e) { var _a; if (e.keyCode === 13) { e.preventDefault(); this.addNewTag((_a = this.$input) === null || _a === void 0 ? void 0 : _a.val()); } else if (e.keyCode === 27) { this.endNewTag(); } }; ClassTagsView.prototype.checkStates = function () { var state = this.em.getState(); var statesEl = this.getStates(); statesEl && statesEl.val(state); }; /** * Triggered when component is changed * @param {Object} e * @public */ ClassTagsView.prototype.componentChanged = function (_a) { var _b = _a === void 0 ? {} : _a, targets = _b.targets; this.updateSelection(targets); }; ClassTagsView.prototype.updateSelection = function (targets) { var trgs = targets || this.getTargets(); trgs = (0,index_all.isArray)(trgs) ? trgs : [trgs]; var selectors = []; if (trgs && trgs.length) { selectors = this.getCommonSelectors({ targets: trgs }); //@ts-ignore TODO This parameters are not in use why do we have them? this.checkSync({ validSelectors: selectors }); } this.collection.reset(selectors); this.updateStateVis(trgs); this.module.__trgCustom(); return selectors; }; ClassTagsView.prototype.getCommonSelectors = function (_a) { var _b = _a === void 0 ? {} : _a, targets = _b.targets, _c = _b.opts, opts = _c === void 0 ? {} : _c; var trgs = targets || this.getTargets(); return this.module.__getCommonSelectors(trgs, opts); }; ClassTagsView.prototype._commonSelectors = function () { var _a; var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return (_a = this.module).__common.apply(_a, args); }; ClassTagsView.prototype.checkSync = function () { var _a = this, $btnSyncEl = _a.$btnSyncEl, config = _a.config, collection = _a.collection; var target = this.getTarget(); var hasStyle; if (target && config.componentFirst && collection.length) { var style = target.getStyle(); hasStyle = !(0,index_all.isEmpty)(style); } $btnSyncEl && $btnSyncEl[hasStyle ? 'show' : 'hide'](); }; ClassTagsView.prototype.getTarget = function () { return this.target.getSelected(); }; ClassTagsView.prototype.getTargets = function () { return this.target.getSelectedAll(); }; /** * Update states visibility. Hides states in case there is no tags * inside collection * @private */ ClassTagsView.prototype.updateStateVis = function (targets) { var em = this.em; var avoidInline = em && em.getConfig().avoidInlineStyle; var display = this.collection.length || avoidInline ? '' : 'none'; this.getStatesC().css('display', display); this.updateSelector(targets); }; ClassTagsView.prototype.__handleStateChange = function () { this.updateSelector(this.getTargets()); }; /** * Update selector helper * @return {this} * @private */ ClassTagsView.prototype.updateSelector = function (targets) { var _this = this; var elSel = this.el.querySelector('[data-selected]'); var result = []; var trgs = targets || this.getTargets(); trgs = (0,index_all.isArray)(trgs) ? trgs : [trgs]; trgs.forEach(function (target) { return result.push(_this.__getName(target)); }); elSel && (elSel.innerHTML = result.join(', ')); this.checkStates(); }; ClassTagsView.prototype.__getName = function (target) { var _a = this, pfx = _a.pfx, config = _a.config, em = _a.em; var selectedName = config.selectedName, componentFirst = config.componentFirst; var result; if ((0,index_all.isString)(target)) { result = html(templateObject_2 || (templateObject_2 = ClassTagsView_makeTemplateObject(["<span class=\"", "sel-gen\">", "</span>"], ["<span class=\"", "sel-gen\">", "</span>"])), pfx, target); } else { var sel = target === null || target === void 0 ? void 0 : target.getSelectors(); if (!sel) return ''; var selectors = sel.getStyleable(); var state = em.get('state'); var idRes = target.getId ? html(templateObject_3 || (templateObject_3 = ClassTagsView_makeTemplateObject(["<span class=\"", "sel-cmp\">", "</span>\n <span class=\"", "sel-id\">#", "</span>"], ["<span class=\"", "sel-cmp\">", "</span>\n <span class=\"", "sel-id\">#", "</span>"])), pfx, target.getName(), pfx, target.getId()) : ''; result = this.collection.getFullString(selectors); result = result ? html(templateObject_4 || (templateObject_4 = ClassTagsView_makeTemplateObject(["<span class=\"", "sel-rule\">", "</span>"], ["<span class=\"", "sel-rule\">", "</span>"])), pfx, result) : target.get('selectorsAdd') || idRes; result = componentFirst && idRes ? idRes : result; result += state ? html(templateObject_5 || (templateObject_5 = ClassTagsView_makeTemplateObject(["<span class=\"", "sel-state\">:", "</span>"], ["<span class=\"", "sel-state\">:", "</span>"])), pfx, state) : ''; result = selectedName ? selectedName({ result: result, state: state, target: target }) : result; } return result && "<span class=\"".concat(pfx, "sel\">").concat(result, "</span>"); }; /** * Triggered when the select with states is changed * @param {Object} e * @private */ ClassTagsView.prototype.stateChanged = function (ev) { var em = this.em; var value = ev.target.value; em.set('state', value); }; /** * Add new tag to collection, if possible, and to the component * @param {Object} e * @private */ ClassTagsView.prototype.addNewTag = function (value) { var label = value.trim(); if (!label) return; this.module.addSelected({ label: label }); this.endNewTag(); // this.updateStateVis(); // Check if required }; /** * Add new object to collection * @param {Object} model Model * @param {Object} fragmentEl Fragment collection * @return {Object} Object created * @private * */ ClassTagsView.prototype.addToClasses = function (model, fragmentEl) { var fragment = fragmentEl; var classes = this.getClasses(); var rendered = new view_ClassTagView({ model: model, config: this.config, coll: this.collection, module: this.module, }).render().el; fragment ? fragment.appendChild(rendered) : classes.append(rendered); return rendered; }; /** * Render the collection of classes * @private */ ClassTagsView.prototype.renderClasses = function () { var _this = this; var frag = document.createDocumentFragment(); var classes = this.getClasses(); classes.empty(); this.collection.each(function (model) { return _this.addToClasses(model, frag); }); classes.append(frag); }; /** * Return classes element * @return {HTMLElement} * @private */ ClassTagsView.prototype.getClasses = function () { return this.$el.find('[data-selectors]'); }; /** * Return states element * @return {HTMLElement} * @private */ ClassTagsView.prototype.getStates = function () { if (!this.$states) { var el = this.$el.find('[data-states]'); this.$states = el[0] && el; } return this.$states; }; /** * Return states container element * @return {HTMLElement} * @private */ ClassTagsView.prototype.getStatesC = function () { if (!this.$statesC) this.$statesC = this.$el.find('#' + this.stateInputC); return this.$statesC; }; ClassTagsView.prototype.renderStates = function () { var _a = this, module = _a.module, em = _a.em; var labelStates = em.t('selectorManager.emptyState'); var options = module .getStates() .map(function (state) { var label = em.t("selectorManager.states.".concat(state.id)) || state.getLabel() || state.id; return "<option value=\"".concat(state.id, "\">").concat(label, "</option>"); }) .join(''); var statesEl = this.getStates(); statesEl && statesEl.html("<option value=\"\">".concat(labelStates, "</option>").concat(options)); this.checkStates(); }; ClassTagsView.prototype.render = function () { var _a = this, em = _a.em, pfx = _a.pfx, ppfx = _a.ppfx, config = _a.config, $el = _a.$el, el = _a.el; var render = config.render, iconSync = config.iconSync, iconAdd = config.iconAdd; var tmpOpts = { iconSync: iconSync, iconAdd: iconAdd, labelHead: em.t('selectorManager.label'), labelInfo: em.t('selectorManager.selected'), ppfx: ppfx, pfx: pfx, el: el, }; $el.html(this.template(tmpOpts)); var renderRes = render && render(tmpOpts); renderRes && renderRes !== el && $el.empty().append(renderRes); this.$input = $el.find('[data-input]'); this.$addBtn = $el.find('[data-add]'); this.$classes = $el.find('#' + pfx + 'tags-c'); this.$btnSyncEl = $el.find('[data-sync-style]'); this.$input.hide(); this.renderStates(); this.renderClasses(); $el.attr('class', "".concat(this.className, " ").concat(ppfx, "one-bg ").concat(ppfx, "two-color")); return this; }; return ClassTagsView; }(common/* View */.G7)); /* harmony default export */ const view_ClassTagsView = (ClassTagsView); var ClassTagsView_templateObject_1, templateObject_2, templateObject_3, templateObject_4, templateObject_5; ;// CONCATENATED MODULE: ./src/selector_manager/index.ts /** * Selectors in GrapesJS are used in CSS Composer inside Rules and in Components as classes. To illustrate this concept let's take * a look at this code: * * ```css * span > #send-btn.btn{ * ... * } * ``` * ```html * <span> * <button id="send-btn" class="btn"></button> * </span> * ``` * * In this scenario we get: * * span -> selector of type `tag` * * send-btn -> selector of type `id` * * btn -> selector of type `class` * * So, for example, being `btn` the same class entity it'll be easier to refactor and track things. * * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/GrapesJS/grapesjs/blob/master/src/selector_manager/config/config.ts) * ```js * const editor = grapesjs.init({ * selectorManager: { * // options * } * }) * ``` * * Once the editor is instantiated you can use its API and listen to its events. Before using these methods, you should get the module from the instance. * * ```js * // Listen to events * editor.on('selector:add', (selector) => { ... }); * * // Use the API * const sm = editor.Selectors; * sm.add(...); * ``` * * ## Available Events * * `selector:add` - Selector added. The [Selector] is passed as an argument to the callback. * * `selector:remove` - Selector removed. The [Selector] is passed as an argument to the callback. * * `selector:update` - Selector updated. The [Selector] and the object containing changes are passed as arguments to the callback. * * `selector:state` - States changed. An object containing all the available data about the triggered event is passed as an argument to the callback. * * `selector` - Catch-all event for all the events mentioned above. An object containing all the available data about the triggered event is passed as an argument to the callback. * * ## Methods * * [getConfig](#getconfig) * * [add](#add) * * [get](#get) * * [remove](#remove) * * [rename](#rename) * * [getAll](#getall) * * [setState](#setstate) * * [getState](#getstate) * * [getStates](#getstates) * * [setStates](#setstates) * * [getSelected](#getselected) * * [addSelected](#addselected) * * [removeSelected](#removeselected) * * [getSelectedTargets](#getselectedtargets) * * [setComponentFirst](#setcomponentfirst) * * [getComponentFirst](#getcomponentfirst) * * [Selector]: selector.html * [State]: state.html * [Component]: component.html * [CssRule]: css_rule.html * * @module Selectors */ var selector_manager_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var selector_manager_assign = ( false) || function () { selector_manager_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return selector_manager_assign.apply(this, arguments); }; var selector_manager_spreadArray = ( false) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var isId = function (str) { return (0,index_all.isString)(str) && str[0] == '#'; }; var isClass = function (str) { return (0,index_all.isString)(str) && str[0] == '.'; }; var selector_manager_evAll = 'selector'; var selector_manager_evPfx = "".concat(selector_manager_evAll, ":"); var selector_manager_evAdd = "".concat(selector_manager_evPfx, "add"); var selector_manager_evUpdate = "".concat(selector_manager_evPfx, "update"); var selector_manager_evRemove = "".concat(selector_manager_evPfx, "remove"); var selector_manager_evRemoveBefore = "".concat(selector_manager_evRemove, ":before"); var evCustom = "".concat(selector_manager_evPfx, "custom"); var evState = "".concat(selector_manager_evPfx, "state"); var selectorEvents = { all: selector_manager_evAll, update: selector_manager_evUpdate, add: selector_manager_evAdd, remove: selector_manager_evRemove, removeBefore: selector_manager_evRemoveBefore, state: evState, custom: evCustom, }; var SelectorManager = /** @class */ (function (_super) { selector_manager_extends(SelectorManager, _super); /** * Get configuration object * @name getConfig * @function * @return {Object} */ function SelectorManager(em) { var _this = _super.call(this, em, 'SelectorManager', new model_Selectors([]), selectorEvents, selector_manager_config_config, { skipListen: true }) || this; _this.Selector = model_Selector; _this.Selectors = model_Selectors; _this.storageKey = ''; (0,index_all.bindAll)(_this, '__updateSelectedByComponents'); var config = _this.config; var ppfx = config.pStylePrefix; if (ppfx) config.stylePrefix = ppfx + config.stylePrefix; // Global selectors container _this.all = new model_Selectors(config.selectors); _this.selected = new model_Selectors([], { em: em, config: config }); _this.states = new common/* Collection */.FE(config.states.map(function (state) { return new model_State(state); }), { model: model_State }); _this.model = new common/* Model */.Hn({ cFirst: config.componentFirst, _undo: true }); _this.__update = (0,index_all.debounce)(function () { return _this.__trgCustom(); }, 0); _this.__initListen({ collections: [_this.states, _this.selected], propagate: [{ entity: _this.states, event: _this.events.state }], }); em.on('change:state', function (m, value) { return em.trigger(evState, value); }); _this.model.on('change:cFirst', function (m, value) { return em.trigger('selector:type', value); }); em.on('component:toggled component:update:classes', _this.__updateSelectedByComponents); var listenTo = 'component:toggled component:update:classes change:device styleManager:update selector:state selector:type style:target'; _this.model.listenTo(em, listenTo, function () { return _this.__update(); }); return _this; } SelectorManager.prototype.__trgCustom = function (opts) { this.em.trigger(this.events.custom, this.__customData(opts)); }; SelectorManager.prototype.getAll = function (opts) { if (opts === void 0) { opts = {}; } return (this.all ? (opts.array ? selector_manager_spreadArray([], this.all.models, true) : this.all) : []); }; SelectorManager.prototype.__customData = function (opts) { if (opts === void 0) { opts = {}; } this.__ctn = this.__ctn || opts.container; return { states: this.getStates(), selected: this.getSelected(), container: this.__ctn, }; }; // postLoad() { // this.__postLoad(); // const { em, model } = this; // const um = em.get('UndoManager'); // um && um.add(model); // um && um.add(this.pages); // }, SelectorManager.prototype.postRender = function () { this.__appendTo(); this.__trgCustom(); }; SelectorManager.prototype.select = function (value, opts) { if (opts === void 0) { opts = {}; } var targets = Array.isArray(value) ? value : [value]; var toSelect = this.em.Styles.select(targets, opts); this.selected.reset(this.__getCommonSelectors(toSelect)); var selTags = this.selectorTags; var res = toSelect .filter(function (i) { return i; }) .map(function (sel) { return ((0,mixins.isComponent)(sel) ? sel : (0,mixins.isRule)(sel) && !sel.get('selectorsAdd') ? sel : sel.getSelectorsString()); }); selTags && selTags.componentChanged({ targets: res }); return this; }; SelectorManager.prototype.addSelector = function (name, opts, cOpts) { if (opts === void 0) { opts = {}; } if (cOpts === void 0) { cOpts = {}; } var props = selector_manager_assign({}, opts); if ((0,index_all.isObject)(name)) { props = name; } else { props.name = name; } if (isId(props.name)) { props.name = props.name.substr(1); props.type = model_Selector.TYPE_ID; } else if (isClass(props.name)) { props.name = props.name.substr(1); } if (props.label && !props.name) { props.name = this.escapeName(props.label); } var cname = props.name; var config = this.getConfig(); var _a = this, all = _a.all, em = _a.em; var selector = cname ? this.get(cname, props.type) : all.where(props)[0]; if (!selector) { var selModel = props instanceof model_Selector ? props : new model_Selector(props, selector_manager_assign(selector_manager_assign({}, cOpts), { config: config, em: em })); return all.add(selModel, cOpts); } return selector; }; SelectorManager.prototype.getSelector = function (name, type) { if (type === void 0) { type = model_Selector.TYPE_CLASS; } if (isId(name)) { name = name.substr(1); type = model_Selector.TYPE_ID; } else if (isClass(name)) { name = name.substr(1); } return this.all.where({ name: name, type: type })[0]; }; /** * Add a new selector to the collection if it does not already exist. * You can pass selectors properties or string identifiers. * @param {Object|String} props Selector properties or string identifiers, eg. `{ name: 'my-class', label: 'My class' }`, `.my-cls` * @param {Object} [opts] Selector options * @return {[Selector]} * @example * const selector = selectorManager.add({ name: 'my-class', label: 'My class' }); * console.log(selector.toString()) // `.my-class` * // Same as * const selector = selectorManager.add('.my-class'); * console.log(selector.toString()) // `.my-class` * */ SelectorManager.prototype.add = function (props, opts) { var _this = this; if (opts === void 0) { opts = {}; } var cOpts = (0,index_all.isString)(props) ? {} : opts; // Keep support for arrays but avoid it in docs if ((0,index_all.isArray)(props)) { return props.map(function (item) { return _this.addSelector(item, opts, cOpts); }); } else { return this.addSelector(props, opts, cOpts); } }; /** * Add class selectors * @param {Array|string} classes Array or string of classes * @return {Array} Array of added selectors * @private * @example * sm.addClass('class1'); * sm.addClass('class1 class2'); * sm.addClass(['class1', 'class2']); * // -> [SelectorObject, ...] */ SelectorManager.prototype.addClass = function (classes) { var _this = this; var added = []; if ((0,index_all.isString)(classes)) { classes = classes.trim().split(' '); } classes.forEach(function (name) { return added.push(_this.addSelector(name)); }); return added; }; /** * Get the selector by its name/type * @param {String} name Selector name or string identifier * @returns {[Selector]|null} * @example * const selector = selectorManager.get('.my-class'); * // Get Id * const selectorId = selectorManager.get('#my-id'); * */ SelectorManager.prototype.get = function (name, type) { var _this = this; // Keep support for arrays but avoid it in docs if ((0,index_all.isArray)(name)) { var result_1 = []; var selectors = name.map(function (item) { return _this.getSelector(item); }).filter(Boolean); selectors.forEach(function (item) { return result_1.indexOf(item) < 0 && result_1.push(item); }); // @ts-ignore return result_1; } else { // @ts-ignore return this.getSelector(name, type); } }; /** * Remove Selector. * @param {String|[Selector]} selector Selector instance or Selector string identifier * @returns {[Selector]} Removed Selector * @example * const removed = selectorManager.remove('.myclass'); * // or by passing the Selector * selectorManager.remove(selectorManager.get('.myclass')); */ SelectorManager.prototype.remove = function (selector, opts) { return this.__remove(selector, opts); }; /** * Rename Selector. * @param {[Selector]} selector Selector to update. * @param {String} name New name for the selector. * @returns {[Selector]} Selector containing the passed name. * @example * const selector = selectorManager.get('myclass'); * const result = selectorManager.rename(selector, 'myclass2'); * console.log(result === selector ? 'Selector updated' : 'Selector with this name exists already'); */ SelectorManager.prototype.rename = function (selector, name, opts) { var newName = this.escapeName(name); var result = this.get(newName); return result || selector.set({ name: newName, label: name }, opts); }; /** * Change the selector state * @param {String} value State value * @returns {this} * @example * selectorManager.setState('hover'); */ SelectorManager.prototype.setState = function (value) { this.em.setState(value); return this; }; /** * Get the current selector state value * @returns {String} */ SelectorManager.prototype.getState = function () { return this.em.getState(); }; /** * Get states * @returns {Array<[State]>} */ SelectorManager.prototype.getStates = function () { return selector_manager_spreadArray([], this.states.models, true); }; /** * Set a new collection of states * @param {Array<Object>} states Array of new states * @returns {Array<[State]>} * @example * const states = selectorManager.setStates([ * { name: 'hover', label: 'Hover' }, * { name: 'nth-of-type(2n)', label: 'Even/Odd' } * ]); */ SelectorManager.prototype.setStates = function (states, opts) { return this.states.reset(states.map(function (state) { return new model_State(state); }), opts); }; /** * Get commonly selected selectors, based on all selected components. * @returns {Array<[Selector]>} * @example * const selected = selectorManager.getSelected(); * console.log(selected.map(s => s.toString())) */ SelectorManager.prototype.getSelected = function () { return this.__getCommon(); }; /** * Get selected selectors. * @returns {Array<[Selector]>} * @example * const selected = selectorManager.getSelectedAll(); * console.log(selected.map(s => s.toString())) */ SelectorManager.prototype.getSelectedAll = function () { return selector_manager_spreadArray([], this.selected.models, true); }; /** * Add new selector to all selected components. * @param {Object|String} props Selector properties or string identifiers, eg. `{ name: 'my-class', label: 'My class' }`, `.my-cls` * @example * selectorManager.addSelected('.new-class'); */ SelectorManager.prototype.addSelected = function (props) { var added = this.add(props); this.em.getSelectedAll().forEach(function (target) { target.getSelectors().add(added); }); // TODO: update selected collection }; /** * Remove a common selector from all selected components. * @param {String|[Selector]} selector Selector instance or Selector string identifier * @example * selectorManager.removeSelected('.myclass'); */ SelectorManager.prototype.removeSelected = function (selector) { this.em.getSelectedAll().forEach(function (trg) { !selector.get('protected') && trg && trg.getSelectors().remove(selector); }); }; SelectorManager.prototype.duplicateSelected = function (selector, opts) { var _this = this; if (opts === void 0) { opts = {}; } var em = this.em; var commonSelectors = this.getSelected(); if (commonSelectors.indexOf(selector) < 0) return; var state = this.getState(); var media = em.getCurrentMedia(); var rule = em.Css.get(commonSelectors, state, media); var styleToApply = rule === null || rule === void 0 ? void 0 : rule.getStyle(); em.getSelectedAll().forEach(function (component) { var selectors = component.getSelectors(); if (selectors.includes(selector)) { var suffix = opts.suffix || ' copy'; var label = selector.getLabel(); var newSelector = _this.addSelector("".concat(label).concat(suffix)); var at = selectors.indexOf(selector); selectors.remove(selector); selectors.add(newSelector, { at: at }); } }); if (styleToApply) { var newRule = em.Css.add(this.getSelected(), state, media); newRule.setStyle(styleToApply); } }; /** * Get the array of currently selected targets. * @returns {Array<[Component]|[CssRule]>} * @example * const targetsToStyle = selectorManager.getSelectedTargets(); * console.log(targetsToStyle.map(target => target.getSelectorsString())) */ SelectorManager.prototype.getSelectedTargets = function () { return this.em.Styles.getSelectedAll(); }; /** * Update component-first option. * If the component-first is enabled, all the style changes will be applied on selected components (ID rules) instead * of selectors (which would change styles on all components with those classes). * @param {Boolean} value */ SelectorManager.prototype.setComponentFirst = function (value) { this.getConfig().componentFirst = value; this.model.set({ cFirst: value }); }; /** * Get the value of component-first option. * @return {Boolean} */ SelectorManager.prototype.getComponentFirst = function () { return this.getConfig().componentFirst; }; /** * Get all selectors * @name getAll * @function * @return {Collection<[Selector]>} * */ /** * Return escaped selector name * @param {String} name Selector name to escape * @returns {String} Escaped name * @private */ SelectorManager.prototype.escapeName = function (name) { var escapeName = this.getConfig().escapeName; return escapeName ? escapeName(name) : model_Selector.escapeName(name); }; /** * Render class selectors. If an array of selectors is provided a new instance of the collection will be rendered * @param {Array<Object>} selectors * @return {HTMLElement} * @private */ SelectorManager.prototype.render = function (selectors) { var selectorTags = this.selectorTags; var config = this.getConfig(); var el = selectorTags === null || selectorTags === void 0 ? void 0 : selectorTags.el; this.selected.reset(selectors); this.selectorTags = new view_ClassTagsView({ el: el, collection: this.selected, //@ts-ignore module: this, config: config, }); return this.selectorTags.render().el; }; SelectorManager.prototype.destroy = function () { var _a = this, selectorTags = _a.selectorTags, model = _a.model; model.stopListening(); this.__update.cancel(); this.__destroy(); selectorTags === null || selectorTags === void 0 ? void 0 : selectorTags.remove(); this.selectorTags = undefined; }; /** * Get common selectors from the current selection. * @return {Array<Selector>} * @private */ SelectorManager.prototype.__getCommon = function () { return this.__getCommonSelectors(this.em.getSelectedAll()); }; SelectorManager.prototype.__getCommonSelectors = function (components, opts) { if (opts === void 0) { opts = {}; } var selectors = components.map(function (cmp) { return cmp.getSelectors && cmp.getSelectors().getValid(opts); }).filter(Boolean); return this.__common.apply(this, selectors); }; SelectorManager.prototype.__common = function () { var _this = this; var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } if (!args.length) return []; if (args.length === 1) return args[0]; if (args.length === 2) return args[0].filter(function (item) { return args[1].indexOf(item) >= 0; }); return (args .slice(1) //@ts-ignore .reduce(function (acc, item) { return _this.__common(acc, item); }, args[0])); }; SelectorManager.prototype.__updateSelectedByComponents = function () { this.selected.reset(this.__getCommon()); }; return SelectorManager; }(ItemManagerModule)); /* harmony default export */ const selector_manager = (SelectorManager); ;// CONCATENATED MODULE: ./src/parser/config/config.ts var parser_config_config_config = { textTags: ['br', 'b', 'i', 'u', 'a', 'ul', 'ol'], parserCss: undefined, parserHtml: undefined, optionsHtml: { htmlType: 'text/html', allowScripts: false, allowUnsafeAttr: false, keepEmptyTextNodes: false, }, }; /* harmony default export */ const parser_config_config = (parser_config_config_config); ;// CONCATENATED MODULE: ./src/parser/model/BrowserParserCss.ts var _a; /** @see https://developer.mozilla.org/en-US/docs/Web/API/CSSRule/type */ var CSS_RULE_TYPES = { STYLE_RULE: 1, CHARSET_RULE: 2, IMPORT_RULE: 3, MEDIA_RULE: 4, FONT_FACE_RULE: 5, PAGE_RULE: 6, KEYFRAMES_RULE: 7, KEYFRAME_RULE: 8, NAMESPACE_RULE: 10, COUNTER_STYLE_RULE: 11, SUPPORTS_RULE: 12, DOCUMENT_RULE: 13, FONT_FEATURE_VALUES_RULE: 14, VIEWPORT_RULE: 15, REGION_STYLE_RULE: 16, }; /** @see https://developer.mozilla.org/en-US/docs/Web/CSS/At-rule */ var AT_RULE_NAMES = (_a = {}, _a[CSS_RULE_TYPES.MEDIA_RULE] = 'media', _a[CSS_RULE_TYPES.FONT_FACE_RULE] = 'font-face', _a[CSS_RULE_TYPES.PAGE_RULE] = 'page', _a[CSS_RULE_TYPES.KEYFRAMES_RULE] = 'keyframes', _a[CSS_RULE_TYPES.COUNTER_STYLE_RULE] = 'counter-style', _a[CSS_RULE_TYPES.SUPPORTS_RULE] = 'supports', _a[CSS_RULE_TYPES.DOCUMENT_RULE] = 'document', _a[CSS_RULE_TYPES.FONT_FEATURE_VALUES_RULE] = 'font-feature-values', _a[CSS_RULE_TYPES.VIEWPORT_RULE] = 'viewport', _a); var AT_RULE_KEYS = (0,index_all.keys)(AT_RULE_NAMES); var SINGLE_AT_RULE_TYPES = [ CSS_RULE_TYPES.FONT_FACE_RULE, CSS_RULE_TYPES.PAGE_RULE, CSS_RULE_TYPES.COUNTER_STYLE_RULE, CSS_RULE_TYPES.VIEWPORT_RULE, ]; var NESTABLE_AT_RULE_NAMES = AT_RULE_KEYS.filter(function (i) { return SINGLE_AT_RULE_TYPES.indexOf(Number(i)) < 0; }) .map(function (i) { return AT_RULE_NAMES[i]; }) .concat(['container', 'layer']); var SINGLE_AT_RULE_NAMES = SINGLE_AT_RULE_TYPES.map(function (n) { return AT_RULE_NAMES[n]; }); /** * Parse selector string to array. * Only classe based are valid as CSS rules inside editor, not valid * selectors will be dropped as additional * It's ok with the last part of the string as state (:hover, :active) * @param {string} str Selectors string * @return {Object} * @example * var res = parseSelector('.test1, .test1.test2, .test2 .test3'); * console.log(res); * // { result: [['test1'], ['test1', 'test2']], add: ['.test2 .test3'] } */ var parseSelector = function (str) { if (str === void 0) { str = ''; } var add = []; var result = []; var sels = str.split(','); for (var i = 0, len = sels.length; i < len; i++) { var sel = sels[i].trim(); // Will accept only concatenated classes and last // class might be with state (eg. :hover), nothing else. // Can also accept SINGLE ID selectors, eg. `#myid`, `#myid:hover` // Composed are not valid: `#myid.some-class`, `#myid.some-class:hover` if (/^(\.{1}[\w\-]+)+(:{1,2}[\w\-()]+)?$/gi.test(sel) || /^(#{1}[\w\-]+){1}(:{1,2}[\w\-()]+)?$/gi.test(sel)) { var cls = sel.split('.').filter(Boolean); result.push(cls); } else { add.push(sel); } } return { result: result, add: add, }; }; /** * Parse style declarations of the node. * @param {CSSRule} node * @return {Object} */ var parseStyle = function (node) { var stl = node.style; var style = {}; for (var i = 0, len = stl.length; i < len; i++) { var propName = stl[i]; var propValue = stl.getPropertyValue(propName); var important = stl.getPropertyPriority(propName); style[propName] = "".concat(propValue).concat(important ? " !".concat(important) : ''); } return style; }; /** * Get the condition when possible * @param {CSSRule} node * @return {string} */ var parseCondition = function (node) { // @ts-ignore var condition = node.conditionText || (node.media && node.media.mediaText) || node.name || node.selectorText || ''; return condition.trim(); }; /** * Create node for the editor * @param {Array<String>} selectors Array containing strings of classes * @param {Object} style Key-value object of style declarations * @return {Object} */ var createNode = function (selectors, style, opts) { if (style === void 0) { style = {}; } if (opts === void 0) { opts = {}; } var node = {}; var selLen = selectors.length; var lastClass = selectors[selLen - 1]; var stateArr = lastClass ? lastClass.split(/:(.+)/) : []; var state = stateArr[1]; // @ts-ignore var atRule = opts.atRule, selectorsAdd = opts.selectorsAdd, mediaText = opts.mediaText; var singleAtRule = SINGLE_AT_RULE_NAMES.indexOf(atRule) >= 0; singleAtRule && (node.singleAtRule = true); atRule && (node.atRuleType = atRule); selectorsAdd && (node.selectorsAdd = selectorsAdd); mediaText && (node.mediaText = mediaText); // Isolate the state from selectors if (state) { selectors[selLen - 1] = stateArr[0]; node.state = state; stateArr.splice(stateArr.length - 1, 1); } node.selectors = selectors; node.style = style; return node; }; var getNestableAtRule = function (node) { var _a = node.cssText, cssText = _a === void 0 ? '' : _a; return NESTABLE_AT_RULE_NAMES.find(function (name) { return cssText.indexOf("@".concat(name)) === 0; }); }; /** * Fetch data from node * @param {StyleSheet|CSSRule} el * @return {Array<Object>} */ var parseNode = function (el) { var result = []; var nodes = el.cssRules || []; for (var i = 0, len = nodes.length; i < len; i++) { var node = nodes[i]; var type = node.type; var singleAtRule = false; var atRuleType = ''; var condition = ''; var sels = node.selectorText || node.keyText || ''; var isSingleAtRule = SINGLE_AT_RULE_TYPES.indexOf(type) >= 0; // Check if the node is an at-rule if (isSingleAtRule) { singleAtRule = true; atRuleType = AT_RULE_NAMES[type]; condition = parseCondition(node); } else if (AT_RULE_KEYS.indexOf("".concat(type)) >= 0 || (!type && getNestableAtRule(node))) { var subRules = parseNode(node); var subAtRuleType = AT_RULE_NAMES[type] || getNestableAtRule(node); condition = parseCondition(node); for (var s = 0, lens = subRules.length; s < lens; s++) { var subRule = subRules[s]; condition && (subRule.mediaText = condition); subRule.atRuleType = subAtRuleType; } result = result.concat(subRules); } if (!sels && !isSingleAtRule) continue; var style = parseStyle(node); var selsParsed = parseSelector(sels); var selsAdd = selsParsed.add; var selsArr = selsParsed.result; var lastRule = void 0; // For each group of selectors for (var k = 0, len3 = selsArr.length; k < len3; k++) { var model = createNode(selsArr[k], style, { atRule: AT_RULE_NAMES[type], }); result.push(model); lastRule = model; } // Need to push somewhere not class-based selectors, if some rule was // created will push them there, otherwise will create a new rule if (selsAdd.length) { var selsAddStr = selsAdd.join(', '); if (lastRule) { lastRule.selectorsAdd = selsAddStr; } else { var model = { selectors: [], selectorsAdd: selsAddStr, style: style, }; singleAtRule && (model.singleAtRule = singleAtRule); atRuleType && (model.atRuleType = atRuleType); condition && (model.mediaText = condition); result.push(model); } } } return result; }; /** * Parse CSS string and return the array of objects * @param {String} str CSS string * @return {Array<Object>} Array of objects for the definition of CSSRules */ /* harmony default export */ const BrowserParserCss = (function (str) { var el = document.createElement('style'); el.innerHTML = str; // There is no .sheet before adding it to the <head> document.head.appendChild(el); var sheet = el.sheet; document.head.removeChild(el); return sheet ? parseNode(sheet) : []; }); ;// CONCATENATED MODULE: ./src/parser/model/ParserCss.ts var ParserCss = function (em, config) { if (config === void 0) { config = {}; } return ({ /** * Parse CSS string to a desired model object * @param {String} input CSS string * @return {Array<Object>} */ parse: function (input) { var _this = this; var output = []; var parserCss = config.parserCss; var editor = em === null || em === void 0 ? void 0 : em.Editor; var nodes = parserCss ? parserCss(input, editor) : BrowserParserCss(input); nodes.forEach(function (node) { return (output = output.concat(_this.checkNode(node))); }); em === null || em === void 0 ? void 0 : em.trigger('parse:css', { input: input, output: output, nodes: nodes }); return output; }, /** * Check the returned node from a custom parser and transforms it to * a valid object for the CSS composer * @return {[type]} */ checkNode: function (node) { var selectors = node.selectors, style = node.style; var result = [node]; if ((0,index_all.isString)(selectors)) { var nodes_1 = []; var parsedNode = node; var selsParsed = parseSelector(selectors); var classSets = selsParsed.result; var selectorsAdd = selsParsed.add.join(', '); var opts_1 = { atRule: parsedNode.atRule, mediaText: parsedNode.params }; if (classSets.length) { classSets.forEach(function (classSet) { nodes_1.push(createNode(classSet, style, opts_1)); }); } else { nodes_1.push(createNode([], style, opts_1)); } if (selectorsAdd) { var lastNode = nodes_1[nodes_1.length - 1]; lastNode.selectorsAdd = selectorsAdd; } result = nodes_1; } return result; }, }); }; /* harmony default export */ const model_ParserCss = (ParserCss); ;// CONCATENATED MODULE: ./src/parser/index.ts var parser_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); /** * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/GrapesJS/grapesjs/blob/master/src/parser/config/config.ts) * ```js * const editor = grapesjs.init({ * parser: { * // options * } * }) * ``` * * Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance * * ```js * const { Parser } = editor; * ``` * ## Available Events * * `parse:html` - On HTML parse, an object containing the input and the output of the parser is passed as an argument * * `parse:css` - On CSS parse, an object containing the input and the output of the parser is passed as an argument * * ## Methods * * [getConfig](#getconfig) * * [parseHtml](#parsehtml) * * [parseCss](#parsecss) * * @module Parser */ var ParserModule = /** @class */ (function (_super) { parser_extends(ParserModule, _super); function ParserModule(em) { var _this = _super.call(this, em, 'Parser', parser_config_config) || this; var config = _this.config; _this.parserCss = model_ParserCss(em, config); _this.parserHtml = model_ParserHtml(em, config); return _this; } /** * Get configuration object * @name getConfig * @function * @return {Object} */ /** * Parse HTML string and return the object containing the Component Definition * @param {String} input HTML string to parse * @param {Object} [options] Options * @param {String} [options.htmlType] [HTML mime type](https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#Argument02) to parse * @param {Boolean} [options.allowScripts=false] Allow `<script>` tags * @param {Boolean} [options.allowUnsafeAttr=false] Allow unsafe HTML attributes (eg. `on*` inline event handlers) * @returns {Object} Object containing the result `{ html: ..., css: ... }` * @example * const resHtml = Parser.parseHtml(`<table><div>Hi</div></table>`, { * htmlType: 'text/html', // default * }); * // By using the `text/html`, this will fix automatically all the HTML syntax issues * // Indeed the final representation, in this case, will be `<div>Hi</div><table></table>` * const resXml = Parser.parseHtml(`<table><div>Hi</div></table>`, { * htmlType: 'application/xml', * }); * // This will preserve the original format as, from the XML point of view, is a valid format */ ParserModule.prototype.parseHtml = function (input, options) { if (options === void 0) { options = {}; } var _a = this, em = _a.em, parserHtml = _a.parserHtml; parserHtml.compTypes = (em.Components.getTypes() || {}); return parserHtml.parse(input, this.parserCss, options); }; /** * Parse CSS string and return an array of valid definition objects for CSSRules * @param {String} input CSS string to parse * @returns {Array<Object>} Array containing the result * @example * const res = Parser.parseCss('.cls { color: red }'); * // [{ ... }] */ ParserModule.prototype.parseCss = function (input) { return this.parserCss.parse(input); }; ParserModule.prototype.destroy = function () { }; return ParserModule; }(abstract_Module)); /* harmony default export */ const parser = (ParserModule); ;// CONCATENATED MODULE: ./src/storage_manager/config/config.ts var storage_manager_config_config_config = { id: 'gjs-', type: 'local', autosave: true, autoload: true, stepsBeforeSave: 1, recovery: false, onStore: function (data) { return data; }, onLoad: function (data) { return data; }, options: { local: { key: 'gjsProject', checkLocal: true, }, remote: { headers: {}, urlStore: '', urlLoad: '', contentTypeJson: true, fetchOptions: '', credentials: 'include', onStore: function (data) { return data; }, onLoad: function (result) { return result; }, }, }, }; /* harmony default export */ const storage_manager_config_config = (storage_manager_config_config_config); ;// CONCATENATED MODULE: ./src/storage_manager/model/LocalStorage.ts var LocalStorage_awaiter = ( false) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var LocalStorage_generator = ( false) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var LocalStorage = /** @class */ (function () { function LocalStorage() { } LocalStorage.prototype.store = function (data, opts) { if (opts === void 0) { opts = {}; } return LocalStorage_awaiter(this, void 0, void 0, function () { return LocalStorage_generator(this, function (_a) { if (this.hasLocal(opts, true)) { localStorage.setItem(opts.key, JSON.stringify(data)); } return [2 /*return*/, data]; }); }); }; LocalStorage.prototype.load = function (opts) { if (opts === void 0) { opts = {}; } return LocalStorage_awaiter(this, void 0, void 0, function () { var result; return LocalStorage_generator(this, function (_a) { result = {}; if (this.hasLocal(opts, true)) { result = JSON.parse(localStorage.getItem(opts.key) || '{}'); } return [2 /*return*/, result]; }); }); }; LocalStorage.prototype.hasLocal = function (opts, thr) { if (opts === void 0) { opts = {}; } if (opts.checkLocal && (!(0,mixins.hasWin)() || !localStorage)) { if (thr) throw new Error('localStorage not available'); return false; } return true; }; return LocalStorage; }()); /* harmony default export */ const model_LocalStorage = (LocalStorage); ;// CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/typeof.js function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } ;// CONCATENATED MODULE: ./node_modules/promise-polyfill/src/finally.js /** * @this {Promise} */ function finallyConstructor(callback) { var constructor = this.constructor; return this.then(function (value) { // @ts-ignore return constructor.resolve(callback()).then(function () { return value; }); }, function (reason) { // @ts-ignore return constructor.resolve(callback()).then(function () { // @ts-ignore return constructor.reject(reason); }); }); } /* harmony default export */ const src_finally = (finallyConstructor); ;// CONCATENATED MODULE: ./node_modules/promise-polyfill/src/allSettled.js function allSettled(arr) { var P = this; return new P(function (resolve, reject) { if (!(arr && typeof arr.length !== 'undefined')) { return reject(new TypeError(_typeof(arr) + ' ' + arr + ' is not iterable(cannot read property Symbol(Symbol.iterator))')); } var args = Array.prototype.slice.call(arr); if (args.length === 0) return resolve([]); var remaining = args.length; function res(i, val) { if (val && (_typeof(val) === 'object' || typeof val === 'function')) { var then = val.then; if (typeof then === 'function') { then.call(val, function (val) { res(i, val); }, function (e) { args[i] = { status: 'rejected', reason: e }; if (--remaining === 0) { resolve(args); } }); return; } } args[i] = { status: 'fulfilled', value: val }; if (--remaining === 0) { resolve(args); } } for (var i = 0; i < args.length; i++) { res(i, args[i]); } }); } /* harmony default export */ const src_allSettled = (allSettled); ;// CONCATENATED MODULE: ./node_modules/promise-polyfill/src/any.js /** * @constructor */ function AggregateError(errors, message) { this.name = 'AggregateError', this.errors = errors; this.message = message || ''; } AggregateError.prototype = Error.prototype; function any(arr) { var P = this; return new P(function (resolve, reject) { if (!(arr && typeof arr.length !== 'undefined')) { return reject(new TypeError('Promise.any accepts an array')); } var args = Array.prototype.slice.call(arr); if (args.length === 0) return reject(); var rejectionReasons = []; for (var i = 0; i < args.length; i++) { try { P.resolve(args[i]).then(resolve).catch(function (error) { rejectionReasons.push(error); if (rejectionReasons.length === args.length) { reject(new AggregateError(rejectionReasons, 'All promises were rejected')); } }); } catch (ex) { reject(ex); } } }); } /* harmony default export */ const src_any = (any); ;// CONCATENATED MODULE: ./node_modules/promise-polyfill/src/index.js // Store setTimeout reference so promise-polyfill will be unaffected by // other code modifying setTimeout (like sinon.useFakeTimers()) var setTimeoutFunc = setTimeout; function isArray(x) { return Boolean(x && typeof x.length !== 'undefined'); } function noop() {} // Polyfill for Function.prototype.bind function bind(fn, thisArg) { return function () { fn.apply(thisArg, arguments); }; } /** * @constructor * @param {Function} fn */ function src_Promise(fn) { if (!(this instanceof src_Promise)) throw new TypeError('Promises must be constructed via new'); if (typeof fn !== 'function') throw new TypeError('not a function'); /** @type {!number} */ this._state = 0; /** @type {!boolean} */ this._handled = false; /** @type {Promise|undefined} */ this._value = undefined; /** @type {!Array<!Function>} */ this._deferreds = []; doResolve(fn, this); } function handle(self, deferred) { while (self._state === 3) { self = self._value; } if (self._state === 0) { self._deferreds.push(deferred); return; } self._handled = true; src_Promise._immediateFn(function () { var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected; if (cb === null) { (self._state === 1 ? resolve : reject)(deferred.promise, self._value); return; } var ret; try { ret = cb(self._value); } catch (e) { reject(deferred.promise, e); return; } resolve(deferred.promise, ret); }); } function resolve(self, newValue) { try { // Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure if (newValue === self) throw new TypeError('A promise cannot be resolved with itself.'); if (newValue && (_typeof(newValue) === 'object' || typeof newValue === 'function')) { var then = newValue.then; if (newValue instanceof src_Promise) { self._state = 3; self._value = newValue; finale(self); return; } else if (typeof then === 'function') { doResolve(bind(then, newValue), self); return; } } self._state = 1; self._value = newValue; finale(self); } catch (e) { reject(self, e); } } function reject(self, newValue) { self._state = 2; self._value = newValue; finale(self); } function finale(self) { if (self._state === 2 && self._deferreds.length === 0) { src_Promise._immediateFn(function () { if (!self._handled) { src_Promise._unhandledRejectionFn(self._value); } }); } for (var i = 0, len = self._deferreds.length; i < len; i++) { handle(self, self._deferreds[i]); } self._deferreds = null; } /** * @constructor */ function Handler(onFulfilled, onRejected, promise) { this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null; this.onRejected = typeof onRejected === 'function' ? onRejected : null; this.promise = promise; } /** * Take a potentially misbehaving resolver function and make sure * onFulfilled and onRejected are only called once. * * Makes no guarantees about asynchrony. */ function doResolve(fn, self) { var done = false; try { fn(function (value) { if (done) return; done = true; resolve(self, value); }, function (reason) { if (done) return; done = true; reject(self, reason); }); } catch (ex) { if (done) return; done = true; reject(self, ex); } } src_Promise.prototype['catch'] = function (onRejected) { return this.then(null, onRejected); }; src_Promise.prototype.then = function (onFulfilled, onRejected) { // @ts-ignore var prom = new this.constructor(noop); handle(this, new Handler(onFulfilled, onRejected, prom)); return prom; }; src_Promise.prototype['finally'] = src_finally; src_Promise.all = function (arr) { return new src_Promise(function (resolve, reject) { if (!isArray(arr)) { return reject(new TypeError('Promise.all accepts an array')); } var args = Array.prototype.slice.call(arr); if (args.length === 0) return resolve([]); var remaining = args.length; function res(i, val) { try { if (val && (_typeof(val) === 'object' || typeof val === 'function')) { var then = val.then; if (typeof then === 'function') { then.call(val, function (val) { res(i, val); }, reject); return; } } args[i] = val; if (--remaining === 0) { resolve(args); } } catch (ex) { reject(ex); } } for (var i = 0; i < args.length; i++) { res(i, args[i]); } }); }; src_Promise.any = src_any; src_Promise.allSettled = src_allSettled; src_Promise.resolve = function (value) { if (value && _typeof(value) === 'object' && value.constructor === src_Promise) { return value; } return new src_Promise(function (resolve) { resolve(value); }); }; src_Promise.reject = function (value) { return new src_Promise(function (resolve, reject) { reject(value); }); }; src_Promise.race = function (arr) { return new src_Promise(function (resolve, reject) { if (!isArray(arr)) { return reject(new TypeError('Promise.race accepts an array')); } for (var i = 0, len = arr.length; i < len; i++) { src_Promise.resolve(arr[i]).then(resolve, reject); } }); }; // Use polyfill for setImmediate for performance gains src_Promise._immediateFn = // @ts-ignore typeof setImmediate === 'function' && function (fn) { // @ts-ignore setImmediate(fn); } || function (fn) { setTimeoutFunc(fn, 0); }; src_Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) { if (typeof console !== 'undefined' && console) { console.warn('Possible Unhandled Promise Rejection:', err); // eslint-disable-line no-console } }; /* harmony default export */ const src = (src_Promise); ;// CONCATENATED MODULE: ./src/utils/fetch.ts // @ts-ignore avoid errors during TS build if ((0,mixins.hasWin)()) { window.Promise = window.Promise || src; } /* harmony default export */ const utils_fetch = (typeof fetch == 'function' ? // @ts-ignore fetch.bind() : function (url, options) { // @ts-ignore avoid errors during TS build return new src(function (res, rej) { var req = new XMLHttpRequest(); req.open(options.method || 'get', url); req.withCredentials = options.credentials == 'include'; for (var k in options.headers || {}) { req.setRequestHeader(k, options.headers[k]); } req.onload = function (e) { return res({ status: req.status, statusText: req.statusText, text: function () { return src.resolve(req.responseText); }, }); }; req.onerror = rej; // Actually, fetch doesn't support onProgress feature if (req.upload && options.onProgress) { req.upload.onprogress = options.onProgress; } // Include body only if present options.body ? req.send(options.body) : req.send(); }); }); ;// CONCATENATED MODULE: ./src/storage_manager/model/RemoteStorage.ts var RemoteStorage_assign = ( false) || function () { RemoteStorage_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return RemoteStorage_assign.apply(this, arguments); }; var RemoteStorage_awaiter = ( false) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var RemoteStorage_generator = ( false) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var RemoteStorage = /** @class */ (function () { function RemoteStorage() { } RemoteStorage.prototype.store = function (data, opts) { if (opts === void 0) { opts = {}; } return RemoteStorage_awaiter(this, void 0, void 0, function () { return RemoteStorage_generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.request(opts.urlStore, this.__props(opts, data), opts)]; case 1: return [2 /*return*/, _a.sent()]; } }); }); }; RemoteStorage.prototype.load = function (opts) { if (opts === void 0) { opts = {}; } return RemoteStorage_awaiter(this, void 0, void 0, function () { return RemoteStorage_generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.request(opts.urlLoad, this.__props(opts), opts)]; case 1: return [2 /*return*/, _a.sent()]; } }); }); }; RemoteStorage.prototype.request = function (url, props, opts) { if (props === void 0) { props = {}; } if (opts === void 0) { opts = {}; } return utils_fetch(url, props) .then(function (res) { var result = res.text(); var isOk = ((res.status / 200) | 0) === 1; return isOk ? result : result.then(Promise.reject); }) .then(function (text) { var parsable = text && (0,index_all.isString)(text); return opts.contentTypeJson && parsable ? JSON.parse(text) : text; }); }; RemoteStorage.prototype.__props = function (opts, data) { if (opts === void 0) { opts = {}; } var typeJson = opts.contentTypeJson; var headers = opts.headers || {}; var fetchOpts = opts.fetchOptions || {}; var reqHead = 'X-Requested-With'; var typeHead = 'Content-Type'; var body; if ((0,index_all.isUndefined)(headers[reqHead])) { headers[reqHead] = 'XMLHttpRequest'; } if ((0,index_all.isUndefined)(headers[typeHead]) && typeJson) { headers[typeHead] = 'application/json; charset=utf-8'; } if (data) { if (typeJson) { body = JSON.stringify(data); } else { body = new FormData(); for (var key in data) { body.append(key, data[key]); } } } var result = { method: body ? 'POST' : 'GET', credentials: opts.credentials, headers: headers, body: body, }; return RemoteStorage_assign(RemoteStorage_assign({}, result), ((0,index_all.isFunction)(fetchOpts) ? fetchOpts(result) : fetchOpts)); }; return RemoteStorage; }()); /* harmony default export */ const model_RemoteStorage = (RemoteStorage); ;// CONCATENATED MODULE: ./src/storage_manager/index.ts /** * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/GrapesJS/grapesjs/blob/master/src/storage_manager/config/config.ts) * ```js * const editor = grapesjs.init({ * storageManager: { * // options * } * }) * ``` * * Once the editor is instantiated you can use its API and listen to its events. Before using these methods, you should get the module from the instance. * * ```js * // Listen to events * editor.on('storage:start', () => { ... }); * * // Use the API * const storageManager = editor.Storage; * storageManager.add(...); * ``` * * ## Available Events * * `storage:start` - Before the storage request is started * * `storage:start:store` - Before the store request. The object to store is passed as an argument (which you can edit) * * `storage:start:load` - Before the load request. Items to load are passed as an argument (which you can edit) * * `storage:load` - Triggered when something was loaded from the storage, loaded object passed as an argument * * `storage:store` - Triggered when something is stored to the storage, stored object passed as an argument * * `storage:end` - After the storage request is ended * * `storage:end:store` - After the store request * * `storage:end:load` - After the load request * * `storage:error` - On any error on storage request, passes the error as an argument * * `storage:error:store` - Error on store request, passes the error as an argument * * `storage:error:load` - Error on load request, passes the error as an argument * * ## Methods * * [getConfig](#getconfig) * * [isAutosave](#isautosave) * * [setAutosave](#setautosave) * * [getStepsBeforeSave](#getstepsbeforesave) * * [setStepsBeforeSave](#setstepsbeforesave) * * [getStorages](#getstorages) * * [getCurrent](#getcurrent) * * [getCurrentStorage](#getcurrentstorage) * * [setCurrent](#setcurrent) * * [getStorageOptions](#getstorageoptions) * * [add](#add) * * [get](#get) * * [store](#store) * * [load](#load) * * @module Storage */ var storage_manager_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var storage_manager_assign = ( false) || function () { storage_manager_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return storage_manager_assign.apply(this, arguments); }; var storage_manager_awaiter = ( false) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var storage_manager_generator = ( false) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var eventStart = 'storage:start'; var eventAfter = 'storage:after'; var eventEnd = 'storage:end'; var eventError = 'storage:error'; var STORAGE_LOCAL = 'local'; var STORAGE_REMOTE = 'remote'; var StorageManager = /** @class */ (function (_super) { storage_manager_extends(StorageManager, _super); function StorageManager(em) { var _this = _super.call(this, em, 'StorageManager', storage_manager_config_config) || this; _this.storages = {}; var config = _this.config; if (config._disable) config.type = undefined; _this.storages = {}; _this.add(STORAGE_LOCAL, new model_LocalStorage()); _this.add(STORAGE_REMOTE, new model_RemoteStorage()); _this.setCurrent(config.type); return _this; } /** * Get configuration object * @name getConfig * @function * @return {Object} */ /** * Check if autosave is enabled. * @returns {Boolean} * */ StorageManager.prototype.isAutosave = function () { return !!this.config.autosave; }; /** * Set autosave value. * @param {Boolean} value * */ StorageManager.prototype.setAutosave = function (value) { this.config.autosave = !!value; return this; }; /** * Returns number of steps required before trigger autosave. * @returns {Number} * */ StorageManager.prototype.getStepsBeforeSave = function () { return this.config.stepsBeforeSave; }; /** * Set steps required before trigger autosave. * @param {Number} value * */ StorageManager.prototype.setStepsBeforeSave = function (value) { this.config.stepsBeforeSave = value; return this; }; /** * Add new storage. * @param {String} type Storage type * @param {Object} storage Storage definition * @param {Function} storage.load Load method * @param {Function} storage.store Store method * @example * storageManager.add('local2', { * async load(storageOptions) { * // ... * }, * async store(data, storageOptions) { * // ... * }, * }); * */ StorageManager.prototype.add = function (type, storage) { this.storages[type] = storage; return this; }; /** * Return storage by type. * @param {String} type Storage type * @returns {Object|null} * */ StorageManager.prototype.get = function (type) { return this.storages[type]; }; /** * Get all storages. * @returns {Object} * */ StorageManager.prototype.getStorages = function () { return this.storages; }; /** * Get current storage type. * @returns {String} * */ StorageManager.prototype.getCurrent = function () { return this.config.currentStorage; }; /** * Set current storage type. * @param {String} type Storage type * */ StorageManager.prototype.setCurrent = function (type) { this.getConfig().currentStorage = type; return this; }; StorageManager.prototype.getCurrentStorage = function () { return this.get(this.getCurrent()); }; /** * Get storage options by type. * @param {String} type Storage type * @returns {Object} * */ StorageManager.prototype.getStorageOptions = function (type) { return this.getCurrentOptions(type); }; /** * Store data in the current storage. * @param {Object} data Project data. * @param {Object} [options] Storage options. * @returns {Object} Stored data. * @example * const data = editor.getProjectData(); * await storageManager.store(data); * */ StorageManager.prototype.store = function (data, options) { if (options === void 0) { options = {}; } return storage_manager_awaiter(this, void 0, void 0, function () { var st, opts, recovery, recoveryOpts, _a, error_1; return storage_manager_generator(this, function (_b) { switch (_b.label) { case 0: st = this.getCurrentStorage(); opts = storage_manager_assign(storage_manager_assign({}, this.getCurrentOptions()), options); recovery = this.getRecoveryStorage(); recoveryOpts = this.getCurrentOptions(STORAGE_LOCAL); _b.label = 1; case 1: _b.trys.push([1, 5, , 9]); return [4 /*yield*/, this.__exec(st, opts, data)]; case 2: _b.sent(); _a = recovery; if (!_a) return [3 /*break*/, 4]; return [4 /*yield*/, this.__exec(recovery, recoveryOpts, {})]; case 3: _a = (_b.sent()); _b.label = 4; case 4: _a; return [3 /*break*/, 9]; case 5: error_1 = _b.sent(); if (!recovery) return [3 /*break*/, 7]; return [4 /*yield*/, this.__exec(recovery, recoveryOpts, data)]; case 6: _b.sent(); return [3 /*break*/, 8]; case 7: throw error_1; case 8: return [3 /*break*/, 9]; case 9: return [2 /*return*/, data]; } }); }); }; /** * Load resource from the current storage by keys * @param {Object} [options] Storage options. * @returns {Object} Loaded data. * @example * const data = await storageManager.load(); * editor.loadProjectData(data); * */ StorageManager.prototype.load = function (options) { if (options === void 0) { options = {}; } return storage_manager_awaiter(this, void 0, void 0, function () { var st, opts, recoveryStorage, result, recoveryData, error_2; return storage_manager_generator(this, function (_a) { switch (_a.label) { case 0: st = this.getCurrentStorage(); opts = storage_manager_assign(storage_manager_assign({}, this.getCurrentOptions()), options); recoveryStorage = this.getRecoveryStorage(); if (!recoveryStorage) return [3 /*break*/, 5]; return [4 /*yield*/, this.__exec(recoveryStorage, this.getCurrentOptions(STORAGE_LOCAL))]; case 1: recoveryData = _a.sent(); if (!!(0,index_all.isEmpty)(recoveryData)) return [3 /*break*/, 5]; _a.label = 2; case 2: _a.trys.push([2, 4, , 5]); return [4 /*yield*/, this.__askRecovery()]; case 3: _a.sent(); result = recoveryData; return [3 /*break*/, 5]; case 4: error_2 = _a.sent(); return [3 /*break*/, 5]; case 5: if (!!result) return [3 /*break*/, 7]; return [4 /*yield*/, this.__exec(st, opts)]; case 6: result = _a.sent(); _a.label = 7; case 7: return [2 /*return*/, result || {}]; } }); }); }; StorageManager.prototype.__askRecovery = function () { var em = this.em; var recovery = this.getRecovery(); return new Promise(function (res, rej) { if ((0,index_all.isFunction)(recovery)) { recovery(res, rej, em === null || em === void 0 ? void 0 : em.getEditor()); } else { confirm(em === null || em === void 0 ? void 0 : em.t('storageManager.recover')) ? res(null) : rej(); } }); }; StorageManager.prototype.getRecovery = function () { return this.config.recovery; }; StorageManager.prototype.getRecoveryStorage = function () { var recovery = this.getRecovery(); return recovery && this.getCurrent() === STORAGE_REMOTE && this.get(STORAGE_LOCAL); }; StorageManager.prototype.__exec = function (storage, opts, data) { var _a; return storage_manager_awaiter(this, void 0, void 0, function () { var ev, _b, onStore, onLoad, result, editor, response, toStore, _c, _d, _e, _f, error_3; return storage_manager_generator(this, function (_g) { switch (_g.label) { case 0: ev = data ? 'store' : 'load'; _b = this.getConfig(), onStore = _b.onStore, onLoad = _b.onLoad; this.onStart(ev, data); if (!storage) { return [2 /*return*/, data || {}]; } _g.label = 1; case 1: _g.trys.push([1, 14, , 15]); editor = (_a = this.em) === null || _a === void 0 ? void 0 : _a.getEditor(); response = void 0; if (!data) return [3 /*break*/, 7]; _c = onStore; if (!_c) return [3 /*break*/, 3]; return [4 /*yield*/, onStore(data, editor)]; case 2: _c = (_g.sent()); _g.label = 3; case 3: toStore = (_c) || data; _d = opts.onStore; if (!_d) return [3 /*break*/, 5]; return [4 /*yield*/, opts.onStore(toStore, editor)]; case 4: _d = (_g.sent()); _g.label = 5; case 5: toStore = (_d) || toStore; return [4 /*yield*/, storage.store(toStore, opts)]; case 6: response = _g.sent(); result = data; return [3 /*break*/, 13]; case 7: return [4 /*yield*/, storage.load(opts)]; case 8: response = _g.sent(); result = this.__clearKeys(response); _e = opts.onLoad; if (!_e) return [3 /*break*/, 10]; return [4 /*yield*/, opts.onLoad(result, editor)]; case 9: _e = (_g.sent()); _g.label = 10; case 10: result = (_e) || result; _f = onLoad; if (!_f) return [3 /*break*/, 12]; return [4 /*yield*/, onLoad(result, editor)]; case 11: _f = (_g.sent()); _g.label = 12; case 12: result = (_f) || result; _g.label = 13; case 13: this.onAfter(ev, result, response); this.onEnd(ev, result); return [3 /*break*/, 15]; case 14: error_3 = _g.sent(); this.onError(ev, error_3); throw error_3; case 15: return [2 /*return*/, result]; } }); }); }; StorageManager.prototype.__clearKeys = function (data) { if (data === void 0) { data = {}; } var config = this.getConfig(); var reg = new RegExp("^".concat(config.id)); var result = {}; for (var itemKey in data) { var itemKeyR = itemKey.replace(reg, ''); result[itemKeyR] = data[itemKey]; } return result; }; StorageManager.prototype.getCurrentOptions = function (type) { var config = this.getConfig(); var current = type || this.getCurrent(); return config.options[current] || {}; }; /** * On start callback * @private */ StorageManager.prototype.onStart = function (ctx, data) { var em = this.em; if (em) { em.trigger(eventStart); ctx && em.trigger("".concat(eventStart, ":").concat(ctx), data); } }; /** * On after callback (before passing data to the callback) * @private */ StorageManager.prototype.onAfter = function (ctx, data, response) { var em = this.em; if (em) { em.trigger(eventAfter); em.trigger("".concat(eventAfter, ":").concat(ctx), data, response); em.trigger("storage:".concat(ctx), data, response); } }; /** * On end callback * @private */ StorageManager.prototype.onEnd = function (ctx, data) { var em = this.em; if (em) { em.trigger(eventEnd); ctx && em.trigger("".concat(eventEnd, ":").concat(ctx), data); } }; /** * On error callback * @private */ StorageManager.prototype.onError = function (ctx, data) { var em = this.em; if (em) { em.trigger(eventError, data); ctx && em.trigger("".concat(eventError, ":").concat(ctx), data); this.onEnd(ctx, data); } }; /** * Check if autoload is possible * @return {Boolean} * @private * */ StorageManager.prototype.canAutoload = function () { var storage = this.getCurrentStorage(); return !!storage && !!this.config.autoload; }; StorageManager.prototype.destroy = function () { this.storages = {}; }; return StorageManager; }(abstract_Module)); /* harmony default export */ const storage_manager = (StorageManager); ;// CONCATENATED MODULE: ./src/trait_manager/config/config.ts var trait_manager_config_config_config = { stylePrefix: 'trt-', appendTo: '', optionsTarget: [{ value: false }, { value: '_blank' }], custom: false, }; /* harmony default export */ const trait_manager_config_config = (trait_manager_config_config_config); // EXTERNAL MODULE: ./src/domain_abstract/view/DomainViews.ts var DomainViews = __nested_webpack_require_911993__(330); ;// CONCATENATED MODULE: ./src/trait_manager/view/TraitView.ts var TraitView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var TraitView_assign = ( false) || function () { TraitView_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return TraitView_assign.apply(this, arguments); }; var TraitView = /** @class */ (function (_super) { TraitView_extends(TraitView, _super); function TraitView(o) { if (o === void 0) { o = {}; } var _this = _super.call(this, o) || this; _this.events = {}; _this.appendInput = true; var _a = o.config, config = _a === void 0 ? {} : _a; var _b = _this, model = _b.model, eventCapture = _b.eventCapture; var target = model.target; var type = model.attributes.type; _this.config = config; _this.em = config.em; _this.ppfx = config.pStylePrefix || ''; _this.pfx = _this.ppfx + config.stylePrefix || ''; _this.target = target; var ppfx = _this.ppfx; _this.clsField = "".concat(ppfx, "field ").concat(ppfx, "field-").concat(type); var evToListen = [ ['change:value', _this.onValueChange], ['remove', _this.removeView], ]; evToListen.forEach(function (_a) { var event = _a[0], clb = _a[1]; model.off(event, clb); _this.listenTo(model, event, clb); }); model.view = _this; _this.listenTo(model, 'change:label', _this.render); _this.listenTo(model, 'change:placeholder', _this.rerender); _this.events = {}; eventCapture.forEach(function (event) { return (_this.events[event] = 'onChange'); }); _this.delegateEvents(); _this.init(); return _this; } /** @ts-ignore */ TraitView.prototype.attributes = function () { return this.model.get('attributes') || {}; }; TraitView.prototype.templateLabel = function (cmp) { var ppfx = this.ppfx; var label = this.getLabel(); return "<div class=\"".concat(ppfx, "label\" title=\"").concat(label, "\">").concat(label, "</div>"); }; TraitView.prototype.templateInput = function (data) { var clsField = this.clsField; return "<div class=\"".concat(clsField, "\" data-input></div>"); }; TraitView.prototype.getClbOpts = function () { return { component: this.target, trait: this.model, elInput: this.getInputElem(), }; }; TraitView.prototype.removeView = function () { this.remove(); this.removed(); }; TraitView.prototype.init = function () { }; TraitView.prototype.removed = function () { }; TraitView.prototype.onRender = function (props) { }; TraitView.prototype.onUpdate = function (props) { }; TraitView.prototype.onEvent = function (props) { }; /** * Fires when the input is changed * @private */ TraitView.prototype.onChange = function (event) { var el = this.getInputElem(); if (el && !(0,index_all.isUndefined)(el.value)) { this.model.set('value', el.value); } this.onEvent(TraitView_assign(TraitView_assign({}, this.getClbOpts()), { event: event })); }; TraitView.prototype.getValueForTarget = function () { return this.model.get('value'); }; TraitView.prototype.setInputValue = function (value) { var el = this.getInputElem(); el && (el.value = value); }; /** * On change callback * @private */ TraitView.prototype.onValueChange = function (model, value, opts) { if (opts === void 0) { opts = {}; } if (opts.fromTarget) { this.setInputValue(model.get('value')); this.postUpdate(); } else { var val = this.getValueForTarget(); model.setTargetValue(val, opts); } }; /** * Render label * @private */ TraitView.prototype.renderLabel = function () { var _a = this, $el = _a.$el, target = _a.target; var label = this.getLabel(); var tpl = this.templateLabel(target); if (this.createLabel) { tpl = this.createLabel({ label: label, component: target, trait: this, }) || ''; } $el.find('[data-label]').append(tpl); }; /** * Returns label for the input * @return {string} * @private */ TraitView.prototype.getLabel = function () { var em = this.em; var _a = this.model.attributes, label = _a.label, name = _a.name; return em.t("traitManager.traits.labels.".concat(name)) || (0,mixins.capitalize)(label || name).replace(/-/g, ' '); }; /** * Returns current target component */ TraitView.prototype.getComponent = function () { return this.target; }; /** * Returns input element * @return {HTMLElement} * @private */ TraitView.prototype.getInputEl = function () { if (!this.$input) { var _a = this, em = _a.em, model = _a.model; var md = model; var name_1 = model.attributes.name; var placeholder = md.get('placeholder') || md.get('default') || ''; var type = md.get('type') || 'text'; var min = md.get('min'); var max = md.get('max'); var value = this.getModelValue(); var input = (0,cash_dom["default"])("<input type=\"".concat(type, "\">")); var i18nAttr = em.t("traitManager.traits.attributes.".concat(name_1)) || {}; input.attr(TraitView_assign({ placeholder: placeholder }, i18nAttr)); if (!(0,index_all.isUndefined)(value)) { md.set({ value: value }, { silent: true }); input.prop('value', value); } if (min) { input.prop('min', min); } if (max) { input.prop('max', max); } this.$input = input; } return this.$input.get(0); }; TraitView.prototype.getInputElem = function () { var _a = this, input = _a.input, $input = _a.$input; return input || ($input && $input.get && $input.get(0)) || this.getElInput(); }; TraitView.prototype.getModelValue = function () { var value; var model = this.model; var target = this.target; var name = model.getName(); if (model.get('changeProp')) { value = target.get(name); } else { var attrs = target.get('attributes'); value = model.get('value') || attrs[name]; } return !(0,index_all.isUndefined)(value) ? value : ''; }; TraitView.prototype.getElInput = function () { return this.elInput; }; /** * Renders input * @private * */ TraitView.prototype.renderField = function () { var _a = this, $el = _a.$el, appendInput = _a.appendInput, model = _a.model; var inputs = $el.find('[data-input]'); var el = inputs[inputs.length - 1]; var tpl = model.el; if (!tpl) { tpl = this.createInput ? this.createInput(this.getClbOpts()) : this.getInputEl(); } if ((0,index_all.isString)(tpl)) { el.innerHTML = tpl; this.elInput = el.firstChild; } else { appendInput ? el.appendChild(tpl) : el.insertBefore(tpl, el.firstChild); this.elInput = tpl; } model.el = this.elInput; }; TraitView.prototype.hasLabel = function () { var label = this.model.attributes.label; return !this.noLabel && label !== false; }; TraitView.prototype.rerender = function () { delete this.model.el; this.render(); }; TraitView.prototype.postUpdate = function () { this.onUpdate(this.getClbOpts()); }; TraitView.prototype.render = function () { var _a = this, $el = _a.$el, pfx = _a.pfx, ppfx = _a.ppfx, model = _a.model; var _b = model.attributes, type = _b.type, id = _b.id; var hasLabel = this.hasLabel && this.hasLabel(); var cls = "".concat(pfx, "trait"); delete this.$input; var tmpl = "<div class=\"".concat(cls, " ").concat(cls, "--").concat(type, "\">\n ").concat(hasLabel ? "<div class=\"".concat(ppfx, "label-wrp\" data-label></div>") : '', "\n <div class=\"").concat(ppfx, "field-wrp ").concat(ppfx, "field-wrp--").concat(type, "\" data-input>\n ").concat(this.templateInput ? (0,index_all.isFunction)(this.templateInput) ? this.templateInput(this.getClbOpts()) : this.templateInput : '', "\n </div>\n </div>"); $el.empty().append(tmpl); hasLabel && this.renderLabel(); this.renderField(); this.el.className = "".concat(cls, "__wrp ").concat(cls, "__wrp-").concat(id); this.postUpdate(); this.onRender(this.getClbOpts()); return this; }; return TraitView; }(common/* View */.G7)); /* harmony default export */ const view_TraitView = (TraitView); TraitView.prototype.eventCapture = ['change']; ;// CONCATENATED MODULE: ./src/trait_manager/view/TraitsView.ts var TraitsView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var TraitsView = /** @class */ (function (_super) { TraitsView_extends(TraitsView, _super); function TraitsView(o, itemsView) { if (o === void 0) { o = {}; } var _this = _super.call(this, o) || this; _this.reuseView = true; _this.itemsView = itemsView; var config = o.config || {}; var em = o.editor; _this.config = config; _this.em = em; _this.ppfx = config.pStylePrefix || ''; _this.pfx = _this.ppfx + config.stylePrefix || ''; _this.className = "".concat(_this.pfx, "traits"); _this.listenTo(em, 'component:toggled', _this.updatedCollection); _this.updatedCollection(); return _this; } /** * Update view collection * @private */ TraitsView.prototype.updatedCollection = function () { var _a = this, ppfx = _a.ppfx, className = _a.className, em = _a.em; var comp = em.getSelected(); this.el.className = "".concat(className, " ").concat(ppfx, "one-bg ").concat(ppfx, "two-color"); // @ts-ignore this.collection = comp ? comp.traits : []; this.render(); }; return TraitsView; }(DomainViews/* default */.Z)); /* harmony default export */ const view_TraitsView = (TraitsView); // @ts-ignore TraitsView.prototype.itemView = view_TraitView; ;// CONCATENATED MODULE: ./src/trait_manager/view/TraitSelectView.ts var TraitSelectView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var TraitSelectView = /** @class */ (function (_super) { TraitSelectView_extends(TraitSelectView, _super); function TraitSelectView(o) { if (o === void 0) { o = {}; } var _this = _super.call(this, o) || this; _this.listenTo(_this.model, 'change:options', _this.rerender); return _this; } TraitSelectView.prototype.templateInput = function () { var _a = this, ppfx = _a.ppfx, clsField = _a.clsField; return "<div class=\"".concat(clsField, "\">\n <div data-input></div>\n <div class=\"").concat(ppfx, "sel-arrow\">\n <div class=\"").concat(ppfx, "d-s-arrow\"></div>\n </div>\n </div>"); }; /** * Returns input element * @return {HTMLElement} * @private */ TraitSelectView.prototype.getInputEl = function () { if (!this.$input) { var _a = this, model = _a.model, em_1 = _a.em; var propName_1 = model.get('name'); var opts = model.get('options') || []; var values_1 = []; var input_1 = '<select>'; opts.forEach(function (el) { var attrs = ''; var name, value, style; if ((0,index_all.isString)(el)) { name = el; value = el; } else { name = el.name || el.label || el.value; value = "".concat((0,index_all.isUndefined)(el.value) ? el.id : el.value).replace(/"/g, '"'); style = el.style ? el.style.replace(/"/g, '"') : ''; attrs += style ? " style=\"".concat(style, "\"") : ''; } var resultName = em_1.t("traitManager.traits.options.".concat(propName_1, ".").concat(value)) || name; input_1 += "<option value=\"".concat(value, "\"").concat(attrs, ">").concat(resultName, "</option>"); values_1.push(value); }); input_1 += '</select>'; this.$input = (0,cash_dom["default"])(input_1); var val = model.getTargetValue(); var valResult = values_1.indexOf(val) >= 0 ? val : model.get('default'); !(0,index_all.isUndefined)(valResult) && this.$input.val(valResult); } return this.$input.get(0); }; return TraitSelectView; }(view_TraitView)); /* harmony default export */ const view_TraitSelectView = (TraitSelectView); ;// CONCATENATED MODULE: ./src/trait_manager/view/TraitCheckboxView.ts var TraitCheckboxView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var TraitCheckboxView = /** @class */ (function (_super) { TraitCheckboxView_extends(TraitCheckboxView, _super); function TraitCheckboxView() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.appendInput = false; return _this; } TraitCheckboxView.prototype.templateInput = function () { var _a = this, ppfx = _a.ppfx, clsField = _a.clsField; return "<label class=\"".concat(clsField, "\" data-input>\n <i class=\"").concat(ppfx, "chk-icon\"></i>\n </label>"); }; /** * Fires when the input is changed * @private */ TraitCheckboxView.prototype.onChange = function () { this.model.set('value', this.getInputElem().checked); }; TraitCheckboxView.prototype.setInputValue = function (value) { var el = this.getInputElem(); el && (el.checked = !!value); }; /** * Returns input element * @return {HTMLElement} * @private */ TraitCheckboxView.prototype.getInputEl = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var toInit = !this.$input; var el = view_TraitView.prototype.getInputEl.apply(this, args); if (toInit) { var checked = void 0, targetValue = void 0; var _a = this, model = _a.model, target = _a.target; var valueFalse = model.attributes.valueFalse; var name_1 = model.getName(); if (model.get('changeProp')) { checked = target.get(name_1); targetValue = checked; } else { targetValue = target.get('attributes')[name_1]; checked = targetValue || targetValue === '' ? !0 : !1; } if (!(0,index_all.isUndefined)(valueFalse) && targetValue === valueFalse) { checked = !1; } el.checked = checked; } return el; }; return TraitCheckboxView; }(view_TraitView)); /* harmony default export */ const view_TraitCheckboxView = (TraitCheckboxView); ;// CONCATENATED MODULE: ./src/domain_abstract/ui/Input.ts var Input_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var Input = /** @class */ (function (_super) { Input_extends(Input, _super); function Input(opts) { if (opts === void 0) { opts = {}; } var _this = _super.call(this, opts) || this; var ppfx = opts.ppfx || ''; _this.opts = opts; _this.ppfx = ppfx; _this.em = opts.target || {}; !opts.onChange && _this.listenTo(_this.model, 'change:value', _this.handleModelChange); return _this; } Input.prototype.template = function () { return "<span class=\"".concat(this.holderClass(), "\"></span>"); }; Input.prototype.inputClass = function () { return "".concat(this.ppfx, "field"); }; Input.prototype.holderClass = function () { return "".concat(this.ppfx, "input-holder"); }; /** * Fired when the element of the property is updated */ Input.prototype.elementUpdated = function () { this.model.trigger('el:change'); }; /** * Set value to the input element * @param {string} value */ Input.prototype.setValue = function (value, opts) { var model = this.model; var val = value || model.get('defaults'); var input = this.getInputEl(); input && (input.value = val); }; /** * Updates the view when the model is changed * */ Input.prototype.handleModelChange = function (model, value, opts) { this.setValue(value, opts); }; /** * Handled when the view is changed */ Input.prototype.handleChange = function (e) { e.stopPropagation(); var value = this.getInputEl().value; this.__onInputChange(value); this.elementUpdated(); }; Input.prototype.__onInputChange = function (value) { this.model.set({ value: value }, { fromInput: 1 }); }; /** * Get the input element * @return {HTMLElement} */ Input.prototype.getInputEl = function () { if (!this.inputEl) { var _a = this, model = _a.model, opts = _a.opts; var type = opts.type || 'text'; var plh = model.get('placeholder') || model.get('defaults') || model.get('default') || ''; this.inputEl = (0,cash_dom["default"])("<input type=\"".concat(type, "\" placeholder=\"").concat(plh, "\">")); } return this.inputEl.get(0); }; Input.prototype.render = function () { this.inputEl = null; var el = this.$el; el.addClass(this.inputClass()); el.html(this.template()); el.find(".".concat(this.holderClass())).append(this.getInputEl()); return this; }; return Input; }(common/* View */.G7)); /* harmony default export */ const ui_Input = (Input); Input.prototype.events = { // @ts-ignore change: 'handleChange', }; ;// CONCATENATED MODULE: ./src/domain_abstract/ui/InputNumber.ts var InputNumber_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var InputNumber = /** @class */ (function (_super) { InputNumber_extends(InputNumber, _super); function InputNumber(opts) { if (opts === void 0) { opts = {}; } var _this = _super.call(this, opts) || this; (0,index_all.bindAll)(_this, 'moveIncrement', 'upIncrement'); _this.doc = document; _this.listenTo(_this.model, 'change:unit', _this.handleModelChange); return _this; } InputNumber.prototype.template = function () { var ppfx = this.ppfx; return "\n <span class=\"".concat(ppfx, "input-holder\"></span>\n <span class=\"").concat(ppfx, "field-units\"></span>\n <div class=\"").concat(ppfx, "field-arrows\" data-arrows>\n <div class=\"").concat(ppfx, "field-arrow-u\" data-arrow-up></div>\n <div class=\"").concat(ppfx, "field-arrow-d\" data-arrow-down></div>\n </div>\n "); }; InputNumber.prototype.inputClass = function () { var ppfx = this.ppfx; return this.opts.contClass || "".concat(ppfx, "field ").concat(ppfx, "field-integer"); }; /** * Set value to the model * @param {string} value * @param {Object} opts */ InputNumber.prototype.setValue = function (value, opts) { var opt = opts || {}; var valid = this.validateInputValue(value, { deepCheck: 1 }); var validObj = { value: valid.value, unit: '' }; // If found some unit value if (valid.unit || valid.force) { validObj.unit = valid.unit; } this.model.set(validObj, opt); // Generally I get silent when I need to reflect data to view without // reupdating the target if (opt.silent) { this.handleModelChange(); } }; /** * Handled when the view is changed */ InputNumber.prototype.handleChange = function (e) { e.stopPropagation(); this.setValue(this.getInputEl().value); this.elementUpdated(); }; /** * Handled when the view is changed */ InputNumber.prototype.handleUnitChange = function (e) { e.stopPropagation(); var value = this.getUnitEl().value; this.model.set('unit', value); this.elementUpdated(); }; /** * Handled when user uses keyboard */ InputNumber.prototype.handleKeyDown = function (e) { if (e.key === 'ArrowUp') { e.preventDefault(); this.upArrowClick(); } if (e.key === 'ArrowDown') { e.preventDefault(); this.downArrowClick(); } }; /** * Fired when the element of the property is updated */ InputNumber.prototype.elementUpdated = function () { this.model.trigger('el:change'); }; /** * Updates the view when the model is changed * */ InputNumber.prototype.handleModelChange = function () { var model = this.model; this.getInputEl().value = model.get('value'); var unitEl = this.getUnitEl(); unitEl && (unitEl.value = model.get('unit') || ''); }; /** * Get the unit element * @return {HTMLElement} */ InputNumber.prototype.getUnitEl = function () { if (!this.unitEl) { var model_1 = this.model; var units = model_1.get('units') || []; if (units.length) { var options_1 = ['<option value="" disabled hidden>-</option>']; units.forEach(function (unit) { var selected = unit == model_1.get('unit') ? 'selected' : ''; options_1.push("<option ".concat(selected, ">").concat(unit, "</option>")); }); var temp = document.createElement('div'); temp.innerHTML = "<select class=\"".concat(this.ppfx, "input-unit\">").concat(options_1.join(''), "</select>"); this.unitEl = temp.firstChild; } } return this.unitEl; }; /** * Invoked when the up arrow is clicked * */ InputNumber.prototype.upArrowClick = function () { var model = this.model; var step = model.get('step'); var value = parseFloat(model.get('value')); this.setValue(this.normalizeValue(value + step)); this.elementUpdated(); }; /** * Invoked when the down arrow is clicked * */ InputNumber.prototype.downArrowClick = function () { var model = this.model; var step = model.get('step'); var value = parseFloat(model.get('value')); this.setValue(this.normalizeValue(value - step)); this.elementUpdated(); }; /** * Change easily integer input value with click&drag method * @param Event * * @return void * */ InputNumber.prototype.downIncrement = function (e) { e.preventDefault(); this.moved = false; var value = this.model.get('value') || 0; value = this.normalizeValue(value); this.current = { y: e.pageY, val: value }; (0,dom.on)(this.doc, 'mousemove', this.moveIncrement); (0,dom.on)(this.doc, 'mouseup', this.upIncrement); }; /** While the increment is clicked, moving the mouse will update input value * @param Object * * @return bool * */ InputNumber.prototype.moveIncrement = function (ev) { this.moved = true; var model = this.model; var step = model.get('step'); var data = this.current; var pos = this.normalizeValue(data.val + (data.y - ev.pageY) * step); var _a = this.validateInputValue(pos), value = _a.value, unit = _a.unit; this.prValue = value; model.set({ value: value, unit: unit }, { avoidStore: 1 }); return false; }; /** * Stop moveIncrement method * */ InputNumber.prototype.upIncrement = function () { var model = this.model; var step = model.get('step'); (0,dom/* off */.S1)(this.doc, 'mouseup', this.upIncrement); (0,dom/* off */.S1)(this.doc, 'mousemove', this.moveIncrement); if (this.prValue && this.moved) { var value = this.prValue - step; // @ts-ignore model.set('value', value, { avoidStore: 1 }).set('value', value + step); this.elementUpdated(); } }; InputNumber.prototype.normalizeValue = function (value, defValue) { if (defValue === void 0) { defValue = 0; } var model = this.model; var step = model.get('step'); var stepDecimals = 0; if (isNaN(value)) { return defValue; } value = parseFloat(value); if (Math.floor(value) !== value) { var side = step.toString().split('.')[1]; stepDecimals = side ? side.length : 0; } return stepDecimals ? parseFloat(value.toFixed(stepDecimals)) : value; }; /** * Validate input value * @param {String} value Raw value * @param {Object} opts Options * @return {Object} Validated string */ InputNumber.prototype.validateInputValue = function (value, opts) { if (opts === void 0) { opts = {}; } var force = 0; var opt = opts || {}; var model = this.model; var defValue = ''; //model.get('defaults'); var val = !(0,index_all.isUndefined)(value) ? value : defValue; var units = opts.units || model.get('units') || []; var unit = model.get('unit') || (units.length && units[0]) || ''; var max = !(0,index_all.isUndefined)(opts.max) ? opts.max : model.get('max'); var min = !(0,index_all.isUndefined)(opts.min) ? opts.min : model.get('min'); var limitlessMax = !!model.get('limitlessMax'); var limitlessMin = !!model.get('limitlessMin'); if (opt.deepCheck) { var fixed = model.get('fixedValues') || []; if (val === '') unit = ''; if (val) { // If the value is one of the fixed values I leave it as it is var regFixed = new RegExp('^' + fixed.join('|'), 'g'); if (fixed.length && regFixed.test(val)) { val = val.match(regFixed)[0]; unit = ''; force = 1; } else { var valCopy = val + ''; val += ''; // Make it suitable for replace val = parseFloat(val.replace(',', '.')); val = !isNaN(val) ? val : defValue; var uN = valCopy.replace(val, ''); // Check if exists as unit if ((0,index_all.indexOf)(units, uN) >= 0) unit = uN; } } } if (!limitlessMax && !(0,index_all.isUndefined)(max) && max !== '') val = val > max ? max : val; if (!limitlessMin && !(0,index_all.isUndefined)(min) && min !== '') val = val < min ? min : val; return { force: force, value: val, unit: unit, }; }; InputNumber.prototype.render = function () { ui_Input.prototype.render.call(this); this.unitEl = null; var unit = this.getUnitEl(); unit && this.$el.find(".".concat(this.ppfx, "field-units")).get(0).appendChild(unit); return this; }; return InputNumber; }(ui_Input)); /* harmony default export */ const ui_InputNumber = (InputNumber); InputNumber.prototype.events = { // @ts-ignore 'change input': 'handleChange', 'change select': 'handleUnitChange', 'click [data-arrow-up]': 'upArrowClick', 'click [data-arrow-down]': 'downArrowClick', 'mousedown [data-arrows]': 'downIncrement', keydown: 'handleKeyDown', }; ;// CONCATENATED MODULE: ./src/trait_manager/view/TraitNumberView.ts var TraitNumberView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var TraitNumberView = /** @class */ (function (_super) { TraitNumberView_extends(TraitNumberView, _super); function TraitNumberView() { return _super !== null && _super.apply(this, arguments) || this; } TraitNumberView.prototype.getValueForTarget = function () { var model = this.model; var _a = model.attributes, value = _a.value, unit = _a.unit; return !(0,index_all.isUndefined)(value) && value !== '' ? value + unit : model.get('default'); }; /** * Returns input element * @return {HTMLElement} * @private */ TraitNumberView.prototype.getInputEl = function () { if (!this.input) { var _a = this, ppfx = _a.ppfx, model = _a.model; var value = this.getModelValue(); var inputNumber = new ui_InputNumber({ contClass: "".concat(ppfx, "field-int"), type: 'number', model: model, ppfx: ppfx, }); inputNumber.render(); this.$input = inputNumber.inputEl; this.$unit = inputNumber.unitEl; // @ts-ignore model.set('value', value, { fromTarget: true }); this.$input.val(value); this.input = inputNumber.el; } return this.input; }; return TraitNumberView; }(view_TraitView)); /* harmony default export */ const view_TraitNumberView = (TraitNumberView); ;// CONCATENATED MODULE: ./src/utils/ColorPicker.ts // @ts-nocheck // Without jquery I have to update few stuff // // Spectrum Colorpicker v1.8.0 // https://github.com/bgrins/spectrum // Author: Brian Grinstead // License: MIT /* harmony default export */ function ColorPicker($, undefined) { 'use strict'; if (!(0,mixins.hasWin)()) return; var defaultOpts = { // Callbacks beforeShow: noop, move: noop, change: noop, show: noop, hide: noop, // Options color: false, flat: false, showInput: false, allowEmpty: false, showButtons: true, clickoutFiresChange: true, showInitial: false, showPalette: false, showPaletteOnly: false, hideAfterPaletteSelect: false, togglePaletteOnly: false, showSelectionPalette: true, localStorageKey: false, appendTo: 'body', maxSelectionSize: 7, cancelText: 'cancel', chooseText: 'choose', togglePaletteMoreText: 'more', togglePaletteLessText: 'less', clearText: 'Clear Color Selection', noColorSelectedText: 'No Color Selected', preferredFormat: false, className: '', containerClassName: '', replacerClassName: '', showAlpha: false, theme: 'sp-light', palette: [['#ffffff', '#000000', '#ff0000', '#ff8000', '#ffff00', '#008000', '#0000ff', '#4b0082', '#9400d3']], selectionPalette: [], disabled: false, offset: null, }, spectrums = [], IE = !!/msie/i.exec(window.navigator.userAgent), rgbaSupport = (function () { function contains(str, substr) { return !!~('' + str).indexOf(substr); } var elem = document.createElement('div'); var style = elem.style; style.cssText = 'background-color:rgba(0,0,0,.5)'; return contains(style.backgroundColor, 'rgba') || contains(style.backgroundColor, 'hsla'); })(), replaceInput = [ "<div class='sp-replacer'>", "<div class='sp-preview'><div class='sp-preview-inner'></div></div>", "<div class='sp-dd'>▼</div>", '</div>', ].join(''), markup = (function () { // IE does not support gradients with multiple stops, so we need to simulate // that for the rainbow slider with 8 divs that each have a single gradient var gradientFix = ''; if (IE) { for (var i = 1; i <= 6; i++) { gradientFix += "<div class='sp-" + i + "'></div>"; } } return [ "<div class='sp-container sp-hidden'>", "<div class='sp-palette-container'>", "<div class='sp-palette sp-thumb sp-cf'></div>", "<div class='sp-palette-button-container sp-cf'>", "<button type='button' class='sp-palette-toggle'></button>", '</div>', '</div>', "<div class='sp-picker-container'>", "<div class='sp-top sp-cf'>", "<div class='sp-fill'></div>", "<div class='sp-top-inner'>", "<div class='sp-color'>", "<div class='sp-sat'>", "<div class='sp-val'>", "<div class='sp-dragger'></div>", '</div>', '</div>', '</div>', "<div class='sp-clear sp-clear-display'>", '</div>', "<div class='sp-hue'>", "<div class='sp-slider'></div>", gradientFix, '</div>', '</div>', "<div class='sp-alpha'><div class='sp-alpha-inner'><div class='sp-alpha-handle'></div></div></div>", '</div>', "<div class='sp-input-container sp-cf'>", "<input class='sp-input' type='text' spellcheck='false' />", '</div>', "<div class='sp-initial sp-thumb sp-cf'></div>", "<div class='sp-button-container sp-cf'>", "<a class='sp-cancel' href='#'></a>", "<button type='button' class='sp-choose'></button>", '</div>', '</div>', '</div>', ].join(''); })(); function paletteTemplate(p, color, className, opts) { var html = []; for (var i = 0; i < p.length; i++) { var current = p[i]; if (current) { var tiny = tinycolor(current); var c = tiny.toHsl().l < 0.5 ? 'sp-thumb-el sp-thumb-dark' : 'sp-thumb-el sp-thumb-light'; c += tinycolor.equals(color, current) ? ' sp-thumb-active' : ''; var formattedString = tiny.toString(opts.preferredFormat || 'rgb'); var swatchStyle = rgbaSupport ? 'background-color:' + tiny.toRgbString() : 'filter:' + tiny.toFilter(); html.push('<span title="' + formattedString + '" data-color="' + tiny.toRgbString() + '" class="' + c + '"><span class="sp-thumb-inner" style="' + swatchStyle + ';"></span></span>'); } else { var cls = 'sp-clear-display'; html.push($('<div />') .append($('<span data-color="" style="background-color:transparent;" class="' + cls + '"></span>').attr('title', opts.noColorSelectedText)) .html()); } } return "<div class='sp-cf " + className + "'>" + html.join('') + '</div>'; } function hideAll() { for (var i = 0; i < spectrums.length; i++) { if (spectrums[i]) { spectrums[i].hide(); } } } function instanceOptions(o, callbackContext) { var opts = $.extend({}, defaultOpts, o); opts.callbacks = { move: bind(opts.move, callbackContext), change: bind(opts.change, callbackContext), show: bind(opts.show, callbackContext), hide: bind(opts.hide, callbackContext), beforeShow: bind(opts.beforeShow, callbackContext), }; return opts; } function spectrum(element, o) { var opts = instanceOptions(o, element), flat = opts.flat, showSelectionPalette = opts.showSelectionPalette, localStorageKey = opts.localStorageKey, theme = opts.theme, callbacks = opts.callbacks, resize = throttle(reflow, 10), visible = false, isDragging = false, isDefault = true, dragWidth = 0, dragHeight = 0, dragHelperHeight = 0, slideHeight = 0, slideWidth = 0, alphaWidth = 0, alphaSlideHelperWidth = 0, slideHelperHeight = 0, currentHue = 0, currentSaturation = 0, currentValue = 0, currentAlpha = 1, palette = [], paletteArray = [], paletteLookup = {}, selectionPalette = opts.selectionPalette.slice(0), maxSelectionSize = opts.maxSelectionSize, draggingClass = 'sp-dragging', shiftMovementDirection = null; var doc = element.ownerDocument, body = doc.body, boundElement = $(element), disabled = false, container = $(markup, doc).addClass(theme), pickerContainer = container.find('.sp-picker-container'), dragger = container.find('.sp-color'), dragHelper = container.find('.sp-dragger'), slider = container.find('.sp-hue'), slideHelper = container.find('.sp-slider'), alphaSliderInner = container.find('.sp-alpha-inner'), alphaSlider = container.find('.sp-alpha'), alphaSlideHelper = container.find('.sp-alpha-handle'), textInput = container.find('.sp-input'), paletteContainer = container.find('.sp-palette'), initialColorContainer = container.find('.sp-initial'), cancelButton = container.find('.sp-cancel'), clearButton = container.find('.sp-clear'), chooseButton = container.find('.sp-choose'), toggleButton = container.find('.sp-palette-toggle'), isInput = boundElement.is('input'), isInputTypeColor = isInput && boundElement.attr('type') === 'color' && inputTypeColorSupport(), shouldReplace = isInput && !flat, replacer = shouldReplace ? $(replaceInput).addClass(theme).addClass(opts.className).addClass(opts.replacerClassName) : $([]), offsetElement = shouldReplace ? replacer : boundElement, previewElement = replacer.find('.sp-preview-inner'), initialColor = opts.color || (isInput && boundElement.val()), colorOnShow = false, currentPreferredFormat = opts.preferredFormat, clickoutFiresChange = !opts.showButtons || opts.clickoutFiresChange, isEmpty = !initialColor, allowEmpty = opts.allowEmpty && !isInputTypeColor; function applyOptions() { if (opts.showPaletteOnly) { opts.showPalette = true; } toggleButton.text(opts.showPaletteOnly ? opts.togglePaletteMoreText : opts.togglePaletteLessText); if (opts.palette) { palette = opts.palette.slice(0); paletteArray = $.isArray(palette[0]) ? palette : [palette]; paletteLookup = {}; for (var i = 0; i < paletteArray.length; i++) { for (var j = 0; j < paletteArray[i].length; j++) { var rgb = tinycolor(paletteArray[i][j]).toRgbString(); paletteLookup[rgb] = true; } } } container.toggleClass('sp-flat', flat); container.toggleClass('sp-input-disabled', !opts.showInput); container.toggleClass('sp-alpha-enabled', opts.showAlpha); container.toggleClass('sp-clear-enabled', allowEmpty); container.toggleClass('sp-buttons-disabled', !opts.showButtons); container.toggleClass('sp-palette-buttons-disabled', !opts.togglePaletteOnly); container.toggleClass('sp-palette-disabled', !opts.showPalette); container.toggleClass('sp-palette-only', opts.showPaletteOnly); container.toggleClass('sp-initial-disabled', !opts.showInitial); container.addClass(opts.className).addClass(opts.containerClassName); reflow(); } function initialize() { if (IE) { container.find('*:not(input)').attr('unselectable', 'on'); } applyOptions(); if (shouldReplace) { boundElement.after(replacer).hide(); } if (!allowEmpty) { clearButton.hide(); } if (flat) { boundElement.after(container).hide(); } else { var appendTo = opts.appendTo === 'parent' ? boundElement.parent() : $(opts.appendTo); if (appendTo.length !== 1) { appendTo = $('body'); } appendTo.append(container); } updateSelectionPaletteFromStorage(); offsetElement.bind('click.spectrum touchstart.spectrum', function (e) { if (!disabled) { toggle(); } e.stopPropagation(); if (!$(e.target).is('input')) { e.preventDefault(); } }); if (boundElement.is(':disabled') || opts.disabled === true) { disable(); } // Prevent clicks from bubbling up to document. This would cause it to be hidden. container.click(stopPropagation); // Handle user typed input textInput.change(setFromTextInput); textInput.bind('paste', function () { setTimeout(setFromTextInput, 1); }); textInput.keydown(function (e) { if (e.keyCode == 13) { setFromTextInput(); } }); cancelButton.text(opts.cancelText); cancelButton.bind('click.spectrum', function (e) { e.stopPropagation(); e.preventDefault(); revert(); hide(); }); clearButton.attr('title', opts.clearText); clearButton.bind('click.spectrum', function (e) { e.stopPropagation(); e.preventDefault(); isEmpty = true; move(); if (flat) { //for the flat style, this is a change event updateOriginalInput(true); } }); chooseButton.text(opts.chooseText); chooseButton.bind('click.spectrum', function (e) { e.stopPropagation(); e.preventDefault(); if (IE && textInput.is(':focus')) { textInput.trigger('change'); } if (isValid()) { updateOriginalInput(true); hide(); } }); toggleButton.text(opts.showPaletteOnly ? opts.togglePaletteMoreText : opts.togglePaletteLessText); toggleButton.bind('click.spectrum', function (e) { e.stopPropagation(); e.preventDefault(); opts.showPaletteOnly = !opts.showPaletteOnly; // To make sure the Picker area is drawn on the right, next to the // Palette area (and not below the palette), first move the Palette // to the left to make space for the picker, plus 5px extra. // The 'applyOptions' function puts the whole container back into place // and takes care of the button-text and the sp-palette-only CSS class. if (!opts.showPaletteOnly && !flat) { container.css('left', '-=' + (pickerContainer.outerWidth(true) + 5)); } applyOptions(); }); draggable(alphaSlider, function (dragX, dragY, e) { currentAlpha = dragX / alphaWidth; isEmpty = false; if (e.shiftKey) { currentAlpha = Math.round(currentAlpha * 10) / 10; } move(); }, dragStart, dragStop); draggable(slider, function (dragX, dragY) { currentHue = parseFloat(dragY / slideHeight); isEmpty = false; if (!opts.showAlpha) { currentAlpha = 1; } move(); }, dragStart, dragStop); draggable(dragger, function (dragX, dragY, e) { // shift+drag should snap the movement to either the x or y axis. if (!e.shiftKey) { shiftMovementDirection = null; } else if (!shiftMovementDirection) { var oldDragX = currentSaturation * dragWidth; var oldDragY = dragHeight - currentValue * dragHeight; var furtherFromX = Math.abs(dragX - oldDragX) > Math.abs(dragY - oldDragY); shiftMovementDirection = furtherFromX ? 'x' : 'y'; } var setSaturation = !shiftMovementDirection || shiftMovementDirection === 'x'; var setValue = !shiftMovementDirection || shiftMovementDirection === 'y'; if (setSaturation) { currentSaturation = parseFloat(dragX / dragWidth); } if (setValue) { currentValue = parseFloat((dragHeight - dragY) / dragHeight); } isEmpty = false; if (!opts.showAlpha) { currentAlpha = 1; } move(); }, dragStart, dragStop); if (!!initialColor) { set(initialColor); // In case color was black - update the preview UI and set the format // since the set function will not run (default color is black). updateUI(); currentPreferredFormat = opts.preferredFormat || tinycolor(initialColor).getFormat(); addColorToSelectionPalette(initialColor); } else { updateUI(); } if (flat) { show(); } function paletteElementClick(e) { if (e.data && e.data.ignore) { set($(e.target).closest('.sp-thumb-el').data('color')); move(); } else { set($(e.target).closest('.sp-thumb-el').data('color')); move(); if (opts.hideAfterPaletteSelect) { updateOriginalInput(true); hide(); } } return false; } var paletteEvent = IE ? 'mousedown.spectrum' : 'click.spectrum touchstart.spectrum'; paletteContainer.delegate('.sp-thumb-el', paletteEvent, paletteElementClick); initialColorContainer.delegate('.sp-thumb-el:nth-child(1)', paletteEvent, { ignore: true }, paletteElementClick); } function updateSelectionPaletteFromStorage() { if (localStorageKey && window.localStorage) { // Migrate old palettes over to new format. May want to remove this eventually. try { var oldPalette = window.localStorage[localStorageKey].split(',#'); if (oldPalette.length > 1) { delete window.localStorage[localStorageKey]; $.each(oldPalette, function (i, c) { addColorToSelectionPalette(c); }); } } catch (e) { } try { selectionPalette = window.localStorage[localStorageKey].split(';'); } catch (e) { } } } function addColorToSelectionPalette(color) { if (showSelectionPalette) { var rgb = tinycolor(color).toRgbString(); if (!paletteLookup[rgb] && $.inArray(rgb, selectionPalette) === -1) { selectionPalette.push(rgb); while (selectionPalette.length > maxSelectionSize) { selectionPalette.shift(); } } if (localStorageKey && window.localStorage) { try { window.localStorage[localStorageKey] = selectionPalette.join(';'); } catch (e) { } } } } function getUniqueSelectionPalette() { var unique = []; if (opts.showPalette) { for (var i = 0; i < selectionPalette.length; i++) { var rgb = tinycolor(selectionPalette[i]).toRgbString(); if (!paletteLookup[rgb]) { unique.push(selectionPalette[i]); } } } return unique.reverse().slice(0, opts.maxSelectionSize); } function drawPalette() { var currentColor = get(); var html = $.map(paletteArray, function (palette, i) { return paletteTemplate(palette, currentColor, 'sp-palette-row sp-palette-row-' + i, opts); }); updateSelectionPaletteFromStorage(); if (selectionPalette) { html.push(paletteTemplate(getUniqueSelectionPalette(), currentColor, 'sp-palette-row sp-palette-row-selection', opts)); } paletteContainer.html(html.join('')); } function drawInitial() { if (opts.showInitial) { var initial = colorOnShow; var current = get(); initialColorContainer.html(paletteTemplate([initial, current], current, 'sp-palette-row-initial', opts)); } } function dragStart() { if (dragHeight <= 0 || dragWidth <= 0 || slideHeight <= 0) { reflow(); } isDragging = true; container.addClass(draggingClass); shiftMovementDirection = null; boundElement.trigger('dragstart.spectrum', [get()]); } function dragStop() { isDragging = false; container.removeClass(draggingClass); boundElement.trigger('dragstop.spectrum', [get()]); } function setFromTextInput() { var value = textInput.val(); if ((value === null || value === '') && allowEmpty) { set(null); updateOriginalInput(true); } else { var tiny = tinycolor(value); if (tiny.isValid()) { set(tiny); updateOriginalInput(true); } else { textInput.addClass('sp-validation-error'); } } } function toggle() { if (visible) { hide(); } else { show(); } } function show() { var event = $.Event('beforeShow.spectrum'); if (visible) { reflow(); return; } boundElement.trigger('beforeShow.spectrum', [get()]); if (callbacks.beforeShow(get()) === false || event.isDefaultPrevented()) { return; } hideAll(); visible = true; var $doc = $(doc); $doc.bind('keydown.spectrum', onkeydown); $doc.bind('click.spectrum', clickout); $(window).bind('resize.spectrum', resize); replacer.addClass('sp-active'); container.removeClass('sp-hidden'); reflow(); updateUI(); colorOnShow = get(); drawInitial(); callbacks.show(colorOnShow); boundElement.trigger('show.spectrum', [colorOnShow]); } function onkeydown(e) { // Close on ESC if (e.keyCode === 27) { hide(); } } function clickout(e) { // Return on right click. if (e.button == 2) { return; } // If a drag event was happening during the mouseup, don't hide // on click. if (isDragging) { return; } if (clickoutFiresChange) { updateOriginalInput(true); } else { revert(); } hide(); } function hide() { // Return if hiding is unnecessary if (!visible || flat) { return; } visible = false; $(doc).unbind('keydown.spectrum', onkeydown); $(doc).unbind('click.spectrum', clickout); $(window).unbind('resize.spectrum', resize); replacer.removeClass('sp-active'); container.addClass('sp-hidden'); callbacks.hide(get()); boundElement.trigger('hide.spectrum', [get()]); } function revert() { set(colorOnShow, true); } function set(color, ignoreFormatChange) { if (tinycolor.equals(color, get())) { // Update UI just in case a validation error needs // to be cleared. updateUI(); return; } var newColor, newHsv; if (!color && allowEmpty) { isEmpty = true; } else { isEmpty = false; isDefault = !color; // if no color is available an empty string will be passed. tinycolor will then set it to #000 newColor = tinycolor(color); newHsv = newColor.toHsv(); currentHue = (newHsv.h % 360) / 360; currentSaturation = newHsv.s; currentValue = newHsv.v; currentAlpha = newHsv.a; } updateUI(); if (newColor && newColor.isValid() && !ignoreFormatChange) { currentPreferredFormat = opts.preferredFormat || newColor.getFormat(); } } function get(opts) { opts = opts || {}; if (allowEmpty && isEmpty) { return null; } return tinycolor.fromRatio({ h: currentHue, s: currentSaturation, v: currentValue, a: Math.round(currentAlpha * 100) / 100, }, { format: opts.format || currentPreferredFormat }); } function isValid() { return !textInput.hasClass('sp-validation-error'); } function move() { updateUI(); callbacks.move(get()); boundElement.trigger('move.spectrum', [get()]); } function updateUI() { textInput.removeClass('sp-validation-error'); updateHelperLocations(); // Update dragger background color (gradients take care of saturation and value). var flatColor = tinycolor.fromRatio({ h: currentHue, s: 1, v: 1 }); dragger.css('background-color', flatColor.toHexString()); // Get a format that alpha will be included in (hex and names ignore alpha) var format = currentPreferredFormat; if (currentAlpha < 1 && !(currentAlpha === 0 && format === 'name')) { if (format === 'hex' || format === 'hex3' || format === 'hex6' || format === 'name') { format = 'rgb'; } } var realColor = get({ format: format }), displayColor = ''; //reset background info for preview element previewElement.removeClass('sp-clear-display'); previewElement.css('background-color', 'transparent'); if (!realColor && allowEmpty) { // Update the replaced elements background with icon indicating no color selection previewElement.addClass('sp-clear-display'); } else { var realHex = realColor.toHexString(), realRgb = realColor.toRgbString(); // Update the replaced elements background color (with actual selected color) if (rgbaSupport || realColor.alpha === 1) { previewElement.css('background-color', realRgb); } else { previewElement.css('background-color', 'transparent'); previewElement.css('filter', realColor.toFilter()); } if (opts.showAlpha) { var rgb = realColor.toRgb(); rgb.a = 0; var realAlpha = tinycolor(rgb).toRgbString(); var gradient = 'linear-gradient(left, ' + realAlpha + ', ' + realHex + ')'; if (IE) { alphaSliderInner.css('filter', tinycolor(realAlpha).toFilter({ gradientType: 1 }, realHex)); } else { alphaSliderInner.css('background', '-webkit-' + gradient); alphaSliderInner.css('background', '-moz-' + gradient); alphaSliderInner.css('background', '-ms-' + gradient); // Use current syntax gradient on unprefixed property. alphaSliderInner.css('background', 'linear-gradient(to right, ' + realAlpha + ', ' + realHex + ')'); } } displayColor = realColor.toString(format); } // Update the text entry input as it changes happen if (opts.showInput) { textInput.val(displayColor); } if (opts.showPalette) { drawPalette(); } drawInitial(); } function updateHelperLocations() { var s = currentSaturation; var v = currentValue; if (allowEmpty && isEmpty) { //if selected color is empty, hide the helpers alphaSlideHelper.hide(); slideHelper.hide(); dragHelper.hide(); } else { //make sure helpers are visible alphaSlideHelper.show(); slideHelper.show(); dragHelper.show(); // Where to show the little circle in that displays your current selected color var dragX = s * dragWidth; var dragY = dragHeight - v * dragHeight; dragX = Math.max(-dragHelperHeight, Math.min(dragWidth - dragHelperHeight, dragX - dragHelperHeight)); dragY = Math.max(-dragHelperHeight, Math.min(dragHeight - dragHelperHeight, dragY - dragHelperHeight)); dragHelper.css({ top: dragY + 'px', left: dragX + 'px', }); var alphaX = currentAlpha * alphaWidth; alphaSlideHelper.css({ left: alphaX - alphaSlideHelperWidth / 2 + 'px', }); // Where to show the bar that displays your current selected hue var slideY = currentHue * slideHeight; slideHelper.css({ top: slideY - slideHelperHeight + 'px', }); } } function updateOriginalInput(fireCallback) { var color = get(), displayColor = '', hasChanged = isDefault ? true : !tinycolor.equals(color, colorOnShow); if (color) { displayColor = color.toString(currentPreferredFormat); // Update the selection palette with the current color !visible && addColorToSelectionPalette(color); } if (isInput) { boundElement.val(displayColor); } if (fireCallback && hasChanged) { callbacks.change(color); boundElement.trigger('change', [color]); } } function reflow() { if (!visible) { return; // Calculations would be useless and wouldn't be reliable anyways } dragWidth = dragger.width(); dragHeight = dragger.height(); dragHelperHeight = dragHelper.height(); slideWidth = slider.width(); slideHeight = slider.height(); slideHelperHeight = slideHelper.height(); alphaWidth = alphaSlider.width(); alphaSlideHelperWidth = alphaSlideHelper.width(); if (!flat) { container.css('position', 'absolute'); if (opts.offset) { container.offset(opts.offset); } else { container.offset(getOffset(container, offsetElement)); } } updateHelperLocations(); if (opts.showPalette) { drawPalette(); } boundElement.trigger('reflow.spectrum'); } function destroy() { boundElement.show(); offsetElement.unbind('click.spectrum touchstart.spectrum'); container.remove(); replacer.remove(); spectrums[spect.id] = null; } function option(optionName, optionValue) { if (optionName === undefined) { return $.extend({}, opts); } if (optionValue === undefined) { return opts[optionName]; } opts[optionName] = optionValue; if (optionName === 'preferredFormat') { currentPreferredFormat = opts.preferredFormat; } applyOptions(); } function enable() { disabled = false; boundElement.attr('disabled', false); offsetElement.removeClass('sp-disabled'); } function disable() { hide(); disabled = true; boundElement.attr('disabled', true); offsetElement.addClass('sp-disabled'); } function setOffset(coord) { opts.offset = coord; reflow(); } initialize(); var spect = { show: show, hide: hide, toggle: toggle, reflow: reflow, option: option, enable: enable, disable: disable, offset: setOffset, set: function (c) { set(c); updateOriginalInput(); }, get: get, destroy: destroy, container: container, }; spect.id = spectrums.push(spect) - 1; return spect; } /** * checkOffset - get the offset below/above and left/right element depending on screen position * Thanks https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.datepicker.js */ function getOffset(picker, input) { var extraY = 0; var dpWidth = picker.outerWidth(); var dpHeight = picker.outerHeight(); var inputHeight = input.outerHeight(); var doc = picker[0].ownerDocument; var docElem = doc.documentElement; var cW = docElem.clientWidth; var cH = docElem.clientHeight; var scL = $(doc).scrollLeft(); var scT = $(doc).scrollTop(); var viewWidth = cW + scL; var viewHeight = cH + scT; var offset = input.offset(); offset.top += inputHeight; offset.left -= Math.min(offset.left, offset.left + dpWidth > viewWidth && viewWidth > dpWidth ? Math.abs(offset.left + dpWidth - viewWidth) : 0); offset.top -= Math.min(offset.top, offset.top + dpHeight > viewHeight && viewHeight > dpHeight ? Math.abs(dpHeight + inputHeight - extraY) : extraY); return offset; } /** * noop - do nothing */ function noop() { } /** * stopPropagation - makes the code only doing this a little easier to read in line */ function stopPropagation(e) { e.stopPropagation(); } /** * Create a function bound to a given object * Thanks to underscore.js */ function bind(func, obj) { var slice = Array.prototype.slice; var args = slice.call(arguments, 2); return function () { return func.apply(obj, args.concat(slice.call(arguments))); }; } /** * Lightweight drag helper. Handles containment within the element, so that * when dragging, the x is within [0,element.width] and y is within [0,element.height] */ function draggable(element, onmove, onstart, onstop) { onmove = onmove || function () { }; onstart = onstart || function () { }; onstop = onstop || function () { }; var doc = document; var dragging = false; var offset = {}; var maxHeight = 0; var maxWidth = 0; var hasTouch = 'ontouchstart' in window; var duringDragEvents = {}; duringDragEvents['selectstart'] = prevent; duringDragEvents['dragstart'] = prevent; duringDragEvents['touchmove mousemove'] = move; duringDragEvents['touchend mouseup'] = stop; function prevent(e) { if (e.stopPropagation) { e.stopPropagation(); } if (e.preventDefault) { e.preventDefault(); } e.returnValue = false; } function move(e) { if (dragging) { // Mouseup happened outside of window if (IE && doc.documentMode < 9 && !e.button) { return stop(); } var t0 = e && e.touches && e.touches[0]; var pageX = (t0 && t0.pageX) || e.pageX; var pageY = (t0 && t0.pageY) || e.pageY; var dragX = Math.max(0, Math.min(pageX - offset.left, maxWidth)); var dragY = Math.max(0, Math.min(pageY - offset.top, maxHeight)); if (hasTouch) { // Stop scrolling in iOS prevent(e); } onmove.apply(element, [dragX, dragY, e]); } } function start(e) { var rightclick = e.which ? e.which == 3 : e.button == 2; if (!rightclick && !dragging) { if (onstart.apply(element, arguments) !== false) { dragging = true; maxHeight = $(element).height(); maxWidth = $(element).width(); offset = $(element).offset(); $(doc).bind(duringDragEvents); $(doc.body).addClass('sp-dragging'); move(e); prevent(e); } } } function stop() { if (dragging) { $(doc).unbind(duringDragEvents); $(doc.body).removeClass('sp-dragging'); // Wait a tick before notifying observers to allow the click event // to fire in Chrome. setTimeout(function () { onstop.apply(element, arguments); }, 0); } dragging = false; } $(element).bind('touchstart mousedown', start); } function throttle(func, wait, debounce) { var timeout; return function () { var context = this, args = arguments; var throttler = function () { timeout = null; func.apply(context, args); }; if (debounce) clearTimeout(timeout); if (debounce || !timeout) timeout = setTimeout(throttler, wait); }; } function inputTypeColorSupport() { return $.fn.spectrum.inputTypeColorSupport(); } /** * Define a jQuery plugin */ var dataID = 'spectrum.id'; $.fn.spectrum = function (opts, extra) { if (typeof opts == 'string') { var returnValue = this; var args = Array.prototype.slice.call(arguments, 1); this.each(function () { var spect = spectrums[$(this).data(dataID)]; if (spect) { var method = spect[opts]; if (!method) { throw new Error("Spectrum: no such method: '" + opts + "'"); } if (opts == 'get') { returnValue = spect.get(); } else if (opts == 'container') { returnValue = spect.container; } else if (opts == 'option') { returnValue = spect.option.apply(spect, args); } else if (opts == 'destroy') { spect.destroy(); $(this).removeData(dataID); } else { method.apply(spect, args); } } }); return returnValue; } // Initializing a new instance of spectrum return this.spectrum('destroy').each(function () { var options = $.extend({}, opts, $(this).data()); var spect = spectrum(this, options); $(this).data(dataID, spect.id); }); }; $.fn.spectrum.load = true; $.fn.spectrum.loadOpts = {}; $.fn.spectrum.draggable = draggable; $.fn.spectrum.defaults = defaultOpts; $.fn.spectrum.inputTypeColorSupport = function inputTypeColorSupport() { if (typeof inputTypeColorSupport._cachedResult === 'undefined') { var colorInput = $("<input type='color'/>")[0]; // if color element is supported, value will default to not null inputTypeColorSupport._cachedResult = colorInput.type === 'color' && colorInput.value !== ''; } return inputTypeColorSupport._cachedResult; }; $.spectrum = {}; $.spectrum.localization = {}; $.spectrum.palettes = {}; $.fn.spectrum.processNativeColorInputs = function () { var colorInputs = $('input[type=color]'); if (colorInputs.length && !inputTypeColorSupport()) { colorInputs.spectrum({ preferredFormat: 'hex6', }); } }; // TinyColor v1.1.2 // https://github.com/bgrins/TinyColor // Brian Grinstead, MIT License //(function() { var trimLeft = /^[\s,#]+/, trimRight = /\s+$/, tinyCounter = 0, math = Math, mathRound = math.round, mathMin = math.min, mathMax = math.max, mathRandom = math.random; var tinycolor = function (color, opts) { color = color ? color : ''; opts = opts || {}; // If input is already a tinycolor, return itself if (color instanceof tinycolor) { return color; } // If we are called as a function, call using new instead if (!(this instanceof tinycolor)) { return new tinycolor(color, opts); } var rgb = inputToRGB(color); (this._originalInput = color), (this._r = rgb.r), (this._g = rgb.g), (this._b = rgb.b), (this._a = rgb.a), (this._roundA = mathRound(100 * this._a) / 100), (this._format = opts.format || rgb.format); this._gradientType = opts.gradientType; // Don't let the range of [0,255] come back in [0,1]. // Potentially lose a little bit of precision here, but will fix issues where // .5 gets interpreted as half of the total, instead of half of 1 // If it was supposed to be 128, this was already taken care of by `inputToRgb` if (this._r < 1) { this._r = mathRound(this._r); } if (this._g < 1) { this._g = mathRound(this._g); } if (this._b < 1) { this._b = mathRound(this._b); } this._ok = rgb.ok; this._tc_id = tinyCounter++; }; tinycolor.prototype = { isDark: function () { return this.getBrightness() < 128; }, isLight: function () { return !this.isDark(); }, isValid: function () { return this._ok; }, getOriginalInput: function () { return this._originalInput; }, getFormat: function () { return this._format; }, getAlpha: function () { return this._a; }, getBrightness: function () { var rgb = this.toRgb(); return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000; }, setAlpha: function (value) { this._a = boundAlpha(value); this._roundA = mathRound(100 * this._a) / 100; return this; }, toHsv: function () { var hsv = rgbToHsv(this._r, this._g, this._b); return { h: hsv.h * 360, s: hsv.s, v: hsv.v, a: this._a }; }, toHsvString: function () { var hsv = rgbToHsv(this._r, this._g, this._b); var h = mathRound(hsv.h * 360), s = mathRound(hsv.s * 100), v = mathRound(hsv.v * 100); return this._a == 1 ? 'hsv(' + h + ', ' + s + '%, ' + v + '%)' : 'hsva(' + h + ', ' + s + '%, ' + v + '%, ' + this._roundA + ')'; }, toHsl: function () { var hsl = rgbToHsl(this._r, this._g, this._b); return { h: hsl.h * 360, s: hsl.s, l: hsl.l, a: this._a }; }, toHslString: function () { var hsl = rgbToHsl(this._r, this._g, this._b); var h = mathRound(hsl.h * 360), s = mathRound(hsl.s * 100), l = mathRound(hsl.l * 100); return this._a == 1 ? 'hsl(' + h + ', ' + s + '%, ' + l + '%)' : 'hsla(' + h + ', ' + s + '%, ' + l + '%, ' + this._roundA + ')'; }, toHex: function (allow3Char) { return rgbToHex(this._r, this._g, this._b, allow3Char); }, toHexString: function (allow3Char) { return '#' + this.toHex(allow3Char); }, toHex8: function () { return rgbaToHex(this._r, this._g, this._b, this._a); }, toHex8String: function () { return '#' + this.toHex8(); }, toRgb: function () { return { r: mathRound(this._r), g: mathRound(this._g), b: mathRound(this._b), a: this._a, }; }, toRgbString: function () { return this._a == 1 ? 'rgb(' + mathRound(this._r) + ', ' + mathRound(this._g) + ', ' + mathRound(this._b) + ')' : 'rgba(' + mathRound(this._r) + ', ' + mathRound(this._g) + ', ' + mathRound(this._b) + ', ' + this._roundA + ')'; }, toPercentageRgb: function () { return { r: mathRound(bound01(this._r, 255) * 100) + '%', g: mathRound(bound01(this._g, 255) * 100) + '%', b: mathRound(bound01(this._b, 255) * 100) + '%', a: this._a, }; }, toPercentageRgbString: function () { return this._a == 1 ? 'rgb(' + mathRound(bound01(this._r, 255) * 100) + '%, ' + mathRound(bound01(this._g, 255) * 100) + '%, ' + mathRound(bound01(this._b, 255) * 100) + '%)' : 'rgba(' + mathRound(bound01(this._r, 255) * 100) + '%, ' + mathRound(bound01(this._g, 255) * 100) + '%, ' + mathRound(bound01(this._b, 255) * 100) + '%, ' + this._roundA + ')'; }, toName: function () { if (this._a === 0) { return 'transparent'; } if (this._a < 1) { return false; } return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false; }, toFilter: function (secondColor) { var hex8String = '#' + rgbaToHex(this._r, this._g, this._b, this._a); var secondHex8String = hex8String; var gradientType = this._gradientType ? 'GradientType = 1, ' : ''; if (secondColor) { var s = tinycolor(secondColor); secondHex8String = s.toHex8String(); } return ('progid:DXImageTransform.Microsoft.gradient(' + gradientType + 'startColorstr=' + hex8String + ',endColorstr=' + secondHex8String + ')'); }, toString: function (format) { var formatSet = !!format; format = format || this._format; var formattedString = false; var hasAlpha = this._a < 1 && this._a >= 0; var needsAlphaFormat = !formatSet && hasAlpha && (format === 'hex' || format === 'hex6' || format === 'hex3' || format === 'name'); if (needsAlphaFormat) { // Special case for "transparent", all other non-alpha formats // will return rgba when there is transparency. if (format === 'name' && this._a === 0) { return this.toName(); } return this.toRgbString(); } if (format === 'rgb') { formattedString = this.toRgbString(); } if (format === 'prgb') { formattedString = this.toPercentageRgbString(); } if (format === 'hex' || format === 'hex6') { formattedString = this.toHexString(); } if (format === 'hex3') { formattedString = this.toHexString(true); } if (format === 'hex8') { formattedString = this.toHex8String(); } if (format === 'name') { formattedString = this.toName(); } if (format === 'hsl') { formattedString = this.toHslString(); } if (format === 'hsv') { formattedString = this.toHsvString(); } return formattedString || this.toHexString(); }, _applyModification: function (fn, args) { var color = fn.apply(null, [this].concat([].slice.call(args))); this._r = color._r; this._g = color._g; this._b = color._b; this.setAlpha(color._a); return this; }, lighten: function () { return this._applyModification(lighten, arguments); }, brighten: function () { return this._applyModification(brighten, arguments); }, darken: function () { return this._applyModification(darken, arguments); }, desaturate: function () { return this._applyModification(desaturate, arguments); }, saturate: function () { return this._applyModification(saturate, arguments); }, greyscale: function () { return this._applyModification(greyscale, arguments); }, spin: function () { return this._applyModification(spin, arguments); }, _applyCombination: function (fn, args) { return fn.apply(null, [this].concat([].slice.call(args))); }, analogous: function () { return this._applyCombination(analogous, arguments); }, complement: function () { return this._applyCombination(complement, arguments); }, monochromatic: function () { return this._applyCombination(monochromatic, arguments); }, splitcomplement: function () { return this._applyCombination(splitcomplement, arguments); }, triad: function () { return this._applyCombination(triad, arguments); }, tetrad: function () { return this._applyCombination(tetrad, arguments); }, }; // If input is an object, force 1 into "1.0" to handle ratios properly // String input requires "1.0" as input, so 1 will be treated as 1 tinycolor.fromRatio = function (color, opts) { if (typeof color == 'object') { var newColor = {}; for (var i in color) { if (color.hasOwnProperty(i)) { if (i === 'a') { newColor[i] = color[i]; } else { newColor[i] = convertToPercentage(color[i]); } } } color = newColor; } return tinycolor(color, opts); }; // Given a string or object, convert that input to RGB // Possible string inputs: // // "red" // "#f00" or "f00" // "#ff0000" or "ff0000" // "#ff000000" or "ff000000" // "rgb 255 0 0" or "rgb (255, 0, 0)" // "rgb 1.0 0 0" or "rgb (1, 0, 0)" // "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1" // "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1" // "hsl(0, 100%, 50%)" or "hsl 0 100% 50%" // "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1" // "hsv(0, 100%, 100%)" or "hsv 0 100% 100%" // function inputToRGB(color) { var rgb = { r: 0, g: 0, b: 0 }; var a = 1; var ok = false; var format = false; if (typeof color == 'string') { color = stringInputToObject(color); } if (typeof color == 'object') { if (color.hasOwnProperty('r') && color.hasOwnProperty('g') && color.hasOwnProperty('b')) { rgb = rgbToRgb(color.r, color.g, color.b); ok = true; format = String(color.r).substr(-1) === '%' ? 'prgb' : 'rgb'; } else if (color.hasOwnProperty('h') && color.hasOwnProperty('s') && color.hasOwnProperty('v')) { color.s = convertToPercentage(color.s); color.v = convertToPercentage(color.v); rgb = hsvToRgb(color.h, color.s, color.v); ok = true; format = 'hsv'; } else if (color.hasOwnProperty('h') && color.hasOwnProperty('s') && color.hasOwnProperty('l')) { color.s = convertToPercentage(color.s); color.l = convertToPercentage(color.l); rgb = hslToRgb(color.h, color.s, color.l); ok = true; format = 'hsl'; } if (color.hasOwnProperty('a')) { a = color.a; } } a = boundAlpha(a); return { ok: ok, format: color.format || format, r: mathMin(255, mathMax(rgb.r, 0)), g: mathMin(255, mathMax(rgb.g, 0)), b: mathMin(255, mathMax(rgb.b, 0)), a: a, }; } // Conversion Functions // -------------------- // `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from: // <http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript> // `rgbToRgb` // Handle bounds / percentage checking to conform to CSS color spec // <http://www.w3.org/TR/css3-color/> // *Assumes:* r, g, b in [0, 255] or [0, 1] // *Returns:* { r, g, b } in [0, 255] function rgbToRgb(r, g, b) { return { r: bound01(r, 255) * 255, g: bound01(g, 255) * 255, b: bound01(b, 255) * 255, }; } // `rgbToHsl` // Converts an RGB color value to HSL. // *Assumes:* r, g, and b are contained in [0, 255] or [0, 1] // *Returns:* { h, s, l } in [0,1] function rgbToHsl(r, g, b) { r = bound01(r, 255); g = bound01(g, 255); b = bound01(b, 255); var max = mathMax(r, g, b), min = mathMin(r, g, b); var h, s, l = (max + min) / 2; if (max == min) { h = s = 0; // achromatic } else { var d = max - min; s = l > 0.5 ? d / (2 - max - min) : d / (max + min); switch (max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return { h: h, s: s, l: l }; } // `hslToRgb` // Converts an HSL color value to RGB. // *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100] // *Returns:* { r, g, b } in the set [0, 255] function hslToRgb(h, s, l) { var r, g, b; h = bound01(h, 360); s = bound01(s, 100); l = bound01(l, 100); function hue2rgb(p, q, t) { if (t < 0) t += 1; if (t > 1) t -= 1; if (t < 1 / 6) return p + (q - p) * 6 * t; if (t < 1 / 2) return q; if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6; return p; } if (s === 0) { r = g = b = l; // achromatic } else { var q = l < 0.5 ? l * (1 + s) : l + s - l * s; var p = 2 * l - q; r = hue2rgb(p, q, h + 1 / 3); g = hue2rgb(p, q, h); b = hue2rgb(p, q, h - 1 / 3); } return { r: r * 255, g: g * 255, b: b * 255 }; } // `rgbToHsv` // Converts an RGB color value to HSV // *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1] // *Returns:* { h, s, v } in [0,1] function rgbToHsv(r, g, b) { r = bound01(r, 255); g = bound01(g, 255); b = bound01(b, 255); var max = mathMax(r, g, b), min = mathMin(r, g, b); var h, s, v = max; var d = max - min; s = max === 0 ? 0 : d / max; if (max == min) { h = 0; // achromatic } else { switch (max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return { h: h, s: s, v: v }; } // `hsvToRgb` // Converts an HSV color value to RGB. // *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100] // *Returns:* { r, g, b } in the set [0, 255] function hsvToRgb(h, s, v) { h = bound01(h, 360) * 6; s = bound01(s, 100); v = bound01(v, 100); var i = math.floor(h), f = h - i, p = v * (1 - s), q = v * (1 - f * s), t = v * (1 - (1 - f) * s), mod = i % 6, r = [v, q, p, p, t, v][mod], g = [t, v, v, q, p, p][mod], b = [p, p, t, v, v, q][mod]; return { r: r * 255, g: g * 255, b: b * 255 }; } // `rgbToHex` // Converts an RGB color to hex // Assumes r, g, and b are contained in the set [0, 255] // Returns a 3 or 6 character hex function rgbToHex(r, g, b, allow3Char) { var hex = [pad2(mathRound(r).toString(16)), pad2(mathRound(g).toString(16)), pad2(mathRound(b).toString(16))]; // Return a 3 character hex if possible if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) { return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0); } return hex.join(''); } // `rgbaToHex` // Converts an RGBA color plus alpha transparency to hex // Assumes r, g, b and a are contained in the set [0, 255] // Returns an 8 character hex function rgbaToHex(r, g, b, a) { var hex = [ pad2(convertDecimalToHex(a)), pad2(mathRound(r).toString(16)), pad2(mathRound(g).toString(16)), pad2(mathRound(b).toString(16)), ]; return hex.join(''); } // `equals` // Can be called with any tinycolor input tinycolor.equals = function (color1, color2) { if (!color1 || !color2) { return false; } return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString(); }; tinycolor.random = function () { return tinycolor.fromRatio({ r: mathRandom(), g: mathRandom(), b: mathRandom(), }); }; // Modification Functions // ---------------------- // Thanks to less.js for some of the basics here // <https://github.com/cloudhead/less.js/blob/master/lib/less/functions.js> function desaturate(color, amount) { amount = amount === 0 ? 0 : amount || 10; var hsl = tinycolor(color).toHsl(); hsl.s -= amount / 100; hsl.s = clamp01(hsl.s); return tinycolor(hsl); } function saturate(color, amount) { amount = amount === 0 ? 0 : amount || 10; var hsl = tinycolor(color).toHsl(); hsl.s += amount / 100; hsl.s = clamp01(hsl.s); return tinycolor(hsl); } function greyscale(color) { return tinycolor(color).desaturate(100); } function lighten(color, amount) { amount = amount === 0 ? 0 : amount || 10; var hsl = tinycolor(color).toHsl(); hsl.l += amount / 100; hsl.l = clamp01(hsl.l); return tinycolor(hsl); } function brighten(color, amount) { amount = amount === 0 ? 0 : amount || 10; var rgb = tinycolor(color).toRgb(); rgb.r = mathMax(0, mathMin(255, rgb.r - mathRound(255 * -(amount / 100)))); rgb.g = mathMax(0, mathMin(255, rgb.g - mathRound(255 * -(amount / 100)))); rgb.b = mathMax(0, mathMin(255, rgb.b - mathRound(255 * -(amount / 100)))); return tinycolor(rgb); } function darken(color, amount) { amount = amount === 0 ? 0 : amount || 10; var hsl = tinycolor(color).toHsl(); hsl.l -= amount / 100; hsl.l = clamp01(hsl.l); return tinycolor(hsl); } // Spin takes a positive or negative amount within [-360, 360] indicating the change of hue. // Values outside of this range will be wrapped into this range. function spin(color, amount) { var hsl = tinycolor(color).toHsl(); var hue = (mathRound(hsl.h) + amount) % 360; hsl.h = hue < 0 ? 360 + hue : hue; return tinycolor(hsl); } // Combination Functions // --------------------- // Thanks to jQuery xColor for some of the ideas behind these // <https://github.com/infusion/jQuery-xcolor/blob/master/jquery.xcolor.js> function complement(color) { var hsl = tinycolor(color).toHsl(); hsl.h = (hsl.h + 180) % 360; return tinycolor(hsl); } function triad(color) { var hsl = tinycolor(color).toHsl(); var h = hsl.h; return [ tinycolor(color), tinycolor({ h: (h + 120) % 360, s: hsl.s, l: hsl.l }), tinycolor({ h: (h + 240) % 360, s: hsl.s, l: hsl.l }), ]; } function tetrad(color) { var hsl = tinycolor(color).toHsl(); var h = hsl.h; return [ tinycolor(color), tinycolor({ h: (h + 90) % 360, s: hsl.s, l: hsl.l }), tinycolor({ h: (h + 180) % 360, s: hsl.s, l: hsl.l }), tinycolor({ h: (h + 270) % 360, s: hsl.s, l: hsl.l }), ]; } function splitcomplement(color) { var hsl = tinycolor(color).toHsl(); var h = hsl.h; return [ tinycolor(color), tinycolor({ h: (h + 72) % 360, s: hsl.s, l: hsl.l }), tinycolor({ h: (h + 216) % 360, s: hsl.s, l: hsl.l }), ]; } function analogous(color, results, slices) { results = results || 6; slices = slices || 30; var hsl = tinycolor(color).toHsl(); var part = 360 / slices; var ret = [tinycolor(color)]; for (hsl.h = (hsl.h - ((part * results) >> 1) + 720) % 360; --results;) { hsl.h = (hsl.h + part) % 360; ret.push(tinycolor(hsl)); } return ret; } function monochromatic(color, results) { results = results || 6; var hsv = tinycolor(color).toHsv(); var h = hsv.h, s = hsv.s, v = hsv.v; var ret = []; var modification = 1 / results; while (results--) { ret.push(tinycolor({ h: h, s: s, v: v })); v = (v + modification) % 1; } return ret; } // Utility Functions // --------------------- tinycolor.mix = function (color1, color2, amount) { amount = amount === 0 ? 0 : amount || 50; var rgb1 = tinycolor(color1).toRgb(); var rgb2 = tinycolor(color2).toRgb(); var p = amount / 100; var w = p * 2 - 1; var a = rgb2.a - rgb1.a; var w1; if (w * a == -1) { w1 = w; } else { w1 = (w + a) / (1 + w * a); } w1 = (w1 + 1) / 2; var w2 = 1 - w1; var rgba = { r: rgb2.r * w1 + rgb1.r * w2, g: rgb2.g * w1 + rgb1.g * w2, b: rgb2.b * w1 + rgb1.b * w2, a: rgb2.a * p + rgb1.a * (1 - p), }; return tinycolor(rgba); }; // Readability Functions // --------------------- // <http://www.w3.org/TR/AERT#color-contrast> // `readability` // Analyze the 2 colors and returns an object with the following properties: // `brightness`: difference in brightness between the two colors // `color`: difference in color/hue between the two colors tinycolor.readability = function (color1, color2) { var c1 = tinycolor(color1); var c2 = tinycolor(color2); var rgb1 = c1.toRgb(); var rgb2 = c2.toRgb(); var brightnessA = c1.getBrightness(); var brightnessB = c2.getBrightness(); var colorDiff = Math.max(rgb1.r, rgb2.r) - Math.min(rgb1.r, rgb2.r) + Math.max(rgb1.g, rgb2.g) - Math.min(rgb1.g, rgb2.g) + Math.max(rgb1.b, rgb2.b) - Math.min(rgb1.b, rgb2.b); return { brightness: Math.abs(brightnessA - brightnessB), color: colorDiff, }; }; // `readable` // http://www.w3.org/TR/AERT#color-contrast // Ensure that foreground and background color combinations provide sufficient contrast. // *Example* // tinycolor.isReadable("#000", "#111") => false tinycolor.isReadable = function (color1, color2) { var readability = tinycolor.readability(color1, color2); return readability.brightness > 125 && readability.color > 500; }; // `mostReadable` // Given a base color and a list of possible foreground or background // colors for that base, returns the most readable color. // *Example* // tinycolor.mostReadable("#123", ["#fff", "#000"]) => "#000" tinycolor.mostReadable = function (baseColor, colorList) { var bestColor = null; var bestScore = 0; var bestIsReadable = false; for (var i = 0; i < colorList.length; i++) { // We normalize both around the "acceptable" breaking point, // but rank brightness constrast higher than hue. var readability = tinycolor.readability(baseColor, colorList[i]); var readable = readability.brightness > 125 && readability.color > 500; var score = 3 * (readability.brightness / 125) + readability.color / 500; if ((readable && !bestIsReadable) || (readable && bestIsReadable && score > bestScore) || (!readable && !bestIsReadable && score > bestScore)) { bestIsReadable = readable; bestScore = score; bestColor = tinycolor(colorList[i]); } } return bestColor; }; // Big List of Colors // ------------------ // <http://www.w3.org/TR/css3-color/#svg-color> var names = (tinycolor.names = { aliceblue: 'f0f8ff', antiquewhite: 'faebd7', aqua: '0ff', aquamarine: '7fffd4', azure: 'f0ffff', beige: 'f5f5dc', bisque: 'ffe4c4', black: '000', blanchedalmond: 'ffebcd', blue: '00f', blueviolet: '8a2be2', brown: 'a52a2a', burlywood: 'deb887', burntsienna: 'ea7e5d', cadetblue: '5f9ea0', chartreuse: '7fff00', chocolate: 'd2691e', coral: 'ff7f50', cornflowerblue: '6495ed', cornsilk: 'fff8dc', crimson: 'dc143c', cyan: '0ff', darkblue: '00008b', darkcyan: '008b8b', darkgoldenrod: 'b8860b', darkgray: 'a9a9a9', darkgreen: '006400', darkgrey: 'a9a9a9', darkkhaki: 'bdb76b', darkmagenta: '8b008b', darkolivegreen: '556b2f', darkorange: 'ff8c00', darkorchid: '9932cc', darkred: '8b0000', darksalmon: 'e9967a', darkseagreen: '8fbc8f', darkslateblue: '483d8b', darkslategray: '2f4f4f', darkslategrey: '2f4f4f', darkturquoise: '00ced1', darkviolet: '9400d3', deeppink: 'ff1493', deepskyblue: '00bfff', dimgray: '696969', dimgrey: '696969', dodgerblue: '1e90ff', firebrick: 'b22222', floralwhite: 'fffaf0', forestgreen: '228b22', fuchsia: 'f0f', gainsboro: 'dcdcdc', ghostwhite: 'f8f8ff', gold: 'ffd700', goldenrod: 'daa520', gray: '808080', green: '008000', greenyellow: 'adff2f', grey: '808080', honeydew: 'f0fff0', hotpink: 'ff69b4', indianred: 'cd5c5c', indigo: '4b0082', ivory: 'fffff0', khaki: 'f0e68c', lavender: 'e6e6fa', lavenderblush: 'fff0f5', lawngreen: '7cfc00', lemonchiffon: 'fffacd', lightblue: 'add8e6', lightcoral: 'f08080', lightcyan: 'e0ffff', lightgoldenrodyellow: 'fafad2', lightgray: 'd3d3d3', lightgreen: '90ee90', lightgrey: 'd3d3d3', lightpink: 'ffb6c1', lightsalmon: 'ffa07a', lightseagreen: '20b2aa', lightskyblue: '87cefa', lightslategray: '789', lightslategrey: '789', lightsteelblue: 'b0c4de', lightyellow: 'ffffe0', lime: '0f0', limegreen: '32cd32', linen: 'faf0e6', magenta: 'f0f', maroon: '800000', mediumaquamarine: '66cdaa', mediumblue: '0000cd', mediumorchid: 'ba55d3', mediumpurple: '9370db', mediumseagreen: '3cb371', mediumslateblue: '7b68ee', mediumspringgreen: '00fa9a', mediumturquoise: '48d1cc', mediumvioletred: 'c71585', midnightblue: '191970', mintcream: 'f5fffa', mistyrose: 'ffe4e1', moccasin: 'ffe4b5', navajowhite: 'ffdead', navy: '000080', oldlace: 'fdf5e6', olive: '808000', olivedrab: '6b8e23', orange: 'ffa500', orangered: 'ff4500', orchid: 'da70d6', palegoldenrod: 'eee8aa', palegreen: '98fb98', paleturquoise: 'afeeee', palevioletred: 'db7093', papayawhip: 'ffefd5', peachpuff: 'ffdab9', peru: 'cd853f', pink: 'ffc0cb', plum: 'dda0dd', powderblue: 'b0e0e6', purple: '800080', rebeccapurple: '663399', red: 'f00', rosybrown: 'bc8f8f', royalblue: '4169e1', saddlebrown: '8b4513', salmon: 'fa8072', sandybrown: 'f4a460', seagreen: '2e8b57', seashell: 'fff5ee', sienna: 'a0522d', silver: 'c0c0c0', skyblue: '87ceeb', slateblue: '6a5acd', slategray: '708090', slategrey: '708090', snow: 'fffafa', springgreen: '00ff7f', steelblue: '4682b4', tan: 'd2b48c', teal: '008080', thistle: 'd8bfd8', tomato: 'ff6347', turquoise: '40e0d0', violet: 'ee82ee', wheat: 'f5deb3', white: 'fff', whitesmoke: 'f5f5f5', yellow: 'ff0', yellowgreen: '9acd32', }); // Make it easy to access colors via `hexNames[hex]` var hexNames = (tinycolor.hexNames = flip(names)); // Utilities // --------- // `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }` function flip(o) { var flipped = {}; for (var i in o) { if (o.hasOwnProperty(i)) { flipped[o[i]] = i; } } return flipped; } // Return a valid alpha value [0,1] with all invalid values being set to 1 function boundAlpha(a) { a = parseFloat(a); if (isNaN(a) || a < 0 || a > 1) { a = 1; } return a; } // Take input from [0, n] and return it as [0, 1] function bound01(n, max) { if (isOnePointZero(n)) { n = '100%'; } var processPercent = isPercentage(n); n = mathMin(max, mathMax(0, parseFloat(n))); // Automatically convert percentage into number if (processPercent) { n = parseInt(n * max, 10) / 100; } // Handle floating point rounding errors if (math.abs(n - max) < 0.000001) { return 1; } // Convert into [0, 1] range if it isn't already return (n % max) / parseFloat(max); } // Force a number between 0 and 1 function clamp01(val) { return mathMin(1, mathMax(0, val)); } // Parse a base-16 hex value into a base-10 integer function parseIntFromHex(val) { return parseInt(val, 16); } // Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1 // <http://stackoverflow.com/questions/7422072/javascript-how-to-detect-number-as-a-decimal-including-1-0> function isOnePointZero(n) { return typeof n == 'string' && n.indexOf('.') != -1 && parseFloat(n) === 1; } // Check to see if string passed in is a percentage function isPercentage(n) { return typeof n === 'string' && n.indexOf('%') != -1; } // Force a hex value to have 2 characters function pad2(c) { return c.length == 1 ? '0' + c : '' + c; } // Replace a decimal with it's percentage value function convertToPercentage(n) { if (n <= 1) { n = n * 100 + '%'; } return n; } // Converts a decimal to a hex value function convertDecimalToHex(d) { return Math.round(parseFloat(d) * 255).toString(16); } // Converts a hex value to a decimal function convertHexToDecimal(h) { return parseIntFromHex(h) / 255; } var matchers = (function () { // <http://www.w3.org/TR/css3-values/#integers> var CSS_INTEGER = '[-\\+]?\\d+%?'; // <http://www.w3.org/TR/css3-values/#number-value> var CSS_NUMBER = '[-\\+]?\\d*\\.\\d+%?'; // Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome. var CSS_UNIT = '(?:' + CSS_NUMBER + ')|(?:' + CSS_INTEGER + ')'; // Actual matching. // Parentheses and commas are optional, but not required. // Whitespace can take the place of commas or opening paren var PERMISSIVE_MATCH3 = '[\\s|\\(]+(' + CSS_UNIT + ')[,|\\s]+(' + CSS_UNIT + ')[,|\\s]+(' + CSS_UNIT + ')\\s*\\)?'; var PERMISSIVE_MATCH4 = '[\\s|\\(]+(' + CSS_UNIT + ')[,|\\s]+(' + CSS_UNIT + ')[,|\\s]+(' + CSS_UNIT + ')[,|\\s]+(' + CSS_UNIT + ')\\s*\\)?'; return { rgb: new RegExp('rgb' + PERMISSIVE_MATCH3), rgba: new RegExp('rgba' + PERMISSIVE_MATCH4), hsl: new RegExp('hsl' + PERMISSIVE_MATCH3), hsla: new RegExp('hsla' + PERMISSIVE_MATCH4), hsv: new RegExp('hsv' + PERMISSIVE_MATCH3), hsva: new RegExp('hsva' + PERMISSIVE_MATCH4), hex3: /^([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, hex6: /^([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/, hex8: /^([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/, }; })(); // `stringInputToObject` // Permissive string parsing. Take in a number of formats, and output an object // based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}` function stringInputToObject(color) { color = color.replace(trimLeft, '').replace(trimRight, '').toLowerCase(); var named = false; if (names[color]) { color = names[color]; named = true; } else if (color == 'transparent') { return { r: 0, g: 0, b: 0, a: 0, format: 'name' }; } // Try to match string input using regular expressions. // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360] // Just return an object and let the conversion functions handle that. // This way the result will be the same whether the tinycolor is initialized with string or object. var match; if ((match = matchers.rgb.exec(color))) { return { r: match[1], g: match[2], b: match[3] }; } if ((match = matchers.rgba.exec(color))) { return { r: match[1], g: match[2], b: match[3], a: match[4] }; } if ((match = matchers.hsl.exec(color))) { return { h: match[1], s: match[2], l: match[3] }; } if ((match = matchers.hsla.exec(color))) { return { h: match[1], s: match[2], l: match[3], a: match[4] }; } if ((match = matchers.hsv.exec(color))) { return { h: match[1], s: match[2], v: match[3] }; } if ((match = matchers.hsva.exec(color))) { return { h: match[1], s: match[2], v: match[3], a: match[4] }; } if ((match = matchers.hex8.exec(color))) { return { a: convertHexToDecimal(match[1]), r: parseIntFromHex(match[2]), g: parseIntFromHex(match[3]), b: parseIntFromHex(match[4]), format: named ? 'name' : 'hex8', }; } if ((match = matchers.hex6.exec(color))) { return { r: parseIntFromHex(match[1]), g: parseIntFromHex(match[2]), b: parseIntFromHex(match[3]), format: named ? 'name' : 'hex', }; } if ((match = matchers.hex3.exec(color))) { return { r: parseIntFromHex(match[1] + '' + match[1]), g: parseIntFromHex(match[2] + '' + match[2]), b: parseIntFromHex(match[3] + '' + match[3]), format: named ? 'name' : 'hex', }; } return false; } window.tinycolor = tinycolor; //})(); $(function () { if ($.fn.spectrum.load) { $.fn.spectrum.processNativeColorInputs(); } }); } ;// CONCATENATED MODULE: ./src/domain_abstract/ui/InputColor.ts var InputColor_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var InputColor_assign = ( false) || function () { InputColor_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return InputColor_assign.apply(this, arguments); }; cash_dom["default"] && ColorPicker(cash_dom["default"]); var getColor = function (color) { var name = color.getFormat() === 'name' && color.toName(); var cl = color.getAlpha() == 1 ? color.toHexString() : color.toRgbString(); return name || cl.replace(/ /g, ''); }; var InputColor = /** @class */ (function (_super) { InputColor_extends(InputColor, _super); function InputColor() { return _super !== null && _super.apply(this, arguments) || this; } InputColor.prototype.template = function () { var ppfx = this.ppfx; return "\n <div class=\"".concat(this.holderClass(), "\"></div>\n <div class=\"").concat(ppfx, "field-colorp\">\n <div class=\"").concat(ppfx, "field-colorp-c\" data-colorp-c>\n <div class=\"").concat(ppfx, "checker-bg\"></div>\n </div>\n </div>\n "); }; InputColor.prototype.inputClass = function () { var ppfx = this.ppfx; return "".concat(ppfx, "field ").concat(ppfx, "field-color"); }; InputColor.prototype.holderClass = function () { return "".concat(this.ppfx, "input-holder"); }; InputColor.prototype.remove = function () { _super.prototype.remove.call(this); this.colorEl.spectrum('destroy'); return this; }; InputColor.prototype.handleChange = function (e) { e.stopPropagation(); var value = e.target.value; if ((0,index_all.isUndefined)(value)) return; this.__onInputChange(value); }; InputColor.prototype.__onInputChange = function (val) { var _a = this, model = _a.model, opts = _a.opts; var onChange = opts.onChange; var value = val; var colorEl = this.getColorEl(); // Check the color by using the ColorPicker's parser if (colorEl) { colorEl.spectrum('set', value); var tc = colorEl.spectrum('get'); var color = value && getColor(tc); color && (value = color); } onChange ? onChange(value) : model.set({ value: value }, { fromInput: 1 }); }; /** * Set value to the model * @param {string} val * @param {Object} opts */ InputColor.prototype.setValue = function (val, opts) { if (opts === void 0) { opts = {}; } var model = this.model; var def = !(0,index_all.isUndefined)(opts.def) ? opts.def : model.get('defaults'); var value = !(0,index_all.isUndefined)(val) ? val : !(0,index_all.isUndefined)(def) ? def : ''; var inputEl = this.getInputEl(); var colorEl = this.getColorEl(); var valueClr = value != 'none' ? value : ''; inputEl.value = value; colorEl.get(0).style.backgroundColor = valueClr; // This prevents from adding multiple thumbs in spectrum if (opts.fromTarget || (opts.fromInput && !opts.avoidStore)) { colorEl.spectrum('set', valueClr); this.noneColor = value == 'none'; this.movedColor = valueClr; } }; /** * Get the color input element * @return {HTMLElement} */ InputColor.prototype.getColorEl = function () { var _this = this; if (!this.colorEl) { var _a = this, em = _a.em, model_1 = _a.model, opts = _a.opts; var ppfx = this.ppfx; var onChange_1 = opts.onChange; var colorEl = (0,cash_dom["default"])("<div class=\"".concat(this.ppfx, "field-color-picker\"></div>")); var cpStyle = colorEl.get(0).style; var elToAppend = em && em.config ? em.config.el : ''; var colorPickerConfig = (em && em.getConfig && em.getConfig().colorPicker) || {}; this.movedColor = ''; var changed_1 = false; var previousColor_1; this.$el.find('[data-colorp-c]').append(colorEl); var handleChange_1 = function (value, complete) { if (complete === void 0) { complete = true; } if (onChange_1) { onChange_1(value, !complete); } else { complete && model_1.setValueFromInput(0, false); // for UndoManager model_1.setValueFromInput(value, complete); } }; // @ts-ignore colorEl.spectrum(InputColor_assign(InputColor_assign(InputColor_assign({ color: model_1.getValue() || false, containerClassName: "".concat(ppfx, "one-bg ").concat(ppfx, "two-color"), appendTo: elToAppend || 'body', maxSelectionSize: 8, showPalette: true, showAlpha: true, chooseText: 'Ok', cancelText: '⨯', palette: [] }, colorPickerConfig), (model_1.get('colorPicker') || {})), { move: function (color) { var cl = getColor(color); _this.movedColor = cl; cpStyle.backgroundColor = cl; handleChange_1(cl, false); }, change: function (color) { changed_1 = true; var cl = getColor(color); cpStyle.backgroundColor = cl; handleChange_1(cl); _this.noneColor = false; }, show: function (color) { changed_1 = false; _this.movedColor = ''; previousColor_1 = onChange_1 ? model_1.getValue({ noDefault: true }) : getColor(color); }, hide: function () { if (!changed_1 && (previousColor_1 || onChange_1)) { if (_this.noneColor) { previousColor_1 = ''; } cpStyle.backgroundColor = previousColor_1; // @ts-ignore colorEl.spectrum('set', previousColor_1); handleChange_1(previousColor_1, false); } } })); if (em && em.on) { this.listenTo(em, 'component:selected', function () { _this.movedColor && handleChange_1(_this.movedColor); changed_1 = true; _this.movedColor = ''; // @ts-ignore colorEl.spectrum('hide'); }); } this.colorEl = colorEl; } return this.colorEl; }; InputColor.prototype.render = function () { ui_Input.prototype.render.call(this); // This will make the color input available on render this.getColorEl(); return this; }; return InputColor; }(ui_Input)); /* harmony default export */ const ui_InputColor = (InputColor); ;// CONCATENATED MODULE: ./src/trait_manager/view/TraitColorView.ts var TraitColorView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var TraitColorView = /** @class */ (function (_super) { TraitColorView_extends(TraitColorView, _super); function TraitColorView() { return _super !== null && _super.apply(this, arguments) || this; } TraitColorView.prototype.templateInput = function () { return ''; }; /** * Returns input element * @return {HTMLElement} * @private */ TraitColorView.prototype.getInputEl = function () { if (!this.input) { var model = this.model; var value = this.getModelValue(); var inputColor = new ui_InputColor({ model: model, target: this.config.em, contClass: this.ppfx + 'field-color', ppfx: this.ppfx, }); var input = inputColor.render(); input.setValue(value, { fromTarget: 1 }); this.input = input.el; } return this.input; }; return TraitColorView; }(view_TraitView)); /* harmony default export */ const view_TraitColorView = (TraitColorView); ;// CONCATENATED MODULE: ./src/trait_manager/view/TraitButtonView.ts var TraitButtonView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var TraitButtonView = /** @class */ (function (_super) { TraitButtonView_extends(TraitButtonView, _super); function TraitButtonView() { return _super !== null && _super.apply(this, arguments) || this; } TraitButtonView.prototype.templateInput = function () { return ''; }; TraitButtonView.prototype.onChange = function () { this.handleClick(); }; TraitButtonView.prototype.handleClick = function () { var _a = this, model = _a.model, em = _a.em; var command = model.get('command'); if (command) { if ((0,index_all.isString)(command)) { em.Commands.run(command); } else { command(em.Editor, model); } } }; TraitButtonView.prototype.renderLabel = function () { if (this.model.get('label')) { view_TraitView.prototype.renderLabel.apply(this); } }; TraitButtonView.prototype.getInputEl = function () { var _a = this, model = _a.model, ppfx = _a.ppfx; var _b = model.props(), labelButton = _b.labelButton, text = _b.text, full = _b.full; var label = labelButton || text; var className = "".concat(ppfx, "btn"); var input = "<button type=\"button\" class=\"".concat(className, "-prim").concat(full ? " ".concat(className, "--full") : '', "\">").concat(label, "</button>"); return input; }; return TraitButtonView; }(view_TraitView)); /* harmony default export */ const view_TraitButtonView = (TraitButtonView); // Fix #4388 TraitButtonView.prototype.eventCapture = ['click button']; ;// CONCATENATED MODULE: ./src/trait_manager/index.ts var trait_manager_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var trait_manager_evAll = 'trait'; var trait_manager_evPfx = "".concat(trait_manager_evAll, ":"); var trait_manager_evCustom = "".concat(trait_manager_evPfx, "custom"); var typesDef = { text: view_TraitView, number: view_TraitNumberView, select: view_TraitSelectView, checkbox: view_TraitCheckboxView, color: view_TraitColorView, button: view_TraitButtonView, }; var TraitManager = /** @class */ (function (_super) { trait_manager_extends(TraitManager, _super); /** * Get configuration object * @name getConfig * @function * @return {Object} */ /** * Initialize module * @private */ function TraitManager(em) { var _this = _super.call(this, em, 'TraitManager', trait_manager_config_config) || this; _this.TraitsView = view_TraitsView; _this.events = { all: trait_manager_evAll, custom: trait_manager_evCustom, }; var model = new common/* Model */.Hn(); _this.model = model; _this.types = typesDef; var upAll = (0,index_all.debounce)(function () { return _this.__upSel(); }, 0); model.listenTo(em, 'component:toggled', upAll); var update = (0,index_all.debounce)(function () { return _this.__onUp(); }, 0); model.listenTo(em, 'trait:update', update); return _this; } TraitManager.prototype.__upSel = function () { this.select(this.em.getSelected()); }; TraitManager.prototype.__onUp = function () { this.select(this.getSelected()); }; TraitManager.prototype.select = function (component) { var traits = component ? component.getTraits() : []; this.model.set({ component: component, traits: traits }); this.__trgCustom(); }; TraitManager.prototype.getSelected = function () { return this.model.get('component'); }; /** * Get traits from the currently selected component. */ TraitManager.prototype.getCurrent = function () { return this.model.get('traits') || []; }; TraitManager.prototype.__trgCustom = function (opts) { if (opts === void 0) { opts = {}; } this.__ctn = this.__ctn || opts.container; this.em.trigger(this.events.custom, { container: this.__ctn }); }; TraitManager.prototype.postRender = function () { this.__appendTo(); }; /** * * Get Traits viewer * @private */ TraitManager.prototype.getTraitsViewer = function () { return this.view; }; /** * Add new trait type * @param {string} name Type name * @param {Object} methods Object representing the trait */ TraitManager.prototype.addType = function (name, trait) { var baseView = this.getType('text'); //@ts-ignore this.types[name] = baseView.extend(trait); }; /** * Get trait type * @param {string} name Type name * @return {Object} */ TraitManager.prototype.getType = function (name) { return this.getTypes()[name]; }; /** * Get all trait types * @returns {Object} */ TraitManager.prototype.getTypes = function () { return this.types; }; TraitManager.prototype.render = function () { var _a = this, view = _a.view, em = _a.em; var config = this.getConfig(); var el = view && view.el; view = new view_TraitsView({ el: el, collection: [], editor: em, config: config, }, this.getTypes()); this.view = view; return view.el; }; TraitManager.prototype.destroy = function () { this.model.stopListening(); this.model.clear(); }; return TraitManager; }(abstract_Module)); /* harmony default export */ const trait_manager = (TraitManager); ;// CONCATENATED MODULE: ./src/navigator/config/config.ts var navigator_config_config_config = { stylePrefix: '', appendTo: '', sortable: true, hidable: true, hideTextnode: true, root: '', showWrapper: true, showHover: true, scrollCanvas: { behavior: 'smooth', block: 'nearest' }, scrollLayers: { behavior: 'auto', block: 'nearest' }, highlightHover: true, custom: false, onInit: function () { }, onRender: function () { }, extend: {}, }; /* harmony default export */ const navigator_config_config = (navigator_config_config_config); ;// CONCATENATED MODULE: ./src/navigator/view/ItemsView.ts var ItemsView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ItemsView = /** @class */ (function (_super) { ItemsView_extends(ItemsView, _super); function ItemsView(opt) { if (opt === void 0) { opt = {}; } var _this = _super.call(this, opt) || this; _this.items = []; _this.opt = opt; var config = opt.config || {}; _this.config = config; _this.parentView = opt.parentView; var pfx = config.stylePrefix || ''; var ppfx = config.pStylePrefix || ''; var coll = _this.collection; _this.listenTo(coll, 'add', _this.addTo); _this.listenTo(coll, 'reset resetNavigator', _this.render); _this.listenTo(coll, 'remove', _this.removeChildren); _this.className = "".concat(pfx, "layers"); var em = config.em; if (config.sortable && !_this.opt.sorter) { var utils = em.Utils; _this.opt.sorter = new utils.Sorter({ // @ts-ignore container: config.sortContainer || _this.el, containerSel: ".".concat(_this.className), itemSel: ".".concat(pfx, "layer"), ignoreViewChildren: 1, onEndMove: function (created, sorter, data) { var srcModel = sorter.getSourceModel(); em.setSelected(srcModel, { forceChange: 1 }); em.trigger("".concat(eventDrag, ":end"), data); }, avoidSelectOnEnd: 1, nested: 1, ppfx: ppfx, pfx: pfx, em: em, }); } // For the sorter _this.$el.data('collection', coll); opt.parent && _this.$el.data('model', opt.parent); return _this; } ItemsView.prototype.removeChildren = function (removed) { // @ts-ignore var view = removed.viewLayer; if (!view) return; view.remove(); // @ts-ignore delete removed.viewLayer; }; /** * Add to collection * @param Object Model * * @return Object * */ ItemsView.prototype.addTo = function (model) { var i = this.collection.indexOf(model); this.addToCollection(model, null, i); }; /** * Add new object to collection * @param Object Model * @param Object Fragment collection * @param integer Index of append * * @return Object Object created * */ ItemsView.prototype.addToCollection = function (model, fragmentEl, index) { var _a = this, parentView = _a.parentView, opt = _a.opt, config = _a.config; var ItemView = opt.ItemView, opened = opt.opened, module = opt.module, level = opt.level, sorter = opt.sorter; var fragment = fragmentEl || null; var item = new ItemView({ ItemView: ItemView, level: level, model: model, parentView: parentView, config: config, sorter: sorter, opened: opened, module: module, }); var rendered = item.render().el; if (fragment) { fragment.appendChild(rendered); } else { if (typeof index !== 'undefined') { var method = 'before'; // If the added model is the last of collection // need to change the logic of append if (this.$el.children().length == index) { index--; method = 'after'; } // In case the added is new in the collection index will be -1 if (index < 0) { this.$el.append(rendered); } else { // @ts-ignore this.$el.children().eq(index)[method](rendered); } } else this.$el.append(rendered); } this.items.push(item); return rendered; }; ItemsView.prototype.remove = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } common/* View */.G7.prototype.remove.apply(this, args); this.items.map(function (i) { return i.remove(); }); return this; }; ItemsView.prototype.render = function () { var _this = this; var frag = document.createDocumentFragment(); var el = this.el; el.innerHTML = ''; this.collection.each(function (model) { return _this.addToCollection(model, frag); }); el.appendChild(frag); el.className = this.className; return this; }; return ItemsView; }(common/* View */.G7)); /* harmony default export */ const view_ItemsView = (ItemsView); ;// CONCATENATED MODULE: ./src/navigator/view/ItemView.ts var ItemView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ItemView_inputProp = 'contentEditable'; var ItemView = /** @class */ (function (_super) { ItemView_extends(ItemView, _super); function ItemView(opt) { var _this = _super.call(this, opt) || this; (0,index_all.bindAll)(_this, '__render'); _this.opt = opt; _this.module = opt.module; _this.config = opt.config || {}; _this.sorter = opt.sorter || ''; _this.parentView = opt.parentView; var _a = _this, model = _a.model, pfx = _a.pfx, ppfx = _a.ppfx; var type = model.get('type') || 'default'; _this.className = "".concat(pfx, "layer ").concat(pfx, "layer__t-").concat(type, " no-select ").concat(ppfx, "two-color"); _this.inputNameCls = "".concat(ppfx, "layer-name"); _this.clsTitleC = "".concat(pfx, "layer-title-c"); _this.clsTitle = "".concat(pfx, "layer-title"); _this.clsCaret = "".concat(pfx, "layer-caret"); _this.clsCount = "".concat(pfx, "layer-count"); _this.clsMove = "".concat(pfx, "layer-move"); _this.clsChildren = "".concat(pfx, "layer-children"); _this.clsNoChild = "".concat(pfx, "layer-no-chld"); _this.clsEdit = "".concat(_this.inputNameCls, "--edit"); _this.clsNoEdit = "".concat(_this.inputNameCls, "--no-edit"); _this.initComponent(); return _this; } ItemView.prototype.events = function () { return { 'mousedown [data-toggle-move]': 'startSort', 'touchstart [data-toggle-move]': 'startSort', 'click [data-toggle-visible]': 'toggleVisibility', 'click [data-toggle-open]': 'toggleOpening', 'click [data-toggle-select]': 'handleSelect', 'mouseover [data-toggle-select]': 'handleHover', 'mouseout [data-toggle-select]': 'handleHoverOut', 'dblclick [data-name]': 'handleEdit', 'keydown [data-name]': 'handleEditKey', 'focusout [data-name]': 'handleEditEnd', }; }; ItemView.prototype.template = function (model) { var _a = this, pfx = _a.pfx, ppfx = _a.ppfx, config = _a.config, clsNoEdit = _a.clsNoEdit, module = _a.module, opt = _a.opt, em = _a.em; var hidable = config.hidable; var count = module.getComponents(model).length; var addClass = !count ? this.clsNoChild : ''; var clsTitle = "".concat(this.clsTitle, " ").concat(addClass); var clsTitleC = "".concat(this.clsTitleC, " ").concat(ppfx, "one-bg"); var clsInput = "".concat(this.inputNameCls, " ").concat(clsNoEdit, " ").concat(ppfx, "no-app"); var level = opt.level + 1; var gut = "".concat(30 + level * 10, "px"); var name = model.getName(); var icon = model.getIcon(); var clsBase = "".concat(pfx, "layer"); var icons = (em === null || em === void 0 ? void 0 : em.getConfig()).icons; var _b = icons, move = _b.move, eye = _b.eye, eyeOff = _b.eyeOff, chevron = _b.chevron; return "\n ".concat(hidable ? "<i class=\"".concat(pfx, "layer-vis\" data-toggle-visible>\n <i class=\"").concat(pfx, "layer-vis-on\">").concat(eye, "</i>\n <i class=\"").concat(pfx, "layer-vis-off\">").concat(eyeOff, "</i>\n </i>") : '', "\n <div class=\"").concat(clsTitleC, "\">\n <div class=\"").concat(clsTitle, "\" style=\"padding-left: ").concat(gut, "\" data-toggle-select>\n <div class=\"").concat(pfx, "layer-title-inn\" title=\"").concat(name, "\">\n <i class=\"").concat(this.clsCaret, "\" data-toggle-open>").concat(chevron, "</i>\n ").concat(icon ? "<span class=\"".concat(clsBase, "__icon\">").concat(icon, "</span>") : '', "\n <span class=\"").concat(clsInput, "\" data-name>").concat(name, "</span>\n </div>\n </div>\n </div>\n <div class=\"").concat(this.clsCount, "\" data-count>").concat(count || '', "</div>\n <div class=\"").concat(this.clsMove, "\" data-toggle-move>").concat(move || '', "</div>\n <div class=\"").concat(this.clsChildren, "\"></div>"); }; Object.defineProperty(ItemView.prototype, "em", { get: function () { return this.module.em; }, enumerable: false, configurable: true }); Object.defineProperty(ItemView.prototype, "ppfx", { get: function () { return this.em.getConfig().stylePrefix; }, enumerable: false, configurable: true }); Object.defineProperty(ItemView.prototype, "pfx", { get: function () { return this.config.stylePrefix; }, enumerable: false, configurable: true }); ItemView.prototype.initComponent = function () { var _this = this; var _a = this, model = _a.model, config = _a.config; var onInit = config.onInit; var components = model.components(); this.listenTo(components, 'remove add reset', this.checkChildren); [ ['change:status', this.updateStatus], ['change:open', this.updateOpening], ['change:layerable', this.updateLayerable], ['change:style:display', this.updateVisibility], ['rerender:layer', this.render], ['change:name change:custom-name', this.updateName], // @ts-ignore ].forEach(function (item) { return _this.listenTo(model, item[0], item[1]); }); this.$el.data('model', model); this.$el.data('collection', components); // @ts-ignore model.viewLayer = this; onInit.bind(this)({ component: model, render: this.__render, listenTo: this.listenTo, }); }; ItemView.prototype.updateName = function () { this.getInputName().innerText = this.model.getName(); }; ItemView.prototype.getVisibilityEl = function () { if (!this.eyeEl) { this.eyeEl = this.$el.children(".".concat(this.pfx, "layer-vis")); } return this.eyeEl; }; ItemView.prototype.updateVisibility = function () { var _a = this, pfx = _a.pfx, model = _a.model, module = _a.module; var hClass = "".concat(pfx, "layer-hidden"); var hidden = !module.isVisible(model); var method = hidden ? 'addClass' : 'removeClass'; this.$el[method](hClass); this.getVisibilityEl()[method]("".concat(pfx, "layer-off")); }; /** * Toggle visibility * @param Event * * @return void * */ ItemView.prototype.toggleVisibility = function (ev) { ev === null || ev === void 0 ? void 0 : ev.stopPropagation(); var _a = this, module = _a.module, model = _a.model; module.setVisible(model, !module.isVisible(model)); }; /** * Handle the edit of the component name */ ItemView.prototype.handleEdit = function (ev) { ev === null || ev === void 0 ? void 0 : ev.stopPropagation(); var _a = this, em = _a.em, $el = _a.$el, clsNoEdit = _a.clsNoEdit, clsEdit = _a.clsEdit; var inputEl = this.getInputName(); inputEl[ItemView_inputProp] = 'true'; inputEl.focus(); document.execCommand('selectAll', false); em.setEditing(true); $el.find(".".concat(this.inputNameCls)).removeClass(clsNoEdit).addClass(clsEdit); }; ItemView.prototype.handleEditKey = function (ev) { ev.stopPropagation(); ((0,dom/* isEscKey */.kl)(ev) || (0,dom/* isEnterKey */.r$)(ev)) && this.handleEditEnd(ev); }; /** * Handle with the end of editing of the component name */ ItemView.prototype.handleEditEnd = function (ev) { ev === null || ev === void 0 ? void 0 : ev.stopPropagation(); var _a = this, em = _a.em, $el = _a.$el, clsNoEdit = _a.clsNoEdit, clsEdit = _a.clsEdit; var inputEl = this.getInputName(); var name = inputEl.textContent; inputEl.scrollLeft = 0; inputEl[ItemView_inputProp] = 'false'; this.setName(name, { component: this.model, propName: 'custom-name' }); em.setEditing(false); $el.find(".".concat(this.inputNameCls)).addClass(clsNoEdit).removeClass(clsEdit); // Ensure to always update the layer name #4544 this.updateName(); }; ItemView.prototype.setName = function (name, _a) { var propName = _a.propName; this.model.set(propName, name); }; /** * Get the input containing the name of the component * @return {HTMLElement} */ ItemView.prototype.getInputName = function () { if (!this.inputName) { this.inputName = this.el.querySelector(".".concat(this.inputNameCls)); } return this.inputName; }; /** * Update item opening * * @return void * */ ItemView.prototype.updateOpening = function () { var _a = this, $el = _a.$el, model = _a.model, pfx = _a.pfx; var clsOpen = 'open'; var clsChvOpen = "".concat(pfx, "layer-open"); var caret = this.getCaret(); if (this.module.isOpen(model)) { $el.addClass(clsOpen); caret.addClass(clsChvOpen); } else { $el.removeClass(clsOpen); caret.removeClass(clsChvOpen); } }; /** * Toggle item opening * @param {Object} e * * @return void * */ ItemView.prototype.toggleOpening = function (ev) { var _a = this, model = _a.model, module = _a.module; ev === null || ev === void 0 ? void 0 : ev.stopImmediatePropagation(); if (!model.get('components').length) return; module.setOpen(model, !module.isOpen(model)); }; /** * Handle component selection */ ItemView.prototype.handleSelect = function (event) { event === null || event === void 0 ? void 0 : event.stopPropagation(); var _a = this, module = _a.module, model = _a.model; module.setLayerData(model, { selected: true }, { event: event }); }; /** * Handle component selection */ ItemView.prototype.handleHover = function (ev) { ev === null || ev === void 0 ? void 0 : ev.stopPropagation(); var _a = this, module = _a.module, model = _a.model; module.setLayerData(model, { hovered: true }); }; ItemView.prototype.handleHoverOut = function (ev) { ev === null || ev === void 0 ? void 0 : ev.stopPropagation(); var _a = this, module = _a.module, model = _a.model; module.setLayerData(model, { hovered: false }); }; /** * Delegate to sorter * @param Event * */ ItemView.prototype.startSort = function (ev) { ev.stopPropagation(); var _a = this, em = _a.em, sorter = _a.sorter; // Right or middel click if (ev.button && ev.button !== 0) return; if (sorter) { sorter.onStart = function (data) { return em.trigger("".concat(eventDrag, ":start"), data); }; sorter.onMoveClb = function (data) { return em.trigger(eventDrag, data); }; sorter.startSort(ev.target); } }; /** * Update item on status change * @param Event * */ ItemView.prototype.updateStatus = function () { // @ts-ignore view_ComponentView.prototype.updateStatus.apply(this, [ { avoidHover: !this.config.highlightHover, noExtHl: true, }, ]); }; /** * Update item aspect after children changes * * @return void * */ ItemView.prototype.checkChildren = function () { var _a = this, model = _a.model, clsNoChild = _a.clsNoChild, $el = _a.$el, module = _a.module; var count = module.getComponents(model).length; var title = $el.children(".".concat(this.clsTitleC)).children(".".concat(this.clsTitle)); var cnt = this.cnt; if (!cnt) { cnt = $el.children('[data-count]').get(0); this.cnt = cnt; } title[count ? 'removeClass' : 'addClass'](clsNoChild); if (cnt) cnt.innerHTML = count || ''; !count && module.setOpen(model, false); }; ItemView.prototype.getCaret = function () { if (!this.caret || !this.caret.length) { this.caret = this.$el.children(".".concat(this.clsTitleC)).find(".".concat(this.clsCaret)); } return this.caret; }; ItemView.prototype.setRoot = function (el) { var _a; el = (0,index_all.isString)(el) ? (_a = this.em.getWrapper()) === null || _a === void 0 ? void 0 : _a.find(el)[0] : el; var model = (0,mixins.getModel)(el, 0); if (!model) return; this.stopListening(); this.model = model; this.initComponent(); this._rendered && this.render(); }; ItemView.prototype.updateLayerable = function () { var parentView = this.parentView; var toRerender = parentView || this; toRerender.render(); }; ItemView.prototype.__clearItems = function () { var _a; (_a = this.items) === null || _a === void 0 ? void 0 : _a.remove(); }; ItemView.prototype.remove = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } common/* View */.G7.prototype.remove.apply(this, args); this.__clearItems(); return this; }; ItemView.prototype.render = function () { var _a = this, model = _a.model, config = _a.config, pfx = _a.pfx, ppfx = _a.ppfx, opt = _a.opt, sorter = _a.sorter; this.__clearItems(); var opened = opt.opened, module = opt.module, ItemView = opt.ItemView; var hidden = !module.__isLayerable(model); var el = this.$el.empty(); var level = opt.level + 1; delete this.inputName; this.items = new view_ItemsView({ ItemView: ItemView, collection: model.get('components'), config: config, sorter: sorter, opened: opened, parentView: this, parent: model, level: level, module: module, }); var children = this.items.render().$el; if (!config.showWrapper && level === 1) { el.append(children); } else { el.html(this.template(model)); el.find(".".concat(this.clsChildren)).append(children); } if (!model.get('draggable') || !config.sortable) { el.children(".".concat(this.clsMove)).remove(); } !module.isVisible(model) && (this.className += " ".concat(pfx, "hide")); hidden && (this.className += " ".concat(ppfx, "hidden")); el.attr('class', this.className); this.updateStatus(); this.updateOpening(); this.updateVisibility(); this.__render(); this._rendered = true; return this; }; ItemView.prototype.__render = function () { var _a = this, model = _a.model, config = _a.config, el = _a.el; var onRender = config.onRender; var opt = { component: model, el: el }; onRender.bind(this)(opt); this.em.trigger('layer:render', opt); }; return ItemView; }(common/* View */.G7)); /* harmony default export */ const view_ItemView = (ItemView); ;// CONCATENATED MODULE: ./src/navigator/index.ts /** * You can customize the initial state of the module from the editor initialization * ```js * const editor = grapesjs.init({ * // ... * layerManager: { * // ... * }, * }) * ``` * * Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance * * ```js * const layers = editor.Layers; * ``` * * ## Available Events * * `layer:root` - Root layer changed. The new root component is passed as an argument to the callback. * * `layer:component` - Component layer is updated. The updated component is passed as an argument to the callback. * * ## Methods * * [setRoot](#setroot) * * [getRoot](#getroot) * * [getComponents](#getcomponents) * * [setOpen](#setopen) * * [isOpen](#isopen) * * [setVisible](#setvisible) * * [isVisible](#isvisible) * * [setlocked](#setlocked) * * [isLocked](#islocked) * * [setName](#setname) * * [getName](#getname) * * [getLayerData](#getlayerdata) * * [Page]: page.html * [Component]: component.html * * @module Layers */ var navigator_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var navigator_assign = ( false) || function () { navigator_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return navigator_assign.apply(this, arguments); }; var navigator_evAll = 'layer'; var navigator_evPfx = "".concat(navigator_evAll, ":"); var evRoot = "".concat(navigator_evPfx, "root"); var evComponent = "".concat(navigator_evPfx, "component"); var navigator_evCustom = "".concat(navigator_evPfx, "custom"); var events = { all: navigator_evAll, root: evRoot, component: evComponent, custom: navigator_evCustom, }; var styleOpts = { mediaText: '' }; var propsToListen = ['open', 'status', 'locked', 'custom-name', 'components', 'classes'] .map(function (p) { return "component:update:".concat(p); }) .join(' '); var isStyleHidden = function (style) { if (style === void 0) { style = {}; } return (style.display || '').trim().indexOf('none') === 0; }; var LayerManager = /** @class */ (function (_super) { navigator_extends(LayerManager, _super); function LayerManager(em) { var _this = _super.call(this, em, 'LayerManager', navigator_config_config) || this; _this.events = events; (0,index_all.bindAll)(_this, 'componentChanged', '__onRootChange', '__onComponent'); _this.model = new ModuleModel/* default */.Z(_this, { opened: {} }); // @ts-ignore _this.config.stylePrefix = _this.config.pStylePrefix; return _this; } LayerManager.prototype.onLoad = function () { var _this = this; var _a = this, em = _a.em, config = _a.config, model = _a.model; model.listenTo(em, 'component:selected', this.componentChanged); model.on('change:root', this.__onRootChange); model.listenTo(em, propsToListen, this.__onComponent); this.componentChanged(); model.listenToOnce(em, 'load', function () { _this.setRoot(config.root); _this.__appendTo(); }); }; /** * Update the root layer with another component. * @param {[Component]|String} component Component to be set as root * @return {[Component]} * @example * const component = editor.getSelected(); * layers.setRoot(component); */ LayerManager.prototype.setRoot = function (component) { var wrapper = this.em.getWrapper(); var root = (0,mixins.isComponent)(component) ? component : wrapper; if (component && (0,index_all.isString)(component) && (0,mixins.hasWin)()) { root = wrapper.find(component)[0] || wrapper; } this.model.set('root', root); return root; }; /** * Get the current root layer. * @return {[Component]} * @example * const layerRoot = layers.getRoot(); */ LayerManager.prototype.getRoot = function () { return this.model.get('root'); // || this.em.getWrapper(); }; /** * Get valid layer child components (eg. excludes non layerable components). * @param {[Component]} component Component from which you want to get child components * @returns {Array<[Component]>} * @example * const component = editor.getSelected(); * const components = layers.getComponents(component); * console.log(components); */ LayerManager.prototype.getComponents = function (component) { var _this = this; return component.components().filter(function (cmp) { return _this.__isLayerable(cmp); }); }; /** * Update the layer open state of the component. * @param {[Component]} component Component to update * @param {Boolean} value */ LayerManager.prototype.setOpen = function (component, value) { component.set('open', value); }; /** * Check the layer open state of the component. * @param {[Component]} component * @returns {Boolean} */ LayerManager.prototype.isOpen = function (component) { return !!component.get('open'); }; /** * Update the layer visibility state of the component. * @param {[Component]} component Component to update * @param {Boolean} value */ LayerManager.prototype.setVisible = function (component, value) { var prevDspKey = '__prev-display'; var style = component.getStyle(styleOpts); var display = style.display; if (value) { var prevDisplay = component.get(prevDspKey); delete style.display; if (prevDisplay) { style.display = prevDisplay; component.unset(prevDspKey); } } else { display && component.set(prevDspKey, display); style.display = 'none'; } component.setStyle(style, styleOpts); this.updateLayer(component); this.em.trigger('component:toggled'); // Updates Style Manager #2938 }; /** * Check the layer visibility state of the component. * @param {[Component]} component * @returns {Boolean} */ LayerManager.prototype.isVisible = function (component) { return !isStyleHidden(component.getStyle(styleOpts)); }; /** * Update the layer locked state of the component. * @param {[Component]} component Component to update * @param {Boolean} value */ LayerManager.prototype.setLocked = function (component, value) { component.set('locked', value); }; /** * Check the layer locked state of the component. * @param {[Component]} component * @returns {Boolean} */ LayerManager.prototype.isLocked = function (component) { return !!component.get('locked'); }; /** * Update the layer name of the component. * @param {[Component]} component Component to update * @param {String} value New name */ LayerManager.prototype.setName = function (component, value) { component.set('custom-name', value); }; /** * Get the layer name of the component. * @param {[Component]} component * @returns {String} Component layer name */ LayerManager.prototype.getName = function (component) { return component.getName(); }; /** * Get layer data from a component. * @param {[Component]} component Component from which you want to read layer data. * @returns {Object} Object containing the layer data. * @example * const component = editor.getSelected(); * const layerData = layers.getLayerData(component); * console.log(layerData); */ LayerManager.prototype.getLayerData = function (component) { var status = component.get('status'); return { name: component.getName(), open: this.isOpen(component), selected: status === 'selected', hovered: status === 'hovered', visible: this.isVisible(component), locked: this.isLocked(component), components: this.getComponents(component), }; }; LayerManager.prototype.setLayerData = function (component, data, opts) { var _a; if (opts === void 0) { opts = {}; } var _b = this, em = _b.em, config = _b.config; var open = data.open, selected = data.selected, hovered = data.hovered, visible = data.visible, locked = data.locked, name = data.name; var cmpOpts = navigator_assign({ fromLayers: true }, opts); if ((0,mixins.isDef)(open)) { this.setOpen(component, open); } if ((0,mixins.isDef)(selected)) { if (selected) { em.setSelected(component, cmpOpts); var scroll_1 = config.scrollCanvas; scroll_1 && ((_a = component.views) === null || _a === void 0 ? void 0 : _a.forEach(function (view) { return view.scrollIntoView(scroll_1); })); } else { em.removeSelected(component, cmpOpts); } } if ((0,mixins.isDef)(hovered) && config.showHover) { hovered ? em.setHovered(component, cmpOpts) : em.setHovered(null, cmpOpts); } if ((0,mixins.isDef)(visible)) { visible !== this.isVisible(component) && this.setVisible(component, visible); } if ((0,mixins.isDef)(locked)) { this.setLocked(component, locked); } if ((0,mixins.isDef)(name)) { this.setName(component, name); } }; /** * Triggered when the selected component is changed * @private */ LayerManager.prototype.componentChanged = function (sel, opts) { var _a; if (opts === void 0) { opts = {}; } // @ts-ignore if (opts.fromLayers) return; var _b = this, em = _b.em, config = _b.config; var scrollLayers = config.scrollLayers; var opened = this.model.get('opened'); var selected = em.getSelected(); var parent = selected === null || selected === void 0 ? void 0 : selected.parent(); for (var cid in opened) { opened[cid].set('open', false); delete opened[cid]; } while (parent) { parent.set('open', true); opened[parent.cid] = parent; parent = parent.parent(); } if (selected && scrollLayers) { // @ts-ignore var el = (_a = selected.viewLayer) === null || _a === void 0 ? void 0 : _a.el; el === null || el === void 0 ? void 0 : el.scrollIntoView(scrollLayers); } }; LayerManager.prototype.getAll = function () { return this.view; }; LayerManager.prototype.render = function () { var _a, _b; var _c = this, config = _c.config, model = _c.model; var ItemView = view_ItemView.extend(config.extend); this.view = new ItemView({ el: (_a = this.view) === null || _a === void 0 ? void 0 : _a.el, ItemView: ItemView, level: 0, config: config, opened: model.get('opened'), model: this.getRoot(), module: this, }); return (_b = this.view) === null || _b === void 0 ? void 0 : _b.render().el; }; LayerManager.prototype.destroy = function () { var _a; (_a = this.view) === null || _a === void 0 ? void 0 : _a.remove(); }; LayerManager.prototype.__onRootChange = function () { var _a; var root = this.getRoot(); (_a = this.view) === null || _a === void 0 ? void 0 : _a.setRoot(root); this.em.trigger(evRoot, root); this.__trgCustom(); }; LayerManager.prototype.__onComponent = function (component) { this.updateLayer(component); }; LayerManager.prototype.__isLayerable = function (cmp) { var tag = cmp.get('tagName'); var hideText = this.config.hideTextnode; var isValid = !hideText || (!cmp.is('textnode') && tag !== 'br'); return isValid && cmp.get('layerable'); }; LayerManager.prototype.__trgCustom = function (opts) { var _a = this, __ctn = _a.__ctn, em = _a.em, events = _a.events; this.__ctn = __ctn || (opts === null || opts === void 0 ? void 0 : opts.container); em.trigger(events.custom, { container: this.__ctn, root: this.getRoot(), }); }; LayerManager.prototype.updateLayer = function (component, opts) { this.em.trigger(evComponent, component, opts); }; return LayerManager; }(abstract_Module)); /* harmony default export */ const src_navigator = (LayerManager); ;// CONCATENATED MODULE: ./src/asset_manager/config/config.ts var asset_manager_config_config_config = { assets: [], noAssets: '', stylePrefix: 'am-', upload: '', uploadName: 'files', headers: {}, params: {}, credentials: 'include', multiUpload: true, autoAdd: true, customFetch: undefined, uploadFile: undefined, embedAsBase64: true, handleAdd: undefined, beforeUpload: undefined, showUrlInput: true, custom: false, dropzone: false, openAssetsOnDrop: true, dropzoneContent: '', }; /* harmony default export */ const asset_manager_config_config = (asset_manager_config_config_config); ;// CONCATENATED MODULE: ./src/asset_manager/model/Asset.ts var Asset_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); /** * @property {String} type Asset type, eg. `'image'`. * @property {String} src Asset URL, eg. `'https://.../image.png'`. * * @module docsjs.Asset */ var Asset = /** @class */ (function (_super) { Asset_extends(Asset, _super); function Asset() { return _super !== null && _super.apply(this, arguments) || this; } Asset.getDefaults = function () { return (0,index_all.result)(this.prototype, 'defaults'); }; Asset.prototype.defaults = function () { return { type: '', src: '', }; }; /** * Get asset type. * @returns {String} * @example * // Asset: { src: 'https://.../image.png', type: 'image' } * asset.getType(); // -> 'image' * */ Asset.prototype.getType = function () { return this.get('type'); }; /** * Get asset URL. * @returns {String} * @example * // Asset: { src: 'https://.../image.png' } * asset.getSrc(); // -> 'https://.../image.png' * */ Asset.prototype.getSrc = function () { return this.get('src'); }; /** * Get filename of the asset (based on `src`). * @returns {String} * @example * // Asset: { src: 'https://.../image.png' } * asset.getFilename(); // -> 'image.png' * // Asset: { src: 'https://.../image' } * asset.getFilename(); // -> 'image' * */ Asset.prototype.getFilename = function () { return this.get('src').split('/').pop().split('?').shift(); }; /** * Get extension of the asset (based on `src`). * @returns {String} * @example * // Asset: { src: 'https://.../image.png' } * asset.getExtension(); // -> 'png' * // Asset: { src: 'https://.../image' } * asset.getExtension(); // -> '' * */ Asset.prototype.getExtension = function () { return this.getFilename().split('.').pop(); }; return Asset; }(common/* Model */.Hn)); /* harmony default export */ const model_Asset = (Asset); Asset.prototype.idAttribute = 'src'; ;// CONCATENATED MODULE: ./src/asset_manager/model/AssetImage.ts var AssetImage_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var AssetImage_assign = ( false) || function () { AssetImage_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return AssetImage_assign.apply(this, arguments); }; var AssetImage = /** @class */ (function (_super) { AssetImage_extends(AssetImage, _super); function AssetImage() { return _super !== null && _super.apply(this, arguments) || this; } AssetImage.prototype.defaults = function () { return AssetImage_assign(AssetImage_assign({}, model_Asset.getDefaults()), { type: 'image', unitDim: 'px', height: 0, width: 0 }); }; return AssetImage; }(model_Asset)); /* harmony default export */ const model_AssetImage = (AssetImage); ;// CONCATENATED MODULE: ./src/asset_manager/view/AssetView.ts var AssetView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var AssetView = /** @class */ (function (_super) { AssetView_extends(AssetView, _super); function AssetView(opt) { var _this = _super.call(this, opt) || this; _this.options = opt; _this.collection = opt.collection; var config = opt.config || {}; _this.config = config; _this.pfx = config.stylePrefix || ''; // @ts-ignore _this.ppfx = config.pStylePrefix || ''; // @ts-ignore _this.em = config.em; _this.className = _this.pfx + 'asset'; _this.listenTo(_this.model, 'destroy remove', _this.remove); // @ts-ignore _this.model.view = _this; var init = _this.init && _this.init.bind(_this); init && init(opt); return _this; } AssetView.prototype.__getBhv = function () { var em = this.em; var am = em === null || em === void 0 ? void 0 : em.Assets; return (am === null || am === void 0 ? void 0 : am.__getBehaviour()) || {}; }; AssetView.prototype.template = function (view, asset) { var pfx = this.pfx; return "\n <div class=\"".concat(pfx, "preview-cont\">\n ").concat(this.getPreview(), "\n </div>\n <div class=\"").concat(pfx, "meta\">\n ").concat(this.getInfo(), "\n </div>\n <div class=\"").concat(pfx, "close\" data-toggle=\"asset-remove\">\n ⨯\n </div>\n "); }; /** * Update target if exists * @param {Model} target * @private * */ AssetView.prototype.updateTarget = function (target) { if (target && target.set) { target.set('attributes', (0,index_all.clone)(target.get('attributes'))); target.set('src', this.model.get('src')); } }; AssetView.prototype.getPreview = function () { return ''; }; AssetView.prototype.getInfo = function () { return ''; }; AssetView.prototype.render = function () { var el = this.el; el.innerHTML = this.template(this, this.model); el.className = this.className; return this; }; return AssetView; }(common/* View */.G7)); /* harmony default export */ const view_AssetView = (AssetView); ;// CONCATENATED MODULE: ./src/asset_manager/view/AssetImageView.ts var AssetImageView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var AssetImageView_makeTemplateObject = ( false) || function (cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; }; var AssetImageView = /** @class */ (function (_super) { AssetImageView_extends(AssetImageView, _super); function AssetImageView() { return _super !== null && _super.apply(this, arguments) || this; } AssetImageView.prototype.getPreview = function () { var _a = this, pfx = _a.pfx, ppfx = _a.ppfx, model = _a.model; var src = model.get('src'); return html(AssetImageView_templateObject_1 || (AssetImageView_templateObject_1 = AssetImageView_makeTemplateObject(["\n <div class=\"", "preview\" style=\"background-image: url('", "');\"></div>\n <div class=\"", "preview-bg ", "checker-bg\"></div>\n "], ["\n <div class=\"", "preview\" style=\"background-image: url('", "');\"></div>\n <div class=\"", "preview-bg ", "checker-bg\"></div>\n "])), pfx, src, pfx, ppfx); }; AssetImageView.prototype.getInfo = function () { var _a = this, pfx = _a.pfx, model = _a.model; var name = model.get('name'); var width = model.get('width'); var height = model.get('height'); var unit = model.get('unitDim'); var dim = width && height ? "".concat(width, "x").concat(height).concat(unit) : ''; name = name || model.getFilename(); return html(AssetImageView_templateObject_2 || (AssetImageView_templateObject_2 = AssetImageView_makeTemplateObject(["\n <div class=\"", "name\">", "</div>\n <div class=\"", "dimensions\">", "</div>\n "], ["\n <div class=\"", "name\">", "</div>\n <div class=\"", "dimensions\">", "</div>\n "])), pfx, name, pfx, dim); }; // @ts-ignore AssetImageView.prototype.init = function (o) { var pfx = this.pfx; this.className += " ".concat(pfx, "asset-image"); }; /** * Triggered when the asset is clicked * @private * */ AssetImageView.prototype.onClick = function () { var _a = this, model = _a.model, pfx = _a.pfx; var select = this.__getBhv().select; // @ts-ignore var onClick = this.config.onClick; var coll = this.collection; coll.trigger('deselectAll'); this.$el.addClass(pfx + 'highlight'); if ((0,index_all.isFunction)(select)) { select(model, false); } else if ((0,index_all.isFunction)(onClick)) { onClick(model); } else { // @ts-ignore this.updateTarget(coll.target); } }; /** * Triggered when the asset is double clicked * @private * */ AssetImageView.prototype.onDblClick = function () { var _a = this, em = _a.em, model = _a.model; var select = this.__getBhv().select; // @ts-ignore var onDblClick = this.config.onDblClick; // @ts-ignore var _b = this.collection, target = _b.target, onSelect = _b.onSelect; if ((0,index_all.isFunction)(select)) { select(model, true); } else if ((0,index_all.isFunction)(onDblClick)) { onDblClick(model); } else { this.updateTarget(target); em === null || em === void 0 ? void 0 : em.Modal.close(); } (0,index_all.isFunction)(onSelect) && onSelect(model); }; /** * Remove asset from collection * @private * */ AssetImageView.prototype.onRemove = function (e) { e.stopImmediatePropagation(); this.model.collection.remove(this.model); }; return AssetImageView; }(view_AssetView)); /* harmony default export */ const view_AssetImageView = (AssetImageView); AssetImageView.prototype.events = { // @ts-ignore 'click [data-toggle=asset-remove]': 'onRemove', click: 'onClick', dblclick: 'onDblClick', }; var AssetImageView_templateObject_1, AssetImageView_templateObject_2; ;// CONCATENATED MODULE: ./src/domain_abstract/model/TypeableCollection.ts var TypeableCollection_assign = ( false) || function () { TypeableCollection_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return TypeableCollection_assign.apply(this, arguments); }; // @ts-nocheck TODO extend View var TypeableCollection = { types: [], initialize: function (models, opts) { var _this = this; if (opts === void 0) { opts = {}; } var em = opts.em; this.em = em; this.opts = opts; this.model = function (attrs, options) { if (attrs === void 0) { attrs = {}; } if (options === void 0) { options = {}; } var Model, View, type; if (attrs && attrs.type) { var baseType = _this.getBaseType(); type = _this.getType(attrs.type); Model = type ? type.model : baseType.model; View = type ? type.view : baseType.view; } else { var typeFound = _this.recognizeType(attrs); type = typeFound.type; Model = type.model; View = type.view; attrs = typeFound.attributes; } var model = new Model(attrs, TypeableCollection_assign(TypeableCollection_assign({}, options), { em: em })); model.typeView = View; return model; }; var init = this.init && this.init.bind(this); init && init(); }, /** * Recognize type by any value * @param {mixed} value * @return {Object} Found type */ recognizeType: function (value) { var types = this.getTypes(); for (var i = 0; i < types.length; i++) { var type = types[i]; var typeFound = type.isType(value); typeFound = typeof typeFound == 'boolean' && typeFound ? { type: type.id } : typeFound; if (typeFound) { return { type: type, attributes: typeFound, }; } } // If, for any reason, the type is not found it'll return the base one return { type: this.getBaseType(), attributes: value, }; }, /** * Returns the base type (last object in the stack) * @return {Object} */ getBaseType: function () { var types = this.getTypes(); return types[types.length - 1]; }, /** * Get types * @return {Array} */ getTypes: function () { return this.types; }, /** * Get type * @param {string} id Type ID * @return {Object} Type definition */ getType: function (id) { var types = this.getTypes(); for (var i = 0; i < types.length; i++) { var type = types[i]; if (type.id === id) { return type; } } }, /** * Add new type * @param {string} id Type ID * @param {Object} definition Definition of the type. Each definition contains * `model` (business logic), `view` (presentation logic) * and `isType` function which recognize the type of the * passed entity * addType('my-type', { * model: {}, * view: {}, * isType: (value) => {}, * }) */ addType: function (id, definition) { var type = this.getType(id); var baseType = this.getBaseType(); var ModelInst = type ? type.model : baseType.model; var ViewInst = type ? type.view : baseType.view; var model = definition.model, view = definition.view, isType = definition.isType; model = model instanceof common/* Model */.Hn || (0,index_all.isFunction)(model) ? model : ModelInst.extend(model || {}); view = view instanceof common/* View */.G7 || (0,index_all.isFunction)(view) ? view : ViewInst.extend(view || {}); // New API if (this.extendViewApi && !definition.model && !definition.view) { view = view.extend(definition); } if (type) { type.model = model; type.view = view; type.isType = isType || type.isType; } else { definition.id = id; definition.model = model; definition.view = view; definition.isType = isType || function (value) { if (value && value.type == id) { return true; } }; this.getTypes().unshift(definition); } }, }; /* harmony default export */ const model_TypeableCollection = (TypeableCollection); ;// CONCATENATED MODULE: ./src/asset_manager/model/Assets.ts var Assets_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var TypeableCollectionExt = common/* Collection */.FE.extend(model_TypeableCollection); var Assets = /** @class */ (function (_super) { Assets_extends(Assets, _super); function Assets() { return _super !== null && _super.apply(this, arguments) || this; } return Assets; }(TypeableCollectionExt)); /* harmony default export */ const model_Assets = (Assets); Assets.prototype.types = [ { id: 'image', model: model_AssetImage, view: view_AssetImageView, isType: function (value) { if (typeof value == 'string') { return { type: 'image', src: value, }; } return value; }, }, ]; ;// CONCATENATED MODULE: ./src/asset_manager/view/AssetsView.ts var AssetsView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var AssetsView = /** @class */ (function (_super) { AssetsView_extends(AssetsView, _super); function AssetsView(o) { if (o === void 0) { o = {}; } var _this = _super.call(this, o) || this; _this.options = o; _this.config = o.config; _this.pfx = _this.config.stylePrefix || ''; // @ts-ignore _this.ppfx = _this.config.pStylePrefix || ''; // @ts-ignore _this.em = _this.config.em; var coll = _this.collection; _this.listenTo(coll, 'reset', _this.renderAssets); _this.listenTo(coll, 'add', _this.addToAsset); _this.listenTo(coll, 'remove', _this.removedAsset); _this.listenTo(coll, 'deselectAll', _this.deselectAll); return _this; } AssetsView.prototype.template = function (_a) { var pfx = _a.pfx, ppfx = _a.ppfx, em = _a.em; var form = ''; if (this.config.showUrlInput) { form = "\n <form class=\"".concat(pfx, "add-asset\">\n <div class=\"").concat(ppfx, "field ").concat(pfx, "add-field\">\n <input placeholder=\"").concat(em === null || em === void 0 ? void 0 : em.t('assetManager.inputPlh'), "\"/>\n </div>\n <button class=\"").concat(ppfx, "btn-prim\">").concat(em === null || em === void 0 ? void 0 : em.t('assetManager.addButton'), "</button>\n <div style=\"clear:both\"></div>\n </form>\n "); } return "\n <div class=\"".concat(pfx, "assets-cont\">\n <div class=\"").concat(pfx, "assets-header\">\n ").concat(form, "\n </div>\n <div class=\"").concat(pfx, "assets\" data-el=\"assets\"></div>\n <div style=\"clear:both\"></div>\n </div>\n "); }; /** * Add new asset to the collection via string * @param {Event} e Event object * @return {this} * @private */ AssetsView.prototype.handleSubmit = function (ev) { ev.preventDefault(); var input = this.getAddInput(); var url = input && input.value.trim(); var handleAdd = this.config.handleAdd; if (!url) { return; } input.value = ''; var assetsEl = this.getAssetsEl(); if (assetsEl) { assetsEl.scrollTop = 0; } if (handleAdd) { handleAdd.bind(this)(url); } else { this.options.globalCollection.add(url, { at: 0 }); } }; /** * Returns assets element * @return {HTMLElement} * @private */ AssetsView.prototype.getAssetsEl = function () { //if(!this.assets) // Not able to cache as after the rerender it losses the ref return this.el.querySelector(".".concat(this.pfx, "assets")); }; /** * Returns input url element * @return {HTMLElement} * @private */ AssetsView.prototype.getAddInput = function () { if (!this.inputUrl || !this.inputUrl.value) { this.inputUrl = this.el.querySelector(".".concat(this.pfx, "add-asset input")); } return this.inputUrl; }; /** * Triggered when an asset is removed * @param {Asset} model Removed asset * @private */ AssetsView.prototype.removedAsset = function (model) { if (!this.collection.length) { this.toggleNoAssets(); } }; /** * Add asset to collection * @private * */ AssetsView.prototype.addToAsset = function (model) { if (this.collection.length == 1) { this.toggleNoAssets(true); } this.addAsset(model); }; /** * Add new asset to collection * @param Object Model * @param Object Fragment collection * @return Object Object created * @private * */ AssetsView.prototype.addAsset = function (model, fragmentEl) { if (fragmentEl === void 0) { fragmentEl = null; } var fragment = fragmentEl; var collection = this.collection; var config = this.config; // @ts-ignore var rendered = new model.typeView({ model: model, collection: collection, config: config, }).render().el; if (fragment) { fragment.appendChild(rendered); } else { var assetsEl = this.getAssetsEl(); if (assetsEl) { assetsEl.insertBefore(rendered, assetsEl.firstChild); } } return rendered; }; /** * Checks if to show noAssets * @param {Boolean} hide * @private */ AssetsView.prototype.toggleNoAssets = function (hide) { if (hide === void 0) { hide = false; } var assetsEl = this.$el.find(".".concat(this.pfx, "assets")); if (hide) { assetsEl.empty(); } else { var noAssets = this.config.noAssets; noAssets && assetsEl.append(noAssets); } }; /** * Deselect all assets * @private * */ AssetsView.prototype.deselectAll = function () { var pfx = this.pfx; this.$el.find(".".concat(pfx, "highlight")).removeClass("".concat(pfx, "highlight")); }; AssetsView.prototype.renderAssets = function () { var _this = this; var fragment = document.createDocumentFragment(); var assets = this.$el.find(".".concat(this.pfx, "assets")); assets.empty(); this.toggleNoAssets(!!this.collection.length); this.collection.each(function (model) { return _this.addAsset(model, fragment); }); assets.append(fragment); }; AssetsView.prototype.render = function () { var fuRendered = this.options.fu.render().el; this.$el.empty(); this.$el.append(fuRendered).append(this.template(this)); this.el.className = "".concat(this.ppfx, "asset-manager"); this.renderAssets(); return this; }; return AssetsView; }(common/* View */.G7)); /* harmony default export */ const view_AssetsView = (AssetsView); AssetsView.prototype.events = { // @ts-ignore submit: 'handleSubmit', }; ;// CONCATENATED MODULE: ./src/asset_manager/view/FileUploader.ts var FileUploader_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var FileUploader_makeTemplateObject = ( false) || function (cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; }; var FileUploaderView = /** @class */ (function (_super) { FileUploader_extends(FileUploaderView, _super); function FileUploaderView(opts) { if (opts === void 0) { opts = {}; } var _this = _super.call(this, opts) || this; _this.options = opts; var c = opts.config || {}; _this.module = opts.module; _this.config = c; // @ts-ignore _this.em = _this.config.em; _this.pfx = c.stylePrefix || ''; _this.ppfx = c.pStylePrefix || ''; _this.target = _this.options.globalCollection || {}; _this.uploadId = _this.pfx + 'uploadFile'; _this.disabled = c.disableUpload !== undefined ? c.disableUpload : !c.upload && !c.embedAsBase64; _this.multiUpload = c.multiUpload !== undefined ? c.multiUpload : true; var uploadFile = c.uploadFile; if (uploadFile) { _this.uploadFile = uploadFile.bind(_this); } else if (!c.upload && c.embedAsBase64) { _this.uploadFile = FileUploaderView.embedAsBase64; } _this.delegateEvents(); return _this; } FileUploaderView.prototype.template = function (_a) { var pfx = _a.pfx, title = _a.title, uploadId = _a.uploadId, disabled = _a.disabled, multiUpload = _a.multiUpload; return html(FileUploader_templateObject_1 || (FileUploader_templateObject_1 = FileUploader_makeTemplateObject(["\n <form>\n <div id=\"", "title\">", "</div>\n <input\n data-input\n type=\"file\"\n id=\"", "\"\n name=\"file\"\n accept=\"*/*\"\n ", "\n ", "\n />\n <div style=\"clear:both;\"></div>\n </form>\n "], ["\n <form>\n <div id=\"", "title\">", "</div>\n <input\n data-input\n type=\"file\"\n id=\"", "\"\n name=\"file\"\n accept=\"*/*\"\n ", "\n ", "\n />\n <div style=\"clear:both;\"></div>\n </form>\n "])), pfx, title, uploadId, disabled ? 'disabled' : '', multiUpload ? 'multiple' : ''); }; FileUploaderView.prototype.events = function () { return { 'change [data-input]': 'uploadFile', }; }; /** * Triggered before the upload is started * @private */ FileUploaderView.prototype.onUploadStart = function () { var module = this.module; module && module.__propEv('asset:upload:start'); }; /** * Triggered after the upload is ended * @param {Object|string} res End result * @private */ FileUploaderView.prototype.onUploadEnd = function (res) { var _a = this, $el = _a.$el, module = _a.module; module && module.__propEv('asset:upload:end', res); var input = $el.find('input'); input && input.val(''); }; /** * Triggered on upload error * @param {Object} err Error * @private */ FileUploaderView.prototype.onUploadError = function (err) { var module = this.module; console.error(err); this.onUploadEnd(err); module && module.__propEv('asset:upload:error', err); }; /** * Triggered on upload response * @param {string} text Response text * @private */ FileUploaderView.prototype.onUploadResponse = function (text, clb) { var _a = this, module = _a.module, config = _a.config, target = _a.target; var json; try { json = typeof text === 'string' ? JSON.parse(text) : text; } catch (e) { json = text; } module && module.__propEv('asset:upload:response', json); if (config.autoAdd && target) { target.add(json.data, { at: 0 }); } this.onUploadEnd(text); clb === null || clb === void 0 ? void 0 : clb(json); }; /** * Upload files * @param {Object} e Event * @return {Promise} * @private * */ FileUploaderView.prototype.uploadFile = function (e, clb) { var _this = this; // @ts-ignore var files = e.dataTransfer ? e.dataTransfer.files : e.target.files; var config = this.config; var beforeUpload = config.beforeUpload; var beforeUploadResponse = beforeUpload && beforeUpload(files); if (beforeUploadResponse === false) return; var body = new FormData(); var params = config.params, customFetch = config.customFetch, fetchOptions = config.fetchOptions; for (var param in params) { body.append(param, params[param]); } if (this.multiUpload) { for (var i = 0; i < files.length; i++) { body.append("".concat(config.uploadName, "[]"), files[i]); } } else if (files.length) { body.append(config.uploadName, files[0]); } var url = config.upload; var headers = config.headers; var reqHead = 'X-Requested-With'; if (typeof headers[reqHead] == 'undefined') { headers[reqHead] = 'XMLHttpRequest'; } if (url) { this.onUploadStart(); var fetchOpts = { method: 'post', credentials: config.credentials || 'include', headers: headers, body: body, }; var fetchOptsResult = (fetchOptions === null || fetchOptions === void 0 ? void 0 : fetchOptions(fetchOpts)) || fetchOpts; var fetchResult = customFetch ? customFetch(url, fetchOptsResult) : utils_fetch(url, fetchOptsResult).then(function (res) { return ((res.status / 200) | 0) == 1 ? res.text() : res.text().then(function (text) { return Promise.reject(text); }); }); return fetchResult .then(function (text) { return _this.onUploadResponse(text, clb); }) .catch(function (err) { return _this.onUploadError(err); }); } }; /** * Make input file droppable * @private * */ FileUploaderView.prototype.initDrop = function () { var that = this; if (!this.uploadForm) { this.uploadForm = this.$el.find('form').get(0); var formEl_1 = this.uploadForm; if ('draggable' in formEl_1) { this.uploadForm.ondragover = function () { formEl_1.className = that.pfx + 'hover'; return false; }; this.uploadForm.ondragleave = function () { formEl_1.className = ''; return false; }; this.uploadForm.ondrop = function (ev) { formEl_1.className = ''; ev.preventDefault(); that.uploadFile(ev); return; }; } } }; FileUploaderView.prototype.initDropzone = function (ev) { var _this = this; var addedCls = 0; var c = this.config; var em = ev.model; var edEl = ev.el; var editor = em.Editor; var frameEl = em.Canvas.getBody(); var ppfx = this.ppfx; var updatedCls = "".concat(ppfx, "dropzone-active"); var dropzoneCls = "".concat(ppfx, "dropzone"); var cleanEditorElCls = function () { edEl.className = edEl.className.replace(updatedCls, '').trim(); addedCls = 0; }; var onDragOver = function () { if (!addedCls) { edEl.className += " ".concat(updatedCls); addedCls = 1; } return false; }; var onDragLeave = function () { cleanEditorElCls(); return false; }; var onDrop = function (e) { cleanEditorElCls(); e.preventDefault(); e.stopPropagation(); _this.uploadFile(e); if (c.openAssetsOnDrop && editor) { var target = editor.getSelected(); editor.runCommand('open-assets', { target: target, onSelect: function () { editor.Modal.close(); editor.AssetManager.setTarget(null); }, }); } return false; }; ev.$el.append("<div class=\"".concat(dropzoneCls, "\">").concat(c.dropzoneContent, "</div>")); cleanEditorElCls(); if ('draggable' in edEl) { [edEl, frameEl].forEach(function (item) { item.ondragover = onDragOver; item.ondragleave = onDragLeave; item.ondrop = onDrop; }); } }; FileUploaderView.prototype.render = function () { var _a = this, $el = _a.$el, pfx = _a.pfx, em = _a.em; $el.html(this.template({ title: em && em.t('assetManager.uploadTitle'), uploadId: this.uploadId, disabled: this.disabled, multiUpload: this.multiUpload, pfx: pfx, })); this.initDrop(); $el.attr('class', pfx + 'file-uploader'); return this; }; FileUploaderView.embedAsBase64 = function (e, clb) { var _this = this; // List files dropped // @ts-ignore var files = e.dataTransfer ? e.dataTransfer.files : e.target.files; var response = { data: [] }; // Unlikely, widely supported now if (!FileReader) { // @ts-ignore this.onUploadError(new Error('Unsupported platform, FileReader is not defined')); return; } var promises = []; var mimeTypeMatcher = /^(.+)\/(.+)$/; var _loop_1 = function (file) { // For each file a reader (to read the base64 URL) // and a promise (to track and merge results and errors) var promise = new Promise(function (resolve, reject) { var reader = new FileReader(); reader.addEventListener('load', function (event) { var type; var name = file.name; // Try to find the MIME type of the file. var match = mimeTypeMatcher.exec(file.type); if (match) { type = match[1]; // The first part in the MIME, "image" in image/png } else { type = file.type; } /* // Show local video files, http://jsfiddle.net/dsbonev/cCCZ2/embedded/result,js,html,css/ var URL = window.URL || window.webkitURL var file = this.files[0] var type = file.type var videoNode = document.createElement('video'); var canPlay = videoNode.canPlayType(type) // can use also for 'audio' types if (canPlay === '') canPlay = 'no' var message = 'Can play type "' + type + '": ' + canPlay var isError = canPlay === 'no' displayMessage(message, isError) if (isError) { return } var fileURL = URL.createObjectURL(file) videoNode.src = fileURL */ // If it's an image, try to find its size if (type === 'image') { var data_1 = { src: reader.result, name: name, type: type, height: 0, width: 0, }; var image_1 = new Image(); image_1.addEventListener('error', function (error) { reject(error); }); image_1.addEventListener('load', function () { data_1.height = image_1.height; data_1.width = image_1.width; resolve(data_1); }); // @ts-ignore image_1.src = data_1.src; } else if (type) { // Not an image, but has a type resolve({ src: reader.result, name: name, type: type, }); } else { // No type found, resolve with the URL only resolve(reader.result); } }); reader.addEventListener('error', function (error) { reject(error); }); reader.addEventListener('abort', function (error) { reject('Aborted'); }); reader.readAsDataURL(file); }); promises.push(promise); }; for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { var file = files_1[_i]; _loop_1(file); } return Promise.all(promises).then(function (data) { response.data = data; // @ts-ignore _this.onUploadResponse(response, clb); }, function (error) { // @ts-ignore _this.onUploadError(error); }); }; return FileUploaderView; }(common/* View */.G7)); /* harmony default export */ const FileUploader = (FileUploaderView); var FileUploader_templateObject_1; ;// CONCATENATED MODULE: ./src/asset_manager/index.ts /** * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/GrapesJS/grapesjs/blob/master/src/asset_manager/config/config.ts) * ```js * const editor = grapesjs.init({ * assetManager: { * // options * } * }) * ``` * * Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance * * ```js * const assetManager = editor.AssetManager; * ``` * * ## Available Events * * `asset:open` - Asset Manager opened. * * `asset:close` - Asset Manager closed. * * `asset:add` - Asset added. The [Asset] is passed as an argument to the callback. * * `asset:remove` - Asset removed. The [Asset] is passed as an argument to the callback. * * `asset:update` - Asset updated. The updated [Asset] and the object containing changes are passed as arguments to the callback. * * `asset:upload:start` - Before the upload is started. * * `asset:upload:end` - After the upload is ended. * * `asset:upload:error` - On any error in upload, passes the error as an argument. * * `asset:upload:response` - On upload response, passes the result as an argument. * * `asset` - Catch-all event for all the events mentioned above. An object containing all the available data about the triggered event is passed as an argument to the callback. * * `asset:custom` - Event for handling custom Asset Manager UI. * * ## Methods * * [open](#open) * * [close](#close) * * [isOpen](#isopen) * * [add](#add) * * [get](#get) * * [getAll](#getall) * * [getAllVisible](#getallvisible) * * [remove](#remove) * * [getContainer](#getcontainer) * * [Asset]: asset.html * * @module Assets */ var asset_manager_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var asset_manager_assign = ( false) || function () { asset_manager_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return asset_manager_assign.apply(this, arguments); }; var asset_manager_spreadArray = ( false) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var asset_manager_evAll = 'asset'; var asset_manager_evPfx = "".concat(asset_manager_evAll, ":"); var asset_manager_evSelect = "".concat(asset_manager_evPfx, "select"); var asset_manager_evUpdate = "".concat(asset_manager_evPfx, "update"); var asset_manager_evAdd = "".concat(asset_manager_evPfx, "add"); var asset_manager_evRemove = "".concat(asset_manager_evPfx, "remove"); var asset_manager_evRemoveBefore = "".concat(asset_manager_evRemove, ":before"); var asset_manager_evCustom = "".concat(asset_manager_evPfx, "custom"); var evOpen = "".concat(asset_manager_evPfx, "open"); var evClose = "".concat(asset_manager_evPfx, "close"); var evUpload = "".concat(asset_manager_evPfx, "upload"); var evUploadStart = "".concat(evUpload, ":start"); var evUploadEnd = "".concat(evUpload, ":end"); var evUploadError = "".concat(evUpload, ":error"); var evUploadRes = "".concat(evUpload, ":response"); var assetCmd = 'open-assets'; var assetEvents = { all: asset_manager_evAll, select: asset_manager_evSelect, update: asset_manager_evUpdate, add: asset_manager_evAdd, remove: asset_manager_evRemove, removeBefore: asset_manager_evRemoveBefore, custom: asset_manager_evCustom, open: evOpen, close: evClose, uploadStart: evUploadStart, uploadEnd: evUploadEnd, uploadError: evUploadError, uploadResponse: evUploadRes, }; var AssetManager = /** @class */ (function (_super) { asset_manager_extends(AssetManager, _super); /** * Initialize module * @param {Object} config Configurations * @private */ function AssetManager(em) { var _this = // @ts-ignore _super.call(this, em, 'AssetManager', new model_Assets([], em), assetEvents, asset_manager_config_config) || this; _this.storageKey = 'assets'; _this.Asset = model_Asset; _this.Assets = model_Assets; var _a = _this, all = _a.all, config = _a.config; // @ts-ignore _this.assetsVis = new model_Assets([]); // @ts-ignore var ppfx = config.pStylePrefix; if (ppfx) { config.stylePrefix = "".concat(ppfx).concat(config.stylePrefix); } // Setup the sync between the global and public collections all.on('add', function (model) { return _this.getAllVisible().add(model); }); all.on('remove', function (model) { return _this.getAllVisible().remove(model); }); _this.__onAllEvent = (0,index_all.debounce)(function () { return _this.__trgCustom(); }, 0); return _this; } AssetManager.prototype.__propEv = function (ev) { var _a, _b; var data = []; for (var _i = 1; _i < arguments.length; _i++) { data[_i - 1] = arguments[_i]; } (_a = this.em).trigger.apply(_a, asset_manager_spreadArray([ev], data, false)); (_b = this.getAll()).trigger.apply(_b, asset_manager_spreadArray([ev], data, false)); }; AssetManager.prototype.__trgCustom = function () { var bhv = this.__getBehaviour(); var custom = this.getConfig().custom; if (!bhv.container && !custom.open) { return; } this.em.trigger(this.events.custom, this.__customData()); }; AssetManager.prototype.__customData = function () { var _this = this; var bhv = this.__getBehaviour(); return { am: this, open: this.isOpen(), assets: this.getAll().models, types: bhv.types || [], container: bhv.container, close: function () { return _this.close(); }, remove: function (asset, opts) { return _this.remove(asset, opts); }, select: function (asset, complete) { var res = _this.add(asset); (0,index_all.isFunction)(bhv.select) && bhv.select(res, complete); }, // extra options: bhv.options || {}, }; }; /** * Open the asset manager. * @param {Object} [options] Options for the asset manager. * @param {Array<String>} [options.types=['image']] Types of assets to show. * @param {Function} [options.select] Type of operation to perform on asset selection. If not specified, nothing will happen. * @example * assetManager.open({ * select(asset, complete) { * const selected = editor.getSelected(); * if (selected && selected.is('image')) { * selected.addAttributes({ src: asset.getSrc() }); * // The default AssetManager UI will trigger `select(asset, false)` on asset click * // and `select(asset, true)` on double-click * complete && assetManager.close(); * } * } * }); * // with your custom types (you should have assets with those types declared) * assetManager.open({ types: ['doc'], ... }); */ AssetManager.prototype.open = function (options) { if (options === void 0) { options = {}; } var cmd = this.em.Commands; cmd.run(assetCmd, asset_manager_assign({ types: ['image'], select: function () { } }, options)); }; /** * Close the asset manager. * @example * assetManager.close(); */ AssetManager.prototype.close = function () { var cmd = this.em.Commands; cmd.stop(assetCmd); }; /** * Checks if the asset manager is open * @returns {Boolean} * @example * assetManager.isOpen(); // true | false */ AssetManager.prototype.isOpen = function () { var cmd = this.em.Commands; return !!(cmd === null || cmd === void 0 ? void 0 : cmd.isActive(assetCmd)); }; /** * Add new asset/s to the collection. URLs are supposed to be unique * @param {String|Object|Array<String>|Array<Object>} asset URL strings or an objects representing the resource. * @param {Object} [opts] Options * @returns {[Asset]} * @example * // As strings * assetManager.add('http://img.jpg'); * assetManager.add(['http://img.jpg', './path/to/img.png']); * * // Using objects you can indicate the type and other meta informations * assetManager.add({ * // type: 'image', // image is default * src: 'http://img.jpg', * height: 300, * width: 200, * }); * assetManager.add([{ src: 'img2.jpg' }, { src: 'img2.png' }]); */ AssetManager.prototype.add = function (asset, opts) { if (opts === void 0) { opts = {}; } // Put the model at the beginning if (typeof opts.at == 'undefined') { opts.at = 0; } return this.all.add(asset, opts); }; /** * Return asset by URL * @param {String} src URL of the asset * @returns {[Asset]|null} * @example * const asset = assetManager.get('http://img.jpg'); */ AssetManager.prototype.get = function (src) { return this.all.where({ src: src })[0] || null; }; /** * Return the global collection, containing all the assets * @returns {Collection<[Asset]>} */ AssetManager.prototype.getAll = function () { return this.all; }; /** * Return the visible collection, which contains assets actually rendered * @returns {Collection<[Asset]>} */ AssetManager.prototype.getAllVisible = function () { return this.assetsVis; }; /** * Remove asset * @param {String|[Asset]} asset Asset or asset URL * @returns {[Asset]} Removed asset * @example * const removed = assetManager.remove('http://img.jpg'); * // or by passing the Asset * const asset = assetManager.get('http://img.jpg'); * assetManager.remove(asset); */ AssetManager.prototype.remove = function (asset, opts) { return this.__remove(asset, opts); }; AssetManager.prototype.store = function () { return this.getProjectData(); }; AssetManager.prototype.load = function (data) { return this.loadProjectData(data); }; /** * Return the Asset Manager Container * @returns {HTMLElement} */ AssetManager.prototype.getContainer = function () { var _a; var bhv = this.__getBehaviour(); return bhv.container || ((_a = this.am) === null || _a === void 0 ? void 0 : _a.el); }; /** * Get assets element container * @returns {HTMLElement} * @private */ AssetManager.prototype.getAssetsEl = function () { var _a; return (_a = this.am) === null || _a === void 0 ? void 0 : _a.el.querySelector('[data-el=assets]'); }; /** * Render assets * @param {array} assets Assets to render, without the argument will render all global assets * @returns {HTMLElement} * @private * @example * // Render all assets * assetManager.render(); * * // Render some of the assets * const assets = assetManager.getAll(); * assetManager.render(assets.filter( * asset => asset.get('category') == 'cats' * )); */ AssetManager.prototype.render = function (assts) { if (this.getConfig().custom) return; var toRender = assts || this.getAll().models; if (!this.am) { var obj = this.__viewParams(); obj.fu = this.FileUploader(); this.am = new view_AssetsView(asset_manager_assign({}, obj)); this.am.render(); } this.assetsVis.reset(toRender); return this.getContainer(); }; AssetManager.prototype.__viewParams = function () { return { collection: this.assetsVis, globalCollection: this.all, config: this.config, module: this, fu: undefined, }; }; /** * Add new type. If you want to get more about type definition we suggest to read the [module's page](/modules/Assets.html) * @param {string} id Type ID * @param {Object} definition Definition of the type. Each definition contains * `model` (business logic), `view` (presentation logic) * and `isType` function which recognize the type of the * passed entity * @private * @example * assetManager.addType('my-type', { * model: {}, * view: {}, * isType: (value) => {}, * }) */ AssetManager.prototype.addType = function (id, definition) { this.getAll().addType(id, definition); }; /** * Get type * @param {string} id Type ID * @returns {Object} Type definition * @private */ AssetManager.prototype.getType = function (id) { return this.getAll().getType(id); }; /** * Get types * @returns {Array} * @private */ AssetManager.prototype.getTypes = function () { return this.getAll().getTypes(); }; //------- AssetManager.prototype.AssetsView = function () { return this.am; }; AssetManager.prototype.FileUploader = function () { if (!this.fu) { this.fu = new FileUploader(this.__viewParams()); } return this.fu; }; AssetManager.prototype.onLoad = function () { var _this = this; this.getAll().reset(this.config.assets); var _a = this, em = _a.em, events = _a.events; em.on("run:".concat(assetCmd), function () { return _this.__propEv(events.open); }); em.on("stop:".concat(assetCmd), function () { return _this.__propEv(events.close); }); }; AssetManager.prototype.postRender = function (editorView) { var _a; this.config.dropzone && ((_a = this.fu) === null || _a === void 0 ? void 0 : _a.initDropzone(editorView)); }; /** * Set new target * @param {Object} m Model * @private * */ AssetManager.prototype.setTarget = function (m) { this.assetsVis.target = m; }; /** * Set callback after asset was selected * @param {Object} f Callback function * @private * */ AssetManager.prototype.onSelect = function (f) { this.assetsVis.onSelect = f; }; /** * Set callback to fire when the asset is clicked * @param {function} func * @private */ AssetManager.prototype.onClick = function (func) { // @ts-ignore this.config.onClick = func; }; /** * Set callback to fire when the asset is double clicked * @param {function} func * @private */ AssetManager.prototype.onDblClick = function (func) { // @ts-ignore this.config.onDblClick = func; }; AssetManager.prototype.__behaviour = function (opts) { if (opts === void 0) { opts = {}; } return (this._bhv = asset_manager_assign(asset_manager_assign({}, (this._bhv || {})), opts)); }; AssetManager.prototype.__getBehaviour = function (opts) { if (opts === void 0) { opts = {}; } return this._bhv || {}; }; AssetManager.prototype.destroy = function () { var _a, _b; this.all.stopListening(); this.all.reset(); this.assetsVis.stopListening(); this.assetsVis.reset(); (_a = this.fu) === null || _a === void 0 ? void 0 : _a.remove(); (_b = this.am) === null || _b === void 0 ? void 0 : _b.remove(); this._bhv = {}; }; return AssetManager; }(ItemManagerModule)); /* harmony default export */ const asset_manager = (AssetManager); ;// CONCATENATED MODULE: ./src/i18n/locale/en.js var traitInputAttr = { placeholder: 'eg. Text here' }; /* harmony default export */ const en = ({ assetManager: { addButton: 'Add image', inputPlh: 'http://path/to/the/image.jpg', modalTitle: 'Select Image', uploadTitle: 'Drop files here or click to upload' }, // Here just as a reference, GrapesJS core doesn't contain any block, // so this should be omitted from other local files blockManager: { labels: { // 'block-id': 'Block Label', }, categories: { // 'category-id': 'Category Label', } }, domComponents: { names: { '': 'Box', wrapper: 'Body', text: 'Text', comment: 'Comment', image: 'Image', video: 'Video', label: 'Label', link: 'Link', map: 'Map', tfoot: 'Table foot', tbody: 'Table body', thead: 'Table head', table: 'Table', row: 'Table row', cell: 'Table cell' } }, deviceManager: { device: 'Device', devices: { desktop: 'Desktop', tablet: 'Tablet', mobileLandscape: 'Mobile Landscape', mobilePortrait: 'Mobile Portrait' } }, panels: { buttons: { titles: { preview: 'Preview', fullscreen: 'Fullscreen', 'sw-visibility': 'View components', 'export-template': 'View code', 'open-sm': 'Open Style Manager', 'open-tm': 'Settings', 'open-layers': 'Open Layer Manager', 'open-blocks': 'Open Blocks' } } }, selectorManager: { label: 'Classes', selected: 'Selected', emptyState: '- State -', states: { hover: 'Hover', active: 'Click', 'nth-of-type(2n)': 'Even/Odd' } }, styleManager: { empty: 'Select an element before using Style Manager', layer: 'Layer', fileButton: 'Images', sectors: { general: 'General', layout: 'Layout', typography: 'Typography', decorations: 'Decorations', extra: 'Extra', flex: 'Flex', dimension: 'Dimension' }, // Default names for sub properties in Composite and Stack types. // Other labels are generated directly from their property names (eg. 'font-size' will be 'Font size'). properties: { 'text-shadow-h': 'X', 'text-shadow-v': 'Y', 'text-shadow-blur': 'Blur', 'text-shadow-color': 'Color', 'box-shadow-h': 'X', 'box-shadow-v': 'Y', 'box-shadow-blur': 'Blur', 'box-shadow-spread': 'Spread', 'box-shadow-color': 'Color', 'box-shadow-type': 'Type', 'margin-top-sub': 'Top', 'margin-right-sub': 'Right', 'margin-bottom-sub': 'Bottom', 'margin-left-sub': 'Left', 'padding-top-sub': 'Top', 'padding-right-sub': 'Right', 'padding-bottom-sub': 'Bottom', 'padding-left-sub': 'Left', 'border-width-sub': 'Width', 'border-style-sub': 'Style', 'border-color-sub': 'Color', 'border-top-left-radius-sub': 'Top Left', 'border-top-right-radius-sub': 'Top Right', 'border-bottom-right-radius-sub': 'Bottom Right', 'border-bottom-left-radius-sub': 'Bottom Left', 'transform-rotate-x': 'Rotate X', 'transform-rotate-y': 'Rotate Y', 'transform-rotate-z': 'Rotate Z', 'transform-scale-x': 'Scale X', 'transform-scale-y': 'Scale Y', 'transform-scale-z': 'Scale Z', 'transition-property-sub': 'Property', 'transition-duration-sub': 'Duration', 'transition-timing-function-sub': 'Timing', 'background-image-sub': 'Image', 'background-repeat-sub': 'Repeat', 'background-position-sub': 'Position', 'background-attachment-sub': 'Attachment', 'background-size-sub': 'Size' } // Translate options in style properties // options: { // float: { // Id of the property // ... // left: 'Left', // {option id}: {Option label} // } // } }, traitManager: { empty: 'Select an element before using Trait Manager', label: 'Component settings', traits: { // The core library generates the name by their `name` property labels: { // id: 'Id', // alt: 'Alt', // title: 'Title', // href: 'Href', }, // In a simple trait, like text input, these are used on input attributes attributes: { id: traitInputAttr, alt: traitInputAttr, title: traitInputAttr, href: { placeholder: 'eg. https://google.com' } }, // In a trait like select, these are used to translate option names options: { target: { false: 'This window', _blank: 'New window' } } } }, storageManager: { recover: 'Do you want to recover unsaved changes?' } }); ;// CONCATENATED MODULE: ./src/i18n/config.ts var i18n_config_config = { locale: 'en', localeFallback: 'en', detectLocale: true, debug: false, messages: { en: en }, messagesAdd: undefined, }; /* harmony default export */ const i18n_config = (i18n_config_config); ;// CONCATENATED MODULE: ./src/i18n/index.ts var i18n_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); /** * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/GrapesJS/grapesjs/blob/master/src/i18n/config.ts) * ```js * const editor = grapesjs.init({ * i18n: { * locale: 'en', * localeFallback: 'en', * messages: { * it: { hello: 'Ciao', ... }, * ... * } * } * }) * ``` * * Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance * * ```js * const i18n = editor.I18n; * ``` * * ### Events * * `i18n:add` - New set of messages is added * * `i18n:update` - The set of messages is updated * * `i18n:locale` - Locale changed * * @module I18n */ var I18nModule = /** @class */ (function (_super) { i18n_extends(I18nModule, _super); /** * Initialize module * @param {Object} config Configurations * @private */ function I18nModule(em) { var _this = _super.call(this, em, 'I18n', i18n_config) || this; var add = _this.config.messagesAdd; add && _this.addMessages(add); if (_this.config.detectLocale) { _this.config.locale = _this._localLang(); } return _this; } /** * Get configuration object * @name getConfig * @function * @return {Object} */ /** * Update current locale * @param {String} locale Locale value * @returns {this} * @example * i18n.setLocale('it'); */ I18nModule.prototype.setLocale = function (locale) { var _a = this, em = _a.em, config = _a.config; var evObj = { value: locale, valuePrev: config.locale }; em && em.trigger('i18n:locale', evObj); config.locale = locale; return this; }; /** * Get current locale * @returns {String} Current locale value */ I18nModule.prototype.getLocale = function () { return this.config.locale; }; /** * Get all messages * @param {String} [lang] Specify the language of messages to return * @param {Object} [opts] Options * @param {Boolean} [opts.debug] Show warnings in case of missing language * @returns {Object} * @example * i18n.getMessages(); * // -> { en: { hello: '...' }, ... } * i18n.getMessages('en'); * // -> { hello: '...' } */ I18nModule.prototype.getMessages = function (lang, opts) { if (opts === void 0) { opts = {}; } var messages = this.config.messages; lang && !messages[lang] && this._debug("'".concat(lang, "' i18n lang not found"), opts); return lang ? messages[lang] : messages; }; /** * Set new set of messages * @param {Object} msg Set of messages * @returns {this} * @example * i18n.getMessages(); * // -> { en: { msg1: 'Msg 1', msg2: 'Msg 2', } } * i18n.setMessages({ en: { msg2: 'Msg 2 up', msg3: 'Msg 3', } }); * // Set replaced * i18n.getMessages(); * // -> { en: { msg2: 'Msg 2 up', msg3: 'Msg 3', } } */ I18nModule.prototype.setMessages = function (msg) { var _a = this, em = _a.em, config = _a.config; config.messages = msg; em && em.trigger('i18n:update', msg); return this; }; /** * Update messages * @param {Object} msg Set of messages to add * @returns {this} * @example * i18n.getMessages(); * // -> { en: { msg1: 'Msg 1', msg2: 'Msg 2', } } * i18n.addMessages({ en: { msg2: 'Msg 2 up', msg3: 'Msg 3', } }); * // Set updated * i18n.getMessages(); * // -> { en: { msg1: 'Msg 1', msg2: 'Msg 2 up', msg3: 'Msg 3', } } */ I18nModule.prototype.addMessages = function (msg) { var em = this.em; var messages = this.config.messages; em && em.trigger('i18n:add', msg); this.setMessages((0,mixins.deepMerge)(messages, msg)); return this; }; /** * Translate the locale message * @param {String} key Label to translate * @param {Object} [opts] Options for the translation * @param {Object} [opts.params] Params for the translation * @param {Boolean} [opts.debug] Show warnings in case of missing resources * @returns {String} * @example * obj.setMessages({ * en: { msg: 'Msg', msg2: 'Msg {test}'}, * it: { msg2: 'Msg {test} it'}, * }); * obj.t('msg'); * // -> outputs `Msg` * obj.t('msg2', { params: { test: 'hello' } }); // use params * // -> outputs `Msg hello` * obj.t('msg2', { l: 'it', params: { test: 'hello' } }); // custom local * // -> outputs `Msg hello it` */ I18nModule.prototype.t = function (key, opts) { if (opts === void 0) { opts = {}; } var config = this.config; var param = opts.params || {}; var locale = opts.l || this.getLocale(); var localeFlb = opts.lFlb || config.localeFallback; var result = this._getMsg(key, locale, opts); // Try with fallback if (!result) result = this._getMsg(key, localeFlb, opts); !result && this._debug("'".concat(key, "' i18n key not found in '").concat(locale, "' lang"), opts); result = result && (0,index_all.isString)(result) ? this._addParams(result, param) : result; return result; }; I18nModule.prototype._localLang = function () { var nav = ((0,mixins.hasWin)() && window.navigator) || {}; // @ts-ignore var lang = nav.language || nav.userLanguage; return lang ? lang.split('-')[0] : 'en'; }; I18nModule.prototype._addParams = function (str, params) { var reg = new RegExp('{([\\w\\d-]*)}', 'g'); return str.replace(reg, function (m, val) { return params[val] || ''; }).trim(); }; I18nModule.prototype._getMsg = function (key, locale, opts) { if (opts === void 0) { opts = {}; } var msgSet = this.getMessages(locale, opts); // Lang set is missing if (!msgSet) return; var result = msgSet[key]; // Check for nested getter if (!result && key.indexOf('.') > 0) { result = key.split('.').reduce(function (lang, key) { if ((0,index_all.isUndefined)(lang)) return; return lang[key]; }, msgSet); } return result; }; I18nModule.prototype._debug = function (str, opts) { if (opts === void 0) { opts = {}; } var _a = this, em = _a.em, config = _a.config; (opts.debug || config.debug) && em && em.logWarning(str); }; I18nModule.prototype.destroy = function () { }; return I18nModule; }(abstract_Module)); /* harmony default export */ const i18n = (I18nModule); ;// CONCATENATED MODULE: ./src/utils/Sorter.ts var Sorter_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var Sorter_assign = ( false) || function () { Sorter_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return Sorter_assign.apply(this, arguments); }; var Sorter_noop = function () { }; var targetSpotType = CanvasSpot/* CanvasSpotBuiltInTypes */.q.Target; var spotTarget = { id: 'sorter-target', type: targetSpotType, }; var Sorter = /** @class */ (function (_super) { Sorter_extends(Sorter, _super); function Sorter() { return _super !== null && _super.apply(this, arguments) || this; } /** @ts-ignore */ Sorter.prototype.initialize = function (opt) { if (opt === void 0) { opt = {}; } this.opt = opt || {}; (0,index_all.bindAll)(this, 'startSort', 'onMove', 'endMove', 'rollback', 'updateOffset', 'moveDragHelper'); var o = opt || {}; this.elT = 0; this.elL = 0; this.borderOffset = o.borderOffset || 10; var el = o.container; this.el = typeof el === 'string' ? document.querySelector(el) : el; this.$el = (0,cash_dom["default"])(this.el); // TODO check if necessary this.containerSel = o.containerSel || 'div'; this.itemSel = o.itemSel || 'div'; this.draggable = o.draggable || true; this.nested = !!o.nested; this.pfx = o.pfx || ''; this.ppfx = o.ppfx || ''; this.freezeClass = o.freezeClass || this.pfx + 'freezed'; this.onStart = o.onStart || Sorter_noop; this.onEndMove = o.onEndMove; this.customTarget = o.customTarget; this.onEnd = o.onEnd; this.direction = o.direction || 'v'; // v (vertical), h (horizontal), a (auto) this.onMoveClb = o.onMove; this.relative = o.relative || false; this.ignoreViewChildren = !!o.ignoreViewChildren; this.plh = o.placer; // Frame offset this.wmargin = o.wmargin || 0; this.offTop = o.offsetTop || 0; this.offLeft = o.offsetLeft || 0; this.document = o.document || document; this.em = o.em; this.canvasRelative = !!o.canvasRelative; this.selectOnEnd = !o.avoidSelectOnEnd; this.scale = o.scale; if (this.em && this.em.on) { this.em.on('change:canvasOffset', this.updateOffset); this.updateOffset(); } }; Sorter.prototype.getScale = function () { return (0,index_all.result)(this, 'scale') || 1; }; Sorter.prototype.getContainerEl = function (elem) { if (elem) this.el = elem; if (!this.el) { var el = this.opt.container; this.el = typeof el === 'string' ? document.querySelector(el) : el; this.$el = (0,cash_dom["default"])(this.el); // TODO check if necessary } return this.el; }; Sorter.prototype.getDocuments = function (el) { var em = this.em; var elDoc = el ? el.ownerDocument : em === null || em === void 0 ? void 0 : em.Canvas.getBody().ownerDocument; var docs = [document]; elDoc && docs.push(elDoc); return docs; }; /** * Triggered when the offset of the editro is changed */ Sorter.prototype.updateOffset = function () { var _a; var offset = ((_a = this.em) === null || _a === void 0 ? void 0 : _a.get('canvasOffset')) || {}; this.offTop = offset.top; this.offLeft = offset.left; }; /** * Set content to drop * @param {String|Object} content */ Sorter.prototype.setDropContent = function (content) { delete this.dropModel; this.dropContent = content; }; Sorter.prototype.updateTextViewCursorPosition = function (e) { var em = this.em; if (!em) return; var Canvas = em.Canvas; var targetDoc = Canvas.getDocument(); var range = null; if (targetDoc.caretRangeFromPoint) { // Chrome var poiner = (0,dom/* getPointerEvent */.VB)(e); range = targetDoc.caretRangeFromPoint(poiner.clientX, poiner.clientY); } else if (e.rangeParent) { // Firefox range = targetDoc.createRange(); range.setStart(e.rangeParent, e.rangeOffset); } var sel = Canvas.getWindow().getSelection(); Canvas.getFrameEl().focus(); sel === null || sel === void 0 ? void 0 : sel.removeAllRanges(); range && (sel === null || sel === void 0 ? void 0 : sel.addRange(range)); this.setContentEditable(this.activeTextModel, true); }; Sorter.prototype.setContentEditable = function (model, mode) { if (model) { // @ts-ignore var el = model.getEl(); if (el.contentEditable != mode) el.contentEditable = mode; } }; /** * Toggle cursor while sorting * @param {Boolean} active */ Sorter.prototype.toggleSortCursor = function (active) { var em = this.em; var cv = em === null || em === void 0 ? void 0 : em.Canvas; // Avoid updating body className as it causes a huge repaint // Noticeable with "fast" drag of blocks cv && (active ? cv.startAutoscroll() : cv.stopAutoscroll()); }; /** * Set drag helper * @param {HTMLElement} el * @param {Event} event */ Sorter.prototype.setDragHelper = function (el, event) { var ev = event || ''; var clonedEl = el.cloneNode(true); var rect = el.getBoundingClientRect(); var computed = getComputedStyle(el); var style = ''; for (var i = 0; i < computed.length; i++) { var prop = computed[i]; style += "".concat(prop, ":").concat(computed.getPropertyValue(prop), ";"); } document.body.appendChild(clonedEl); clonedEl.className += " ".concat(this.pfx, "bdrag"); clonedEl.setAttribute('style', style); this.dragHelper = clonedEl; clonedEl.style.width = "".concat(rect.width, "px"); clonedEl.style.height = "".concat(rect.height, "px"); ev && this.moveDragHelper(ev); // Listen mouse move events if (this.em) { var $doc = (0,cash_dom["default"])(this.em.Canvas.getBody().ownerDocument); $doc.off('mousemove', this.moveDragHelper).on('mousemove', this.moveDragHelper); } (0,cash_dom["default"])(document).off('mousemove', this.moveDragHelper).on('mousemove', this.moveDragHelper); }; /** * Update the position of the helper * @param {Event} e */ Sorter.prototype.moveDragHelper = function (e) { var doc = e.target.ownerDocument; if (!this.dragHelper || !doc) { return; } var posY = e.pageY; var posX = e.pageX; var addTop = 0; var addLeft = 0; // @ts-ignore var window = doc.defaultView || doc.parentWindow; var frame = window.frameElement; var dragHelperStyle = this.dragHelper.style; // If frame is present that means mouse has moved over the editor's canvas, // which is rendered inside the iframe and the mouse move event comes from // the iframe, not the parent window. Mouse position relative to the frame's // parent window needs to account for the frame's position relative to the // parent window. if (frame) { var frameRect = frame.getBoundingClientRect(); addTop = frameRect.top + document.documentElement.scrollTop; addLeft = frameRect.left + document.documentElement.scrollLeft; posY = e.clientY; posX = e.clientX; } dragHelperStyle.top = posY + addTop + 'px'; dragHelperStyle.left = posX + addLeft + 'px'; }; /** * Returns true if the element matches with selector * @param {Element} el * @param {String} selector * @return {Boolean} */ Sorter.prototype.matches = function (el, selector) { return mixins.matches.call(el, selector); }; /** * Closest parent * @param {Element} el * @param {String} selector * @return {Element|null} */ Sorter.prototype.closest = function (el, selector) { if (!el) return; var elem = el.parentNode; while (elem && elem.nodeType === 1) { if (this.matches(elem, selector)) return elem; elem = elem.parentNode; } }; /** * Get the offset of the element * @param {HTMLElement} el * @return {Object} */ Sorter.prototype.offset = function (el) { var rect = el.getBoundingClientRect(); return { top: rect.top + document.body.scrollTop, left: rect.left + document.body.scrollLeft, }; }; /** * Create placeholder * @return {HTMLElement} */ Sorter.prototype.createPlaceholder = function () { var pfx = this.pfx; var el = document.createElement('div'); var ins = document.createElement('div'); el.className = pfx + 'placeholder'; el.style.display = 'none'; el.style.pointerEvents = 'none'; ins.className = pfx + 'placeholder-int'; el.appendChild(ins); return el; }; /** * Picking component to move * @param {HTMLElement} src * */ Sorter.prototype.startSort = function (src, opts) { var _a, _b; if (opts === void 0) { opts = {}; } var _c = this, em = _c.em, itemSel = _c.itemSel, containerSel = _c.containerSel, plh = _c.plh; var container = this.getContainerEl(opts.container); var docs = this.getDocuments(src); var srcModel; delete this.dropModel; delete this.target; delete this.prevTarget; this.moved = false; // Check if the start element is a valid one, if not, try the closest valid one if (src && !this.matches(src, "".concat(itemSel, ", ").concat(containerSel))) { src = this.closest(src, itemSel); } this.sourceEl = src; // Create placeholder if doesn't exist yet if (!plh) { this.plh = this.createPlaceholder(); container.appendChild(this.plh); } if (src) { srcModel = this.getSourceModel(src); (srcModel === null || srcModel === void 0 ? void 0 : srcModel.set) && srcModel.set('status', 'freezed'); this.srcModel = srcModel; } (0,dom.on)(container, 'mousemove dragover', this.onMove); (0,dom.on)(docs, 'mouseup dragend touchend', this.endMove); (0,dom.on)(docs, 'keydown', this.rollback); this.onStart({ sorter: this, target: srcModel, // @ts-ignore parent: srcModel && ((_a = srcModel.parent) === null || _a === void 0 ? void 0 : _a.call(srcModel)), // @ts-ignore index: srcModel && ((_b = srcModel.index) === null || _b === void 0 ? void 0 : _b.call(srcModel)), }); // Avoid strange effects on dragging em === null || em === void 0 ? void 0 : em.clearSelection(); this.toggleSortCursor(true); em === null || em === void 0 ? void 0 : em.trigger('sorter:drag:start', src, srcModel); }; /** * Get the model from HTMLElement target * @return {Model|null} */ Sorter.prototype.getTargetModel = function (el) { var elem = el || this.target; return (0,cash_dom["default"])(elem).data('model'); }; /** * Get the model of the current source element (element to drag) * @return {Model} */ Sorter.prototype.getSourceModel = function (source, _a) { var _this = this; var _b = _a === void 0 ? {} : _a, target = _b.target, _c = _b.avoidChildren, avoidChildren = _c === void 0 ? 1 : _c; var _d = this, em = _d.em, sourceEl = _d.sourceEl; var src = source || sourceEl; var _e = this, dropModel = _e.dropModel, dropContent = _e.dropContent; var isTextable = function (src) { return src && target && src.opt && src.opt.avoidChildren && _this.isTextableActive(src, target); }; if (dropContent && em) { if (isTextable(dropModel)) { dropModel = undefined; } if (!dropModel) { var comps = em.Components.getComponents(); var opts = { avoidChildren: avoidChildren, avoidStore: 1, avoidUpdateStyle: 1, }; var tempModel = comps.add(dropContent, Sorter_assign(Sorter_assign({}, opts), { temporary: true })); // @ts-ignore dropModel = comps.remove(tempModel, opts); dropModel = dropModel instanceof Array ? dropModel[0] : dropModel; this.dropModel = dropModel; if (isTextable(dropModel)) { return this.getSourceModel(src, { target: target, avoidChildren: 0 }); } } return dropModel; } return src && (0,cash_dom["default"])(src).data('model'); }; /** * Highlight target * @param {Model|null} model */ Sorter.prototype.selectTargetModel = function (model, source) { if (model instanceof common/* Collection */.FE) { return; } // Prevents loops in Firefox // https://github.com/GrapesJS/grapesjs/issues/2911 if (source && source === model) return; var targetModel = this.targetModel; // Reset the previous model but not if it's the same as the source // https://github.com/GrapesJS/grapesjs/issues/2478#issuecomment-570314736 if (targetModel && targetModel !== this.srcModel) { targetModel.set('status', ''); } if (model === null || model === void 0 ? void 0 : model.set) { var cv_1 = this.em.Canvas; var Select = CanvasSpot/* CanvasSpotBuiltInTypes */.q.Select, Hover = CanvasSpot/* CanvasSpotBuiltInTypes */.q.Hover, Spacing = CanvasSpot/* CanvasSpotBuiltInTypes */.q.Spacing; [Select, Hover, Spacing].forEach(function (type) { return cv_1.removeSpots({ type: type }); }); cv_1.addSpot(Sorter_assign(Sorter_assign({}, spotTarget), { component: model })); model.set('status', 'selected-parent'); this.targetModel = model; } }; /** * During move * @param {Event} e * */ Sorter.prototype.onMove = function (e) { var ev = e; var _a = this, em = _a.em, onMoveClb = _a.onMoveClb, plh = _a.plh, customTarget = _a.customTarget; this.moved = true; // Turn placeholder visibile var dsp = plh.style.display; if (!dsp || dsp === 'none') plh.style.display = 'block'; // Cache all necessary positions var eO = this.offset(this.el); this.elT = this.wmargin ? Math.abs(eO.top) : eO.top; this.elL = this.wmargin ? Math.abs(eO.left) : eO.left; var rY = e.pageY - this.elT + this.el.scrollTop; var rX = e.pageX - this.elL + this.el.scrollLeft; if (this.canvasRelative && em) { var mousePos = em.Canvas.getMouseRelativeCanvas(e, { noScroll: 1 }); rX = mousePos.x; rY = mousePos.y; } this.rX = rX; this.rY = rY; this.eventMove = e; //var targetNew = this.getTargetFromEl(e.target); var sourceModel = this.getSourceModel(); var targetEl = customTarget ? customTarget({ sorter: this, event: e }) : e.target; var dims = this.dimsFromTarget(targetEl, rX, rY); var target = this.target; var targetModel = target && this.getTargetModel(target); this.selectTargetModel(targetModel, sourceModel); if (!targetModel) plh.style.display = 'none'; if (!target) return; this.lastDims = dims; var pos = this.findPosition(dims, rX, rY); if (this.isTextableActive(sourceModel, targetModel)) { this.activeTextModel = targetModel; plh.style.display = 'none'; this.lastPos = pos; this.updateTextViewCursorPosition(ev); } else { this.disableTextable(); delete this.activeTextModel; // If there is a significant changes with the pointer if (!this.lastPos || this.lastPos.index != pos.index || this.lastPos.method != pos.method) { this.movePlaceholder(this.plh, dims, pos, this.prevTargetDim); if (!this.$plh) this.$plh = (0,cash_dom["default"])(this.plh); // With canvasRelative the offset is calculated automatically for // each element if (!this.canvasRelative) { if (this.offTop) this.$plh.css('top', '+=' + this.offTop + 'px'); if (this.offLeft) this.$plh.css('left', '+=' + this.offLeft + 'px'); } this.lastPos = pos; } } (0,index_all.isFunction)(onMoveClb) && onMoveClb({ event: e, target: sourceModel, parent: targetModel, index: pos.index + (pos.method == 'after' ? 1 : 0), }); em && em.trigger('sorter:drag', { target: target, targetModel: targetModel, sourceModel: sourceModel, dims: dims, pos: pos, x: rX, y: rY, }); }; Sorter.prototype.isTextableActive = function (src, trg) { var _a; return ((_a = src === null || src === void 0 ? void 0 : src.get) === null || _a === void 0 ? void 0 : _a.call(src, 'textable')) && (trg === null || trg === void 0 ? void 0 : trg.isInstanceOf('text')); }; Sorter.prototype.disableTextable = function () { var activeTextModel = this.activeTextModel; // @ts-ignore activeTextModel === null || activeTextModel === void 0 ? void 0 : activeTextModel.getView().disableEditing(); this.setContentEditable(activeTextModel, false); }; /** * Returns true if the elements is in flow, so is not in flow where * for example the component is with float:left * @param {HTMLElement} el * @param {HTMLElement} parent * @return {Boolean} * @private * */ Sorter.prototype.isInFlow = function (el, parent) { if (!el) return false; parent = parent || document.body; var ch = -1, h; var elem = el; h = elem.offsetHeight; if ( /*h < ch || */!this.styleInFlow(elem, parent)) return false; else return true; }; /** * Check if el has style to be in flow * @param {HTMLElement} el * @param {HTMLElement} parent * @return {Boolean} * @private */ Sorter.prototype.styleInFlow = function (el, parent) { if ((0,dom/* isTextNode */.BM)(el)) return; var style = el.style || {}; var $el = (0,cash_dom["default"])(el); var $parent = parent && (0,cash_dom["default"])(parent); if (style.overflow && style.overflow !== 'visible') return; var propFloat = $el.css('float'); if (propFloat && propFloat !== 'none') return; if ($parent && $parent.css('display') == 'flex' && $parent.css('flex-direction') !== 'column') return; switch (style.position) { case 'static': case 'relative': case '': break; default: return; } switch (el.tagName) { case 'TR': case 'TBODY': case 'THEAD': case 'TFOOT': return true; } switch ($el.css('display')) { case 'block': case 'list-item': case 'table': case 'flex': case 'grid': return true; } return; }; /** * Check if the target is valid with the actual source * @param {HTMLElement} trg * @return {Boolean} */ Sorter.prototype.validTarget = function (trg, src) { var trgModel = this.getTargetModel(trg); var srcModel = this.getSourceModel(src, { target: trgModel }); // @ts-ignore src = srcModel && srcModel.view && srcModel.view.el; trg = trgModel && trgModel.view && trgModel.view.el; var result = { valid: true, src: src, srcModel: srcModel, trg: trg, trgModel: trgModel, draggable: false, droppable: false, dragInfo: '', dropInfo: '', }; if (!src || !trg) { result.valid = false; return result; } // Check if the source is draggable in target var draggable = srcModel.get('draggable'); if ((0,index_all.isFunction)(draggable)) { var res = draggable(srcModel, trgModel); result.dragInfo = res; result.draggable = res; draggable = res; } else { draggable = draggable instanceof Array ? draggable.join(', ') : draggable; result.dragInfo = draggable; draggable = (0,index_all.isString)(draggable) ? this.matches(trg, draggable) : draggable; result.draggable = draggable; } // Check if the target could accept the source var droppable = trgModel.get('droppable'); if ((0,index_all.isFunction)(droppable)) { var res = droppable(srcModel, trgModel); result.droppable = res; result.dropInfo = res; droppable = res; } else { droppable = droppable instanceof common/* Collection */.FE ? 1 : droppable; droppable = droppable instanceof Array ? droppable.join(', ') : droppable; result.dropInfo = droppable; droppable = (0,index_all.isString)(droppable) ? this.matches(src, droppable) : droppable; droppable = draggable && this.isTextableActive(srcModel, trgModel) ? 1 : droppable; result.droppable = droppable; } if (!droppable || !draggable) { result.valid = false; } return result; }; /** * Get dimensions of nodes relative to the coordinates * @param {HTMLElement} target * @param {number} rX Relative X position * @param {number} rY Relative Y position * @return {Array<Array>} */ Sorter.prototype.dimsFromTarget = function (target, rX, rY) { if (rX === void 0) { rX = 0; } if (rY === void 0) { rY = 0; } var em = this.em; var dims = []; if (!target) { return dims; } // Select the first valuable target if (!this.matches(target, "".concat(this.itemSel, ", ").concat(this.containerSel))) { target = this.closest(target, this.itemSel); } // If draggable is an array the target will be one of those if (this.draggable instanceof Array) { target = this.closest(target, this.draggable.join(',')); } if (!target) { return dims; } // Check if the target is different from the previous one if (this.prevTarget && this.prevTarget != target) { delete this.prevTarget; } // New target found if (!this.prevTarget) { this.targetP = this.closest(target, this.containerSel); // Check if the source is valid with the target var validResult = this.validTarget(target); em && em.trigger('sorter:drag:validation', validResult); if (!validResult.valid && this.targetP) { return this.dimsFromTarget(this.targetP, rX, rY); } this.prevTarget = target; this.prevTargetDim = this.getDim(target); this.cacheDimsP = this.getChildrenDim(this.targetP); this.cacheDims = this.getChildrenDim(target); } // If the target is the previous one will return the cached dims if (this.prevTarget == target) dims = this.cacheDims; // Target when I will drop element to sort this.target = this.prevTarget; // Generally, on any new target the poiner enters inside its area and // triggers nearBorders(), so have to take care of this if (this.nearBorders(this.prevTargetDim, rX, rY) || (!this.nested && !this.cacheDims.length)) { var targetParent = this.targetP; if (targetParent && this.validTarget(targetParent).valid) { dims = this.cacheDimsP; this.target = targetParent; } } delete this.lastPos; return dims; }; /** * Get valid target from element * This method should replace dimsFromTarget() * @param {HTMLElement} el * @return {HTMLElement} */ Sorter.prototype.getTargetFromEl = function (el) { var target = el; var targetParent; var targetPrev = this.targetPrev; var em = this.em; var containerSel = this.containerSel; var itemSel = this.itemSel; // Select the first valuable target if (!this.matches(target, "".concat(itemSel, ", ").concat(containerSel))) { target = this.closest(target, itemSel); } // If draggable is an array the target will be one of those // TODO check if this options is used somewhere if (this.draggable instanceof Array) { target = this.closest(target, this.draggable.join(',')); } // Check if the target is different from the previous one if (targetPrev && targetPrev != target) { delete this.targetPrev; } // New target found if (!this.targetPrev) { targetParent = this.closest(target, containerSel); // If the current target is not valid (src/trg reasons) try with // the parent one (if exists) var validResult = this.validTarget(target); em && em.trigger('sorter:drag:validation', validResult); if (!validResult.valid && targetParent) { return this.getTargetFromEl(targetParent); } this.targetPrev = target; } // Generally, on any new target the poiner enters inside its area and // triggers nearBorders(), so have to take care of this if (this.nearElBorders(target)) { targetParent = this.closest(target, containerSel); if (targetParent && this.validTarget(targetParent).valid) { target = targetParent; } } return target; }; /** * Check if the current pointer is neare to element borders * @return {Boolen} */ Sorter.prototype.nearElBorders = function (el) { var off = 10; var rect = el.getBoundingClientRect(); var body = el.ownerDocument.body; var _a = this.getCurrentPos(), x = _a.x, y = _a.y; var top = rect.top + body.scrollTop; var left = rect.left + body.scrollLeft; var width = rect.width; var height = rect.height; if (y < top + off || // near top edge y > top + height - off || // near bottom edge x < left + off || // near left edge x > left + width - off // near right edge ) { return 1; } }; Sorter.prototype.getCurrentPos = function () { var ev = this.eventMove; var x = (ev === null || ev === void 0 ? void 0 : ev.pageX) || 0; var y = (ev === null || ev === void 0 ? void 0 : ev.pageY) || 0; return { x: x, y: y }; }; /** * Returns dimensions and positions about the element * @param {HTMLElement} el * @return {Array<number>} */ Sorter.prototype.getDim = function (el) { var _a = this, em = _a.em, canvasRelative = _a.canvasRelative; var canvas = em === null || em === void 0 ? void 0 : em.Canvas; var offsets = canvas ? canvas.getElementOffsets(el) : {}; var top, left, height, width; if (canvasRelative && em) { var pos = canvas.getElementPos(el, { noScroll: 1 }); top = pos.top; // - offsets.marginTop; left = pos.left; // - offsets.marginLeft; height = pos.height; // + offsets.marginTop + offsets.marginBottom; width = pos.width; // + offsets.marginLeft + offsets.marginRight; } else { var o = this.offset(el); top = this.relative ? el.offsetTop : o.top - (this.wmargin ? -1 : 1) * this.elT; left = this.relative ? el.offsetLeft : o.left - (this.wmargin ? -1 : 1) * this.elL; height = el.offsetHeight; width = el.offsetWidth; } return { top: top, left: left, height: height, width: width, offsets: offsets }; }; /** * Get children dimensions * @param {HTMLELement} el Element root * @return {Array} * */ Sorter.prototype.getChildrenDim = function (trg) { var _this = this; var dims = []; if (!trg) return dims; // Get children based on getChildrenContainer var trgModel = this.getTargetModel(trg); if (trgModel && trgModel.view && !this.ignoreViewChildren) { var view = trgModel.getCurrentView ? trgModel.getCurrentView() : trgModel.view; trg = view.getChildrenContainer(); } (0,index_all.each)(trg.children, function (ele, i) { var el = ele; var model = (0,mixins.getModel)(el, cash_dom["default"]); var elIndex = model && model.index ? model.index() : i; if (!(0,dom/* isTextNode */.BM)(el) && !_this.matches(el, _this.itemSel)) { return; } var dim = _this.getDim(el); var dir = _this.direction; var dirValue; if (dir == 'v') dirValue = true; else if (dir == 'h') dirValue = false; else dirValue = _this.isInFlow(el, trg); dim.dir = dirValue; dim.el = el; dim.indexEl = elIndex; dims.push(dim); }); return dims; }; /** * Check if the coordinates are near to the borders * @param {Array<number>} dim * @param {number} rX Relative X position * @param {number} rY Relative Y position * @return {Boolean} * */ Sorter.prototype.nearBorders = function (dim, rX, rY) { var result = false; var off = this.borderOffset; var x = rX || 0; var y = rY || 0; var t = dim.top; var l = dim.left; var h = dim.height; var w = dim.width; if (t + off > y || y > t + h - off || l + off > x || x > l + w - off) result = true; return result; }; /** * Find the position based on passed dimensions and coordinates * @param {Array<Array>} dims Dimensions of nodes to parse * @param {number} posX X coordindate * @param {number} posY Y coordindate * @return {Object} * */ Sorter.prototype.findPosition = function (dims, posX, posY) { var result = { index: 0, indexEl: 0, method: 'before' }; var leftLimit = 0; var xLimit = 0; var dimRight = 0; var yLimit = 0; var xCenter = 0; var yCenter = 0; var dimDown = 0; var dim; // Each dim is: Top, Left, Height, Width for (var i = 0, len = dims.length; i < len; i++) { dim = dims[i]; var top_1 = dim.top, left = dim.left, height = dim.height, width = dim.width; // Right position of the element. Left + Width dimRight = left + width; // Bottom position of the element. Top + Height dimDown = top_1 + height; // X center position of the element. Left + (Width / 2) xCenter = left + width / 2; // Y center position of the element. Top + (Height / 2) yCenter = top_1 + height / 2; // Skip if over the limits if ((xLimit && left > xLimit) || (yLimit && yCenter >= yLimit) || // >= avoid issue with clearfixes (leftLimit && dimRight < leftLimit)) continue; result.index = i; result.indexEl = dim.indexEl; // If it's not in flow (like 'float' element) if (!dim.dir) { if (posY < dimDown) yLimit = dimDown; //If x lefter than center if (posX < xCenter) { xLimit = xCenter; result.method = 'before'; } else { leftLimit = xCenter; result.method = 'after'; } } else { // If y upper than center if (posY < yCenter) { result.method = 'before'; break; } else result.method = 'after'; // After last element } } return result; }; /** * Updates the position of the placeholder * @param {HTMLElement} phl * @param {Array<Array>} dims * @param {Object} pos Position object * @param {Array<number>} trgDim target dimensions ([top, left, height, width]) * */ Sorter.prototype.movePlaceholder = function (plh, dims, pos, trgDim) { var marg = 0; var t = 0; var l = 0; var w = ''; var h = ''; var un = 'px'; var margI = 5; var method = pos.method; var elDim = dims[pos.index]; // Placeholder orientation plh.classList.remove('vertical'); plh.classList.add('horizontal'); if (elDim) { // If it's not in flow (like 'float' element) var top_2 = elDim.top, left = elDim.left, height = elDim.height, width = elDim.width; if (!elDim.dir) { w = 'auto'; h = height - marg * 2 + un; t = top_2 + marg; l = method == 'before' ? left - marg : left + width - marg; plh.classList.remove('horizontal'); plh.classList.add('vertical'); } else { w = width + un; h = 'auto'; t = method == 'before' ? top_2 - marg : top_2 + height - marg; l = left; } } else { // Placeholder inside the component if (!this.nested) { plh.style.display = 'none'; return; } if (trgDim) { var offset = trgDim.offsets || {}; var pT = offset.paddingTop || margI; var pL = offset.paddingLeft || margI; t = trgDim.top + pT; l = trgDim.left + pL; w = parseInt("".concat(trgDim.width)) - pL * 2 + un; h = 'auto'; } } plh.style.top = t + un; plh.style.left = l + un; if (w) plh.style.width = w; if (h) plh.style.height = h; }; /** * Build an array of all the parents, including the component itself * @return {Model|null} */ Sorter.prototype.parents = function (model) { return model ? [model].concat(this.parents(model.parent())) : []; }; /** * Sort according to the position in the dom * @param {Object} obj1 contains {model, parents} * @param {Object} obj2 contains {model, parents} */ Sorter.prototype.sort = function (obj1, obj2) { // common ancesters var ancesters = obj1.parents.filter(function (p) { return obj2.parents.includes(p); }); var ancester = ancesters[0]; if (!ancester) { // this is never supposed to happen return obj2.model.index() - obj1.model.index(); } // find siblings in the common ancester // the sibling is the element inside the ancester var s1 = obj1.parents[obj1.parents.indexOf(ancester) - 1]; var s2 = obj2.parents[obj2.parents.indexOf(ancester) - 1]; // order according to the position in the DOM return s2.index() - s1.index(); }; /** * Leave item * @param event * * @return void * */ Sorter.prototype.endMove = function () { var _this = this; var _a; var src = this.sourceEl; var moved = []; var docs = this.getDocuments(); var container = this.getContainerEl(); var onEndMove = this.onEndMove; var onEnd = this.onEnd; var _b = this, target = _b.target, lastPos = _b.lastPos; var srcModel; (0,dom/* off */.S1)(container, 'mousemove dragover', this.onMove); (0,dom/* off */.S1)(docs, 'mouseup dragend touchend', this.endMove); (0,dom/* off */.S1)(docs, 'keydown', this.rollback); this.plh.style.display = 'none'; if (src) { srcModel = this.getSourceModel(); if (this.selectOnEnd && srcModel && srcModel.set) { srcModel.set('status', ''); srcModel.set('status', 'selected'); } } if (this.moved && target) { var toMove = this.toMove; var toMoveArr = (0,index_all.isArray)(toMove) ? toMove : toMove ? [toMove] : [src]; var domPositionOffset_1 = 0; if (toMoveArr.length === 1) { // do not sort the array in this case // there are cases for the sorter where toMoveArr is [undefined] // which allows the drop from blocks, native D&D and sort of layers in Style Manager moved.push(this.move(target, toMoveArr[0], lastPos)); } else { toMoveArr // add the model's parents .map(function (model) { return ({ model: model, parents: _this.parents(model), }); }) // sort based on elements positions in the dom .sort(this.sort) // move each component to the new parent and position .forEach(function (_a) { var model = _a.model; // @ts-ignore store state before move var index = model.index(); // @ts-ignore var parent = model.parent().getEl(); // move the component to the desired position moved.push(_this.move(target, model, Sorter_assign(Sorter_assign({}, lastPos), { indexEl: lastPos.indexEl - domPositionOffset_1, index: lastPos.index - domPositionOffset_1 }))); // when the element is dragged to the same parent and after its position // it will be removed from the children list // in that case we need to adjust the following elements target position if (parent === target && index <= lastPos.index) { // the next elements will be inserted 1 element before this one domPositionOffset_1++; } }); } } if (this.plh) this.plh.style.display = 'none'; var dragHelper = this.dragHelper; if (dragHelper) { dragHelper.parentNode.removeChild(dragHelper); delete this.dragHelper; } this.disableTextable(); this.selectTargetModel(); this.toggleSortCursor(); (_a = this.em) === null || _a === void 0 ? void 0 : _a.Canvas.removeSpots(spotTarget); delete this.toMove; delete this.eventMove; delete this.dropModel; if ((0,index_all.isFunction)(onEndMove)) { var data_1 = { target: srcModel, // @ts-ignore parent: srcModel && srcModel.parent(), // @ts-ignore index: srcModel && srcModel.index(), }; moved.length ? moved.forEach(function (m) { return onEndMove(m, _this, data_1); }) : onEndMove(null, this, Sorter_assign(Sorter_assign({}, data_1), { cancelled: 1 })); } (0,index_all.isFunction)(onEnd) && onEnd({ sorter: this }); }; /** * Move component to new position * @param {HTMLElement} dst Destination target * @param {HTMLElement} src Element to move * @param {Object} pos Object with position coordinates * */ Sorter.prototype.move = function (dst, src, pos) { var _a = this, em = _a.em, dropContent = _a.dropContent; var srcEl = (0,mixins.getElement)(src); var warns = []; var index = pos.method === 'after' ? pos.indexEl + 1 : pos.indexEl; var validResult = this.validTarget(dst, srcEl); var targetCollection = (0,cash_dom["default"])(dst).data('collection'); var trgModel = validResult.trgModel, srcModel = validResult.srcModel, draggable = validResult.draggable; var droppable = trgModel instanceof common/* Collection */.FE ? 1 : validResult.droppable; var modelToDrop, created; if (targetCollection && droppable && draggable) { var opts = { at: index, action: 'move-component' }; var isTextable = this.isTextableActive(srcModel, trgModel); if (!dropContent) { var srcIndex = srcModel.collection.indexOf(srcModel); var sameCollection = targetCollection === srcModel.collection; var sameIndex = srcIndex === index || srcIndex === index - 1; var canRemove = !sameCollection || !sameIndex || isTextable; if (canRemove) { modelToDrop = srcModel.collection.remove(srcModel, { temporary: true, }); if (sameCollection && index > srcIndex) { opts.at = index - 1; } } } else { // @ts-ignore modelToDrop = (0,index_all.isFunction)(dropContent) ? dropContent() : dropContent; opts.avoidUpdateStyle = true; opts.action = 'add-component'; } if (modelToDrop) { if (isTextable) { delete opts.at; created = trgModel.getView().insertComponent(modelToDrop, opts); } else { created = targetCollection.add(modelToDrop, opts); } } delete this.dropContent; delete this.prevTarget; // This will recalculate children dimensions } else if (em) { var dropInfo = validResult.dropInfo || (trgModel === null || trgModel === void 0 ? void 0 : trgModel.get('droppable')); var dragInfo = validResult.dragInfo || (srcModel === null || srcModel === void 0 ? void 0 : srcModel.get('draggable')); !targetCollection && warns.push('Target collection not found'); !droppable && dropInfo && warns.push("Target is not droppable, accepts [".concat(dropInfo, "]")); !draggable && dragInfo && warns.push("Component not draggable, acceptable by [".concat(dragInfo, "]")); em.logWarning('Invalid target position', { errors: warns, model: srcModel, context: 'sorter', target: trgModel, }); } em === null || em === void 0 ? void 0 : em.trigger('sorter:drag:end', { targetCollection: targetCollection, modelToDrop: modelToDrop, warns: warns, validResult: validResult, dst: dst, srcEl: srcEl, }); return created; }; /** * Rollback to previous situation * @param {Event} * @param {Bool} Indicates if rollback in anycase * */ Sorter.prototype.rollback = function (e) { (0,dom/* off */.S1)(this.getDocuments(), 'keydown', this.rollback); var key = e.which || e.keyCode; if (key == 27) { this.moved = false; this.endMove(); } }; return Sorter; }(common/* View */.G7)); /* harmony default export */ const utils_Sorter = (Sorter); ;// CONCATENATED MODULE: ./src/utils/Resizer.ts var Resizer_assign = ( false) || function () { Resizer_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return Resizer_assign.apply(this, arguments); }; var createHandler = function (name, opts) { if (opts === void 0) { opts = {}; } var pfx = opts.prefix || ''; var el = document.createElement('i'); el.className = pfx + 'resizer-h ' + pfx + 'resizer-h-' + name; el.setAttribute('data-' + pfx + 'handler', name); return el; }; var getBoundingRect = function (el, win) { var w = win || window; var rect = el.getBoundingClientRect(); return { left: rect.left + w.pageXOffset, top: rect.top + w.pageYOffset, width: rect.width, height: rect.height, }; }; var Resizer = /** @class */ (function () { /** * Init the Resizer with options * @param {Object} options */ function Resizer(opts) { if (opts === void 0) { opts = {}; } this.defOpts = { ratioDefault: false, onUpdateContainer: function () { }, step: 1, minDim: 10, maxDim: Infinity, unitHeight: 'px', unitWidth: 'px', keyHeight: 'height', keyWidth: 'width', currentUnit: true, silentFrames: false, avoidContainerUpdate: false, keepAutoHeight: false, keepAutoWidth: false, autoHeight: false, autoWidth: false, tl: true, tc: true, tr: true, cl: true, cr: true, bl: true, bc: true, br: true, }; this.opts = Resizer_assign({}, this.defOpts); this.setOptions(opts); (0,index_all.bindAll)(this, 'handleKeyDown', 'handleMouseDown', 'move', 'stop'); } /** * Get current connfiguration options * @return {Object} */ Resizer.prototype.getConfig = function () { return this.opts; }; /** * Setup options * @param {Object} options */ Resizer.prototype.setOptions = function (options, reset) { if (options === void 0) { options = {}; } this.opts = Resizer_assign(Resizer_assign({}, (reset ? this.defOpts : this.opts)), options); this.setup(); }; /** * Setup resizer */ Resizer.prototype.setup = function () { var opts = this.opts; var pfx = opts.prefix || ''; var appendTo = opts.appendTo || document.body; var container = this.container; // Create container if not yet exist if (!container) { container = document.createElement('div'); container.className = "".concat(pfx, "resizer-c"); appendTo.appendChild(container); this.container = container; } while (container.firstChild) { container.removeChild(container.firstChild); } // Create handlers var handlers = {}; ['tl', 'tc', 'tr', 'cl', 'cr', 'bl', 'bc', 'br'].forEach( // @ts-ignore function (hdl) { return (handlers[hdl] = opts[hdl] ? createHandler(hdl, opts) : null); }); for (var n in handlers) { var handler = handlers[n]; handler && container.appendChild(handler); } this.handlers = handlers; this.mousePosFetcher = opts.mousePosFetcher; this.updateTarget = opts.updateTarget; this.posFetcher = opts.posFetcher; this.onStart = opts.onStart; this.onMove = opts.onMove; this.onEnd = opts.onEnd; this.onUpdateContainer = opts.onUpdateContainer; }; /** * Toggle iframes pointer event * @param {Boolean} silent If true, iframes will be silented */ Resizer.prototype.toggleFrames = function (silent) { if (this.opts.silentFrames) { var frames_1 = document.querySelectorAll('iframe'); (0,index_all.each)(frames_1, function (frame) { return (frame.style.pointerEvents = silent ? 'none' : ''); }); } }; /** * Detects if the passed element is a resize handler * @param {HTMLElement} el * @return {Boolean} */ Resizer.prototype.isHandler = function (el) { var handlers = this.handlers; for (var n in handlers) { if (handlers[n] === el) return true; } return false; }; /** * Returns the focused element * @return {HTMLElement} */ Resizer.prototype.getFocusedEl = function () { return this.el; }; /** * Returns the parent of the focused element * @return {HTMLElement} */ Resizer.prototype.getParentEl = function () { var _a; return (_a = this.el) === null || _a === void 0 ? void 0 : _a.parentElement; }; /** * Returns documents */ Resizer.prototype.getDocumentEl = function () { return [this.el.ownerDocument, document]; }; /** * Return element position * @param {HTMLElement} el * @param {Object} opts Custom options * @return {Object} */ Resizer.prototype.getElementPos = function (el, opts) { if (opts === void 0) { opts = {}; } var posFetcher = this.posFetcher; return posFetcher ? posFetcher(el, opts) : getBoundingRect(el); }; /** * Focus resizer on the element, attaches handlers to it * @param {HTMLElement} el */ Resizer.prototype.focus = function (el) { // Avoid focusing on already focused element if (el && el === this.el) { return; } this.el = el; this.updateContainer({ forceShow: true }); (0,dom.on)(this.getDocumentEl(), 'pointerdown', this.handleMouseDown); }; /** * Blur from element */ Resizer.prototype.blur = function () { this.container.style.display = 'none'; if (this.el) { (0,dom/* off */.S1)(this.getDocumentEl(), 'pointerdown', this.handleMouseDown); delete this.el; } }; /** * Start resizing * @param {Event} e */ Resizer.prototype.start = function (ev) { var e = ev; // @ts-ignore Right or middel click if (e.button !== 0) return; e.preventDefault(); e.stopPropagation(); var el = this.el; var parentEl = this.getParentEl(); var resizer = this; var config = this.opts || {}; var mouseFetch = this.mousePosFetcher; var attrName = 'data-' + config.prefix + 'handler'; var rect = this.getElementPos(el, { avoidFrameZoom: true, avoidFrameOffset: true }); var parentRect = this.getElementPos(parentEl); var target = e.target; this.handlerAttr = target.getAttribute(attrName); this.clickedHandler = target; this.startDim = { t: rect.top, l: rect.left, w: rect.width, h: rect.height, }; this.rectDim = { t: rect.top, l: rect.left, w: rect.width, h: rect.height, }; this.startPos = mouseFetch ? mouseFetch(e) : { x: e.clientX, y: e.clientY, }; this.parentDim = { t: parentRect.top, l: parentRect.left, w: parentRect.width, h: parentRect.height, }; // Listen events var docs = this.getDocumentEl(); this.docs = docs; (0,dom.on)(docs, 'pointermove', this.move); (0,dom.on)(docs, 'keydown', this.handleKeyDown); (0,dom.on)(docs, 'pointerup', this.stop); (0,index_all.isFunction)(this.onStart) && this.onStart(e, { docs: docs, config: config, el: el, resizer: resizer }); this.toggleFrames(true); this.move(e); }; /** * While resizing * @param {Event} e */ Resizer.prototype.move = function (ev) { var e = ev; var onMove = this.onMove; var mouseFetch = this.mousePosFetcher; var currentPos = mouseFetch ? mouseFetch(e) : { x: e.clientX, y: e.clientY, }; this.currentPos = currentPos; this.delta = { x: currentPos.x - this.startPos.x, y: currentPos.y - this.startPos.y, }; this.keys = { shift: e.shiftKey, ctrl: e.ctrlKey, alt: e.altKey, }; this.rectDim = this.calc(this); this.updateRect(false); // Move callback onMove && onMove(e); }; /** * Stop resizing * @param {Event} e */ Resizer.prototype.stop = function (e) { var el = this.el; var config = this.opts; var docs = this.docs || this.getDocumentEl(); (0,dom/* off */.S1)(docs, 'pointermove', this.move); (0,dom/* off */.S1)(docs, 'keydown', this.handleKeyDown); (0,dom/* off */.S1)(docs, 'pointerup', this.stop); this.updateRect(true); this.toggleFrames(); (0,index_all.isFunction)(this.onEnd) && this.onEnd(e, { docs: docs, config: config, el: el, resizer: this }); delete this.docs; }; /** * Update rect */ Resizer.prototype.updateRect = function (store) { var el = this.el; var resizer = this; var config = this.opts; var rect = this.rectDim; var updateTarget = this.updateTarget; var selectedHandler = this.getSelectedHandler(); var unitHeight = config.unitHeight, unitWidth = config.unitWidth, keyWidth = config.keyWidth, keyHeight = config.keyHeight; // Use custom updating strategy if requested if ((0,index_all.isFunction)(updateTarget)) { updateTarget(el, rect, { store: store, selectedHandler: selectedHandler, resizer: resizer, config: config, }); } else { var elStyle = el.style; elStyle[keyWidth] = rect.w + unitWidth; elStyle[keyHeight] = rect.h + unitHeight; elStyle.top = rect.t + unitHeight; elStyle.left = rect.l + unitWidth; } this.updateContainer(); }; Resizer.prototype.updateContainer = function (opt) { var _a; if (opt === void 0) { opt = {}; } var _b = this, opts = _b.opts, container = _b.container, el = _b.el; var style = container.style; if (!opts.avoidContainerUpdate && el) { // On component resize container fits the tool, // to check if this update is required somewhere else point // const toUpdate = ['left', 'top', 'width', 'height']; // const rectEl = this.getElementPos(el, { target: 'container' }); // toUpdate.forEach(pos => (style[pos] = `${rectEl[pos]}px`)); if (opt.forceShow) style.display = 'block'; } (_a = this.onUpdateContainer) === null || _a === void 0 ? void 0 : _a.call(this, { el: container, resizer: this, opts: Resizer_assign(Resizer_assign({}, opts), opt), }); }; /** * Get selected handler name * @return {string} */ Resizer.prototype.getSelectedHandler = function () { var handlers = this.handlers; if (!this.selectedHandler) { return; } for (var n in handlers) { if (handlers[n] === this.selectedHandler) return n; } }; /** * Handle ESC key * @param {Event} e */ Resizer.prototype.handleKeyDown = function (e) { // @ts-ignore if (e.keyCode === 27) { // Rollback to initial dimensions this.rectDim = this.startDim; this.stop(e); } }; /** * Handle mousedown to check if it's possible to start resizing * @param {Event} e */ Resizer.prototype.handleMouseDown = function (e) { var el = e.target; if (this.isHandler(el)) { this.selectedHandler = el; this.start(e); } else if (el !== this.el) { delete this.selectedHandler; this.blur(); } }; /** * All positioning logic * @return {Object} */ Resizer.prototype.calc = function (data) { var value; var opts = this.opts || {}; var step = opts.step; var startDim = this.startDim; var minDim = opts.minDim; var maxDim = opts.maxDim; var deltaX = data.delta.x; var deltaY = data.delta.y; var parentW = this.parentDim.w; var parentH = this.parentDim.h; var unitWidth = this.opts.unitWidth; var unitHeight = this.opts.unitHeight; var startW = unitWidth === '%' ? (startDim.w / 100) * parentW : startDim.w; var startH = unitHeight === '%' ? (startDim.h / 100) * parentH : startDim.h; var box = { t: startDim.t, l: startDim.l, w: startW, h: startH, }; if (!data) return; var attr = data.handlerAttr; if (~attr.indexOf('r')) { value = unitWidth === '%' ? (0,mixins.normalizeFloat)(((startW + deltaX * step) / parentW) * 100, 0.01) : (0,mixins.normalizeFloat)(startW + deltaX * step, step); value = Math.max(minDim, value); maxDim && (value = Math.min(maxDim, value)); box.w = value; } if (~attr.indexOf('b')) { value = unitHeight === '%' ? (0,mixins.normalizeFloat)(((startH + deltaY * step) / parentH) * 100, 0.01) : (0,mixins.normalizeFloat)(startH + deltaY * step, step); value = Math.max(minDim, value); maxDim && (value = Math.min(maxDim, value)); box.h = value; } if (~attr.indexOf('l')) { value = unitWidth === '%' ? (0,mixins.normalizeFloat)(((startW - deltaX * step) / parentW) * 100, 0.01) : (0,mixins.normalizeFloat)(startW - deltaX * step, step); value = Math.max(minDim, value); maxDim && (value = Math.min(maxDim, value)); box.w = value; } if (~attr.indexOf('t')) { value = unitHeight === '%' ? (0,mixins.normalizeFloat)(((startH - deltaY * step) / parentH) * 100, 0.01) : (0,mixins.normalizeFloat)(startH - deltaY * step, step); value = Math.max(minDim, value); maxDim && (value = Math.min(maxDim, value)); box.h = value; } // Enforce aspect ratio (unless shift key is being held) var ratioActive = opts.ratioDefault ? !data.keys.shift : data.keys.shift; if (attr.indexOf('c') < 0 && ratioActive) { var ratio = startDim.w / startDim.h; if (box.w / box.h > ratio) { box.h = Math.round(box.w / ratio); } else { box.w = Math.round(box.h * ratio); } } if (~attr.indexOf('l')) { box.l += startDim.w - box.w; } if (~attr.indexOf('t')) { box.t += startDim.h - box.h; } for (var key in box) { var i = key; box[i] = parseInt("".concat(box[i]), 10); } return box; }; return Resizer; }()); /* harmony default export */ const utils_Resizer = (Resizer); ;// CONCATENATED MODULE: ./src/utils/index.ts var utils_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var utils_assign = ( false) || function () { utils_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return utils_assign.apply(this, arguments); }; var UtilsModule = /** @class */ (function (_super) { utils_extends(UtilsModule, _super); function UtilsModule(em) { var _this = _super.call(this, em, 'Utils') || this; _this.Sorter = utils_Sorter; _this.Resizer = utils_Resizer; _this.Dragger = Dragger/* default */.Z; _this.helpers = utils_assign({}, mixins); return _this; } UtilsModule.prototype.destroy = function () { }; return UtilsModule; }(abstract_Module)); /* harmony default export */ const utils = (UtilsModule); ;// CONCATENATED MODULE: ./src/utils/keymaster.ts // @ts-nocheck // The initial version of this library was borrowed from https://github.com/madrobby/keymaster // and adapted to the GrapesJS's need var k, _handlers = {}, _mods = { 16: false, 18: false, 17: false, 91: false, }, _scope = 'all', // modifier keys _MODIFIERS = { '⇧': 16, shift: 16, '⌥': 18, alt: 18, option: 18, '⌃': 17, ctrl: 17, control: 17, '⌘': 91, command: 91, }, // special keys _MAP = { backspace: 8, tab: 9, clear: 12, enter: 13, return: 13, esc: 27, escape: 27, space: 32, left: 37, up: 38, right: 39, down: 40, del: 46, delete: 46, home: 36, end: 35, pageup: 33, pagedown: 34, ',': 188, '.': 190, '/': 191, '`': 192, '-': 189, '=': 187, ';': 186, "'": 222, '[': 219, ']': 221, '\\': 220, }, code = function (x) { return _MAP[x] || x.toUpperCase().charCodeAt(0); }, _downKeys = []; for (k = 1; k < 20; k++) _MAP['f' + k] = 111 + k; // IE doesn't support Array#indexOf, so have a simple replacement function index(array, item) { var i = array.length; while (i--) if (array[i] === item) return i; return -1; } // for comparing mods before unassignment function compareArray(a1, a2) { if (a1.length != a2.length) return false; for (var i = 0; i < a1.length; i++) { if (a1[i] !== a2[i]) return false; } return true; } var modifierMap = { 16: 'shiftKey', 18: 'altKey', 17: 'ctrlKey', 91: 'metaKey', }; function updateModifierKey(event) { for (k in _mods) _mods[k] = event[modifierMap[k]]; } // handle keydown event function dispatch(event) { var key, handler, k, i, modifiersMatch, scope; key = event.keyCode; if (index(_downKeys, key) == -1) { _downKeys.push(key); } // if a modifier key, set the key.<modifierkeyname> property to true and return if (key == 93 || key == 224) key = 91; // right command on webkit, command on Gecko if (key in _mods) { _mods[key] = true; // 'assignKey' from inside this closure is exported to window.key for (k in _MODIFIERS) if (_MODIFIERS[k] == key) assignKey[k] = true; return; } updateModifierKey(event); // see if we need to ignore the keypress (filter() can can be overridden) // by default ignore key presses if a select, textarea, or input is focused if (!assignKey.filter.call(this, event)) return; // abort if no potentially matching shortcuts found if (!(key in _handlers)) return; scope = getScope(); // for each potential shortcut for (i = 0; i < _handlers[key].length; i++) { handler = _handlers[key][i]; // see if it's in the current scope if (handler.scope == scope || handler.scope == 'all') { // check if modifiers match if any modifiersMatch = handler.mods.length > 0; for (k in _mods) if ((!_mods[k] && index(handler.mods, +k) > -1) || (_mods[k] && index(handler.mods, +k) == -1)) modifiersMatch = false; // call the handler and stop the event if neccessary if ((handler.mods.length == 0 && !_mods[16] && !_mods[18] && !_mods[17] && !_mods[91]) || modifiersMatch) { if (handler.method(event, handler) === false) { if (event.preventDefault) event.preventDefault(); else event.returnValue = false; if (event.stopPropagation) event.stopPropagation(); if (event.cancelBubble) event.cancelBubble = true; } } } } } // unset modifier keys on keyup function clearModifier(event) { var key = event.keyCode, k, i = index(_downKeys, key); // remove key from _downKeys if (i >= 0) { _downKeys.splice(i, 1); } if (key == 93 || key == 224) key = 91; if (key in _mods) { _mods[key] = false; for (k in _MODIFIERS) if (_MODIFIERS[k] == key) assignKey[k] = false; } } function resetModifiers() { for (k in _mods) _mods[k] = false; for (k in _MODIFIERS) assignKey[k] = false; } // parse and assign shortcut function assignKey(key, scope, method) { var keys, mods; keys = getKeys(key); if (method === undefined) { method = scope; scope = 'all'; } // for each shortcut for (var i = 0; i < keys.length; i++) { // set modifier keys if any mods = []; key = keys[i].split('+'); if (key.length > 1) { mods = getMods(key); key = [key[key.length - 1]]; } // convert to keycode and... key = key[0]; key = code(key); // ...store handler if (!(key in _handlers)) _handlers[key] = []; _handlers[key].push({ shortcut: keys[i], scope: scope, method: method, key: keys[i], mods: mods, }); } } // unbind all handlers for given key in current scope function unbindKey(key, scope) { var multipleKeys, keys, mods = [], i, j, obj; multipleKeys = getKeys(key); for (j = 0; j < multipleKeys.length; j++) { keys = multipleKeys[j].split('+'); if (keys.length > 1) { mods = getMods(keys); } key = keys[keys.length - 1]; key = code(key); if (scope === undefined) { scope = getScope(); } if (!_handlers[key]) { return; } for (i = 0; i < _handlers[key].length; i++) { obj = _handlers[key][i]; // only clear handlers if correct scope and mods match if (obj.scope === scope && compareArray(obj.mods, mods)) { _handlers[key][i] = {}; } } } } // Returns true if the key with code 'keyCode' is currently down // Converts strings into key codes. function isPressed(keyCode) { if (typeof keyCode == 'string') { keyCode = code(keyCode); } return index(_downKeys, keyCode) != -1; } function getPressedKeyCodes() { return _downKeys.slice(0); } function filter(event) { var tagName = (event.target || event.srcElement).tagName; // ignore keypressed in any elements that support keyboard data input return !(tagName == 'INPUT' || tagName == 'SELECT' || tagName == 'TEXTAREA'); } // initialize key.<modifier> to false for (k in _MODIFIERS) assignKey[k] = false; // set current scope (default 'all') function setScope(scope) { _scope = scope || 'all'; } function getScope() { return _scope || 'all'; } // delete all handlers for a given scope function deleteScope(scope) { var key, handlers, i; for (key in _handlers) { handlers = _handlers[key]; for (i = 0; i < handlers.length;) { if (handlers[i].scope === scope) handlers.splice(i, 1); else i++; } } } // abstract key logic for assign and unassign function getKeys(key) { var keys; key = key.replace(/\s/g, ''); keys = key.split(','); if (keys[keys.length - 1] == '') { keys[keys.length - 2] += ','; } return keys; } // abstract mods logic for assign and unassign function getMods(key) { var mods = key.slice(0, key.length - 1); for (var mi = 0; mi < mods.length; mi++) mods[mi] = _MODIFIERS[mods[mi]]; return mods; } // cross-browser events function addEvent(object, event, method) { if (object.addEventListener) object.addEventListener(event, method, false); else if (object.attachEvent) object.attachEvent('on' + event, function () { method(window.event); }); } // set window.key and window.key.set/get/deleteScope, and the default filter assignKey.setScope = setScope; assignKey.getScope = getScope; assignKey.deleteScope = deleteScope; assignKey.filter = filter; assignKey.isPressed = isPressed; assignKey.getPressedKeyCodes = getPressedKeyCodes; assignKey.unbind = unbindKey; assignKey.handlers = _handlers; assignKey.init = function (win) { // set the handlers globally on document // Passing _scope to a callback to ensure it remains the same by execution. Fixes #48 addEvent(win.document, 'keydown', function (event) { dispatch(event); }); addEvent(win.document, 'keyup', clearModifier); addEvent(win, 'focus', resetModifiers); }; /* harmony default export */ const keymaster = (assignKey); ;// CONCATENATED MODULE: ./src/keymaps/config.ts var keymaps_config_config = { defaults: { 'core:undo': { keys: '⌘+z, ctrl+z', handler: 'core:undo', opts: { prevent: true }, }, 'core:redo': { keys: '⌘+shift+z, ctrl+shift+z', handler: 'core:redo', opts: { prevent: true }, }, 'core:copy': { keys: '⌘+c, ctrl+c', handler: 'core:copy', }, 'core:paste': { keys: '⌘+v, ctrl+v', handler: 'core:paste', }, 'core:component-next': { keys: 's', handler: 'core:component-next', }, 'core:component-prev': { keys: 'w', handler: 'core:component-prev', }, 'core:component-enter': { keys: 'd', handler: 'core:component-enter', }, 'core:component-exit': { keys: 'a', handler: 'core:component-exit', }, 'core:component-delete': { keys: 'backspace, delete', handler: 'core:component-delete', opts: { prevent: true }, }, }, }; /* harmony default export */ const keymaps_config = (keymaps_config_config); ;// CONCATENATED MODULE: ./src/keymaps/index.ts /** * You can customize the initial state of the module from the editor initialization * ```js * const editor = grapesjs.init({ * keymaps: { * // Object of keymaps * defaults: { * 'your-namespace:keymap-name' { * keys: '⌘+z, ctrl+z', * handler: 'some-command-id' * }, * ... * } * } * }) * ``` * * Once the editor is instantiated you can use its API and listen to its events. Before using these methods, you should get the module from the instance. * * ```js * // Listen to events * editor.on('keymap:add', () => { ... }); * * // Use the API * const keymaps = editor.Keymaps; * keymaps.add(...); * ``` * * ## Available Events * * `keymap:add` - New keymap added. The new keyamp object is passed as an argument * * `keymap:remove` - Keymap removed. The removed keyamp object is passed as an argument * * `keymap:emit` - Some keymap emitted, in arguments you get keymapId, shortcutUsed, Event * * `keymap:emit:{keymapId}` - `keymapId` emitted, in arguments you get keymapId, shortcutUsed, Event * * ## Methods * * [getConfig](#getconfig) * * [add](#add) * * [get](#get) * * [getAll](#getAll) * * [remove](#remove) * * [removeAll](#removeall) * * @module Keymaps */ var keymaps_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var keymaps_spreadArray = ( false) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; (0,mixins.hasWin)() && keymaster.init(window); var KeymapsModule = /** @class */ (function (_super) { keymaps_extends(KeymapsModule, _super); function KeymapsModule(em) { var _this = _super.call(this, em, 'Keymaps', keymaps_config) || this; _this.keymaster = keymaster; _this.keymaps = {}; return _this; } KeymapsModule.prototype.onLoad = function () { var defKeys = this.config.defaults; for (var id in defKeys) { var value = defKeys[id]; this.add(id, value.keys, value.handler, value.opts || {}); } }; /** * Get configuration object * @name getConfig * @function * @return {Object} */ /** * Add new keymap * @param {string} id Keymap id * @param {string} keys Keymap keys, eg. `ctrl+a`, `⌘+z, ctrl+z` * @param {Function|string} handler Keymap handler, might be a function * @param {Object} [opts={}] Options * @param {Boolean} [opts.force=false] Force the handler to be executed. * @param {Boolean} [opts.prevent=false] Prevent default of the original triggered event. * @returns {Object} Added keymap * @example * // 'ns' is just a custom namespace * keymaps.add('ns:my-keymap', '⌘+j, ⌘+u, ctrl+j, alt+u', editor => { * console.log('do stuff'); * }); * // or * keymaps.add('ns:my-keymap', '⌘+s, ctrl+s', 'some-gjs-command', { * // Prevent the default browser action * prevent: true, * }); * * // listen to events * editor.on('keymap:emit', (id, shortcut, event) => { * // ... * }) */ KeymapsModule.prototype.add = function (id, keys, handler, opts) { if (opts === void 0) { opts = {}; } var em = this.em; var cmd = em.Commands; var editor = em.getEditor(); var canvas = em.Canvas; var keymap = { id: id, keys: keys, handler: handler }; var pk = this.keymaps[id]; pk && this.remove(id); this.keymaps[id] = keymap; keymaster(keys, function (e, h) { // It's safer putting handlers resolution inside the callback var opt = { event: e, h: h }; var handlerRes = (0,index_all.isString)(handler) ? cmd.get(handler) : handler; var ableTorun = !em.isEditing() && !editor.Canvas.isInputFocused(); if (ableTorun || opts.force) { opts.prevent && canvas.getCanvasView().preventDefault(e); (0,index_all.isFunction)(handlerRes) ? handlerRes(editor, 0, opt) : cmd.runCommand(handlerRes, opt); var args = [id, h.shortcut, e]; em.trigger.apply(em, keymaps_spreadArray(['keymap:emit'], args, false)); em.trigger.apply(em, keymaps_spreadArray(["keymap:emit:".concat(id)], args, false)); } }, undefined); em.trigger('keymap:add', keymap); return keymap; }; /** * Get the keymap by id * @param {string} id Keymap id * @return {Object} Keymap object * @example * keymaps.get('ns:my-keymap'); * // -> {keys, handler}; */ KeymapsModule.prototype.get = function (id) { return this.keymaps[id]; }; /** * Get all keymaps * @return {Object} * @example * keymaps.getAll(); * // -> {id1: {}, id2: {}}; */ KeymapsModule.prototype.getAll = function () { return this.keymaps; }; /** * Remove the keymap by id * @param {string} id Keymap id * @return {Object} Removed keymap * @example * keymaps.remove('ns:my-keymap'); * // -> {keys, handler}; */ KeymapsModule.prototype.remove = function (id) { var em = this.em; var keymap = this.get(id); if (keymap) { delete this.keymaps[id]; keymap.keys.split(', ').forEach(function (k) { // @ts-ignore keymaster.unbind(k.trim()); }); em === null || em === void 0 ? void 0 : em.trigger('keymap:remove', keymap); return keymap; } }; /** * Remove all binded keymaps * @return {this} */ KeymapsModule.prototype.removeAll = function () { var _this = this; Object.keys(this.keymaps).forEach(function (keymap) { return _this.remove(keymap); }); keymaster.handlers = {}; return this; }; KeymapsModule.prototype.destroy = function () { this.removeAll(); this.keymaps = {}; }; return KeymapsModule; }(abstract_Module)); /* harmony default export */ const keymaps = (KeymapsModule); ;// CONCATENATED MODULE: ./src/modal_dialog/config/config.ts var modal_dialog_config_config_config = { stylePrefix: 'mdl-', title: '', content: '', backdrop: true, custom: false, extend: {}, }; /* harmony default export */ const modal_dialog_config_config = (modal_dialog_config_config_config); ;// CONCATENATED MODULE: ./src/modal_dialog/model/Modal.ts var Modal_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var Modal = /** @class */ (function (_super) { Modal_extends(Modal, _super); function Modal() { return _super !== null && _super.apply(this, arguments) || this; } Modal.prototype.defaults = function () { return { title: '', content: '', attributes: {}, open: false, }; }; Modal.prototype.open = function () { this.set('open', true); }; Modal.prototype.close = function () { this.set('open', false); }; return Modal; }(ModuleModel/* default */.Z)); /* harmony default export */ const model_Modal = (Modal); ;// CONCATENATED MODULE: ./src/modal_dialog/view/ModalView.ts var ModalView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ModalView_assign = ( false) || function () { ModalView_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return ModalView_assign.apply(this, arguments); }; var ModalView = /** @class */ (function (_super) { ModalView_extends(ModalView, _super); function ModalView(o) { var _this = _super.call(this, o) || this; var model = _this.model; _this.listenTo(model, 'change:open', _this.updateOpen); _this.listenTo(model, 'change:title', _this.updateTitle); _this.listenTo(model, 'change:content', _this.updateContent); return _this; } ModalView.prototype.template = function (_a) { var pfx = _a.pfx, ppfx = _a.ppfx, content = _a.content, title = _a.title; return "<div class=\"".concat(pfx, "dialog ").concat(ppfx, "one-bg ").concat(ppfx, "two-color\">\n <div class=\"").concat(pfx, "header\">\n <div class=\"").concat(pfx, "title\">").concat(title, "</div>\n <div class=\"").concat(pfx, "btn-close\" data-close-modal>⨯</div>\n </div>\n <div class=\"").concat(pfx, "content\">\n <div id=\"").concat(pfx, "c\">").concat(content, "</div>\n <div style=\"clear:both\"></div>\n </div>\n </div>\n <div class=\"").concat(pfx, "collector\" style=\"display: none\"></div>"); }; ModalView.prototype.events = function () { return { click: 'onClick', 'click [data-close-modal]': 'hide', }; }; ModalView.prototype.onClick = function (e) { var bkd = this.config.backdrop; bkd && e.target === this.el && this.hide(); }; /** * Returns collector element * @return {HTMLElement} * @private */ ModalView.prototype.getCollector = function () { if (!this.$collector) this.$collector = this.$el.find('.' + this.pfx + 'collector'); return this.$collector; }; /** * Returns content element * @return {HTMLElement} */ ModalView.prototype.getContent = function () { var pfx = this.pfx; if (!this.$content) { this.$content = this.$el.find(".".concat(pfx, "content #").concat(pfx, "c")); } return this.$content; }; /** * Returns title element * @return {HTMLElement} * @private */ ModalView.prototype.getTitle = function (opts) { if (opts === void 0) { opts = {}; } if (!this.$title) this.$title = this.$el.find('.' + this.pfx + 'title'); return opts.$ ? this.$title : this.$title.get(0); }; /** * Update content * @private * */ ModalView.prototype.updateContent = function () { var content = this.getContent(); var children = content.children(); var coll = this.getCollector(); var body = this.model.get('content'); children.length && coll.append(children); content.empty().append(body); }; /** * Update title * @private * */ ModalView.prototype.updateTitle = function () { var title = this.getTitle({ $: true }); //@ts-ignore title && title.empty().append(this.model.get('title')); }; /** * Update open * @private * */ ModalView.prototype.updateOpen = function () { this.el.style.display = this.model.get('open') ? '' : 'none'; }; /** * Hide modal * @private * */ ModalView.prototype.hide = function () { this.model.close(); }; /** * Show modal * @private * */ ModalView.prototype.show = function () { this.model.open(); }; ModalView.prototype.updateAttr = function (attr) { var _a = this, pfx = _a.pfx, $el = _a.$el, el = _a.el; //@ts-ignore var currAttr = [].slice.call(el.attributes).map(function (i) { return i.name; }); $el.removeAttr(currAttr.join(' ')); $el.attr(ModalView_assign(ModalView_assign({}, (attr || {})), { class: "".concat(pfx, "container ").concat((attr && attr.class) || '').trim() })); }; ModalView.prototype.render = function () { var el = this.$el; var obj = this.model.toJSON(); obj.pfx = this.pfx; obj.ppfx = this.ppfx; el.html(this.template(obj)); this.updateAttr(); this.updateOpen(); return this; }; return ModalView; }(abstract_ModuleView)); /* harmony default export */ const view_ModalView = (ModalView); ;// CONCATENATED MODULE: ./src/modal_dialog/index.ts /** * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/GrapesJS/grapesjs/blob/master/src/modal_dialog/config/config.ts) * ```js * const editor = grapesjs.init({ * modal: { * // options * } * }) * ``` * * Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance * * ```js * const modal = editor.Modal; * ``` * * ## Available Events * * `modal:open` - Modal is opened * * `modal:close` - Modal is closed * * `modal` - Event triggered on any change related to the modal. An object containing all the available data about the triggered event is passed as an argument to the callback. * * ## Methods * * [open](#open) * * [close](#close) * * [isOpen](#isopen) * * [setTitle](#settitle) * * [getTitle](#gettitle) * * [setContent](#setcontent) * * [getContent](#getcontent) * * [onceClose](#onceclose) * * [onceOpen](#onceopen) * * @module Modal */ var modal_dialog_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ModalModule = /** @class */ (function (_super) { modal_dialog_extends(ModalModule, _super); /** * Initialize module. Automatically called with a new instance of the editor * @param {Object} config Configurations * @private */ function ModalModule(em) { var _this = _super.call(this, em, 'Modal', modal_dialog_config_config) || this; _this.model = new model_Modal(_this); _this.model.on('change:open', function (m, enable) { em.trigger("modal:".concat(enable ? 'open' : 'close')); }); _this.model.on('change', (0,index_all.debounce)(function () { var data = _this._evData(); var custom = _this.config.custom; //@ts-ignore (0,index_all.isFunction)(custom) && custom(data); em.trigger('modal', data); }, 0)); return _this; } ModalModule.prototype._evData = function () { var _this = this; var titl = this.getTitle(); var cnt = this.getContent(); var _a = this.model.attributes, open = _a.open, attributes = _a.attributes; return { open: open, attributes: attributes, title: (0,index_all.isString)(titl) ? (0,dom/* createText */.rw)(titl) : titl, //@ts-ignore content: (0,index_all.isString)(cnt) ? (0,dom/* createText */.rw)(cnt) : cnt.get ? cnt.get(0) : cnt, close: function () { _this.close(); }, }; }; ModalModule.prototype.postRender = function (view) { var el = view.model.config.el || view.el; var res = this.render(); res && (el === null || el === void 0 ? void 0 : el.appendChild(res)); }; /** * Open the modal window * @param {Object} [opts={}] Options * @param {String|HTMLElement} [opts.title] Title to set for the modal * @param {String|HTMLElement} [opts.content] Content to set for the modal * @param {Object} [opts.attributes] Updates the modal wrapper with custom attributes * @returns {this} * @example * modal.open({ * title: 'My title', * content: 'My content', * attributes: { class: 'my-class' }, * }); */ ModalModule.prototype.open = function (opts) { if (opts === void 0) { opts = {}; } var attr = opts.attributes || {}; opts.title && this.setTitle(opts.title); opts.content && this.setContent(opts.content); this.model.set('attributes', attr); this.model.open(); this.modal && this.modal.updateAttr(attr); return this; }; /** * Close the modal window * @returns {this} * @example * modal.close(); */ ModalModule.prototype.close = function () { this.model.close(); return this; }; /** * Execute callback when the modal will be closed. * The callback will be called one only time * @param {Function} clb Callback to call * @returns {this} * @example * modal.onceClose(() => { * console.log('The modal is closed'); * }); */ ModalModule.prototype.onceClose = function (clb) { this.em.once('modal:close', clb); return this; }; /** * Execute callback when the modal will be opened. * The callback will be called one only time * @param {Function} clb Callback to call * @returns {this} * @example * modal.onceOpen(() => { * console.log('The modal is opened'); * }); */ ModalModule.prototype.onceOpen = function (clb) { this.em.once('modal:open', clb); return this; }; /** * Checks if the modal window is open * @returns {Boolean} * @example * modal.isOpen(); // true | false */ ModalModule.prototype.isOpen = function () { return !!this.model.get('open'); }; /** * Set the title to the modal window * @param {string | HTMLElement} title Title * @returns {this} * @example * // pass a string * modal.setTitle('Some title'); * // or an HTMLElement * const el = document.createElement('div'); * el.innerText = 'New title'; * modal.setTitle(el); */ ModalModule.prototype.setTitle = function (title) { this.model.set('title', title); return this; }; /** * Returns the title of the modal window * @returns {string | HTMLElement} * @example * modal.getTitle(); */ ModalModule.prototype.getTitle = function () { return this.model.get('title'); }; /** * Set the content of the modal window * @param {string | HTMLElement} content Content * @returns {this} * @example * // pass a string * modal.setContent('Some content'); * // or an HTMLElement * const el = document.createElement('div'); * el.innerText = 'New content'; * modal.setContent(el); */ ModalModule.prototype.setContent = function (content) { this.model.set('content', ' '); this.model.set('content', content); return this; }; /** * Get the content of the modal window * @returns {string | HTMLElement} * @example * modal.getContent(); */ ModalModule.prototype.getContent = function () { return this.model.get('content'); }; /** * Returns content element * @return {HTMLElement} * @private */ ModalModule.prototype.getContentEl = function () { var _a; return (_a = this.modal) === null || _a === void 0 ? void 0 : _a.getContent().get(0); }; /** * Returns modal model * @return {Model} * @private */ ModalModule.prototype.getModel = function () { return this.model; }; /** * Render the modal window * @return {HTMLElement} * @private */ ModalModule.prototype.render = function () { var _a; if (this.config.custom) return; var View = view_ModalView.extend(this.config.extend); var el = this.modal && this.modal.el; this.modal = new View({ el: el, model: this.model, config: this.config, }); return (_a = this.modal) === null || _a === void 0 ? void 0 : _a.render().el; }; ModalModule.prototype.destroy = function () { var _a; (_a = this.modal) === null || _a === void 0 ? void 0 : _a.remove(); }; return ModalModule; }(abstract_Module)); /* harmony default export */ const modal_dialog = (ModalModule); ;// CONCATENATED MODULE: ./src/panels/config/config.ts var swv = 'sw-visibility'; var expt = 'export-template'; var osm = 'open-sm'; var otm = 'open-tm'; var ola = 'open-layers'; var obl = 'open-blocks'; var ful = 'fullscreen'; var prv = 'preview'; var panels_config_config_config = { stylePrefix: 'pn-', defaults: [ { id: 'commands', buttons: [{}], }, { id: 'options', buttons: [ { active: true, id: swv, className: 'fa fa-square-o', command: 'core:component-outline', context: swv, attributes: { title: 'View components' }, }, { id: prv, className: 'fa fa-eye', command: prv, context: prv, attributes: { title: 'Preview' }, }, { id: ful, className: 'fa fa-arrows-alt', command: ful, context: ful, attributes: { title: 'Fullscreen' }, }, { id: expt, className: 'fa fa-code', command: expt, attributes: { title: 'View code' }, }, ], }, { id: 'views', buttons: [ { id: osm, className: 'fa fa-paint-brush', command: osm, active: true, togglable: false, attributes: { title: 'Open Style Manager' }, }, { id: otm, className: 'fa fa-cog', command: otm, togglable: false, attributes: { title: 'Settings' }, }, { id: ola, className: 'fa fa-bars', command: ola, togglable: false, attributes: { title: 'Open Layer Manager' }, }, { id: obl, className: 'fa fa-th-large', command: obl, togglable: false, attributes: { title: 'Open Blocks' }, }, ], }, ], }; /* harmony default export */ const panels_config_config = (panels_config_config_config); ;// CONCATENATED MODULE: ./src/panels/model/Button.ts var Button_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var Button = /** @class */ (function (_super) { Button_extends(Button, _super); function Button(module, options) { var _this = _super.call(this, module, options) || this; if (_this.get('buttons').length) { _this.set('buttons', new model_Buttons(_this.module, _this.get('buttons'))); } return _this; } Button.prototype.defaults = function () { return { id: '', label: '', tagName: 'span', className: '', command: '', context: '', buttons: [], attributes: {}, options: {}, active: false, dragDrop: false, togglable: true, runDefaultCommand: true, stopDefaultCommand: false, disable: false, }; }; Object.defineProperty(Button.prototype, "className", { get: function () { return this.get('className'); }, enumerable: false, configurable: true }); Object.defineProperty(Button.prototype, "command", { get: function () { return this.get('command'); }, enumerable: false, configurable: true }); Object.defineProperty(Button.prototype, "active", { get: function () { return this.get('active'); }, set: function (isActive) { this.set('active', isActive); }, enumerable: false, configurable: true }); Object.defineProperty(Button.prototype, "togglable", { get: function () { return this.get('togglable'); }, enumerable: false, configurable: true }); Object.defineProperty(Button.prototype, "runDefaultCommand", { get: function () { return this.get('runDefaultCommand'); }, enumerable: false, configurable: true }); Object.defineProperty(Button.prototype, "stopDefaultCommand", { get: function () { return this.get('stopDefaultCommand'); }, enumerable: false, configurable: true }); Object.defineProperty(Button.prototype, "disable", { get: function () { return this.get('disable'); }, enumerable: false, configurable: true }); return Button; }(ModuleModel/* default */.Z)); /* harmony default export */ const model_Button = (Button); ;// CONCATENATED MODULE: ./src/panels/model/Buttons.ts var Buttons_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var Buttons = /** @class */ (function (_super) { Buttons_extends(Buttons, _super); function Buttons(module, models) { return _super.call(this, module, models, model_Button) || this; } /** * Deactivate all buttons, except one passed * @param {Object} except Model to ignore * @param {Boolean} r Recursive flag * * @return void * */ Buttons.prototype.deactivateAllExceptOne = function (except, r) { this.forEach(function (model, index) { if (model !== except) { model.set('active', false); if (r && model.get('buttons').length) model.get('buttons').deactivateAllExceptOne(except, r); } }); }; /** * Deactivate all buttons * @param {String} ctx Context string * * @return void * */ Buttons.prototype.deactivateAll = function (ctx, sender) { var context = ctx || ''; this.forEach(function (model) { if (model.get('context') == context && model !== sender) { //@ts-ignore model.set('active', false, { fromCollection: true }); } }); }; /** * Disables all buttons * @param {String} ctx Context string * * @return void * */ Buttons.prototype.disableAllButtons = function (ctx) { var context = ctx || ''; this.forEach(function (model, index) { if (model.get('context') == context) { model.set('disable', true); } }); }; /** * Disables all buttons, except one passed * @param {Object} except Model to ignore * @param {Boolean} r Recursive flag * * @return void * */ Buttons.prototype.disableAllButtonsExceptOne = function (except, r) { this.forEach(function (model, index) { if (model !== except) { model.set('disable', true); if (r && model.get('buttons').length) model.get('buttons').disableAllButtonsExceptOne(except, r); } }); }; return Buttons; }(abstract_ModuleCollection)); /* harmony default export */ const model_Buttons = (Buttons); Buttons.prototype.model = model_Button; ;// CONCATENATED MODULE: ./src/panels/model/Panel.ts var Panel_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var Panel = /** @class */ (function (_super) { Panel_extends(Panel, _super); function Panel(module, options) { var _this = _super.call(this, module, options) || this; var btn = _this.get('buttons') || []; _this.buttons = new model_Buttons(module, btn); return _this; } Panel.prototype.defaults = function () { return { id: '', content: '', visible: true, buttons: [], attributes: {}, }; }; Object.defineProperty(Panel.prototype, "buttons", { get: function () { return this.get('buttons'); }, set: function (buttons) { this.set('buttons', buttons); }, enumerable: false, configurable: true }); return Panel; }(ModuleModel/* default */.Z)); /* harmony default export */ const model_Panel = (Panel); ;// CONCATENATED MODULE: ./src/panels/model/Panels.ts var Panels_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var Panels = /** @class */ (function (_super) { Panels_extends(Panels, _super); function Panels(module, models) { return _super.call(this, module, models, model_Panel) || this; } return Panels; }(abstract_ModuleCollection)); /* harmony default export */ const model_Panels = (Panels); Panels.prototype.model = model_Panel; ;// CONCATENATED MODULE: ./src/panels/view/ButtonView.ts var ButtonView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ButtonView_assign = ( false) || function () { ButtonView_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return ButtonView_assign.apply(this, arguments); }; var ButtonView = /** @class */ (function (_super) { ButtonView_extends(ButtonView, _super); function ButtonView(o) { var _this = _super.call(this, o) || this; var _a = _this, model = _a.model, em = _a.em, pfx = _a.pfx, ppfx = _a.ppfx; var cls = model.className; var _b = model.attributes, command = _b.command, listen = _b.listen; _this.id = pfx + model.get('id'); _this.activeCls = "".concat(pfx, "active ").concat(ppfx, "four-color"); _this.disableCls = "".concat(ppfx, "disabled"); _this.btnsVisCls = "".concat(pfx, "visible"); _this.className = pfx + 'btn' + (cls ? ' ' + cls : ''); _this.listenTo(model, 'change', _this.render); _this.listenTo(model, 'change:active updateActive', _this.updateActive); _this.listenTo(model, 'checkActive', _this.checkActive); _this.listenTo(model, 'change:bntsVis', _this.updateBtnsVis); _this.listenTo(model, 'change:attributes', _this.updateAttributes); _this.listenTo(model, 'change:className', _this.updateClassName); _this.listenTo(model, 'change:disable', _this.updateDisable); if (em && (0,index_all.isString)(command) && listen) { var chnOpt_1 = { fromListen: true }; _this.listenTo(em, "run:".concat(command), function () { return model.set('active', true, chnOpt_1); }); _this.listenTo(em, "stop:".concat(command), function () { return model.set('active', false, chnOpt_1); }); } if (em && em.get) _this.commands = em.get('Commands'); return _this; } //@ts-ignore ButtonView.prototype.tagName = function () { return this.model.get('tagName'); }; ButtonView.prototype.events = function () { return { click: 'clicked', }; }; /** * Updates class name of the button * * @return void * */ ButtonView.prototype.updateClassName = function () { var _a = this, model = _a.model, pfx = _a.pfx; var cls = model.className; var attrCls = model.get('attributes').class; var classStr = "".concat(attrCls ? attrCls : '', " ").concat(pfx, "btn ").concat(cls ? cls : ''); this.$el.attr('class', classStr.trim()); }; /** * Updates attributes of the button * * @return void * */ ButtonView.prototype.updateAttributes = function () { var _a = this, em = _a.em, model = _a.model, $el = _a.$el; var attr = model.get('attributes') || {}; var title = em && em.t && em.t("panels.buttons.titles.".concat(model.id)); $el.attr(attr); title && $el.attr({ title: title }); this.updateClassName(); }; /** * Updates visibility of children buttons * * @return void * */ ButtonView.prototype.updateBtnsVis = function () { if (!this.$buttons) return; if (this.model.get('bntsVis')) this.$buttons.addClass(this.btnsVisCls); else this.$buttons.removeClass(this.btnsVisCls); }; /** * Update active status of the button * * @return void * */ ButtonView.prototype.updateActive = function (m, v, opts) { var _a; if (opts === void 0) { opts = {}; } var _b = this, model = _b.model, commands = _b.commands, $el = _b.$el, activeCls = _b.activeCls; var fromCollection = opts.fromCollection, fromListen = opts.fromListen; var context = model.get('context'); var options = model.get('options'); var commandName = model.command; var command = {}; if (!commandName) return; if (commands && (0,index_all.isString)(commandName)) { command = commands.get(commandName) || {}; } else if ((0,index_all.isFunction)(commandName)) { command = commands.create({ run: commandName }); } else if (commandName !== null && (0,index_all.isObject)(commandName)) { command = commands.create(commandName); } if (model.active) { !fromCollection && ((_a = model.collection) === null || _a === void 0 ? void 0 : _a.deactivateAll(context, model)); model.set('active', true, { silent: true }).trigger('checkActive'); !fromListen && commands.runCommand(command, ButtonView_assign(ButtonView_assign({}, options), { sender: model })); // Disable button if the command has no stop method //@ts-ignore command.noStop && model.set('active', false); } else { $el.removeClass(activeCls); !fromListen && commands.stopCommand(command, ButtonView_assign(ButtonView_assign({}, options), { sender: model, force: 1 })); } }; ButtonView.prototype.updateDisable = function () { var _a = this, disableCls = _a.disableCls, model = _a.model; var disable = model.disable; this.$el[disable ? 'addClass' : 'removeClass'](disableCls); }; /** * Update active style status * * @return void * */ ButtonView.prototype.checkActive = function () { var _a = this, model = _a.model, $el = _a.$el, activeCls = _a.activeCls; model.active ? $el.addClass(activeCls) : $el.removeClass(activeCls); }; /** * Triggered when button is clicked * @return void * */ ButtonView.prototype.clicked = function () { var model = this.model; if (model.get('bntsVis') || model.disable || !model.command) return; this.toggleActive(); }; ButtonView.prototype.toggleActive = function () { var _a = this, model = _a.model, em = _a.em; var active = model.active, togglable = model.togglable; if (active && !togglable) return; model.active = !active; // If the stop is requested if (active) { if (model.runDefaultCommand) em.runDefault(); } else { if (model.stopDefaultCommand) em.stopDefault(); } }; ButtonView.prototype.render = function () { var model = this.model; var label = model.get('label'); var $el = this.$el; !model.get('el') && $el.empty(); this.updateAttributes(); label && $el.append(label); this.checkActive(); this.updateDisable(); return this; }; return ButtonView; }(abstract_ModuleView)); /* harmony default export */ const view_ButtonView = (ButtonView); ;// CONCATENATED MODULE: ./src/panels/view/ButtonsView.ts var ButtonsView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ButtonsView = /** @class */ (function (_super) { ButtonsView_extends(ButtonsView, _super); function ButtonsView(collection) { var _this = _super.call(this, { collection: collection }) || this; _this.listenTo(_this.collection, 'add', _this.addTo); _this.listenTo(_this.collection, 'reset remove', _this.render); _this.className = _this.pfx + 'buttons'; return _this; } /** * Add to collection * @param Object Model * * @return Object * */ ButtonsView.prototype.addTo = function (model) { this.addToCollection(model); }; /** * Add new object to collection * @param Object Model * @param Object Fragment collection * * @return Object Object created * */ ButtonsView.prototype.addToCollection = function (model, fragmentEl) { var fragment = fragmentEl || null; var el = model.get('el'); var view = new view_ButtonView({ el: el, model: model, }); var rendered = view.render().el; if (fragment) { fragment.appendChild(rendered); } else { this.$el.append(rendered); } return rendered; }; ButtonsView.prototype.render = function () { var _this = this; var fragment = document.createDocumentFragment(); this.$el.empty(); this.collection.each(function (model) { return _this.addToCollection(model, fragment); }); this.$el.append(fragment); this.$el.attr('class', (0,index_all.result)(this, 'className')); return this; }; return ButtonsView; }(abstract_ModuleView)); /* harmony default export */ const view_ButtonsView = (ButtonsView); ;// CONCATENATED MODULE: ./src/panels/view/PanelView.ts var PanelView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var PanelView_assign = ( false) || function () { PanelView_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return PanelView_assign.apply(this, arguments); }; var PanelView = /** @class */ (function (_super) { PanelView_extends(PanelView, _super); function PanelView(model) { var _this = _super.call(this, { model: model, el: model.get('el') }) || this; _this.className = _this.pfx + 'panel'; _this.id = _this.pfx + model.get('id'); _this.listenTo(model, 'change:appendContent', _this.appendContent); _this.listenTo(model, 'change:content', _this.updateContent); _this.listenTo(model, 'change:visible', _this.toggleVisible); model.view = _this; return _this; } /** * Append content of the panel * */ PanelView.prototype.appendContent = function () { this.$el.append(this.model.get('appendContent')); }; /** * Update content * */ PanelView.prototype.updateContent = function () { this.$el.html(this.model.get('content')); }; PanelView.prototype.toggleVisible = function () { if (!this.model.get('visible')) { this.$el.addClass("".concat(this.ppfx, "hidden")); return; } this.$el.removeClass("".concat(this.ppfx, "hidden")); }; //@ts-ignore PanelView.prototype.attributes = function () { return this.model.get('attributes'); }; PanelView.prototype.initResize = function () { var em = this.em; var editor = em === null || em === void 0 ? void 0 : em.Editor; var resizable = this.model.get('resizable'); if (editor && resizable) { var resz = resizable === true ? [true, true, true, true] : resizable; var resLen = resz.length; var tc = void 0, cr = void 0, bc = void 0, cl = false; // Choose which sides of the panel are resizable if (resLen == 2) { var resBools = resz; tc = resBools[0]; bc = resBools[0]; cr = resBools[1]; cl = resBools[1]; } else if (resLen == 4) { var resBools = resz; tc = resBools[0]; cr = resBools[1]; bc = resBools[2]; cl = resBools[3]; } var resizer_1 = new editor.Utils.Resizer(PanelView_assign({ tc: tc, cr: cr, bc: bc, cl: cl, tl: false, tr: false, bl: false, br: false, appendTo: this.el, silentFrames: true, avoidContainerUpdate: true, prefix: editor.getConfig().stylePrefix, onEnd: function () { em && em.trigger('change:canvasOffset'); }, posFetcher: function (el, _a) { var target = _a.target; var style = el.style; var config = resizer_1.getConfig(); var keyWidth = config.keyWidth; var keyHeight = config.keyHeight; var rect = el.getBoundingClientRect(); var forContainer = target == 'container'; var styleWidth = style[keyWidth]; var styleHeight = style[keyHeight]; var width = styleWidth && !forContainer ? parseFloat(styleWidth) : rect.width; var height = styleHeight && !forContainer ? parseFloat(styleHeight) : rect.height; return { left: 0, top: 0, width: width, height: height, }; } }, (resizable && typeof resizable !== 'boolean' ? resizable : {}))); resizer_1.blur = function () { }; resizer_1.focus(this.el); } }; PanelView.prototype.render = function () { var buttons = this.model.buttons; var $el = this.$el; var ppfx = this.ppfx; var cls = "".concat(this.className, " ").concat(this.id, " ").concat(ppfx, "one-bg ").concat(ppfx, "two-color"); $el.addClass(cls); this.toggleVisible(); if (buttons.length) { var buttonsView = new view_ButtonsView(buttons); $el.append(buttonsView.render().el); } $el.append(this.model.get('content')); return this; }; return PanelView; }(abstract_ModuleView)); /* harmony default export */ const view_PanelView = (PanelView); ;// CONCATENATED MODULE: ./src/panels/view/PanelsView.ts var PanelsView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var PanelsView = /** @class */ (function (_super) { PanelsView_extends(PanelsView, _super); function PanelsView(target) { var _this = _super.call(this, { collection: target }) || this; _this.listenTo(target, 'add', _this.addTo); _this.listenTo(target, 'reset', _this.render); _this.listenTo(target, 'remove', _this.onRemove); _this.className = _this.pfx + 'panels'; return _this; } PanelsView.prototype.onRemove = function (model) { var view = model.view; view && view.remove(); }; /** * Add to collection * @param Object Model * * @return Object * @private * */ PanelsView.prototype.addTo = function (model) { this.addToCollection(model); }; /** * Add new object to collection * @param Object Model * @param Object Fragment collection * @param integer Index of append * * @return Object Object created * @private * */ PanelsView.prototype.addToCollection = function (model, fragmentEl) { var fragment = fragmentEl || null; var el = model.get('el'); var view = new view_PanelView(model); var rendered = view.render().el; var appendTo = model.get('appendTo'); // Do nothing if the panel was requested to be another element if (el) { } else if (appendTo) { var appendEl = document.querySelector(appendTo); appendEl === null || appendEl === void 0 ? void 0 : appendEl.appendChild(rendered); } else { if (fragment) { fragment.appendChild(rendered); } else { this.$el.append(rendered); } } view.initResize(); return rendered; }; PanelsView.prototype.render = function () { var _this = this; var $el = this.$el; var frag = document.createDocumentFragment(); $el.empty(); this.collection.each(function (model) { return _this.addToCollection(model, frag); }); $el.append(frag); $el.attr('class', this.className); return this; }; return PanelsView; }(abstract_ModuleView)); /* harmony default export */ const view_PanelsView = (PanelsView); ;// CONCATENATED MODULE: ./src/panels/index.ts var panels_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); /** * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/GrapesJS/grapesjs/blob/master/src/panels/config/config.ts) * ```js * const editor = grapesjs.init({ * panels: { * // options * } * }) * ``` * * Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance * * ```js * const panelManager = editor.Panels; * ``` * * * [addPanel](#addpanel) * * [addButton](#addbutton) * * [getButton](#getbutton) * * [getPanel](#getpanel) * * [getPanels](#getpanels) * * [getPanelsEl](#getpanelsel) * * [removePanel](#removepanel) * * [removeButton](#removebutton) * * @module Panels */ var PanelManager = /** @class */ (function (_super) { panels_extends(PanelManager, _super); /** * Initialize module. Automatically called with a new instance of the editor * @param {Object} config Configurations * @private */ function PanelManager(em) { var _this = _super.call(this, em, 'Panels', panels_config_config) || this; _this.panels = new model_Panels(_this, _this.config.defaults); for (var name in panels_config_config) { //@ts-ignore if (!(name in _this.config)) _this.config[name] = panels_config_config[name]; } return _this; } /** * Returns the collection of panels * @return {Collection} Collection of panel */ PanelManager.prototype.getPanels = function () { return this.panels; }; /** * Returns panels element * @return {HTMLElement} */ PanelManager.prototype.getPanelsEl = function () { var _a; return (_a = this.PanelsViewObj) === null || _a === void 0 ? void 0 : _a.el; }; /** * Add new panel to the collection * @param {Object|Panel} panel Object with right properties or an instance of Panel * @return {Panel} Added panel. Useful in case passed argument was an Object * @example * const newPanel = panelManager.addPanel({ * id: 'myNewPanel', * visible: true, * buttons: [...], * }); */ PanelManager.prototype.addPanel = function (panel) { return this.panels.add(panel); }; /** * Remove a panel from the collection * @param {Panel|String} panel Panel instance or panel id * @return {Panel} Removed panel * @example * const somePanel = panelManager.getPanel('somePanel'); * const removedPanel = panelManager.removePanel(somePanel); * * // or by id * const removedPanel = panelManager.removePanel('myNewPanel'); * */ PanelManager.prototype.removePanel = function (panel) { return this.panels.remove(panel); }; /** * Get panel by ID * @param {string} id Id string * @return {Panel|null} * @example * const myPanel = panelManager.getPanel('myPanel'); */ PanelManager.prototype.getPanel = function (id) { var res = this.panels.where({ id: id }); return res.length ? res[0] : null; }; /** * Add button to the panel * @param {string} panelId Panel's ID * @param {Object|Button} button Button object or instance of Button * @return {Button|null} Added button. Useful in case passed button was an Object * @example * const newButton = panelManager.addButton('myNewPanel',{ * id: 'myNewButton', * className: 'someClass', * command: 'someCommand', * attributes: { title: 'Some title'}, * active: false, * }); * // It's also possible to pass the command as an object * // with .run and .stop methods * ... * command: { * run: function(editor) { * ... * }, * stop: function(editor) { * ... * } * }, * // Or simply like a function which will be evaluated as a single .run command * ... * command: function(editor) { * ... * } */ PanelManager.prototype.addButton = function (panelId, button) { var pn = this.getPanel(panelId); return pn ? pn.buttons.add(button) : null; }; /** * Remove button from the panel * @param {String} panelId Panel's ID * @param {String} buttonId Button's ID * @return {Button|null} Removed button. * @example * const removedButton = panelManager.addButton('myNewPanel',{ * id: 'myNewButton', * className: 'someClass', * command: 'someCommand', * attributes: { title: 'Some title'}, * active: false, * }); * * const removedButton = panelManager.removeButton('myNewPanel', 'myNewButton'); * */ PanelManager.prototype.removeButton = function (panelId, button) { var pn = this.getPanel(panelId); return pn && pn.buttons.remove(button); }; /** * Get button from the panel * @param {string} panelId Panel's ID * @param {string} id Button's ID * @return {Button|null} * @example * const button = panelManager.getButton('myPanel', 'myButton'); */ PanelManager.prototype.getButton = function (panelId, id) { var pn = this.getPanel(panelId); if (pn) { var res = pn.buttons.where({ id: id }); return res.length ? res[0] : null; } return null; }; /** * Render panels and buttons * @return {HTMLElement} * @private */ PanelManager.prototype.render = function () { var _a; (_a = this.PanelsViewObj) === null || _a === void 0 ? void 0 : _a.remove(); this.PanelsViewObj = new view_PanelsView(this.panels); return this.PanelsViewObj.render().el; }; /** * Active activable buttons * @private */ PanelManager.prototype.active = function () { this.getPanels().each(function (p) { p.buttons.each(function (btn) { btn.get('active') && btn.trigger('updateActive'); }); }); }; /** * Disable buttons flagged as disabled * @private */ PanelManager.prototype.disableButtons = function () { this.getPanels().each(function (p) { p.buttons.each(function (btn) { if (btn.get('disable')) btn.trigger('change:disable'); }); }); }; PanelManager.prototype.destroy = function () { this.panels.reset(); this.panels.stopListening(); this.PanelsViewObj && this.PanelsViewObj.remove(); }; return PanelManager; }(abstract_Module)); /* harmony default export */ const panels = (PanelManager); ;// CONCATENATED MODULE: ./src/code_manager/config/config.ts var code_manager_config_config_config = { stylePrefix: 'cm-', optsCodeViewer: {}, }; /* harmony default export */ const code_manager_config_config = (code_manager_config_config_config); ;// CONCATENATED MODULE: ./src/code_manager/model/HtmlGenerator.ts var HtmlGenerator_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var HtmlGenerator_rest = ( false) || 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 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; var HTMLGenerator = /** @class */ (function (_super) { HtmlGenerator_extends(HTMLGenerator, _super); function HTMLGenerator() { return _super !== null && _super.apply(this, arguments) || this; } HTMLGenerator.prototype.build = function (model, opts) { if (opts === void 0) { opts = {}; } var em = opts.em, restOpts = HtmlGenerator_rest(opts, ["em"]); var htmlOpts = restOpts; // Remove unnecessary IDs if (opts.cleanId && em) { var rules = em.Css.getAll(); var idRules_1 = rules .toJSON() .map(function (rule) { var sels = rule.selectors; var sel = sels && sels.length === 1 && sels.models[0]; return sel && sel.isId() && sel.get('name'); }) .filter(Boolean); if (!htmlOpts.attributes) { htmlOpts.attributes = function (mod, attrs) { var id = attrs.id; if (id && id[0] === 'i' && // all autogenerated IDs start with 'i' !mod.get('script') && // if the component has script, we have to leave the ID !mod.get('attributes').id && // id is not intentionally in attributes idRules_1.indexOf(id) < 0 // we shouldn't have any rule with this ID ) { delete attrs.id; } return attrs; }; } } return model.toHTML(htmlOpts); }; return HTMLGenerator; }(common/* Model */.Hn)); /* harmony default export */ const HtmlGenerator = (HTMLGenerator); ;// CONCATENATED MODULE: ./src/code_manager/model/JsonGenerator.ts var JsonGenerator_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var JsonGenerator = /** @class */ (function (_super) { JsonGenerator_extends(JsonGenerator, _super); function JsonGenerator() { return _super !== null && _super.apply(this, arguments) || this; } JsonGenerator.prototype.build = function (model) { var _this = this; // @ts-ignore var json = model.toJSON(); this.beforeEach(json); (0,index_all.each)(json, function (v, attr) { var obj = json[attr]; if (obj instanceof common/* Model */.Hn) { // @ts-ignore json[attr] = _this.build(obj); } else if (obj instanceof common/* Collection */.FE) { var coll = obj; json[attr] = []; if (coll.length) { coll.forEach(function (el, index) { json[attr][index] = _this.build(el); }); } } }); return json; }; /** * Execute on each object * @param {Object} obj */ JsonGenerator.prototype.beforeEach = function (obj) { delete obj.status; }; return JsonGenerator; }(common/* Model */.Hn)); /* harmony default export */ const model_JsonGenerator = (JsonGenerator); ;// CONCATENATED MODULE: ./src/code_manager/model/JsGenerator.ts var JsGenerator_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); function isFunctionEmpty(fn) { var _a; var content = ((_a = fn.toString().match(/\{([\s\S]*)\}/m)) === null || _a === void 0 ? void 0 : _a[1]) || ''; // content between first and last { } return content.replace(/^\s*\/\/.*$/gm, '').trim().length === 0; // remove comments } var JsGenerator = /** @class */ (function (_super) { JsGenerator_extends(JsGenerator, _super); function JsGenerator() { return _super !== null && _super.apply(this, arguments) || this; } JsGenerator.prototype.mapModel = function (model) { var _a; var _this = this; var code = ''; var script = model.get('script-export') || model.get('script'); var type = model.get('type'); var comps = model.get('components'); var id = model.getId(); if (script) { // If the component has scripts we need to expose his ID var attr = model.get('attributes'); attr = (0,index_all.extend)({}, attr, { id: id }); model.set('attributes', attr, { silent: true }); // @ts-ignore var scrStr = model.getScriptString(script); var scrProps = model.get('script-props'); // If the script was updated, I'll put its code in a separate container if (model.get('scriptUpdated') && !scrProps) { this.mapJs[type + '-' + id] = { ids: [id], code: scrStr }; } else { var props = void 0; var mapType = this.mapJs[type]; if (scrProps) { props = model.__getScriptProps(); } if (mapType) { mapType.ids.push(id); if (props) mapType.props[id] = props; } else { var res = { ids: [id], code: scrStr }; if (props) res.props = (_a = {}, _a[id] = props, _a); this.mapJs[type] = res; } } } comps.forEach(function (model) { code += _this.mapModel(model); }); return code; }; JsGenerator.prototype.build = function (model) { this.mapJs = {}; this.mapModel(model); var code = ''; for (var type in this.mapJs) { var mapType = this.mapJs[type]; if (!mapType.code) { continue; } if (mapType.props) { if (isFunctionEmpty(mapType.code)) { continue; } code += "\n var props = ".concat(JSON.stringify(mapType.props), ";\n var ids = Object.keys(props).map(function(id) { return '#'+id }).join(',');\n var els = document.querySelectorAll(ids);\n for (var i = 0, len = els.length; i < len; i++) {\n var el = els[i];\n (").concat(mapType.code, ".bind(el))(props[el.id]);\n }"); } else { // Deprecated var ids = '#' + mapType.ids.join(', #'); code += "\n var items = document.querySelectorAll('".concat(ids, "');\n for (var i = 0, len = items.length; i < len; i++) {\n (function(){\n").concat(mapType.code, "\n}.bind(items[i]))();\n }"); } } return code; }; return JsGenerator; }(common/* Model */.Hn)); /* harmony default export */ const model_JsGenerator = (JsGenerator); ;// CONCATENATED MODULE: ./src/code_manager/model/CodeMirrorEditor.ts var CodeMirrorEditor_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var CodeMirrorEditor_assign = ( false) || function () { CodeMirrorEditor_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return CodeMirrorEditor_assign.apply(this, arguments); }; var CodeMirror; if ((0,mixins.hasWin)()) { CodeMirror = __nested_webpack_require_911993__(631); __nested_webpack_require_911993__(531); __nested_webpack_require_911993__(629); __nested_webpack_require_911993__(210); } var CodeMirrorEditor = /** @class */ (function (_super) { CodeMirrorEditor_extends(CodeMirrorEditor, _super); function CodeMirrorEditor() { return _super !== null && _super.apply(this, arguments) || this; } CodeMirrorEditor.prototype.defaults = function () { return { input: '', label: '', codeName: '', theme: 'hopscotch', readOnly: true, lineNumbers: true, autoFormat: true, }; }; CodeMirrorEditor.prototype.init = function (el) { (0,index_all.bindAll)(this, 'onChange'); this.editor = CodeMirror.fromTextArea(el, CodeMirrorEditor_assign({ dragDrop: false, lineWrapping: true, mode: this.get('codeName') }, this.attributes)); this.element = el; this.editor.on('change', this.onChange); return this; }; CodeMirrorEditor.prototype.onChange = function () { this.trigger('update', this); }; CodeMirrorEditor.prototype.getEditor = function () { return this.editor; }; /** * The element where the viewer is attached * @return {HTMLElement} */ CodeMirrorEditor.prototype.getElement = function () { return this.element; }; /** * Set the element which contains the viewer attached. * Generally, it should be just a textarea, but some editor might require * a container for it some in that case this method can be used * @param {HTMLElement} el * @return {self} */ CodeMirrorEditor.prototype.setElement = function (el) { this.element = el; return this; }; /** * Refresh the viewer * @return {self} */ CodeMirrorEditor.prototype.refresh = function () { this.getEditor().refresh(); return this; }; /** * Focus the viewer * @return {self} */ CodeMirrorEditor.prototype.focus = function () { this.getEditor().focus(); return this; }; CodeMirrorEditor.prototype.getContent = function () { var ed = this.getEditor(); return ed && ed.getValue(); }; /** @inheritdoc */ CodeMirrorEditor.prototype.setContent = function (value, opts) { var _this = this; if (opts === void 0) { opts = {}; } var editor = this.editor; if (!editor) return; editor.setValue(value); var autoFormat = this.get('autoFormat'); var canAutoFormat = editor.autoFormatRange && (autoFormat === true || (Array.isArray(autoFormat) && autoFormat.includes(this.get('codeName')))); if (canAutoFormat) { CodeMirror.commands.selectAll(editor); editor.autoFormatRange(editor.getCursor(true), editor.getCursor(false)); CodeMirror.commands.goDocStart(editor); } !opts.noRefresh && setTimeout(function () { return _this.refresh(); }); }; return CodeMirrorEditor; }(common/* Model */.Hn)); /* harmony default export */ const model_CodeMirrorEditor = (CodeMirrorEditor); // @ts-ignore CodeMirrorEditor.prototype.CodeMirror = CodeMirror; ;// CONCATENATED MODULE: ./src/code_manager/view/EditorView.ts var EditorView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var EditorView_makeTemplateObject = ( false) || function (cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; }; var CodeEditorView = /** @class */ (function (_super) { EditorView_extends(CodeEditorView, _super); function CodeEditorView() { return _super !== null && _super.apply(this, arguments) || this; } CodeEditorView.prototype.template = function (_a) { var pfx = _a.pfx, codeName = _a.codeName, label = _a.label; return html(EditorView_templateObject_1 || (EditorView_templateObject_1 = EditorView_makeTemplateObject(["\n <div class=\"", "editor\" id=\"", "", "\">\n <div id=\"", "title\">", "</div>\n <div id=\"", "code\"></div>\n </div>\n "], ["\n <div class=\"", "editor\" id=\"", "", "\">\n <div id=\"", "title\">", "</div>\n <div id=\"", "code\"></div>\n </div>\n "])), pfx, pfx, codeName, pfx, label, pfx); }; CodeEditorView.prototype.initialize = function (o) { this.config = o.config || {}; this.pfx = this.config.stylePrefix; }; CodeEditorView.prototype.render = function () { var _a, _b; var _c = this, model = _c.model, pfx = _c.pfx, $el = _c.$el; var obj = model.toJSON(); var toAppend = model.get('input') || ((_b = (_a = model).getElement) === null || _b === void 0 ? void 0 : _b.call(_a)); obj.pfx = pfx; $el.html(this.template(obj)); $el.attr('class', "".concat(pfx, "editor-c")); $el.find("#".concat(pfx, "code")).append(toAppend); return this; }; return CodeEditorView; }(common/* View */.G7)); /* harmony default export */ const EditorView = (CodeEditorView); var EditorView_templateObject_1; ;// CONCATENATED MODULE: ./src/code_manager/index.ts var code_manager_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var code_manager_assign = ( false) || function () { code_manager_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return code_manager_assign.apply(this, arguments); }; /** * - [addGenerator](#addgenerator) * - [getGenerator](#getgenerator) * - [getGenerators](#getgenerators) * - [addViewer](#addviewer) * - [getViewer](#getviewer) * - [getViewers](#getviewers) * - [updateViewer](#updateviewer) * - [getCode](#getcode) * * * Before using methods you should get first the module from the editor instance, in this way: * * ```js * var codeManager = editor.CodeManager; * ``` * * @module CodeManager */ var defaultViewer = 'CodeMirror'; var CodeManagerModule = /** @class */ (function (_super) { code_manager_extends(CodeManagerModule, _super); function CodeManagerModule(em) { var _this = _super.call(this, em, 'CodeManager', code_manager_config_config) || this; _this.EditorView = EditorView; var config = _this.config; var ppfx = config.pStylePrefix; if (ppfx) config.stylePrefix = ppfx + config.stylePrefix; _this.generators = {}; _this.viewers = {}; _this.defGenerators = { html: new HtmlGenerator(), css: new model_CssGenerator(), json: new model_JsonGenerator(), js: new model_JsGenerator(), }; _this.defViewers = { CodeMirror: new model_CodeMirrorEditor() }; _this.loadDefaultGenerators().loadDefaultViewers(); return _this; } /** * Add new code generator to the collection * @param {string} id Code generator ID * @param {Object} generator Code generator wrapper * @param {Function} generator.build Function that builds the code * @return {this} * @example * codeManager.addGenerator('html7',{ * build: function(model){ * return 'myCode'; * } * }); * */ CodeManagerModule.prototype.addGenerator = function (id, generator) { this.generators[id] = generator; return this; }; /** * Get code generator by id * @param {string} id Code generator ID * @return {Object|null} * @example * var generator = codeManager.getGenerator('html7'); * generator.build = function(model){ * //extend * }; * */ CodeManagerModule.prototype.getGenerator = function (id) { return this.generators[id]; }; /** * Returns all code generators * @return {Array<Object>} * */ CodeManagerModule.prototype.getGenerators = function () { return this.generators; }; /** * Add new code viewer * @param {string} id Code viewer ID * @param {Object} viewer Code viewer wrapper * @param {Function} viewer.init Set element on which viewer will be displayed * @param {Function} viewer.setContent Set content to the viewer * @return {this} * @example * codeManager.addViewer('ace',{ * init: function(el){ * var ace = require('ace-editor'); * this.editor = ace.edit(el.id); * }, * setContent: function(code){ * this.editor.setValue(code); * } * }); * */ CodeManagerModule.prototype.addViewer = function (id, viewer) { this.viewers[id] = viewer; return this; }; /** * Get code viewer by id * @param {string} id Code viewer ID * @return {Object|null} * @example * var viewer = codeManager.getViewer('ace'); * */ CodeManagerModule.prototype.getViewer = function (id) { return this.viewers[id]; }; /** * Returns all code viewers * @return {Array<Object>} * */ CodeManagerModule.prototype.getViewers = function () { return this.viewers; }; CodeManagerModule.prototype.createViewer = function (opts) { if (opts === void 0) { opts = {}; } var type = !(0,index_all.isUndefined)(opts.type) ? opts.type : defaultViewer; var viewer = this.getViewer(type) && this.getViewer(type).clone(); var cont = document.createElement('div'); var txtarea = document.createElement('textarea'); cont.appendChild(txtarea); viewer.set(code_manager_assign(code_manager_assign({}, this.config.optsCodeViewer), opts)); viewer.init(txtarea); viewer.setElement(cont); return viewer; }; /** * Update code viewer content * @param {Object} viewer Viewer instance * @param {string} code Code string * @example * var AceViewer = codeManager.getViewer('ace'); * // ... * var viewer = AceViewer.init(el); * // ... * codeManager.updateViewer(AceViewer, 'code'); * */ CodeManagerModule.prototype.updateViewer = function (viewer, code) { viewer.setContent(code); }; /** * Get code from model * @param {Object} model Any kind of model that will be passed to the build method of generator * @param {string} genId Code generator id * @param {Object} [opt] Options * @return {string} * @example * var codeStr = codeManager.getCode(model, 'html'); * */ CodeManagerModule.prototype.getCode = function (model, genId, opt) { if (opt === void 0) { opt = {}; } opt.em = this.em; var generator = this.getGenerator(genId); return generator ? generator.build(model, opt) : ''; }; /** * Load default code generators * @return {this} * @private * */ CodeManagerModule.prototype.loadDefaultGenerators = function () { for (var id in this.defGenerators) { this.addGenerator(id, this.defGenerators[id]); } return this; }; /** * Load default code viewers * @return {this} * @private * */ CodeManagerModule.prototype.loadDefaultViewers = function () { for (var id in this.defViewers) { this.addViewer(id, this.defViewers[id]); } return this; }; CodeManagerModule.prototype.destroy = function () { }; return CodeManagerModule; }(abstract_Module)); /* harmony default export */ const code_manager = (CodeManagerModule); // EXTERNAL MODULE: ./node_modules/backbone-undo/Backbone.Undo.js var Backbone_Undo = __nested_webpack_require_911993__(410); var Backbone_Undo_default = /*#__PURE__*/__nested_webpack_require_911993__.n(Backbone_Undo); ;// CONCATENATED MODULE: ./src/undo_manager/config.ts var undo_manager_config_config = { maximumStackLength: 500, trackSelection: true, }; /* harmony default export */ const undo_manager_config = (undo_manager_config_config); ;// CONCATENATED MODULE: ./src/undo_manager/index.ts var undo_manager_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var undo_manager_assign = ( false) || function () { undo_manager_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return undo_manager_assign.apply(this, arguments); }; var undo_manager_spreadArray = ( false) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; /** * This module allows to manage the stack of changes applied in canvas. * Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance * * ```js * const um = editor.UndoManager; * ``` * * * [getConfig](#getconfig) * * [add](#add) * * [remove](#remove) * * [removeAll](#removeall) * * [start](#start) * * [stop](#stop) * * [undo](#undo) * * [undoAll](#undoall) * * [redo](#redo) * * [redoAll](#redoall) * * [hasUndo](#hasundo) * * [hasRedo](#hasredo) * * [getStack](#getstack) * * [clear](#clear) * * @module UndoManager */ // @ts-ignore var hasSkip = function (opts) { return opts.avoidStore || opts.noUndo; }; var getChanged = function (obj) { return Object.keys(obj.changedAttributes()); }; var UndoManagerModule = /** @class */ (function (_super) { undo_manager_extends(UndoManagerModule, _super); function UndoManagerModule(em) { var _this = _super.call(this, em, 'UndoManager', undo_manager_config) || this; if (_this.config._disable) { _this.config.maximumStackLength = 0; } var fromUndo = true; _this.um = new (Backbone_Undo_default())(undo_manager_assign({ track: true, register: [] }, _this.config)); _this.um.changeUndoType('change', { condition: function (object) { var hasUndo = object.get('_undo'); if (hasUndo) { var undoExc_1 = object.get('_undoexc'); if ((0,index_all.isArray)(undoExc_1)) { if (getChanged(object).some(function (chn) { return undoExc_1.indexOf(chn) >= 0; })) return false; } if ((0,index_all.isBoolean)(hasUndo)) return true; if ((0,index_all.isArray)(hasUndo)) { if (getChanged(object).some(function (chn) { return hasUndo.indexOf(chn) >= 0; })) return true; } } return false; }, on: function (object, v, opts) { var _this = this; !this.beforeCache && (this.beforeCache = object.previousAttributes()); var opt = opts || v || {}; opt.noUndo && setTimeout(function () { _this.beforeCache = null; }); if (hasSkip(opt)) { return; } else { var after = object.toJSON({ fromUndo: fromUndo }); var result = { object: object, before: this.beforeCache, after: after, }; this.beforeCache = null; // Skip undo in case of empty changes if ((0,index_all.isEmpty)(after)) return; return result; } }, }); _this.um.changeUndoType('add', { on: function (model, collection, options) { if (options === void 0) { options = {}; } if (hasSkip(options) || !_this.isRegistered(collection)) return; return { object: collection, before: undefined, after: model, options: undo_manager_assign(undo_manager_assign({}, options), { fromUndo: fromUndo }), }; }, }); _this.um.changeUndoType('remove', { on: function (model, collection, options) { if (options === void 0) { options = {}; } if (hasSkip(options) || !_this.isRegistered(collection)) return; return { object: collection, before: model, after: undefined, options: undo_manager_assign(undo_manager_assign({}, options), { fromUndo: fromUndo }), }; }, }); _this.um.changeUndoType('reset', { undo: function (collection, before) { collection.reset(before, { fromUndo: fromUndo }); }, redo: function (collection, b, after) { collection.reset(after, { fromUndo: fromUndo }); }, on: function (collection, options) { if (options === void 0) { options = {}; } if (hasSkip(options) || !_this.isRegistered(collection)) return; return { object: collection, before: options.previousModels, after: undo_manager_spreadArray([], collection.models, true), options: undo_manager_assign(undo_manager_assign({}, options), { fromUndo: fromUndo }), }; }, }); _this.um.on('undo redo', function () { em.trigger('change:canvasOffset'); em.getSelectedAll().map(function (c) { return c.trigger('rerender:layer'); }); }); ['undo', 'redo'].forEach(function (ev) { return _this.um.on(ev, function () { return em.trigger(ev); }); }); return _this; } UndoManagerModule.prototype.postLoad = function () { var _a = this, config = _a.config, em = _a.em; config.trackSelection && em && this.add(em.get('selected')); }; /** * Get configuration object * @name getConfig * @function * @return {Object} */ /** * Add an entity (Model/Collection) to track * Note: New Components and CSSRules will be added automatically * @param {Model|Collection} entity Entity to track * @return {this} * @example * um.add(someModelOrCollection); */ UndoManagerModule.prototype.add = function (entity) { this.um.register(entity); return this; }; /** * Remove and stop tracking the entity (Model/Collection) * @param {Model|Collection} entity Entity to remove * @return {this} * @example * um.remove(someModelOrCollection); */ UndoManagerModule.prototype.remove = function (entity) { this.um.unregister(entity); return this; }; /** * Remove all entities * @return {this} * @example * um.removeAll(); */ UndoManagerModule.prototype.removeAll = function () { this.um.unregisterAll(); return this; }; /** * Start/resume tracking changes * @return {this} * @example * um.start(); */ UndoManagerModule.prototype.start = function () { this.um.startTracking(); return this; }; /** * Stop tracking changes * @return {this} * @example * um.stop(); */ UndoManagerModule.prototype.stop = function () { this.um.stopTracking(); return this; }; /** * Undo last change * @return {this} * @example * um.undo(); */ UndoManagerModule.prototype.undo = function (all) { if (all === void 0) { all = true; } var _a = this, em = _a.em, um = _a.um; !em.isEditing() && um.undo(all); return this; }; /** * Undo all changes * @return {this} * @example * um.undoAll(); */ UndoManagerModule.prototype.undoAll = function () { this.um.undoAll(); return this; }; /** * Redo last change * @return {this} * @example * um.redo(); */ UndoManagerModule.prototype.redo = function (all) { if (all === void 0) { all = true; } var _a = this, em = _a.em, um = _a.um; !em.isEditing() && um.redo(all); return this; }; /** * Redo all changes * @return {this} * @example * um.redoAll(); */ UndoManagerModule.prototype.redoAll = function () { this.um.redoAll(); return this; }; /** * Checks if exists an available undo * @return {Boolean} * @example * um.hasUndo(); */ UndoManagerModule.prototype.hasUndo = function () { return !!this.um.isAvailable('undo'); }; /** * Checks if exists an available redo * @return {Boolean} * @example * um.hasRedo(); */ UndoManagerModule.prototype.hasRedo = function () { return !!this.um.isAvailable('redo'); }; /** * Check if the entity (Model/Collection) to tracked * Note: New Components and CSSRules will be added automatically * @param {Model|Collection} entity Entity to track * @returns {Boolean} */ UndoManagerModule.prototype.isRegistered = function (obj) { return !!this.getInstance().objectRegistry.isRegistered(obj); }; /** * Get stack of changes * @return {Collection} * @example * const stack = um.getStack(); * stack.each(item => ...); */ UndoManagerModule.prototype.getStack = function () { return this.um.stack; }; /** * Get grouped undo manager stack. * The difference between `getStack` is when you do multiple operations at a time, * like appending multiple components: * `editor.getWrapper().append('<div>C1</div><div>C2</div>');` * `getStack` will return a collection length of 2. * `getStackGroup` instead will group them as a single operation (the first * inserted component will be returned in the list) by returning an array length of 1. * @return {Array} * @private */ UndoManagerModule.prototype.getStackGroup = function () { var result = []; var inserted = []; this.getStack().forEach(function (item) { var index = item.get('magicFusionIndex'); if (inserted.indexOf(index) < 0) { inserted.push(index); result.push(item); } }); return result; }; UndoManagerModule.prototype.skip = function (clb) { this.stop(); clb(); this.start(); }; UndoManagerModule.prototype.getGroupedStack = function () { var result = {}; var stack = this.getStack(); var createItem = function (item, index) { var _a = item.attributes, type = _a.type, after = _a.after, before = _a.before, object = _a.object, _b = _a.options, options = _b === void 0 ? {} : _b; return { index: index, type: type, after: after, before: before, object: object, options: options }; }; stack.forEach(function (item, i) { var index = item.get('magicFusionIndex'); var value = createItem(item, i); if (!result[index]) { result[index] = [value]; } else { result[index].push(value); } }); return Object.keys(result).map(function (index) { var actions = result[index]; return { index: actions[actions.length - 1].index, actions: actions, labels: (0,index_all.unique)(actions.reduce(function (res, item) { var _a; var label = (_a = item.options) === null || _a === void 0 ? void 0 : _a.action; label && res.push(label); return res; }, [])), }; }); }; UndoManagerModule.prototype.goToGroup = function (group) { var _this = this; if (!group) return; var current = this.getPointer(); var goTo = group.index - current; (0,index_all.times)(Math.abs(goTo), function () { _this[goTo < 0 ? 'undo' : 'redo'](false); }); }; UndoManagerModule.prototype.getPointer = function () { // @ts-ignore return this.getStack().pointer; }; /** * Clear the stack * @return {this} * @example * um.clear(); */ UndoManagerModule.prototype.clear = function () { this.um.clear(); return this; }; UndoManagerModule.prototype.getInstance = function () { return this.um; }; UndoManagerModule.prototype.destroy = function () { this.clear().removeAll(); }; return UndoManagerModule; }(abstract_Module)); /* harmony default export */ const undo_manager = (UndoManagerModule); ;// CONCATENATED MODULE: ./src/rich_text_editor/config/config.ts var rich_text_editor_config_config_config = { stylePrefix: 'rte-', adjustToolbar: true, actions: ['bold', 'italic', 'underline', 'strikethrough', 'link', 'wrap'], custom: false, }; /* harmony default export */ const rich_text_editor_config_config = (rich_text_editor_config_config_config); ;// CONCATENATED MODULE: ./src/rich_text_editor/model/RichTextEditor.ts // The initial version of this RTE was borrowed from https://github.com/jaredreich/pell // and adapted to the GrapesJS's need var RichTextEditor_assign = ( false) || function () { RichTextEditor_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return RichTextEditor_assign.apply(this, arguments); }; var RichTextEditorActionState; (function (RichTextEditorActionState) { RichTextEditorActionState[RichTextEditorActionState["ACTIVE"] = 1] = "ACTIVE"; RichTextEditorActionState[RichTextEditorActionState["INACTIVE"] = 0] = "INACTIVE"; RichTextEditorActionState[RichTextEditorActionState["DISABLED"] = -1] = "DISABLED"; })(RichTextEditorActionState || (RichTextEditorActionState = {})); var RTE_KEY = '_rte'; var btnState = { ACTIVE: 1, INACTIVE: 0, DISABLED: -1, }; var isValidTag = function (rte, tagName) { if (tagName === void 0) { tagName = 'A'; } var _a = rte.selection() || {}, anchorNode = _a.anchorNode, focusNode = _a.focusNode; var parentAnchor = anchorNode === null || anchorNode === void 0 ? void 0 : anchorNode.parentNode; var parentFocus = focusNode === null || focusNode === void 0 ? void 0 : focusNode.parentNode; return (parentAnchor === null || parentAnchor === void 0 ? void 0 : parentAnchor.nodeName) == tagName || (parentFocus === null || parentFocus === void 0 ? void 0 : parentFocus.nodeName) == tagName; }; var customElAttr = 'data-selectme'; var defActions = { bold: { name: 'bold', icon: '<b>B</b>', attributes: { title: 'Bold' }, result: function (rte) { return rte.exec('bold'); }, }, italic: { name: 'italic', icon: '<i>I</i>', attributes: { title: 'Italic' }, result: function (rte) { return rte.exec('italic'); }, }, underline: { name: 'underline', icon: '<u>U</u>', attributes: { title: 'Underline' }, result: function (rte) { return rte.exec('underline'); }, }, strikethrough: { name: 'strikethrough', icon: '<s>S</s>', attributes: { title: 'Strike-through' }, result: function (rte) { return rte.exec('strikeThrough'); }, }, link: { icon: "<svg viewBox=\"0 0 24 24\">\n <path fill=\"currentColor\" d=\"M3.9,12C3.9,10.29 5.29,8.9 7,8.9H11V7H7A5,5 0 0,0 2,12A5,5 0 0,0 7,17H11V15.1H7C5.29,15.1 3.9,13.71 3.9,12M8,13H16V11H8V13M17,7H13V8.9H17C18.71,8.9 20.1,10.29 20.1,12C20.1,13.71 18.71,15.1 17,15.1H13V17H17A5,5 0 0,0 22,12A5,5 0 0,0 17,7Z\" />\n </svg>", name: 'link', attributes: { style: 'font-size:1.4rem;padding:0 4px 2px;', title: 'Link', }, state: function (rte) { return rte && rte.selection() && isValidTag(rte) ? btnState.ACTIVE : btnState.INACTIVE; }, result: function (rte) { if (isValidTag(rte)) { rte.exec('unlink'); } else { rte.insertHTML("<a href=\"\" ".concat(customElAttr, ">").concat(rte.selection(), "</a>"), { select: true, }); } }, }, wrap: { name: 'wrap', icon: "<svg viewBox=\"0 0 24 24\">\n <path fill=\"currentColor\" d=\"M20.71,4.63L19.37,3.29C19,2.9 18.35,2.9 17.96,3.29L9,12.25L11.75,15L20.71,6.04C21.1,5.65 21.1,5 20.71,4.63M7,14A3,3 0 0,0 4,17C4,18.31 2.84,19 2,19C2.92,20.22 4.5,21 6,21A4,4 0 0,0 10,17A3,3 0 0,0 7,14Z\" />\n </svg>", attributes: { title: 'Wrap for style' }, state: function (rte) { return (rte === null || rte === void 0 ? void 0 : rte.selection()) && isValidTag(rte, 'SPAN') ? btnState.DISABLED : btnState.INACTIVE; }, result: function (rte) { !isValidTag(rte, 'SPAN') && rte.insertHTML("<span ".concat(customElAttr, ">").concat(rte.selection(), "</span>"), { select: true, }); }, }, }; var RichTextEditor = /** @class */ (function () { function RichTextEditor(em, el, settings) { var _this = this; if (settings === void 0) { settings = {}; } this.em = em; this.settings = settings; if (el[RTE_KEY]) { return el[RTE_KEY]; } el[RTE_KEY] = this; this.setEl(el); this.updateActiveActions = this.updateActiveActions.bind(this); this.__onKeydown = this.__onKeydown.bind(this); this.__onPaste = this.__onPaste.bind(this); var acts = (settings.actions || []).map(function (action) { var result = action; if ((0,index_all.isString)(action)) { result = RichTextEditor_assign({}, defActions[action]); } else if (defActions[action.name]) { result = RichTextEditor_assign(RichTextEditor_assign({}, defActions[action.name]), action); } return result; }); var actions = acts.length ? acts : Object.keys(defActions).map(function (a) { return defActions[a]; }); settings.classes = RichTextEditor_assign({ actionbar: 'actionbar', button: 'action', active: 'active', disabled: 'disabled', inactive: 'inactive' }, settings.classes); var classes = settings.classes; var actionbar = settings.actionbar; this.actionbar = actionbar; this.classes = classes; this.actions = actions; if (!actionbar) { if (!this.isCustom(settings.module)) { var actionbarCont = settings.actionbarContainer; actionbar = document.createElement('div'); actionbar.className = classes.actionbar; actionbarCont === null || actionbarCont === void 0 ? void 0 : actionbarCont.appendChild(actionbar); this.actionbar = actionbar; } actions.forEach(function (action) { return _this.addAction(action); }); } settings.styleWithCSS && this.exec('styleWithCSS'); return this; } RichTextEditor.prototype.isCustom = function (module) { var rte = module || this.em.RichTextEditor; return !!((rte === null || rte === void 0 ? void 0 : rte.config.custom) || (rte === null || rte === void 0 ? void 0 : rte.customRte)); }; RichTextEditor.prototype.destroy = function () { }; RichTextEditor.prototype.setEl = function (el) { this.el = el; this.doc = el.ownerDocument; }; RichTextEditor.prototype.updateActiveActions = function () { var _this = this; var actions = this.getActions(); actions.forEach(function (action) { var update = action.update, btn = action.btn; var _a = _this.classes, active = _a.active, inactive = _a.inactive, disabled = _a.disabled; var state = action.state; var name = action.name; var doc = _this.doc; var currentState = RichTextEditorActionState.INACTIVE; if (btn) { btn.className = btn.className.replace(active, '').trim(); btn.className = btn.className.replace(inactive, '').trim(); btn.className = btn.className.replace(disabled, '').trim(); } // if there is a state function, which depicts the state, // i.e. `active`, `disabled`, then call it if (state) { var newState = state(_this, doc); currentState = newState; if (btn) { switch (newState) { case btnState.ACTIVE: btn.className += " ".concat(active); break; case btnState.INACTIVE: btn.className += " ".concat(inactive); break; case btnState.DISABLED: btn.className += " ".concat(disabled); break; } } } else { // otherwise default to checking if the name command is supported & enabled if (doc.queryCommandSupported(name) && doc.queryCommandState(name)) { btn && (btn.className += " ".concat(active)); currentState = RichTextEditorActionState.ACTIVE; } } action.currentState = currentState; update === null || update === void 0 ? void 0 : update(_this, action); }); actions.length && this.em.RichTextEditor.__dbdTrgCustom(); }; RichTextEditor.prototype.enable = function (opts) { if (this.enabled) return this; return this.__toggleEffects(true, opts); }; RichTextEditor.prototype.disable = function () { return this.__toggleEffects(false); }; RichTextEditor.prototype.__toggleEffects = function (enable, opts) { if (enable === void 0) { enable = false; } if (opts === void 0) { opts = {}; } var method = enable ? dom.on : dom/* off */.S1; var _a = this, el = _a.el, doc = _a.doc; var actionbar = this.actionbarEl(); actionbar && (actionbar.style.display = enable ? '' : 'none'); el.contentEditable = "".concat(!!enable); method(el, 'mouseup keyup', this.updateActiveActions); method(doc, 'keydown', this.__onKeydown); method(doc, 'paste', this.__onPaste); this.enabled = enable; if (enable) { var event_1 = opts.event; this.syncActions(); this.updateActiveActions(); if (event_1) { var range = null; if (doc.caretRangeFromPoint) { var poiner = (0,dom/* getPointerEvent */.VB)(event_1); range = doc.caretRangeFromPoint(poiner.clientX, poiner.clientY); // @ts-ignore } else if (event_1.rangeParent) { range = doc.createRange(); // @ts-ignore range.setStart(event_1.rangeParent, event_1.rangeOffset); } var sel = doc.getSelection(); sel === null || sel === void 0 ? void 0 : sel.removeAllRanges(); range && (sel === null || sel === void 0 ? void 0 : sel.addRange(range)); } el.focus(); } return this; }; RichTextEditor.prototype.__onKeydown = function (event) { var ev = event; var doc = this.doc; var cmdList = ['insertOrderedList', 'insertUnorderedList']; if (ev.key === 'Enter' && !cmdList.some(function (cmd) { return doc.queryCommandState(cmd); })) { doc.execCommand('insertLineBreak'); ev.preventDefault(); } }; RichTextEditor.prototype.__onPaste = function (ev) { // @ts-ignore var clipboardData = ev.clipboardData || window.clipboardData; var text = clipboardData.getData('text'); var textHtml = clipboardData.getData('text/html'); // Replace \n with <br> in case of plain text if (text && !textHtml) { ev.preventDefault(); var html = text.replace(/(?:\r\n|\r|\n)/g, '<br/>'); this.doc.execCommand('insertHTML', false, html); } }; /** * Sync actions with the current RTE */ RichTextEditor.prototype.syncActions = function () { var _this = this; this.getActions().forEach(function (action) { if (_this.actionbar) { if (!action.state || (action.state && action.state(_this, _this.doc) >= 0)) { var event_2 = action.event || 'click'; var btn = action.btn; if (btn) { btn["on".concat(event_2)] = function () { action.result(_this, action); _this.updateActiveActions(); }; } } } }); }; /** * Add new action to the actionbar * @param {Object} action * @param {Object} [opts={}] */ RichTextEditor.prototype.addAction = function (action, opts) { if (opts === void 0) { opts = {}; } var sync = opts.sync; var actionbar = this.actionbarEl(); if (actionbar) { var icon = action.icon, _a = action.attributes, attr = _a === void 0 ? {} : _a; var btn = document.createElement('span'); btn.className = this.classes.button; action.btn = btn; for (var key in attr) { btn.setAttribute(key, attr[key]); } if (typeof icon == 'string') { btn.innerHTML = icon; } else { btn.appendChild(icon); } actionbar.appendChild(btn); } if (sync) { this.actions.push(action); this.syncActions(); } }; /** * Get the array of current actions * @return {Array} */ RichTextEditor.prototype.getActions = function () { return this.actions; }; /** * Returns the Selection instance * @return {Selection} */ RichTextEditor.prototype.selection = function () { return this.doc.getSelection(); }; /** * Wrapper around [execCommand](https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand) to allow * you to perform operations like `insertText` * @param {string} command Command name * @param {any} [value=null Command's arguments */ RichTextEditor.prototype.exec = function (command, value) { this.doc.execCommand(command, false, value); }; /** * Get the actionbar element * @return {HTMLElement} */ RichTextEditor.prototype.actionbarEl = function () { return this.actionbar; }; /** * Set custom HTML to the selection, useful as the default 'insertHTML' command * doesn't work in the same way on all browsers * @param {string} value HTML string */ RichTextEditor.prototype.insertHTML = function (value, _a) { var _b = _a === void 0 ? {} : _a, select = _b.select; var _c = this, em = _c.em, doc = _c.doc, el = _c.el; var sel = doc.getSelection(); if (sel && sel.rangeCount) { var model_1 = (0,mixins.getModel)(el); var node = doc.createElement('div'); var range_1 = sel.getRangeAt(0); range_1.deleteContents(); if ((0,index_all.isString)(value)) { node.innerHTML = value; } else if (value) { node.appendChild(value); } Array.prototype.slice.call(node.childNodes).forEach(function (nd) { range_1.insertNode(nd); }); sel.removeAllRanges(); sel.addRange(range_1); el.focus(); if (select && model_1) { model_1.once('rte:disable', function () { var toSel = model_1.find("[".concat(customElAttr, "]"))[0]; if (!toSel) return; em.setSelected(toSel); toSel.removeAttributes(customElAttr); }); model_1.trigger('disable'); } } }; return RichTextEditor; }()); /* harmony default export */ const model_RichTextEditor = (RichTextEditor); ;// CONCATENATED MODULE: ./src/rich_text_editor/index.ts /** * This module allows to customize the built-in toolbar of the Rich Text Editor and use commands from the [HTML Editing APIs](https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand). * It's highly recommended to keep this toolbar as small as possible, especially from styling commands (eg. 'fontSize') and leave this task to the Style Manager * * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/GrapesJS/grapesjs/blob/master/src/rich_text_editor/config/config.ts) * ```js * const editor = grapesjs.init({ * richTextEditor: { * // options * } * }) * ``` * * Once the editor is instantiated you can use its API and listen to its events. Before using these methods, you should get the module from the instance. * * ```js * // Listen to events * editor.on('rte:enable', () => { ... }); * * // Use the API * const rte = editor.RichTextEditor; * rte.add(...); * ``` * * ## Available Events * * `rte:enable` - RTE enabled. The view, on which RTE is enabled, is passed as an argument * * `rte:disable` - RTE disabled. The view, on which RTE is disabled, is passed as an argument * * ## Methods * * [add](#add) * * [get](#get) * * [run](#run) * * [getAll](#getall) * * [remove](#remove) * * [getToolbarEl](#gettoolbarel) * * @module RichTextEditor */ var rich_text_editor_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var rich_text_editor_awaiter = ( false) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var rich_text_editor_generator = ( false) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var rich_text_editor_spreadArray = ( false) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var eventsUp = 'change:canvasOffset frame:scroll component:update'; var evEnable = 'rte:enable'; var evDisable = 'rte:disable'; var rich_text_editor_evCustom = 'rte:custom'; var rich_text_editor_events = { enable: evEnable, disable: evDisable, custom: rich_text_editor_evCustom, }; var RichTextEditorModule = /** @class */ (function (_super) { rich_text_editor_extends(RichTextEditorModule, _super); /** * Get configuration object * @name getConfig * @function * @return {Object} */ function RichTextEditorModule(em) { var _this = _super.call(this, em, 'RichTextEditor', rich_text_editor_config_config) || this; _this.events = rich_text_editor_events; var config = _this.config; var ppfx = config.pStylePrefix; if (ppfx) { config.stylePrefix = ppfx + config.stylePrefix; } _this.pfx = config.stylePrefix; _this.actions = config.actions || []; var model = new common/* Model */.Hn(); _this.model = model; model.on('change:currentView', _this.__trgCustom, _this); _this.__dbdTrgCustom = (0,index_all.debounce)(function () { return _this.__trgCustom(); }, 0); return _this; } RichTextEditorModule.prototype.onLoad = function () { if (!(0,mixins.hasWin)()) return; var config = this.config; var ppfx = config.pStylePrefix; var isCustom = config.custom; var toolbar = (0,dom/* createEl */.ut)('div', { class: (0,dom.cx)("".concat(ppfx, "rte-toolbar"), !isCustom && "".concat(ppfx, "one-bg ").concat(ppfx, "rte-toolbar-ui")), }); this.toolbar = toolbar; this.initRte((0,dom/* createEl */.ut)('div')); //Avoid closing on toolbar clicking (0,dom.on)(toolbar, 'mousedown', function (e) { return e.stopPropagation(); }); }; RichTextEditorModule.prototype.__trgCustom = function () { var _a = this, model = _a.model, em = _a.em, events = _a.events; em.trigger(events.custom, { enabled: !!model.get('currentView'), container: this.getToolbarEl(), actions: this.getAll(), }); }; RichTextEditorModule.prototype.destroy = function () { var _a, _b, _c; (_a = this.globalRte) === null || _a === void 0 ? void 0 : _a.destroy(); (_c = (_b = this.customRte) === null || _b === void 0 ? void 0 : _b.destroy) === null || _c === void 0 ? void 0 : _c.call(_b); this.model.stopListening().clear({ silent: true }); this.__dbdTrgCustom.cancel(); (0,dom/* removeEl */.L_)(this.toolbar); }; /** * Post render callback * @param {View} ev * @private */ RichTextEditorModule.prototype.postRender = function (ev) { var canvas = ev.model.get('Canvas'); this.toolbar.style.pointerEvents = 'all'; this.hideToolbar(); canvas.getToolsEl().appendChild(this.toolbar); }; /** * Init the built-in RTE * @param {HTMLElement} el * @return {RichTextEditor} * @private */ RichTextEditorModule.prototype.initRte = function (el) { var globalRte = this.globalRte; var _a = this, em = _a.em, pfx = _a.pfx, actionbar = _a.actionbar, config = _a.config; var actions = this.actions || rich_text_editor_spreadArray([], config.actions, true); var classes = { actionbar: "".concat(pfx, "actionbar"), button: "".concat(pfx, "action"), active: "".concat(pfx, "active"), inactive: "".concat(pfx, "inactive"), disabled: "".concat(pfx, "disabled"), }; if (!globalRte) { globalRte = new model_RichTextEditor(em, el, { classes: classes, actions: actions, actionbar: actionbar, actionbarContainer: this.toolbar, module: this, }); this.globalRte = globalRte; } else { globalRte.em = em; globalRte.setEl(el); } if (globalRte.actionbar) { this.actionbar = globalRte.actionbar; } if (globalRte.actions) { this.actions = globalRte.actions; } return globalRte; }; /** * Add a new action to the built-in RTE toolbar * @param {string} name Action name * @param {Object} action Action options * @example * rte.add('bold', { * icon: '<b>B</b>', * attributes: {title: 'Bold'}, * result: rte => rte.exec('bold') * }); * rte.add('link', { * icon: document.getElementById('t'), * attributes: { title: 'Link' }, * // Example on how to wrap selected content * result: rte => rte.insertHTML(`<a href="#">${rte.selection()}</a>`) * }); * // An example with fontSize * rte.add('fontSize', { * icon: `<select class="gjs-field"> * <option>1</option> * <option>4</option> * <option>7</option> * </select>`, * // Bind the 'result' on 'change' listener * event: 'change', * result: (rte, action) => rte.exec('fontSize', action.btn.firstChild.value), * // Callback on any input change (mousedown, keydown, etc..) * update: (rte, action) => { * const value = rte.doc.queryCommandValue(action.name); * if (value != 'false') { // value is a string * action.btn.firstChild.value = value; * } * } * }) * // An example with state * const isValidAnchor = (rte) => { * // a utility function to help determine if the selected is a valid anchor node * const anchor = rte.selection().anchorNode; * const parentNode = anchor && anchor.parentNode; * const nextSibling = anchor && anchor.nextSibling; * return (parentNode && parentNode.nodeName == 'A') || (nextSibling && nextSibling.nodeName == 'A') * } * rte.add('toggleAnchor', { * icon: `<span style="transform:rotate(45deg)">⫘</span>`, * state: (rte, doc) => { * if (rte && rte.selection()) { * // `btnState` is a integer, -1 for disabled, 0 for inactive, 1 for active * return isValidAnchor(rte) ? btnState.ACTIVE : btnState.INACTIVE; * } else { * return btnState.INACTIVE; * } * }, * result: (rte, action) => { * if (isValidAnchor(rte)) { * rte.exec('unlink'); * } else { * rte.insertHTML(`<a class="link" href="">${rte.selection()}</a>`); * } * } * }) */ RichTextEditorModule.prototype.add = function (name, action) { var _a; if (action === void 0) { action = {}; } action.name = name; (_a = this.globalRte) === null || _a === void 0 ? void 0 : _a.addAction(action, { sync: true }); }; /** * Get the action by its name * @param {string} name Action name * @return {Object} * @example * const action = rte.get('bold'); * // {name: 'bold', ...} */ RichTextEditorModule.prototype.get = function (name) { var _a; var result; (_a = this.globalRte) === null || _a === void 0 ? void 0 : _a.getActions().forEach(function (action) { if (action.name == name) { result = action; } }); return result; }; /** * Get all actions * @return {Array} */ RichTextEditorModule.prototype.getAll = function () { var _a; return ((_a = this.globalRte) === null || _a === void 0 ? void 0 : _a.getActions()) || []; }; /** * Remove the action from the toolbar * @param {string} name * @return {Object} Removed action * @example * const action = rte.remove('bold'); * // {name: 'bold', ...} */ RichTextEditorModule.prototype.remove = function (name) { var _a; var actions = this.getAll(); var action = this.get(name); if (action) { var btn = action.btn; var index = actions.indexOf(action); (_a = btn === null || btn === void 0 ? void 0 : btn.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(btn); actions.splice(index, 1); } return action; }; /** * Run action command. * @param action Action to run * @example * const action = rte.get('bold'); * rte.run(action) // or rte.run('bold') */ RichTextEditorModule.prototype.run = function (action) { var rte = this.globalRte; var actionRes = (0,index_all.isString)(action) ? this.get(action) : action; if (rte && actionRes) { actionRes.result(rte, actionRes); rte.updateActiveActions(); } }; /** * Get the toolbar element * @return {HTMLElement} */ RichTextEditorModule.prototype.getToolbarEl = function () { return this.toolbar; }; /** * Triggered when the offset of the editor is changed * @private */ RichTextEditorModule.prototype.updatePosition = function () { var _a = this, em = _a.em, toolbar = _a.toolbar; var un = 'px'; var canvas = em.Canvas; var style = toolbar.style; var pos = canvas.getTargetToElementFixed(this.lastEl, toolbar, { event: 'rteToolbarPosUpdate', left: 0, }); ['top', 'left', 'bottom', 'right'].forEach(function (key) { var value = pos[key]; if ((0,mixins.isDef)(value)) { style[key] = (0,index_all.isString)(value) ? value : (value || 0) + un; } }); }; /** * Enable rich text editor on the element * @param {View} view Component view * @param {Object} rte The instance of already defined RTE * @private * */ RichTextEditorModule.prototype.enable = function (view, rte, opts) { if (opts === void 0) { opts = {}; } return rich_text_editor_awaiter(this, void 0, void 0, function () { var _a, customRte, em, el, rteInst; return rich_text_editor_generator(this, function (_b) { switch (_b.label) { case 0: this.lastEl = view.el; _a = this, customRte = _a.customRte, em = _a.em; el = view.getChildrenContainer(); this.toolbar.style.display = ''; return [4 /*yield*/, (customRte ? customRte.enable(el, rte) : this.initRte(el).enable(opts))]; case 1: rteInst = _b.sent(); if (em) { setTimeout(this.updatePosition.bind(this), 0); em.off(eventsUp, this.updatePosition, this); em.on(eventsUp, this.updatePosition, this); em.trigger('rte:enable', view, rteInst); } this.model.set({ currentView: view }); return [2 /*return*/, rteInst]; } }); }); }; RichTextEditorModule.prototype.getContent = function (view, rte) { return rich_text_editor_awaiter(this, void 0, void 0, function () { var customRte; return rich_text_editor_generator(this, function (_a) { switch (_a.label) { case 0: customRte = this.customRte; if (!(customRte && rte && (0,index_all.isFunction)(customRte.getContent))) return [3 /*break*/, 2]; return [4 /*yield*/, customRte.getContent(view.el, rte)]; case 1: return [2 /*return*/, _a.sent()]; case 2: return [2 /*return*/, view.getChildrenContainer().innerHTML]; } }); }); }; RichTextEditorModule.prototype.hideToolbar = function () { var style = this.toolbar.style; var size = '-1000px'; style.top = size; style.left = size; style.display = 'none'; }; /** * Unbind rich text editor from the element * @param {View} view * @param {Object} rte The instance of already defined RTE * @private * */ RichTextEditorModule.prototype.disable = function (view, rte) { var em = this.em; var customRte = this.customRte; // @ts-ignore var el = view.getChildrenContainer(); if (customRte) { customRte.disable(el, rte); } else { rte && rte.disable(); } this.hideToolbar(); if (em) { em.off(eventsUp, this.updatePosition, this); em.trigger('rte:disable', view, rte); } this.model.unset('currentView'); }; return RichTextEditorModule; }(abstract_Module)); /* harmony default export */ const rich_text_editor = (RichTextEditorModule); // EXTERNAL MODULE: ./src/commands/view/CommandAbstract.ts var CommandAbstract = __nested_webpack_require_911993__(790); ;// CONCATENATED MODULE: ./src/commands/config/config.ts var commands_config_config_config = { stylePrefix: 'com-', defaults: {}, strict: true, }; /* harmony default export */ const commands_config_config = (commands_config_config_config); ;// CONCATENATED MODULE: ./src/commands/index.ts /** * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/GrapesJS/grapesjs/blob/master/src/commands/config/config.ts) * ```js * const editor = grapesjs.init({ * commands: { * // options * } * }) * ``` * * Once the editor is instantiated you can use its API and listen to its events. Before using these methods, you should get the module from the instance. * * ```js * // Listen to events * editor.on('run', () => { ... }); * * // Use the API * const commands = editor.Commands; * commands.add(...); * ``` * ** ## Available Events * * `run:{commandName}` - Triggered when some command is called to run (eg. editor.runCommand('preview')) * * `stop:{commandName}` - Triggered when some command is called to stop (eg. editor.stopCommand('preview')) * * `run:{commandName}:before` - Triggered before the command is called * * `stop:{commandName}:before` - Triggered before the command is called to stop * * `abort:{commandName}` - Triggered when the command execution is aborted (`editor.on(`run:preview:before`, opts => opts.abort = 1);`) * * `run` - Triggered on run of any command. The id and the result are passed as arguments to the callback * * `stop` - Triggered on stop of any command. The id and the result are passed as arguments to the callback * * ## Methods * * [add](#add) * * [get](#get) * * [getAll](#getall) * * [extend](#extend) * * [has](#has) * * [run](#run) * * [stop](#stop) * * [isActive](#isactive) * * [getActive](#getactive) * * @module Commands */ var commands_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var commands_assign = ( false) || function () { commands_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return commands_assign.apply(this, arguments); }; var commands_spreadArray = ( false) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var commandsDef = [ ['preview', 'Preview', 'preview'], ['resize', 'Resize', 'resize'], ['fullscreen', 'Fullscreen', 'fullscreen'], ['copy', 'CopyComponent'], ['paste', 'PasteComponent'], ['canvas-move', 'CanvasMove'], ['canvas-clear', 'CanvasClear'], ['open-code', 'ExportTemplate', 'export-template'], ['open-layers', 'OpenLayers', 'open-layers'], ['open-styles', 'OpenStyleManager', 'open-sm'], ['open-traits', 'OpenTraitManager', 'open-tm'], ['open-blocks', 'OpenBlocks', 'open-blocks'], ['open-assets', 'OpenAssets', 'open-assets'], ['component-select', 'SelectComponent', 'select-comp'], ['component-outline', 'SwitchVisibility', 'sw-visibility'], ['component-offset', 'ShowOffset', 'show-offset'], ['component-move', 'MoveComponent', 'move-comp'], ['component-next', 'ComponentNext'], ['component-prev', 'ComponentPrev'], ['component-enter', 'ComponentEnter'], ['component-exit', 'ComponentExit', 'select-parent'], ['component-delete', 'ComponentDelete'], ['component-style-clear', 'ComponentStyleClear'], ['component-drag', 'ComponentDrag'], ]; var CommandsModule = /** @class */ (function (_super) { commands_extends(CommandsModule, _super); /** * @private */ function CommandsModule(em) { var _this = _super.call(this, em, 'Commands', commands_config_config) || this; _this.CommandAbstract = CommandAbstract["default"]; _this.defaultCommands = {}; _this.commands = {}; _this.active = {}; var config = _this.config; var ppfx = config.pStylePrefix; var defaultCommands = _this.defaultCommands; if (ppfx) { config.stylePrefix = ppfx + config.stylePrefix; } // Load commands passed via configuration Object.keys(config.defaults).forEach(function (k) { var obj = config.defaults[k]; if (obj.id) _this.add(obj.id, obj); }); defaultCommands['tlb-delete'] = { run: function (ed) { return ed.runCommand('core:component-delete'); }, }; defaultCommands['tlb-clone'] = { run: function (ed) { ed.runCommand('core:copy'); ed.runCommand('core:paste', { action: 'clone-component' }); }, }; defaultCommands['tlb-move'] = { run: function (ed, sender, opts) { if (opts === void 0) { opts = {}; } var dragger; var em = ed.getModel(); var event = opts && opts.event; var target = opts.target; var sel = target || ed.getSelected(); var selAll = target ? [target] : commands_spreadArray([], ed.getSelectedAll(), true); var nativeDrag = event && event.type == 'dragstart'; var defComOptions = { preserveSelected: 1 }; var modes = ['absolute', 'translate']; if (!sel || !sel.get('draggable')) { return em.logWarning('The element is not draggable'); } var mode = sel.get('dmode') || em.get('dmode'); var hideTlb = function () { return em.stopDefault(defComOptions); }; var altMode = (0,index_all.includes)(modes, mode); selAll.forEach(function (sel) { return sel.trigger('disable'); }); // Without setTimeout the ghost image disappears nativeDrag ? setTimeout(hideTlb, 0) : hideTlb(); var onStart = function (data) { em.trigger("".concat(eventDrag, ":start"), data); }; var onDrag = function (data) { em.trigger(eventDrag, data); }; var onEnd = function (e, opts, data) { selAll.forEach(function (sel) { return sel.set('status', 'selected'); }); ed.select(selAll); sel.emitUpdate(); em.trigger("".concat(eventDrag, ":end"), data); // Defer selectComponent in order to prevent canvas "freeze" #2692 setTimeout(function () { return em.runDefault(defComOptions); }); // Dirty patch to prevent parent selection on drop (altMode || data.cancelled) && em.set('_cmpDrag', 1); }; if (altMode) { // TODO move grabbing func in editor/canvas from the Sorter dragger = ed.runCommand('core:component-drag', { guidesInfo: 1, mode: mode, target: sel, onStart: onStart, onDrag: onDrag, onEnd: onEnd, event: event, }); } else { if (nativeDrag) { event.dataTransfer.setDragImage(sel.view.el, 0, 0); //sel.set('status', 'freezed'); } var cmdMove = ed.Commands.get('move-comp'); cmdMove.onStart = onStart; cmdMove.onDrag = onDrag; cmdMove.onEndMoveFromModel = onEnd; // @ts-ignore cmdMove.initSorterFromModels(selAll); } selAll.forEach(function (sel) { return sel.set('status', 'freezed-selected'); }); }, }; // Core commands defaultCommands['core:undo'] = function (e) { return e.UndoManager.undo(); }; defaultCommands['core:redo'] = function (e) { return e.UndoManager.redo(); }; commandsDef.forEach(function (item) { var oldCmd = item[2]; var cmd = __nested_webpack_require_911993__(828)("./".concat(item[1])).default; var cmdName = "core:".concat(item[0]); defaultCommands[cmdName] = cmd; if (oldCmd) { defaultCommands[oldCmd] = cmd; // Propogate old commands (can be removed once we stop to call old commands) ['run', 'stop'].forEach(function (name) { em.on("".concat(name, ":").concat(oldCmd), function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return em.trigger.apply(em, commands_spreadArray(["".concat(name, ":").concat(cmdName)], args, false)); }); }); } }); // @ts-ignore TODO check where it's used config.model = em.Canvas; for (var id in defaultCommands) { _this.add(id, defaultCommands[id]); } return _this; } /** * Add new command to the collection * @param {string} id Command's ID * @param {Object|Function} command Object representing your command, * By passing just a function it's intended as a stateless command * (just like passing an object with only `run` method). * @return {this} * @example * commands.add('myCommand', { * run(editor, sender) { * alert('Hello world!'); * }, * stop(editor, sender) { * }, * }); * // As a function * commands.add('myCommand2', editor => { ... }); * */ CommandsModule.prototype.add = function (id, command) { var result = (0,index_all.isFunction)(command) ? { run: command } : command; if (!result.stop) { result.noStop = true; } delete result.initialize; result.id = id; this.commands[id] = CommandAbstract["default"].extend(result); return this; }; /** * Get command by ID * @param {string} id Command's ID * @return {Object} Object representing the command * @example * var myCommand = commands.get('myCommand'); * myCommand.run(); * */ CommandsModule.prototype.get = function (id) { var command = this.commands[id]; if ((0,index_all.isFunction)(command)) { command = new command(this.config); this.commands[id] = command; } else if (!command) { this.em.logWarning("'".concat(id, "' command not found")); } return command; }; /** * Extend the command. The command to extend should be defined as an object * @param {string} id Command's ID * @param {Object} Object with the new command functions * @returns {this} * @example * commands.extend('old-command', { * someInnerFunction() { * // ... * } * }); * */ CommandsModule.prototype.extend = function (id, cmd) { if (cmd === void 0) { cmd = {}; } var command = this.get(id); if (command) { var cmdObj = commands_assign(commands_assign({}, command.constructor.prototype), cmd); this.add(id, cmdObj); // Extend also old name commands if exist var oldCmd = commandsDef.filter(function (cmd) { return "core:".concat(cmd[0]) === id && cmd[2]; })[0]; oldCmd && this.add(oldCmd[2], cmdObj); } return this; }; /** * Check if command exists * @param {string} id Command's ID * @return {Boolean} * */ CommandsModule.prototype.has = function (id) { return !!this.commands[id]; }; /** * Get an object containing all the commands * @return {Object} */ CommandsModule.prototype.getAll = function () { return this.commands; }; /** * Execute the command * @param {String} id Command ID * @param {Object} [options={}] Options * @return {*} The return is defined by the command * @example * commands.run('myCommand', { someOption: 1 }); */ CommandsModule.prototype.run = function (id, options) { if (options === void 0) { options = {}; } return this.runCommand(this.get(id), options); }; /** * Stop the command * @param {String} id Command ID * @param {Object} [options={}] Options * @return {*} The return is defined by the command * @example * commands.stop('myCommand', { someOption: 1 }); */ CommandsModule.prototype.stop = function (id, options) { if (options === void 0) { options = {}; } return this.stopCommand(this.get(id), options); }; /** * Check if the command is active. You activate commands with `run` * and disable them with `stop`. If the command was created without `stop` * method it can't be registered as active * @param {String} id Command id * @return {Boolean} * @example * const cId = 'some-command'; * commands.run(cId); * commands.isActive(cId); * // -> true * commands.stop(cId); * commands.isActive(cId); * // -> false */ CommandsModule.prototype.isActive = function (id) { return this.getActive().hasOwnProperty(id); }; /** * Get all active commands * @return {Object} * @example * console.log(commands.getActive()); * // -> { someCommand: itsLastReturn, anotherOne: ... }; */ CommandsModule.prototype.getActive = function () { return this.active; }; /** * Run command via its object * @param {Object} command * @param {Object} options * @return {*} Result of the command * @private */ CommandsModule.prototype.runCommand = function (command, options) { if (options === void 0) { options = {}; } var result; if (command && command.run) { var _a = this, em = _a.em, config = _a.config; var id = command.id; var editor = em.Editor; if (!this.isActive(id) || options.force || !config.strict) { // @ts-ignore result = editor && command.callRun(editor, options); if (id && command.stop && !command.noStop && !options.abort) { this.active[id] = result; } } } return result; }; /** * Stop the command * @param {Object} command * @param {Object} options * @return {*} Result of the command * @private */ CommandsModule.prototype.stopCommand = function (command, options) { if (options === void 0) { options = {}; } var result; if (command && command.run) { var _a = this, em = _a.em, config = _a.config; var id = command.id; var editor = em.Editor; if (this.isActive(id) || options.force || !config.strict) { if (id) delete this.active[id]; // @ts-ignore result = command.callStop(editor, options); } } return result; }; /** * Create anonymous Command instance * @param {Object} command Command object * @return {Command} * @private * */ CommandsModule.prototype.create = function (command) { if (!command.stop) command.noStop = true; var cmd = CommandAbstract["default"].extend(command); return new cmd(this.config); }; CommandsModule.prototype.destroy = function () { this.defaultCommands = {}; this.commands = {}; this.active = {}; }; return CommandsModule; }(abstract_Module)); /* harmony default export */ const commands = (CommandsModule); ;// CONCATENATED MODULE: ./src/style_manager/config/config.ts /* harmony default export */ const style_manager_config_config = ({ sectors: [ { name: 'General', open: false, properties: ['display', 'float', 'position', 'top', 'right', 'left', 'bottom'], }, { name: 'Flex', open: false, properties: [ 'flex-direction', 'flex-wrap', 'justify-content', 'align-items', 'align-content', 'order', 'flex-basis', 'flex-grow', 'flex-shrink', 'align-self', ], }, { name: 'Dimension', open: false, properties: ['width', 'height', 'max-width', 'min-height', 'margin', 'padding'], }, { name: 'Typography', open: false, properties: [ 'font-family', 'font-size', 'font-weight', 'letter-spacing', 'color', 'line-height', 'text-align', 'text-shadow', ], }, { name: 'Decorations', open: false, properties: ['background-color', 'border-radius', 'border', 'box-shadow', 'background'], }, { name: 'Extra', open: false, properties: ['opacity', 'transition', 'transform'], }, ], appendTo: '', stylePrefix: 'sm-', custom: false, hideNotStylable: true, highlightChanged: true, highlightComputed: true, showComputed: true, clearProperties: true, avoidComputed: ['width', 'height'], }); ;// CONCATENATED MODULE: ./src/style_manager/model/Property.ts var Property_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var Property_assign = ( false) || function () { Property_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return Property_assign.apply(this, arguments); }; var Property_rest = ( false) || 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 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; var Property_spreadArray = ( false) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; /** * @typedef Property * @property {String} id Property id, eg. `my-property-id`. * @property {String} property Related CSS property name, eg. `text-align`. * @property {String} default Defaul value of the property. * @property {String} label Label to use in UI, eg. `Text Align`. * @property {Function} [onChange] Change callback. * \n * ```js * onChange: ({ property, from, to }) => { * console.log(`Changed property`, property.getName(), { from, to }); * } * ``` * */ var Property = /** @class */ (function (_super) { Property_extends(Property, _super); function Property() { return _super !== null && _super.apply(this, arguments) || this; } Property.getDefaults = function () { return (0,index_all.result)(this.prototype, 'defaults'); }; /** * @private * @ts-ignore */ Property.prototype.defaults = function () { return { name: '', property: '', type: '', defaults: '', info: '', value: '', icon: '', functionName: '', status: '', visible: true, fixedValues: ['initial', 'inherit'], full: false, important: false, toRequire: false, requires: undefined, requiresParent: null, parentTarget: null, }; }; Property.prototype.initialize = function (props, opts) { if (props === void 0) { props = {}; } if (opts === void 0) { opts = {}; } this.em = opts.em; var id = this.getId() || ''; var name = this.get('name') || this.get('label') || ''; // @ts-ignore !this.get('property') && this.set('property', (name || id).replace(/ /g, '-')); var prop = this.get('property'); !this.get('id') && this.set('id', prop); // @ts-ignore !name && this.set('name', (0,mixins.capitalize)(prop).replace(/-/g, ' ')); this.on('change', this.__upTargets); // @ts-ignore Property.callInit(this, props, opts); }; Property.prototype.__getParentProp = function () { var _a, _b; // @ts-ignore return (_b = (_a = this.collection) === null || _a === void 0 ? void 0 : _a.opts) === null || _b === void 0 ? void 0 : _b.parentProp; }; Property.prototype.__upTargets = function (p, opts) { var _a; var _this = this; if (opts === void 0) { opts = {}; } var em = this.em; var sm = em.Styles; var name = this.getName(); var isClear = opts.__clear; var value = isClear ? '' : this.__getFullValue(opts); var parentProp = this.__getParentProp(); var to = this.changedAttributes(); var from = (0,index_all.keys)(to).reduce(function (a, i) { a[i] = _this.previous(i); return a; }, {}); var kProps = Property_spreadArray(Property_spreadArray([], (0,index_all.keys)(this.__getClearProps()), true), ['__p'], false); var toProps = (0,index_all.keys)(to); var applyStyle = !opts.__up && !parentProp && (isClear || kProps.some(function (k) { return toProps.indexOf(k) >= 0; })); var onChange = this.get('onChange'); var evOpts = { property: this, from: from, to: to, value: value, opts: opts }; sm.__trgEv(sm.events.propertyUpdate, evOpts); onChange && onChange(evOpts); applyStyle && this.__upTargetsStyle((_a = {}, _a[name] = value, _a), opts); }; Property.prototype.__upTargetsStyle = function (style, opts) { var _a; var sm = (_a = this.em) === null || _a === void 0 ? void 0 : _a.get('StyleManager'); sm === null || sm === void 0 ? void 0 : sm.addStyleTargets(Property_assign(Property_assign({}, style), { __p: !!opts.avoidStore }), opts); }; Property.prototype._up = function (props, opts) { if (opts === void 0) { opts = {}; } if (opts.noTarget) opts.__up = true; var partial = opts.partial, rest = Property_rest(opts, ["partial"]); // @ts-ignore props.__p = !!(rest.avoidStore || partial); return this.set(props, Property_assign(Property_assign({}, rest), { avoidStore: props.__p })); }; Property.prototype.up = function (props, opts) { if (opts === void 0) { opts = {}; } // @ts-ignore this.set(props, Property_assign(Property_assign({}, opts), { __up: true })); }; Property.prototype.init = function () { }; /** * Get property id. * @returns {String} */ Property.prototype.getId = function () { return this.get('id'); }; /** * Get the property type. * The type of the property is defined on property creation and based on its value the proper Property class is assigned. * The default type is `base`. * @returns {String} */ Property.prototype.getType = function () { return this.get('type'); }; /** * Get name (the CSS property name). * @returns {String} */ Property.prototype.getName = function () { return this.get('property'); }; /** * Get property label. * @param {Object} [opts={}] Options * @param {Boolean} [opts.locale=true] Use the locale string from i18n module * @returns {String} */ Property.prototype.getLabel = function (opts) { var _a; if (opts === void 0) { opts = {}; } var _b = opts.locale, locale = _b === void 0 ? true : _b; var id = this.getId(); var name = this.get('name') || this.get('label'); return (locale && ((_a = this.em) === null || _a === void 0 ? void 0 : _a.t("styleManager.properties.".concat(id)))) || name; }; /** * Get property value. * @param {Object} [opts={}] Options * @param {Boolean} [opts.noDefault=false] Avoid returning the default value * @returns {String} */ Property.prototype.getValue = function (opts) { if (opts === void 0) { opts = {}; } var noDefault = opts.noDefault; var val = this.get('value'); return !this.hasValue() && !noDefault ? this.getDefaultValue() : val; }; /** * Check if the property has value. * @param {Object} [opts={}] Options * @param {Boolean} [opts.noParent=false] Ignore the value if it comes from the parent target. * @returns {Boolean} */ Property.prototype.hasValue = function (opts) { if (opts === void 0) { opts = {}; } var noParent = opts.noParent; var parentValue = noParent && this.getParentTarget(); var val = this.get('value'); return !(0,index_all.isUndefined)(val) && val !== '' && !parentValue; }; /** * Indicates if the current value is coming from a parent target (eg. another CSSRule). * @returns {Boolean} */ Property.prototype.hasValueParent = function () { return this.hasValue() && !this.hasValue({ noParent: true }); }; /** * Get the CSS style object of the property. * @param {Object} [opts={}] Options * @param {Boolean} [opts.camelCase] Return property name in camelCase. * @return {Object} * @example * // In case the property is `color` with a value of `red`. * console.log(property.getStyle()); * // { color: 'red' }; */ Property.prototype.getStyle = function (opts) { var _a; if (opts === void 0) { opts = {}; } var name = this.getName(); var key = opts.camelCase ? (0,mixins.camelCase)(name) : name; return _a = {}, _a[key] = this.__getFullValue(opts), _a; }; /** * Get the default value. * @return {string} */ Property.prototype.getDefaultValue = function () { var def = this.get('default'); return "".concat(!(0,index_all.isUndefined)(def) ? def : this.get('defaults')); }; /** * Update the value. * The change is also propagated to the selected targets (eg. CSS rule). * @param {String} value New value * @param {Object} [opts={}] Options * @param {Boolean} [opts.partial=false] If `true` the update on targets won't be considered complete (not stored in UndoManager) * @param {Boolean} [opts.noTarget=false] If `true` the change won't be propagated to selected targets. */ Property.prototype.upValue = function (value, opts) { if (opts === void 0) { opts = {}; } var parsed = value === null || value === '' ? this.__getClearProps() : this.__parseValue(value, opts); return this._up(parsed, opts); }; /** * Check if the property is visible * @returns {Boolean} */ Property.prototype.isVisible = function () { return !!this.get('visible'); }; /** * Clear the value. * The change is also propagated to the selected targets (eg. the css property is cleared). * @param {Object} [opts={}] Options * @param {Boolean} [opts.noTarget=false] If `true` the change won't be propagated to selected targets. */ Property.prototype.clear = function (opts) { if (opts === void 0) { opts = {}; } this._up(this.__getClearProps(), Property_assign(Property_assign({}, opts), { __clear: true })); return this; }; /** * Indicates if the current value comes directly from the selected target and so can be cleared. * @returns {Boolean} */ Property.prototype.canClear = function () { var parent = this.getParent(); return parent ? parent.__canClearProp(this) : this.hasValue({ noParent: true }); }; /** * If the current property is a sub-property, this will return the parent Property. * @returns {[Property]|null} */ Property.prototype.getParent = function () { return this.__getParentProp(); }; /** * Indicates if the property is full-width in UI. * @returns {Boolean} */ Property.prototype.isFull = function () { return !!this.get('full'); }; Property.prototype.__parseValue = function (value, opts) { return this.parseValue(value, opts); }; Property.prototype.__getClearProps = function () { return { value: '' }; }; /** * Update value * @param {any} value * @param {Boolen} [complete=true] Indicates if it's a final state * @param {Object} [opts={}] Options * @private */ Property.prototype.setValue = function (value, complete, opts) { if (complete === void 0) { complete = true; } if (opts === void 0) { opts = {}; } var parsed = this.parseValue(value); var avoidStore = !complete; // @ts-ignore !avoidStore && this.set({ value: undefined }, { avoidStore: avoidStore, silent: true }); this.set(parsed, Property_assign({ avoidStore: avoidStore }, opts)); }; /** * Like `setValue` but, in addition, prevents the update of the input element * as the changes should come from the input itself. * This method is useful with the definition of custom properties * @param {any} value * @param {Boolen} [complete=true] Indicates if it's a final state * @param {Object} [opts={}] Options * @private * @deprecated */ Property.prototype.setValueFromInput = function (value, complete, opts) { if (opts === void 0) { opts = {}; } this.setValue(value, complete, Property_assign(Property_assign({}, opts), { fromInput: 1 })); }; /** * Parse a raw value, generally fetched from the target, for this property * @param {string} value Raw value string * @return {Object} * @private * @example * // example with an Input type * prop.parseValue('translateX(10deg)'); * // -> { value: 10, unit: 'deg', functionName: 'translateX' } * */ Property.prototype.parseValue = function (value, opts) { if (opts === void 0) { opts = {}; } var result = { value: value }; var imp = '!important'; if ((0,index_all.isString)(value) && value.indexOf(imp) !== -1) { result.value = value.replace(imp, '').trim(); result.important = true; } if (!this.get('functionName') && !opts.complete) { return result; } var args = []; var valueStr = "".concat(result.value); var start = valueStr.indexOf('(') + 1; var end = valueStr.lastIndexOf(')'); var functionName = valueStr.substring(0, start - 1); if (functionName) result.functionName = functionName; args.push(start); // Will try even if the last closing parentheses is not found if (end >= 0) { args.push(end); } result.value = String.prototype.substring.apply(valueStr, args); if (opts.numeric) { var num = parseFloat(result.value); result.unit = result.value.replace(num, ''); result.value = num; } return result; }; /** * Helper function to safely split a string of values. * Useful when style values are inside functions * eg: * -> input: 'value(1,2,4), 123, value(4,5)' -- default separator: ',' * -> output: ['value(1,2,4)', '123', 'value(4,5)'] * @param {String} values Values to split * @param {String} [separator] Separator * @private */ // splitValues(values, separator = ',') { // const res = []; // const op = '('; // const cl = ')'; // let curr = ''; // let acc = 0; // (values || '').split('').forEach(str => { // if (str == op) { // acc++; // curr = curr + op; // } else if (str == cl && acc > 0) { // acc--; // curr = curr + cl; // } else if (str === separator && acc == 0) { // res.push(curr); // curr = ''; // } else { // curr = curr + str; // } // }); // curr !== '' && res.push(curr); // return res.map(i => i.trim()); // } Property.prototype.__getFullValue = function (_a) { var _b = _a === void 0 ? {} : _a, withDefault = _b.withDefault; return !this.hasValue() && withDefault ? this.getDefaultValue() : this.getFullValue(); }; /** * Get a complete value of the property. * This probably will replace the getValue when all * properties models will be splitted * @param {String} val Custom value to replace the one on the model * @return {string} * @private */ Property.prototype.getFullValue = function (val, opts) { if (opts === void 0) { opts = {}; } var fn = this.get('functionName'); var def = this.getDefaultValue(); var value = (0,index_all.isUndefined)(val) ? this.get('value') : val; var hasValue = !(0,index_all.isUndefined)(value) && value !== ''; if (value && def && value === def) { return def; } if (fn && hasValue) { var fnParameter = fn === 'url' ? "'".concat(value.replace(/'|"/g, ''), "'") : value; value = "".concat(fn, "(").concat(fnParameter, ")"); } if (hasValue && this.get('important') && !opts.skipImportant) { value = "".concat(value, " !important"); } return value || ''; }; Property.prototype.__setParentTarget = function (parentTarget) { this.up({ parentTarget: parentTarget }); }; Property.prototype.getParentTarget = function () { return this.get('parentTarget') || null; }; Property.prototype.__parseFn = function (input) { if (input === void 0) { input = ''; } var start = input.indexOf('(') + 1; var end = input.lastIndexOf(')'); return { name: input.substring(0, start - 1).trim(), value: String.prototype.substring.apply(input, [start, end >= 0 ? end : undefined]).trim(), }; }; Property.prototype.__checkVisibility = function (_a) { var target = _a.target, component = _a.component, sectors = _a.sectors; var trg = component || target; if (!trg) return false; var id = this.getId(); var property = this.getName(); var toRequire = this.get('toRequire'); var requires = this.get('requires'); var requiresParent = this.get('requiresParent'); var unstylable = trg.get('unstylable'); var stylableReq = trg.get('stylable-require'); var stylable = trg.get('stylable'); // Stylable could also be an array indicating with which property // the target could be styled if ((0,index_all.isArray)(stylable)) { stylable = stylable.indexOf(property) >= 0; } // Check if the property was signed as unstylable if ((0,index_all.isArray)(unstylable)) { stylable = unstylable.indexOf(property) < 0; } // Check if the property is available only if requested if (toRequire) { stylable = !target || (stylableReq && (stylableReq.indexOf(id) >= 0 || stylableReq.indexOf(property) >= 0)); } // Check if the property is available based on other property's values if (sectors && requires) { var properties_1 = (0,index_all.keys)(requires); sectors.forEach(function (sector) { sector.getProperties().forEach(function (model) { if ((0,index_all.includes)(properties_1, model.id)) { var values = requires[model.id]; stylable = stylable && (0,index_all.includes)(values, model.get('value')); } }); }); } // Check if the property is available based on parent's property values if (requiresParent) { var parent_1 = component && component.parent(); var parentEl = parent_1 && parent_1.getEl(); if (parentEl) { var styles_1 = (0,mixins.hasWin)() ? window.getComputedStyle(parentEl) : {}; (0,index_all.each)(requiresParent, function (values, property) { stylable = stylable && styles_1[property] && (0,index_all.includes)(values, styles_1[property]); }); } else { stylable = false; } } return !!stylable; }; return Property; }(common/* Model */.Hn)); /* harmony default export */ const model_Property = (Property); // @ts-ignore Property.callParentInit = function (property, ctx, props, opts) { if (opts === void 0) { opts = {}; } property.prototype.initialize.apply(ctx, [ props, Property_assign(Property_assign({}, opts), { skipInit: 1 }), ]); }; // @ts-ignore Property.callInit = function (context, props, opts) { if (opts === void 0) { opts = {}; } !opts.skipInit && context.init(props, opts); }; ;// CONCATENATED MODULE: ./src/style_manager/model/Layer.ts var Layer_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var Layer_assign = ( false) || function () { Layer_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return Layer_assign.apply(this, arguments); }; var Layer = /** @class */ (function (_super) { Layer_extends(Layer, _super); function Layer() { return _super !== null && _super.apply(this, arguments) || this; } Layer.prototype.defaults = function () { return { values: {}, }; }; Layer.prototype.initialize = function () { var cl = this.collection; // @ts-ignore this.prop = cl === null || cl === void 0 ? void 0 : cl.prop; }; /** * Get layer id. * @returns {String} */ Layer.prototype.getId = function () { return this.cid; }; /** * Get layer index. * @returns {Number} */ Layer.prototype.getIndex = function () { var coll = this.collection; return coll ? coll.indexOf(this) : -1; }; /** * Get layer values. * @param {Object} [opts={}] Options * @param {Boolean} [opts.camelCase] Return property names in camelCase. * @returns {Object} */ Layer.prototype.getValues = function (opts) { if (opts === void 0) { opts = {}; } var values = this.get('values'); return opts.camelCase ? Object.keys(values).reduce(function (res, key) { res[(0,mixins.camelCase)(key)] = values[key]; return res; }, {}) : values; }; /** * Get layer label. * @returns {String} */ Layer.prototype.getLabel = function () { var _a; return (_a = this.prop) === null || _a === void 0 ? void 0 : _a.getLayerLabel(this); }; /** * Check if the layer is selected. * @returns {Boolean} */ Layer.prototype.isSelected = function () { var _a; return ((_a = this.prop) === null || _a === void 0 ? void 0 : _a.getSelectedLayer()) === this; }; /** * Select the layer. */ Layer.prototype.select = function () { var _a; return (_a = this.prop) === null || _a === void 0 ? void 0 : _a.selectLayer(this); }; /** * Remove the layer. */ Layer.prototype.remove = function () { var _a; return (_a = this.prop) === null || _a === void 0 ? void 0 : _a.removeLayer(this); }; /** * Move layer to a new index. * @param {Number} index New index */ Layer.prototype.move = function (index) { var _a; return (_a = this.prop) === null || _a === void 0 ? void 0 : _a.moveLayer(this, index); }; /** * Get style object for the preview. * @param {Object} [opts={}] Options. Same of `PropertyStack.getStyleFromLayer` * @returns {Object} Style object */ Layer.prototype.getStylePreview = function (opts) { var _a; if (opts === void 0) { opts = {}; } return (_a = this.prop) === null || _a === void 0 ? void 0 : _a.getStylePreview(this, opts); }; /** * Check if the property has the preview enabled for this layer. * @returns {Boolean} */ Layer.prototype.hasPreview = function () { var _a; return !!((_a = this.prop) === null || _a === void 0 ? void 0 : _a.get('preview')); }; Layer.prototype.upValues = function (props) { if (props === void 0) { props = {}; } return this.set('values', Layer_assign(Layer_assign({}, this.getValues()), props)); }; return Layer; }(common/* Model */.Hn)); /* harmony default export */ const model_Layer = (Layer); ;// CONCATENATED MODULE: ./src/style_manager/model/Layers.ts var Layers_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var Layers = /** @class */ (function (_super) { Layers_extends(Layers, _super); function Layers() { return _super !== null && _super.apply(this, arguments) || this; } Layers.prototype.initialize = function (p, opts) { if (opts === void 0) { opts = {}; } this.prop = opts.prop; }; return Layers; }(common/* Collection */.FE)); /* harmony default export */ const model_Layers = (Layers); Layers.prototype.model = model_Layer; ;// CONCATENATED MODULE: ./src/style_manager/model/PropertyComposite.ts var PropertyComposite_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var PropertyComposite_assign = ( false) || function () { PropertyComposite_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return PropertyComposite_assign.apply(this, arguments); }; var PropertyComposite_spreadArray = ( false) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var isNumberType = function (type) { return type === 'integer' || type === 'number'; }; /** * * [Property]: property.html * * * @typedef PropertyComposite * @property {Array<Object>} properties Array of sub properties, eg. `[{ type: 'number', property: 'margin-top' }, ...]` * @property {Boolean} [detached=false] Indicate if the final CSS property is splitted (detached: `margin-top: X; margin-right: Y; ...`) or combined (not detached: `margin: X Y ...;`) * @property {String|RegExp} [separator=' '] Value used to split property values, default `" "`. * @property {String} [join=' '] Value used to join property values, default `" "`. * @property {Function} [fromStyle] Custom logic for getting property values from the target style object. * \n * ```js * fromStyle: (style) => { * const margins = parseMarginShorthand(style.margin); * return { * 'margin-top': margins.top, * // ... * }; * } * ``` * @property {Function} [toStyle] Custom logic for creating the CSS style object to apply on selected targets. * \n * ```js * toStyle: (values) => { * const top = values['margin-top'] || 0; * const right = values['margin-right'] || 0; * // ... * return { * margin: `${top} ${right} ...`, * }; * } * ``` */ var PropertyComposite = /** @class */ (function (_super) { PropertyComposite_extends(PropertyComposite, _super); function PropertyComposite() { return _super !== null && _super.apply(this, arguments) || this; } PropertyComposite.prototype.defaults = function () { return PropertyComposite_assign(PropertyComposite_assign({}, model_Property.getDefaults()), { detached: false, properties: [], separator: ' ', join: null, fromStyle: null, toStyle: null, full: true }); }; PropertyComposite.prototype.initialize = function (props, opts) { if (props === void 0) { props = {}; } if (opts === void 0) { opts = {}; } // @ts-ignore model_Property.callParentInit(model_Property, this, props, opts); var em = this.em; var properties = new model_Properties(this.get('properties') || [], { em: em, parentProp: this, }); this.set('properties', properties, { silent: true }); this.listenTo(properties, 'change', this.__upProperties); // @ts-ignore model_Property.callInit(this, props, opts); }; Object.defineProperty(PropertyComposite.prototype, "properties", { get: function () { // @ts-ignore return this.get('properties') || []; }, enumerable: false, configurable: true }); /** * Get properties. * @returns {Array<[Property]>} */ PropertyComposite.prototype.getProperties = function () { // @ts-ignore return PropertyComposite_spreadArray([], this.get('properties').models, true); }; /** * Get property by id. * @param {String} id Property id. * @returns {[Property]|null} */ PropertyComposite.prototype.getProperty = function (id) { return this.properties.filter(function (prop) { return prop.getId() === id || prop.getName() === id; })[0]; }; /** * Get property at index. * @param {Number} index * @returns {[Property]|null} */ PropertyComposite.prototype.getPropertyAt = function (index) { // @ts-ignore return this.get('properties').at(index); }; /** * Check if the property is detached. * @returns {Boolean} */ PropertyComposite.prototype.isDetached = function () { return !!this.get('detached'); }; /** * Get current values of properties. * @param {Object} [opts={}] Options * @param {Boolean} [opts.byName=false] Use property names as a key instead of the id. * @returns {Object} * @example * // In case the property is `margin` with sub properties like `margin-top`, `margin-right`, etc. * console.log(property.getValues()); * // { 'margin-top': '10px', 'margin-right': '20px', ... }; */ PropertyComposite.prototype.getValues = function (_a) { var _b = _a === void 0 ? {} : _a, byName = _b.byName; return this.getProperties().reduce(function (res, prop) { var key = byName ? prop.getName() : prop.getId(); res[key] = "".concat(prop.__getFullValue()); return res; }, {}); }; /** * Get property separator. * @returns {RegExp} */ PropertyComposite.prototype.getSeparator = function () { return this.getSplitSeparator(); }; /** * Get the join value. * @returns {String} */ PropertyComposite.prototype.getJoin = function () { return this.__getJoin(); }; /** * Get style object from current properties * @param {Object} [opts={}] Options * @param {Boolean} [opts.camelCase] Return property names in camelCase. * @returns {Object} Style object * @private */ PropertyComposite.prototype.getStyleFromProps = function (opts) { var _a; if (opts === void 0) { opts = {}; } var name = this.getName(); var join = this.__getJoin(); var toStyle = this.get('toStyle'); var values = this.getValues(); var style = {}; if (toStyle) { style = toStyle(values, { join: join, name: name, property: this }); } else { values = this.getValues({ byName: true }); if (this.isDetached()) { style = values; } else { var value = this.getProperties() .map(function (p) { return p.__getFullValue({ withDefault: 1 }); }) .filter(Boolean) .join(join); style = (_a = {}, _a[name] = value, _a); } } if (this.isDetached()) { style[name] = ''; } else { style[name] = style[name] || ''; style = PropertyComposite_assign(PropertyComposite_assign({}, style), this.getProperties().reduce(function (acc, prop) { acc[prop.getName()] = ''; return acc; }, {})); } return opts.camelCase ? Object.keys(style).reduce(function (res, key) { res[(0,mixins.camelCase)(key)] = style[key]; return res; }, {}) : style; }; PropertyComposite.prototype.getSplitSeparator = function () { return new RegExp("".concat(this.get('separator'), "(?![^\\(]*\\))")); }; PropertyComposite.prototype.__upProperties = function (p, opts) { if (opts === void 0) { opts = {}; } if (opts.__up || opts.__clearIn) return; var parentProp = this.__getParentProp(); if (parentProp) return parentProp.__upProperties(this, opts); this.__upTargetsStyleProps(opts, p); }; PropertyComposite.prototype.__upTargetsStyleProps = function (opts, prop) { var _a; if (opts === void 0) { opts = {}; } var style = this.getStyleFromProps(); if (this.isDetached() && prop) { var name_1 = prop.getName(); style = (_a = {}, _a[name_1] = style[name_1], _a); } this.__upTargetsStyle(style, opts); }; PropertyComposite.prototype._up = function (props, opts) { if (opts === void 0) { opts = {}; } this.__setProperties(this.__getSplitValue(props.value), opts); model_Property.prototype._up.call(this, props, opts); return this; }; PropertyComposite.prototype.getStyle = function (opts) { return this.getStyleFromProps(opts); }; PropertyComposite.prototype.__getFullValue = function (opts) { if (opts === void 0) { opts = {}; } if (this.isDetached() || opts.__clear) return ''; var result = this.getStyleFromProps()[this.getName()] || ''; return getLastStyleValue(result); }; PropertyComposite.prototype.__getJoin = function () { var join = this.get('join'); return (0,index_all.isString)(join) ? join : this.get('separator'); }; PropertyComposite.prototype.__styleHasProps = function (style) { if (style === void 0) { style = {}; } var name = this.getName(); var props = this.getProperties(); var nameProps = props.map(function (prop) { return prop.getName(); }); var allNameProps = PropertyComposite_spreadArray([name], nameProps, true); return allNameProps.some(function (prop) { return !(0,index_all.isUndefined)(style[prop]) && style[prop] !== ''; }); }; PropertyComposite.prototype.__splitValue = function (value, sep) { return getLastStyleValue(value) .split(sep) .map(function (value) { return value.trim(); }) .filter(Boolean); }; PropertyComposite.prototype.__splitStyleName = function (style, name, sep) { return this.__splitValue(style[name] || '', sep); }; PropertyComposite.prototype.__getSplitValue = function (value, _a) { if (value === void 0) { value = ''; } var _b = _a === void 0 ? {} : _a, byName = _b.byName; var props = this.getProperties(); var props4Nums = props.length === 4 && props.every(function (prop) { return isNumberType(prop.getType()); }); var values = this.__splitValue(value, this.getSplitSeparator()); var result = {}; props.forEach(function (prop, i) { var value = values[i]; var res = !(0,index_all.isUndefined)(value) ? value : ''; // : prop.getDefaultValue(); if (props4Nums) { // Try to get value from a shorthand: // 11px -> 11px 11px 11px 11xp // 11px 22px -> 11px 22px 11px 22xp var len = values.length; res = values[i] || values[(i % len) + (len != 1 && len % 2 ? 1 : 0)] || res; } var key = byName ? prop.getName() : prop.getId(); result[key] = res || ''; }); return result; }; PropertyComposite.prototype.__getPropsFromStyle = function (style, opts) { if (style === void 0) { style = {}; } if (opts === void 0) { opts = {}; } if (!this.__styleHasProps(style)) return null; var byName = opts.byName; var name = this.getName(); var props = this.getProperties(); var sep = this.getSplitSeparator(); var fromStyle = this.get('fromStyle'); var result = fromStyle ? fromStyle(style, { property: this, name: name, separator: sep }) : {}; if (!fromStyle) { // Get props from the main property result = this.__getSplitValue(style[name] || '', { byName: byName }); // Get props from the inner properties props.forEach(function (prop) { var value = style[prop.getName()]; var key = byName ? prop.getName() : prop.getId(); if (!(0,index_all.isUndefined)(value) && value !== '') result[key] = value; }); } return result; }; PropertyComposite.prototype.__setProperties = function (values, opts) { if (values === void 0) { values = {}; } if (opts === void 0) { opts = {}; } this.getProperties().forEach(function (prop) { var value = values[prop.getId()]; prop.__getFullValue() !== value && prop.upValue(value, opts); }); // Keep track of the values, otherwise clear() will not trigger changes. var valuesStr = (0,index_all.keys)(values) .map(function (k) { return values[k]; }) .join(' '); this.set('value', valuesStr, { silent: true }); }; PropertyComposite.prototype.clear = function () { var _this = this; this.getProperties().map(function (p) { return p.clear({ __clearIn: !_this.isDetached() }); }); model_Property.prototype.clear.call(this); return this; }; PropertyComposite.prototype.hasValue = function (opts) { return this.getProperties().some(function (prop) { return prop.hasValue(opts); }); }; PropertyComposite.prototype.getFullValue = function () { return this.__getFullValue(); }; PropertyComposite.prototype.__canClearProp = function (prop) { return this.isDetached() && prop.hasValue({ noParent: true }); }; return PropertyComposite; }(model_Property)); /* harmony default export */ const model_PropertyComposite = (PropertyComposite); ;// CONCATENATED MODULE: ./src/style_manager/model/PropertyStack.ts var PropertyStack_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var PropertyStack_assign = ( false) || function () { PropertyStack_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return PropertyStack_assign.apply(this, arguments); }; var PropertyStack_rest = ( false) || 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 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; var VALUES_REG = /,(?![^\(]*\))/; var PARTS_REG = /\s(?![^(]*\))/; /** * * [Layer]: layer.html * * * @typedef PropertyStack * @property {Boolean} [preview=false] Indicate if the layer should display a preview. * @property {String|RegExp} [layerSeparator=', '] The separator used to split layer values. * @property {String} [layerJoin=', '] Value used to join layer values. * @property {Function} [layerLabel] Custom logic for creating layer labels. * \n * ```js * layerLabel: (layer) => { * const values = layer.getValues(); * return `A: ${values['prop-a']} B: ${values['prop-b']}`; * } * ``` * */ var PropertyStack = /** @class */ (function (_super) { PropertyStack_extends(PropertyStack, _super); function PropertyStack() { return _super !== null && _super.apply(this, arguments) || this; } PropertyStack.prototype.defaults = function () { return PropertyStack_assign(PropertyStack_assign({}, model_PropertyComposite.getDefaults()), { layers: [], layerSeparator: ', ', layerJoin: '', prepend: 0, preview: false, layerLabel: null, selectedLayer: null }); }; PropertyStack.prototype.initialize = function (props, opts) { if (props === void 0) { props = {}; } if (opts === void 0) { opts = {}; } // @ts-ignore model_PropertyComposite.callParentInit(model_PropertyComposite, this, props, opts); var layers = this.get('layers'); var layersColl = new model_Layers(layers, { prop: this }); // @ts-ignore layersColl.property = this; // @ts-ignore layersColl.properties = this.get('properties'); this.set('layers', layersColl, { silent: true }); this.on('change:selectedLayer', this.__upSelected); this.listenTo(layersColl, 'add remove', this.__upLayers); // @ts-ignore model_PropertyComposite.callInit(this, props, opts); }; /** * Get all available layers. * @returns {Array<[Layer]>} */ PropertyStack.prototype.getLayers = function () { return this.__getLayers().models; }; PropertyStack.prototype.__getLayers = function () { return this.get('layers'); }; /** * Get layer by index. * @param {Number} [index=0] Layer index position. * @returns {[Layer]|null} * @example * // Get the first layer * const layerFirst = property.getLayer(0); * // Get the last layer * const layers = this.getLayers(); * const layerLast = property.getLayer(layers.length - 1); */ PropertyStack.prototype.getLayer = function (index) { if (index === void 0) { index = 0; } return this.__getLayers().at(index) || undefined; }; /** * Get selected layer. * @returns {[Layer] | undefined} */ PropertyStack.prototype.getSelectedLayer = function () { var layer = this.get('selectedLayer'); return layer && layer.getIndex() >= 0 ? layer : undefined; }; /** * Select layer. * Without a selected layer any update made on inner properties has no effect. * @param {[Layer]} layer Layer to select * @example * const layer = property.getLayer(0); * property.selectLayer(layer); */ PropertyStack.prototype.selectLayer = function (layer) { return this.set('selectedLayer', layer, { __select: true }); }; /** * Select layer by index. * @param {Number} index Index of the layer to select. * @example * property.selectLayerAt(1); */ PropertyStack.prototype.selectLayerAt = function (index) { if (index === void 0) { index = 0; } var layer = this.getLayer(index); return layer && this.selectLayer(layer); }; /** * Move layer by index. * @param {[Layer]} layer Layer to move. * @param {Number} index New layer index. * @example * const layer = property.getLayer(1); * property.moveLayer(layer, 0); */ PropertyStack.prototype.moveLayer = function (layer, index) { if (index === void 0) { index = 0; } var currIndex = layer ? layer.getIndex() : -1; if (currIndex >= 0 && (0,index_all.isNumber)(index) && index >= 0 && index < this.getLayers().length && currIndex !== index) { this.removeLayer(layer); this.__getLayers().add(layer, { at: index }); } }; /** * Add new layer to the stack. * @param {Object} [props={}] Custom property values to use in a new layer. * @param {Object} [opts={}] Options * @param {Number} [opts.at] Position index (by default the layer will be appended at the end). * @returns {[Layer]} Added layer. * @example * // Add new layer at the beginning of the stack with custom values * property.addLayer({ 'sub-prop1': 'value1', 'sub-prop2': 'value2' }, { at: 0 }); */ PropertyStack.prototype.addLayer = function (props, opts) { if (props === void 0) { props = {}; } if (opts === void 0) { opts = {}; } var values = {}; this.getProperties().forEach(function (prop) { var key = prop.getId(); var value = props[key]; values[key] = (0,index_all.isUndefined)(value) ? prop.getDefaultValue() : value; }); var layer = this.__getLayers().push({ values: values }, opts); return layer; }; /** * Remove layer. * @param {[Layer]} layer Layer to remove. * @returns {[Layer]} Removed layer * @example * const layer = property.getLayer(0); * property.removeLayer(layer); */ PropertyStack.prototype.removeLayer = function (layer) { return this.__getLayers().remove(layer); }; /** * Remove layer by index. * @param {Number} index Index of the layer to remove * @returns {[Layer]|null} Removed layer * @example * property.removeLayerAt(0); */ PropertyStack.prototype.removeLayerAt = function (index) { if (index === void 0) { index = 0; } var layer = this.getLayer(index); return layer ? this.removeLayer(layer) : null; }; /** * Get the layer label. The label can be customized with the `layerLabel` property. * @param {[Layer]} layer * @returns {String} * @example * const layer = this.getLayer(1); * const label = this.getLayerLabel(layer); */ PropertyStack.prototype.getLayerLabel = function (layer) { var result = ''; if (layer) { var layerLabel = this.get('layerLabel'); var values_1 = layer.getValues(); var index = layer.getIndex(); if (layerLabel) { result = layerLabel(layer, { index: index, values: values_1, property: this }); } else { var parts_1 = []; this.getProperties().map(function (prop) { parts_1.push(values_1[prop.getId()]); }); result = parts_1.filter(Boolean).join(' '); } } return result; }; /** * Get style object from the layer. * @param {[Layer]} layer * @param {Object} [opts={}] Options * @param {Boolean} [opts.camelCase] Return property names in camelCase. * @param {Object} [opts.number] Limit the result of the number types, eg. `number: { min: -3, max: 3 }` * @returns {Object} Style object */ PropertyStack.prototype.getStyleFromLayer = function (layer, opts) { var _a; if (opts === void 0) { opts = {}; } var join = this.__getJoin(); var joinLayers = this.__getJoinLayers(); var toStyle = this.get('toStyle'); var name = this.getName(); var values = layer.getValues(); var style; if (toStyle) { style = toStyle(values, { join: join, joinLayers: joinLayers, name: name, layer: layer, property: this, }); } else { var result = this.getProperties().map(function (prop) { var name = prop.getName(); var val = values[prop.getId()]; var value = (0,index_all.isUndefined)(val) ? prop.getDefaultValue() : val; // Limit number values if necessary (useful for previews) if (opts.number && isNumberType(prop.getType())) { var newVal = prop.parseValue(val, opts.number); value = "".concat(newVal.value).concat(newVal.unit); } return { name: name, value: value }; }); style = this.isDetached() ? result.reduce(function (acc, item) { acc[item.name] = item.value; return acc; }, {}) : (_a = {}, _a[this.getName()] = result.map(function (r) { return r.value; }).join(join), _a); } return opts.camelCase ? Object.keys(style).reduce(function (res, key) { res[(0,mixins.camelCase)(key)] = style[key]; return res; }, {}) : style; }; /** * Get preview style object from the layer. * If the property has `preview: false` the returned object will be empty. * @param {[Layer]} layer * @param {Object} [opts={}] Options. Same of `getStyleFromLayer` * @returns {Object} Style object */ PropertyStack.prototype.getStylePreview = function (layer, opts) { if (opts === void 0) { opts = {}; } var result = {}; var preview = this.get('preview'); if (preview) { result = this.getStyleFromLayer(layer, opts); } return result; }; /** * Get layer separator. * @return {RegExp} */ PropertyStack.prototype.getLayerSeparator = function () { var sep = this.get('layerSeparator'); return (0,index_all.isString)(sep) ? new RegExp("".concat(sep, "(?![^\\(]*\\))")) : sep; }; PropertyStack.prototype.__upProperties = function (prop, opts) { var _a; if (opts === void 0) { opts = {}; } var layer = this.getSelectedLayer(); if (!layer) return; layer.upValues((_a = {}, _a[prop.getId()] = prop.__getFullValue(), _a)); if (opts.__up) return; this.__upTargetsStyleProps(opts); }; PropertyStack.prototype.__upLayers = function (m, c, o) { this.__upTargetsStyleProps(o || c); }; PropertyStack.prototype.__upTargets = function (p, opts) { if (opts === void 0) { opts = {}; } if (opts.__select) return; return model_Property.prototype.__upTargets.call(this, p, opts); }; PropertyStack.prototype.__upTargetsStyleProps = function (opts) { if (opts === void 0) { opts = {}; } this.__upTargetsStyle(this.getStyleFromLayers(), opts); }; PropertyStack.prototype.__upTargetsStyle = function (style, opts) { return model_Property.prototype.__upTargetsStyle.call(this, style, opts); }; PropertyStack.prototype.__upSelected = function (_a, opts) { var _b = _a === void 0 ? {} : _a, noEvent = _b.noEvent; if (opts === void 0) { opts = {}; } var sm = this.em.Styles; var selected = this.getSelectedLayer(); var values = selected === null || selected === void 0 ? void 0 : selected.getValues(); // Update properties by layer value values && this.getProperties().forEach(function (prop) { var _a; var value = (_a = values[prop.getId()]) !== null && _a !== void 0 ? _a : ''; prop.__getFullValue() !== value && prop.upValue(value, PropertyStack_assign(PropertyStack_assign({}, opts), { __up: true })); }); !noEvent && sm.__trgEv(sm.events.layerSelect, { property: this }); }; // @ts-ignore PropertyStack.prototype._up = function (props, opts) { if (opts === void 0) { opts = {}; } var _a = props.__layers, __layers = _a === void 0 ? [] : _a, rest = PropertyStack_rest(props, ["__layers"]); // Detached props will update their layers later in sm.__upProp !this.isDetached() && this.__setLayers(__layers); this.__upSelected({ noEvent: true }, opts); model_Property.prototype._up.call(this, rest, opts); return this; }; PropertyStack.prototype.__setLayers = function (newLayers) { if (newLayers === void 0) { newLayers = []; } var layers = this.__getLayers(); var layersNew = newLayers.map(function (values) { return ({ values: values }); }); if (layers.length === layersNew.length) { layersNew.map(function (layer, n) { var _a; return (_a = layers.at(n)) === null || _a === void 0 ? void 0 : _a.upValues(layer.values); }); } else { this.__getLayers().reset(layersNew); } this.__upSelected({ noEvent: true }); }; PropertyStack.prototype.__parseValue = function (value) { var _this = this; var result = this.parseValue(value); result.__layers = value .split(VALUES_REG) .map(function (v) { return v.trim(); }) .map(function (v) { return _this.__parseLayer(v); }) .filter(Boolean); return result; }; PropertyStack.prototype.__parseLayer = function (value) { var parseFn = this.get('parseLayer'); var values = value.split(PARTS_REG); var properties = this.getProperties(); return parseFn ? parseFn({ value: value, values: values }) : properties.reduce(function (acc, prop, i) { var value = values[i]; acc[prop.getId()] = !(0,index_all.isUndefined)(value) ? value : prop.getDefaultValue(); return acc; }, {}); }; PropertyStack.prototype.__getLayersFromStyle = function (style) { var _this = this; if (style === void 0) { style = {}; } if (!this.__styleHasProps(style)) return null; var name = this.getName(); var props = this.getProperties(); var sep = this.getLayerSeparator(); var fromStyle = this.get('fromStyle'); var result = fromStyle ? fromStyle(style, { property: this, name: name, separatorLayers: sep }) : []; if (!fromStyle) { // Get layers from the main property var layers_1 = this.__splitStyleName(style, name, sep) .map(function (value) { return value.split(_this.getSplitSeparator()); }) .map(function (parts) { var result = {}; props.forEach(function (prop, i) { var value = parts[i]; result[prop.getId()] = !(0,index_all.isUndefined)(value) ? value : prop.getDefaultValue(); }); return result; }); // Get layers from the inner properties props.forEach(function (prop) { var id = prop.getId(); _this.__splitStyleName(style, prop.getName(), sep) .map(function (value) { var _a; return (_a = {}, _a[id] = value || prop.getDefaultValue(), _a); }) .forEach(function (inLayer, i) { layers_1[i] = layers_1[i] ? PropertyStack_assign(PropertyStack_assign({}, layers_1[i]), inLayer) : inLayer; }); }); result = layers_1; } return (0,index_all.isArray)(result) ? result : [result]; }; PropertyStack.prototype.getStyle = function (opts) { if (opts === void 0) { opts = {}; } return this.getStyleFromLayers(opts); }; PropertyStack.prototype.getStyleFromLayers = function (opts) { var _this = this; if (opts === void 0) { opts = {}; } var result = {}; var name = this.getName(); var layers = this.getLayers(); var props = this.getProperties(); var styles = layers.map(function (l) { return _this.getStyleFromLayer(l, opts); }); styles.forEach(function (style) { (0,index_all.keys)(style).map(function (key) { if (!result[key]) { // @ts-ignore result[key] = []; } // @ts-ignore result[key].push(style[key]); }); }); (0,index_all.keys)(result).map(function (key) { // @ts-ignore result[key] = result[key].join(_this.__getJoinLayers()); }); if (this.isDetached()) { result[name] = ''; !layers.length && props.map(function (prop) { result[prop.getName()] = ''; }); } else { var style = props.reduce(function (acc, prop) { acc[prop.getName()] = ''; return acc; }, {}); result[name] = result[name] || ''; result = PropertyStack_assign(PropertyStack_assign({}, result), style); } return result; }; PropertyStack.prototype.__getJoinLayers = function () { var join = this.get('layerJoin'); var sep = this.get('layerSeparator'); return join || ((0,index_all.isString)(sep) ? sep : join); }; PropertyStack.prototype.__getFullValue = function () { if (this.get('detached')) return ''; var style = this.getStyleFromLayers(); return getLastStyleValue(style[this.getName()]); }; /** * Extended * @private */ PropertyStack.prototype.hasValue = function (opts) { if (opts === void 0) { opts = {}; } var noParent = opts.noParent; var parentValue = noParent && this.getParentTarget(); return this.getLayers().length > 0 && !parentValue; }; /** * Extended * @private */ PropertyStack.prototype.clear = function (opts) { if (opts === void 0) { opts = {}; } this.__getLayers().reset(); this.__upTargetsStyleProps(opts); model_Property.prototype.clear.call(this); return this; }; PropertyStack.prototype.__canClearProp = function () { return false; }; return PropertyStack; }(model_PropertyComposite)); /* harmony default export */ const model_PropertyStack = (PropertyStack); ;// CONCATENATED MODULE: ./src/style_manager/view/PropertyView.ts var PropertyView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var PropertyView_assign = ( false) || function () { PropertyView_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return PropertyView_assign.apply(this, arguments); }; var PropertyView_rest = ( false) || 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 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; var PropertyView_spreadArray = ( false) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var clearProp = 'data-clear-style'; var PropertyView = /** @class */ (function (_super) { PropertyView_extends(PropertyView, _super); function PropertyView(o) { if (o === void 0) { o = {}; } var _this = _super.call(this, o) || this; (0,index_all.bindAll)(_this, '__change', '__updateStyle'); // @ts-ignore var config = o.config || {}; var em = config.em; _this.config = config; _this.em = em; _this.pfx = config.stylePrefix || ''; _this.ppfx = config.pStylePrefix || ''; _this.__destroyFn = _this.destroy ? _this.destroy.bind(_this) : function () { }; var model = _this.model; // @ts-ignore model.view = _this; // Put a sligh delay on debounce in order to execute the update // post styleManager.__upProps trigger. _this.onValueChange = (0,index_all.debounce)(_this.onValueChange.bind(_this), 10); _this.updateStatus = (0,index_all.debounce)(_this.updateStatus.bind(_this), 0); _this.listenTo(model, 'destroy remove', _this.remove); _this.listenTo(model, 'change:visible', _this.updateVisibility); _this.listenTo(model, 'change:name change:className change:full', _this.render); _this.listenTo(model, 'change:value', _this.onValueChange); _this.listenTo(model, 'change:parentTarget', _this.updateStatus); _this.listenTo(em, 'change:device', _this.onValueChange); // @ts-ignore var init = _this.init && _this.init.bind(_this); init && init(); return _this; } PropertyView.prototype.events = function () { var _a; return _a = { change: 'inputValueChanged' }, _a["click [".concat(clearProp, "]")] = 'clear', _a; }; PropertyView.prototype.template = function (model) { var _a = this, pfx = _a.pfx, ppfx = _a.ppfx; return "\n <div class=\"".concat(pfx, "label\" data-sm-label></div>\n <div class=\"").concat(ppfx, "fields\" data-sm-fields></div>\n "); }; PropertyView.prototype.templateLabel = function (model) { var _a = this, pfx = _a.pfx, em = _a.em; var parent = model.parent; var _b = model.attributes, _c = _b.icon, icon = _c === void 0 ? '' : _c, _d = _b.info, info = _d === void 0 ? '' : _d; var icons = em === null || em === void 0 ? void 0 : em.getConfig().icons; var iconClose = (icons === null || icons === void 0 ? void 0 : icons.close) || ''; return "\n <span class=\"".concat(pfx, "icon ").concat(icon, "\" title=\"").concat(info, "\">\n ").concat(model.getLabel(), "\n </span>\n ").concat(!parent ? "<div class=\"".concat(pfx, "clear\" style=\"display: none\" ").concat(clearProp, ">").concat(iconClose, "</div>") : '', "\n "); }; PropertyView.prototype.templateInput = function (model) { return "\n <div class=\"".concat(this.ppfx, "field\">\n <input placeholder=\"").concat(model.getDefaultValue(), "\"/>\n </div>\n "); }; PropertyView.prototype.remove = function () { var _this = this; common/* View */.G7.prototype.remove.apply(this, arguments); // @ts-ignore ['em', 'input', '$input', 'view'].forEach(function (i) { return (_this[i] = null); }); this.__destroyFn(this._getClbOpts()); return this; }; /** * Triggers when the status changes. The status indicates if the value of * the proprerty is changed or inherited * @private */ PropertyView.prototype.updateStatus = function () { var _a; var _b = this, model = _b.model, pfx = _b.pfx, ppfx = _b.ppfx, config = _b.config; var updatedCls = "".concat(ppfx, "four-color"); var computedCls = "".concat(ppfx, "color-warn"); var labelEl = this.$el.children(".".concat(pfx, "label")); var clearStyleEl = this.getClearEl(); var clearStyle = clearStyleEl ? clearStyleEl.style : {}; labelEl.removeClass("".concat(updatedCls, " ").concat(computedCls)); clearStyle.display = 'none'; if (model.hasValue({ noParent: true }) && config.highlightChanged) { labelEl.addClass(updatedCls); config.clearProperties && (clearStyle.display = ''); } else if (model.hasValue() && config.highlightComputed) { labelEl.addClass(computedCls); } (_a = this.parent) === null || _a === void 0 ? void 0 : _a.updateStatus(); }; /** * Clear the property from the target */ PropertyView.prototype.clear = function (ev) { ev && ev.stopPropagation(); this.model.clear(); }; /** * Get clear element * @return {HTMLElement} */ PropertyView.prototype.getClearEl = function () { if (!this.clearEl) { this.clearEl = this.el.querySelector("[".concat(clearProp, "]")); } return this.clearEl; }; /** * Triggers when the value of element input/s is changed, so have to update * the value of the model which will propogate those changes to the target */ PropertyView.prototype.inputValueChanged = function (ev) { ev && ev.stopPropagation(); // Skip the default update in case a custom emit method is defined if (this.emit) return; this.model.upValue(ev.target.value); }; PropertyView.prototype.onValueChange = function (m, val, opt) { if (opt === void 0) { opt = {}; } this.setValue(this.model.getFullValue(undefined, { skipImportant: true })); this.updateStatus(); }; /** * Update the element input. * Usually the value is a result of `model.getFullValue()` * @param {String} value The value from the model * */ PropertyView.prototype.setValue = function (value) { var model = this.model; var result = (0,index_all.isUndefined)(value) || value === '' ? model.getDefaultValue() : value; if (this.update) return this.__update(result); this.__setValueInput(result); }; PropertyView.prototype.__setValueInput = function (value) { var input = this.getInputEl(); input && (input.value = value); }; PropertyView.prototype.getInputEl = function () { if (!this.input) { this.input = this.el.querySelector('input'); } return this.input; }; PropertyView.prototype.updateVisibility = function () { this.el.style.display = this.model.isVisible() ? '' : 'none'; }; PropertyView.prototype.clearCached = function () { delete this.clearEl; delete this.input; delete this.$input; }; PropertyView.prototype.__unset = function () { var unset = this.unset && this.unset.bind(this); unset && unset(this._getClbOpts()); }; PropertyView.prototype.__update = function (value) { var update = this.update && this.update.bind(this); update && update(PropertyView_assign(PropertyView_assign({}, this._getClbOpts()), { value: value })); }; PropertyView.prototype.__change = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var emit = this.emit && this.emit.bind(this); emit && emit.apply(void 0, PropertyView_spreadArray([this._getClbOpts()], args, false)); }; PropertyView.prototype.__updateStyle = function (value, _a) { if (_a === void 0) { _a = {}; } var complete = _a.complete, partial = _a.partial, opts = PropertyView_rest(_a, ["complete", "partial"]); var model = this.model; var final = complete !== false && partial !== true; if ((0,mixins.isObject)(value)) { model.__upTargetsStyle(value, { avoidStore: !final }); } else { model.upValue(value, { partial: !final }); } }; PropertyView.prototype._getClbOpts = function () { var _a = this, model = _a.model, el = _a.el, createdEl = _a.createdEl; return { el: el, createdEl: createdEl, property: model, props: model.attributes, change: this.__change, updateStyle: this.__updateStyle, }; }; PropertyView.prototype.render = function () { this.clearCached(); var _a = this, pfx = _a.pfx, model = _a.model, el = _a.el, $el = _a.$el; var name = model.getName(); var type = model.getType(); var cls = model.get('className') || ''; var className = "".concat(pfx, "property"); // Support old integer classname var clsType = type === 'number' ? "".concat(pfx).concat(type, " ").concat(pfx, "integer") : "".concat(pfx).concat(type); this.createdEl && this.__destroyFn(this._getClbOpts()); $el.empty().append(this.template(model)); $el.find('[data-sm-label]').append(this.templateLabel(model)); var create = this.create && this.create.bind(this); this.createdEl = create && create(this._getClbOpts()); $el.find('[data-sm-fields]').append(this.createdEl || this.templateInput(model)); el.className = "".concat(className, " ").concat(clsType, " ").concat(className, "__").concat(name, " ").concat(cls).trim(); el.className += model.isFull() ? " ".concat(className, "--full") : ''; var onRender = this.onRender && this.onRender.bind(this); onRender && onRender(); this.setValue(model.getValue()); return this; }; PropertyView.prototype.onRender = function () { }; return PropertyView; }(common/* View */.G7)); /* harmony default export */ const view_PropertyView = (PropertyView); ;// CONCATENATED MODULE: ./src/style_manager/view/PropertiesView.ts var PropertiesView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var PropertiesView = /** @class */ (function (_super) { PropertiesView_extends(PropertiesView, _super); function PropertiesView(o) { var _this = _super.call(this, o) || this; _this.config = o.config || {}; _this.pfx = _this.config.stylePrefix || ''; _this.properties = []; _this.parent = o.parent; var coll = _this.collection; _this.listenTo(coll, 'add', _this.addTo); _this.listenTo(coll, 'reset', _this.render); return _this; } PropertiesView.prototype.addTo = function (model, coll, opts) { this.add(model, null, opts); }; PropertiesView.prototype.add = function (model, frag, opts) { if (opts === void 0) { opts = {}; } var _a = this, parent = _a.parent, config = _a.config; var appendTo = frag || this.el; var view = new model.typeView({ model: model, config: config }); parent && (view.parent = parent); view.render(); var rendered = view.el; this.properties.push(view); (0,dom/* appendAtIndex */.$Q)(appendTo, rendered, opts.at); }; PropertiesView.prototype.remove = function () { common/* View */.G7.prototype.remove.apply(this, arguments); this.clearItems(); return this; }; PropertiesView.prototype.clearItems = function () { this.properties.forEach(function (item) { return item.remove(); }); this.properties = []; }; PropertiesView.prototype.render = function () { var _this = this; var _a = this, $el = _a.$el, pfx = _a.pfx; this.clearItems(); var fragment = document.createDocumentFragment(); this.collection.forEach(function (model) { return _this.add(model, fragment); }); $el.empty(); $el.append(fragment); $el.attr('class', "".concat(pfx, "properties")); return this; }; return PropertiesView; }(common/* View */.G7)); /* harmony default export */ const view_PropertiesView = (PropertiesView); ;// CONCATENATED MODULE: ./src/style_manager/view/PropertyCompositeView.ts var PropertyCompositeView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var PropertyCompositeView_assign = ( false) || function () { PropertyCompositeView_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return PropertyCompositeView_assign.apply(this, arguments); }; var PropertyCompositeView = /** @class */ (function (_super) { PropertyCompositeView_extends(PropertyCompositeView, _super); function PropertyCompositeView() { return _super !== null && _super.apply(this, arguments) || this; } PropertyCompositeView.prototype.templateInput = function () { var pfx = this.pfx; return "\n <div class=\"".concat(pfx, "field ").concat(pfx, "composite\">\n <span id=\"").concat(pfx, "input-holder\"></span>\n </div>\n "); }; PropertyCompositeView.prototype.remove = function () { var _a; (_a = this.props) === null || _a === void 0 ? void 0 : _a.remove(); view_PropertyView.prototype.remove.apply(this, arguments); return this; }; PropertyCompositeView.prototype.onValueChange = function () { }; PropertyCompositeView.prototype.onRender = function () { var pfx = this.pfx; var model = this.model; var props = model.get('properties'); if (props.length && !this.props) { var detached = model.isDetached(); var propsView = new view_PropertiesView({ config: PropertyCompositeView_assign(PropertyCompositeView_assign({}, this.config), { highlightComputed: detached, highlightChanged: detached }), // @ts-ignore collection: props, parent: this, }); propsView.render(); this.$el.find("#".concat(pfx, "input-holder")).append(propsView.el); this.props = propsView; } }; PropertyCompositeView.prototype.clearCached = function () { view_PropertyView.prototype.clearCached.apply(this, arguments); delete this.props; }; return PropertyCompositeView; }(view_PropertyView)); /* harmony default export */ const view_PropertyCompositeView = (PropertyCompositeView); ;// CONCATENATED MODULE: ./src/style_manager/view/LayerView.ts var LayerView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var LayerView = /** @class */ (function (_super) { LayerView_extends(LayerView, _super); function LayerView() { return _super !== null && _super.apply(this, arguments) || this; } LayerView.prototype.events = function () { return { click: 'select', 'click [data-close-layer]': 'removeItem', 'mousedown [data-move-layer]': 'initSorter', 'touchstart [data-move-layer]': 'initSorter', }; }; LayerView.prototype.template = function () { var _a = this, pfx = _a.pfx, ppfx = _a.ppfx, em = _a.em; var icons = em === null || em === void 0 ? void 0 : em.getConfig().icons; var iconClose = (icons === null || icons === void 0 ? void 0 : icons.close) || ''; var iconMove = (icons === null || icons === void 0 ? void 0 : icons.move) || ''; return "\n <div class=\"".concat(pfx, "label-wrp\">\n <div id=\"").concat(pfx, "move\" class=\"").concat(ppfx, "no-touch-actions\" data-move-layer>\n ").concat(iconMove, "\n </div>\n <div id=\"").concat(pfx, "label\" data-label></div>\n <div id=\"").concat(pfx, "preview-box\" class=\"").concat(pfx, "layer-preview\" style=\"display: none\" data-preview-box>\n <div id=\"").concat(pfx, "preview\" class=\"").concat(pfx, "layer-preview-cnt\" data-preview></div>\n </div>\n <div id=\"").concat(pfx, "close-layer\" class=\"").concat(pfx, "btn-close\" data-close-layer>\n ").concat(iconClose, "\n </div>\n </div>\n <div id=\"").concat(pfx, "inputs\" data-properties></div>\n "); }; LayerView.prototype.initialize = function (o) { if (o === void 0) { o = {}; } var model = this.model; var config = o.config || {}; this.em = config.em; this.config = config; this.sorter = o.sorter; this.pfx = config.stylePrefix || ''; this.ppfx = config.pStylePrefix || ''; this.propertyView = o.propertyView; var pModel = this.propertyView.model; this.listenTo(model, 'destroy remove', this.remove); this.listenTo(model, 'change:values', this.updateLabel); this.listenTo(pModel, 'change:selectedLayer', this.updateVisibility); // For the sorter model.view = this; // @ts-ignore model.set({ droppable: 0, draggable: 1 }); this.$el.data('model', model); }; LayerView.prototype.initSorter = function () { var _a; (_a = this.sorter) === null || _a === void 0 ? void 0 : _a.startSort(this.el); }; LayerView.prototype.removeItem = function (ev) { ev && ev.stopPropagation(); this.model.remove(); }; LayerView.prototype.select = function () { this.model.select(); }; LayerView.prototype.getPropertiesWrapper = function () { if (!this.propsWrapEl) this.propsWrapEl = this.el.querySelector('[data-properties]'); return this.propsWrapEl; }; LayerView.prototype.getPreviewEl = function () { if (!this.previewEl) this.previewEl = this.el.querySelector('[data-preview]'); return this.previewEl; }; LayerView.prototype.getLabelEl = function () { if (!this.labelEl) this.labelEl = this.el.querySelector('[data-label]'); return this.labelEl; }; LayerView.prototype.updateLabel = function () { var model = this.model; var label = model.getLabel(); this.getLabelEl().innerHTML = label; if (model.hasPreview()) { var prvEl = this.getPreviewEl(); var style_1 = model.getStylePreview({ number: { min: -3, max: 3 } }); var styleStr = (0,index_all.keys)(style_1) .map(function (k) { return "".concat(k, ":").concat(style_1[k]); }) .join(';'); prvEl.setAttribute('style', styleStr); } }; LayerView.prototype.updateVisibility = function () { var _a; var _b = this, pfx = _b.pfx, model = _b.model, propertyView = _b.propertyView; var wrapEl = this.getPropertiesWrapper(); var isSelected = model.isSelected(); wrapEl.style.display = isSelected ? '' : 'none'; this.$el[isSelected ? 'addClass' : 'removeClass']("".concat(pfx, "active")); isSelected && wrapEl.appendChild((_a = propertyView.props) === null || _a === void 0 ? void 0 : _a.el); }; LayerView.prototype.render = function () { var _a = this, el = _a.el, pfx = _a.pfx, model = _a.model; el.innerHTML = this.template(); el.className = "".concat(pfx, "layer"); if (model.hasPreview()) { el.querySelector('[data-preview-box]').style.display = ''; } this.updateLabel(); this.updateVisibility(); return this; }; return LayerView; }(common/* View */.G7)); /* harmony default export */ const view_LayerView = (LayerView); ;// CONCATENATED MODULE: ./src/style_manager/view/LayersView.ts var LayersView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var LayersView = /** @class */ (function (_super) { LayersView_extends(LayersView, _super); function LayersView(o) { var _this = _super.call(this, o) || this; var coll = _this.collection; var config = o.config || {}; var em = config.em; var pfx = config.stylePrefix || ''; var ppfx = config.pStylePrefix || ''; _this.config = config; _this.pfx = pfx; _this.ppfx = ppfx; _this.propertyView = o.propertyView; _this.className = "".concat(pfx, "layers ").concat(ppfx, "field"); _this.listenTo(coll, 'add', _this.addTo); _this.listenTo(coll, 'reset', _this.reset); _this.items = []; // For the Sorter var utils = em === null || em === void 0 ? void 0 : em.Utils; _this.sorter = utils ? new utils.Sorter({ // @ts-ignore container: _this.el, ignoreViewChildren: 1, containerSel: ".".concat(pfx, "layers"), itemSel: ".".concat(pfx, "layer"), pfx: config.pStylePrefix, em: em, }) : ''; // @ts-ignore coll.view = _this; _this.$el.data('model', coll); _this.$el.data('collection', coll); return _this; } LayersView.prototype.addTo = function (model) { var i = this.collection.indexOf(model); this.addToCollection(model, null, i); }; LayersView.prototype.addToCollection = function (model, fragmentEl, index) { var fragment = fragmentEl || null; var _a = this, propertyView = _a.propertyView, config = _a.config, sorter = _a.sorter, $el = _a.$el; var view = new view_LayerView({ model: model, // @ts-ignore config: config, sorter: sorter, propertyView: propertyView, }); var rendered = view.render().el; this.items.push(view); if (fragment) { fragment.appendChild(rendered); } else { if (typeof index != 'undefined') { var method = 'before'; if ($el.children().length === index) { index--; method = 'after'; } if (index < 0) { $el.append(rendered); } else { // @ts-ignore $el.children().eq(index)[method](rendered); } } else { $el.append(rendered); } } return rendered; }; LayersView.prototype.reset = function (coll, opts) { this.clearItems(); this.render(); }; LayersView.prototype.remove = function () { this.clearItems(); common/* View */.G7.prototype.remove.apply(this, arguments); return this; }; LayersView.prototype.clearItems = function () { this.items.forEach(function (item) { return item.remove(); }); this.items = []; }; LayersView.prototype.render = function () { var _this = this; var _a = this, $el = _a.$el, sorter = _a.sorter; var frag = document.createDocumentFragment(); $el.empty(); this.collection.forEach(function (m) { return _this.addToCollection(m, frag); }); $el.append(frag); $el.attr('class', this.className); if (sorter) sorter.plh = null; return this; }; return LayersView; }(common/* View */.G7)); /* harmony default export */ const view_LayersView = (LayersView); ;// CONCATENATED MODULE: ./src/style_manager/view/PropertyStackView.ts var PropertyStackView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var PropertyStackView_assign = ( false) || function () { PropertyStackView_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return PropertyStackView_assign.apply(this, arguments); }; var PropertyStackView = /** @class */ (function (_super) { PropertyStackView_extends(PropertyStackView, _super); function PropertyStackView() { return _super !== null && _super.apply(this, arguments) || this; } PropertyStackView.prototype.events = function () { return PropertyStackView_assign(PropertyStackView_assign({}, view_PropertyCompositeView.prototype.events()), { 'click [data-add-layer]': 'addLayer', change: '' }); }; PropertyStackView.prototype.templateInput = function () { var _a = this, pfx = _a.pfx, em = _a.em; var icons = em === null || em === void 0 ? void 0 : em.getConfig().icons; var iconPlus = (icons === null || icons === void 0 ? void 0 : icons.plus) || '+'; return "\n <div class=\"".concat(pfx, "field ").concat(pfx, "stack\">\n <button type=\"button\" id=\"").concat(pfx, "add\" data-add-layer>\n ").concat(iconPlus, "\n </button>\n <div data-layers-wrapper></div>\n </div>\n "); }; PropertyStackView.prototype.init = function () { var model = this.model; this.listenTo(model.__getLayers(), 'change reset', this.updateStatus); }; PropertyStackView.prototype.addLayer = function () { this.model.addLayer({}, { at: 0 }); }; /** * There is no need to handle input update by the property itself, * this will be done by layers * @private */ PropertyStackView.prototype.setValue = function () { }; PropertyStackView.prototype.remove = function () { var _a; (_a = this.layersView) === null || _a === void 0 ? void 0 : _a.remove(); view_PropertyCompositeView.prototype.remove.apply(this, arguments); return this; }; PropertyStackView.prototype.clearCached = function () { view_PropertyCompositeView.prototype.clearCached.apply(this, arguments); delete this.layersView; }; PropertyStackView.prototype.onRender = function () { var _a = this, model = _a.model, el = _a.el, config = _a.config; var props = model.get('properties'); if (props.length && !this.props) { var propsView = new view_PropertiesView({ config: PropertyStackView_assign(PropertyStackView_assign({}, config), { highlightComputed: false, highlightChanged: false }), // @ts-ignore collection: props, parent: this, }); propsView.render(); var layersView = new view_LayersView({ collection: model.__getLayers(), // @ts-ignore config: config, propertyView: this, }); layersView.render(); var fieldEl = el.querySelector('[data-layers-wrapper]'); fieldEl.appendChild(layersView.el); this.props = propsView; this.layersView = layersView; } }; return PropertyStackView; }(view_PropertyCompositeView)); /* harmony default export */ const view_PropertyStackView = (PropertyStackView); ;// CONCATENATED MODULE: ./src/style_manager/view/PropertyFileView.ts var PropertyFileView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var PropertyFileView_assign = ( false) || function () { PropertyFileView_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return PropertyFileView_assign.apply(this, arguments); }; var PropertyFileView = /** @class */ (function (_super) { PropertyFileView_extends(PropertyFileView, _super); function PropertyFileView() { return _super !== null && _super.apply(this, arguments) || this; } PropertyFileView.prototype.events = function () { return PropertyFileView_assign(PropertyFileView_assign({}, view_PropertyView.prototype.events()), { 'click [data-clear-asset]': 'clear', 'click [data-open-assets]': 'openAssetManager' }); }; PropertyFileView.prototype.templateInput = function () { var _a; var _b = this, pfx = _b.pfx, em = _b.em; var icons = (_a = this.em) === null || _a === void 0 ? void 0 : _a.getConfig().icons; var iconClose = icons === null || icons === void 0 ? void 0 : icons.close; return "\n <div class=\"".concat(pfx, "field ").concat(pfx, "file\">\n <div id='").concat(pfx, "input-holder'>\n <div class=\"").concat(pfx, "btn-c\">\n <button class=\"").concat(pfx, "btn\" id=\"").concat(pfx, "images\" type=\"button\" data-open-assets>\n ").concat(em.t('styleManager.fileButton'), "\n </button>\n </div>\n <div style=\"clear:both;\"></div>\n </div>\n <div id=\"").concat(pfx, "preview-box\" class=\"").concat(pfx, "preview-file\" data-preview-box>\n <div id=\"").concat(pfx, "preview-file\" class=\"").concat(pfx, "preview-file-cnt\" data-preview></div>\n <div id=\"").concat(pfx, "close\" class=\"").concat(pfx, "preview-file-close\" data-clear-asset>").concat(iconClose, "</div>\n </div>\n </div>\n "); }; PropertyFileView.prototype.__setValueInput = function (value) { var _a = this, model = _a.model, el = _a.el; var valueDef = model.getDefaultValue(); var prvBoxEl = el.querySelector('[data-preview-box]'); var prvEl = el.querySelector('[data-preview]'); prvBoxEl.style.display = !value || value === valueDef ? 'none' : ''; prvEl.style.backgroundImage = value || model.getDefaultValue(); }; PropertyFileView.prototype.openAssetManager = function () { var _this = this; var _a; var am = (_a = this.em) === null || _a === void 0 ? void 0 : _a.Assets; am === null || am === void 0 ? void 0 : am.open({ select: function (asset, complete) { var url = (0,index_all.isString)(asset) ? asset : asset.get('src'); _this.model.upValue(url, { partial: !complete }); complete && am.close(); }, types: ['image'], accept: 'image/*', }); }; return PropertyFileView; }(view_PropertyView)); /* harmony default export */ const view_PropertyFileView = (PropertyFileView); ;// CONCATENATED MODULE: ./src/style_manager/view/PropertyNumberView.ts var PropertyNumberView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var PropertyNumberView = /** @class */ (function (_super) { PropertyNumberView_extends(PropertyNumberView, _super); function PropertyNumberView() { return _super !== null && _super.apply(this, arguments) || this; } PropertyNumberView.prototype.templateInput = function (m) { return ''; }; PropertyNumberView.prototype.init = function () { var model = this.model; this.listenTo(model, 'change:unit', this.onValueChange); this.listenTo(model, 'change:units', this.render); }; PropertyNumberView.prototype.setValue = function (v) { // handled by this.inputInst }; PropertyNumberView.prototype.onRender = function () { var _a = this, ppfx = _a.ppfx, model = _a.model, el = _a.el; if (!this.inputInst) { var input = model.input; input.ppfx = ppfx; input.render(); var fields = el.querySelector(".".concat(ppfx, "fields")); fields.appendChild(input.el); this.input = input.inputEl.get(0); this.inputInst = input; } }; PropertyNumberView.prototype.clearCached = function () { view_PropertyView.prototype.clearCached.apply(this, arguments); this.inputInst = null; }; return PropertyNumberView; }(view_PropertyView)); /* harmony default export */ const view_PropertyNumberView = (PropertyNumberView); ;// CONCATENATED MODULE: ./src/style_manager/view/PropertyColorView.ts var PropertyColorView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var PropertyColorView = /** @class */ (function (_super) { PropertyColorView_extends(PropertyColorView, _super); function PropertyColorView() { return _super !== null && _super.apply(this, arguments) || this; } PropertyColorView.prototype.setValue = function (value) { var _a; (_a = this.inputInst) === null || _a === void 0 ? void 0 : _a.setValue(value, { fromTarget: 1, def: this.model.getDefaultValue(), }); }; PropertyColorView.prototype.remove = function () { var _this = this; view_PropertyNumberView.prototype.remove.apply(this, arguments); var inp = this.inputInst; inp && inp.remove && inp.remove(); // @ts-ignore ['inputInst', '$color'].forEach(function (i) { return (_this[i] = null); }); return this; }; PropertyColorView.prototype.__handleChange = function (value, partial) { this.model.upValue(value, { partial: partial }); }; PropertyColorView.prototype.onRender = function () { var _a; if (!this.inputInst) { this.__handleChange = this.__handleChange.bind(this); var _b = this, ppfx = _b.ppfx, model = _b.model, em = _b.em, el = _b.el; var inputColor = new ui_InputColor({ target: em, model: model, ppfx: ppfx, onChange: this.__handleChange, }); var input = inputColor.render(); el.querySelector(".".concat(ppfx, "fields")).appendChild(input.el); this.input = (_a = input.inputEl) === null || _a === void 0 ? void 0 : _a.get(0); this.inputInst = input; } }; return PropertyColorView; }(view_PropertyNumberView)); /* harmony default export */ const view_PropertyColorView = (PropertyColorView); ;// CONCATENATED MODULE: ./src/style_manager/model/PropertySelect.ts var PropertySelect_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var PropertySelect_assign = ( false) || function () { PropertySelect_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return PropertySelect_assign.apply(this, arguments); }; var PropertySelect_spreadArray = ( false) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; /** * @typedef PropertySelect * @property {Array<Object>} options Array of option definitions. * \n * ```js * options: [ * { id: '100', label: 'Set 100' }, * { id: '200', label: 'Set 200' }, * ] * ``` */ var PropertySelect = /** @class */ (function (_super) { PropertySelect_extends(PropertySelect, _super); function PropertySelect() { return _super !== null && _super.apply(this, arguments) || this; } PropertySelect.prototype.defaults = function () { return PropertySelect_assign(PropertySelect_assign({}, model_Property.getDefaults()), { options: [], full: 0 }); }; /** * Get available options. * @returns {Array<Object>} Array of options */ PropertySelect.prototype.getOptions = function () { // support old list property var _a = this.attributes, options = _a.options, list = _a.list; return (options && options.length ? options : list) || []; }; /** * Get current selected option or by id. * @param {String} [id] Option id. * @returns {Object | null} */ PropertySelect.prototype.getOption = function (id) { var _this = this; var idSel = (0,mixins.isDef)(id) ? id : this.getValue(); return this.getOptions().filter(function (o) { return _this.getOptionId(o) === idSel; })[0] || null; }; /** * Update options. * @param {Array<Object>} value New array of options, eg. `[{ id: 'val-1', label: 'Value 1' }]` */ PropertySelect.prototype.setOptions = function (value) { if (value === void 0) { value = []; } this.set('options', value); return this; }; /** * Add new option. * @param {Object} value Option object, eg. `{ id: 'val-1', label: 'Value 1' }` */ PropertySelect.prototype.addOption = function (value) { if (value) { var opts = this.getOptions(); this.setOptions(PropertySelect_spreadArray(PropertySelect_spreadArray([], opts, true), [value], false)); } return this; }; /** * Get the option id from the option object. * @param {Object} option Option object * @returns {String} Option id */ PropertySelect.prototype.getOptionId = function (option) { return (0,mixins.isDef)(option.id) ? option.id : option.value; }; /** * Get option label. * @param {String|Object} id Option id or the option object * @param {Object} [opts={}] Options * @param {Boolean} [opts.locale=true] Use the locale string from i18n module * @returns {String} Option label */ PropertySelect.prototype.getOptionLabel = function (id, opts) { var _a; if (opts === void 0) { opts = {}; } var _b = opts.locale, locale = _b === void 0 ? true : _b; var option = ((0,index_all.isString)(id) ? this.getOption(id) : id) || {}; var optId = this.getOptionId(option); var label = option.label || option.name || optId; var propId = opts.property || this.getId(); return (locale && ((_a = this.em) === null || _a === void 0 ? void 0 : _a.t("styleManager.options.".concat(propId, ".").concat(optId)))) || label; }; PropertySelect.prototype.initialize = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } model_Property.prototype.initialize.apply(this, args); this.listenTo(this, 'change:options', this.__onOptionChange); }; PropertySelect.prototype.__onOptionChange = function () { this.set('list', this.get('options')); }; return PropertySelect; }(model_Property)); /* harmony default export */ const model_PropertySelect = (PropertySelect); ;// CONCATENATED MODULE: ./src/style_manager/view/PropertySelectView.ts var PropertySelectView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var PropertySelectView = /** @class */ (function (_super) { PropertySelectView_extends(PropertySelectView, _super); function PropertySelectView(o) { var _this = _super.call(this, o) || this; _this.listenTo(_this.model, 'change:options', _this.updateOptions); return _this; } PropertySelectView.prototype.templateInput = function () { var _a = this, pfx = _a.pfx, ppfx = _a.ppfx; return "\n <div class=\"".concat(ppfx, "field ").concat(ppfx, "select\">\n <span id=\"").concat(pfx, "input-holder\"></span>\n <div class=\"").concat(ppfx, "sel-arrow\">\n <div class=\"").concat(ppfx, "d-s-arrow\"></div>\n </div>\n </div>\n "); }; PropertySelectView.prototype.updateOptions = function () { delete this.input; this.onRender(); }; PropertySelectView.prototype.onRender = function () { var pfx = this.pfx; var model = this.model; var options = model.getOptions(); if (!this.input) { var optionsRes_1 = []; options.forEach(function (option) { var id = model.getOptionId(option); var name = model.getOptionLabel(id); var style = option.style ? option.style.replace(/"/g, '"') : ''; var styleAttr = style ? "style=\"".concat(style, "\"") : ''; var value = id.replace(/"/g, '"'); optionsRes_1.push("<option value=\"".concat(value, "\" ").concat(styleAttr, ">").concat(name, "</option>")); }); var inputH = this.el.querySelector("#".concat(pfx, "input-holder")); inputH.innerHTML = "<select>".concat(optionsRes_1.join(''), "</select>"); this.input = inputH.firstChild; } }; PropertySelectView.prototype.__setValueInput = function (value) { var model = this.model; var input = this.getInputEl(); var firstOpt = model.getOptions()[0]; var firstId = firstOpt ? model.getOptionId(firstOpt) : ''; input && (input.value = value || firstId); }; return PropertySelectView; }(view_PropertyView)); /* harmony default export */ const view_PropertySelectView = (PropertySelectView); ;// CONCATENATED MODULE: ./src/style_manager/model/PropertyRadio.ts var PropertyRadio_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var PropertyRadio_assign = ( false) || function () { PropertyRadio_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return PropertyRadio_assign.apply(this, arguments); }; var PropertyRadio = /** @class */ (function (_super) { PropertyRadio_extends(PropertyRadio, _super); function PropertyRadio() { return _super !== null && _super.apply(this, arguments) || this; } PropertyRadio.prototype.defaults = function () { return PropertyRadio_assign(PropertyRadio_assign({}, model_PropertySelect.getDefaults()), { full: 1 }); }; return PropertyRadio; }(model_PropertySelect)); /* harmony default export */ const model_PropertyRadio = (PropertyRadio); ;// CONCATENATED MODULE: ./src/style_manager/view/PropertyRadioView.ts var PropertyRadioView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var PropertyRadioView = /** @class */ (function (_super) { PropertyRadioView_extends(PropertyRadioView, _super); function PropertyRadioView() { return _super !== null && _super.apply(this, arguments) || this; } PropertyRadioView.prototype.templateInput = function () { var ppfx = this.ppfx; return "<div class=\"".concat(ppfx, "field ").concat(ppfx, "field-radio\"></div>"); }; PropertyRadioView.prototype.onRender = function () { var _a = this, pfx = _a.pfx, ppfx = _a.ppfx; var model = this.model; var itemCls = "".concat(ppfx, "radio-item-label"); var prop = model.getName(); var options = model.getOptions(); var clsInput = "".concat(pfx, "radio ").concat(pfx, "radio-").concat(prop); var cid = model.cid; if (!this.input) { var optionsRes_1 = []; options.forEach(function (opt) { var cls = opt.className ? "".concat(opt.className, " ").concat(pfx, "icon ").concat(itemCls) : ''; var id = model.getOptionId(opt); var elId = "".concat(prop, "-").concat(id, "-").concat(cid); var labelEl = cls ? '' : model.getOptionLabel(id); var titleAttr = opt.title ? "title=\"".concat(opt.title, "\"") : ''; var checked = model.getValue() === id ? 'checked' : ''; optionsRes_1.push("\n <div class=\"".concat(ppfx, "radio-item\">\n <input type=\"radio\" class=\"").concat(clsInput, "\" id=\"").concat(elId, "\" name=\"").concat(prop, "-").concat(cid, "\" value=\"").concat(id, "\" ").concat(checked, "/>\n <label class=\"").concat(cls || itemCls, "\" ").concat(titleAttr, " for=\"").concat(elId, "\">").concat(labelEl, "</label>\n </div>\n ")); }); var inputHld = this.el.querySelector(".".concat(ppfx, "field")); inputHld.innerHTML = "<div class=\"".concat(ppfx, "radio-items\">").concat(optionsRes_1.join(''), "</div>"); this.input = inputHld.firstChild; } }; PropertyRadioView.prototype.__setValueInput = function (value) { var _a; var model = this.model; var id = value || model.getDefaultValue(); var inputIn = (_a = this.getInputEl()) === null || _a === void 0 ? void 0 : _a.querySelector("[value=\"".concat(id, "\"]")); inputIn && (inputIn.checked = true); }; return PropertyRadioView; }(view_PropertySelectView)); /* harmony default export */ const view_PropertyRadioView = (PropertyRadioView); ;// CONCATENATED MODULE: ./src/style_manager/model/PropertyNumber.ts var PropertyNumber_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var PropertyNumber_assign = ( false) || function () { PropertyNumber_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return PropertyNumber_assign.apply(this, arguments); }; /** * @typedef PropertyNumber * @property {Array<String>} units Array of units, eg. `['px', '%']` * @property {Number} min Minimum value. * @property {Number} max Maximum value. * @property {Number} step Step value. * */ var PropertyNumber = /** @class */ (function (_super) { PropertyNumber_extends(PropertyNumber, _super); function PropertyNumber() { return _super !== null && _super.apply(this, arguments) || this; } PropertyNumber.prototype.defaults = function () { return PropertyNumber_assign(PropertyNumber_assign({}, model_Property.getDefaults()), { units: [], unit: '', min: '', max: '', step: 1 }); }; /** * Get property units. * @returns {Array<String>} */ PropertyNumber.prototype.getUnits = function () { return this.get('units') || []; }; /** * Get property unit value. * @returns {String} */ PropertyNumber.prototype.getUnit = function () { return this.get('unit'); }; /** * Get min value. * @returns {Number} */ PropertyNumber.prototype.getMin = function () { return this.get('min'); }; /** * Get max value. * @returns {Number} */ PropertyNumber.prototype.getMax = function () { return this.get('max'); }; /** * Get step value. * @returns {Number} */ PropertyNumber.prototype.getStep = function () { return this.get('step'); }; /** * Update property unit value. * The change is also propagated to the selected targets. * @param {String} unit New unit value * @param {Object} [opts={}] Options * @param {Boolean} [opts.noTarget=false] If `true` the change won't be propagated to selected targets. * @returns {String} */ PropertyNumber.prototype.upUnit = function (unit, opts) { if (opts === void 0) { opts = {}; } return this._up({ unit: unit }, opts); }; PropertyNumber.prototype.initialize = function (props, opts) { if (props === void 0) { props = {}; } if (opts === void 0) { opts = {}; } // @ts-ignore model_Property.callParentInit(model_Property, this, props, opts); var unit = this.get('unit'); var units = this.getUnits(); this.input = (0,mixins.hasWin)() ? new ui_InputNumber({ model: this }) : undefined; if (units.length && !unit) { this.set('unit', units[0], { silent: true }); } // @ts-ignore model_Property.callInit(this, props, opts); }; PropertyNumber.prototype.__getClearProps = function () { return PropertyNumber_assign(PropertyNumber_assign({}, model_Property.prototype.__getClearProps()), { unit: '' }); }; PropertyNumber.prototype.parseValue = function (val, opts) { if (opts === void 0) { opts = {}; } var parsed = model_Property.prototype.parseValue.apply(this, arguments); var _a = this.input.validateInputValue(parsed.value, PropertyNumber_assign({ deepCheck: 1 }, opts)), value = _a.value, unit = _a.unit; parsed.value = value; parsed.unit = unit; return parsed; }; PropertyNumber.prototype.getFullValue = function () { var valueProp = this.get('value'); var unitProp = this.get('unit'); var value = !(0,index_all.isUndefined)(valueProp) ? "".concat(valueProp) : ''; var unit = !(0,index_all.isUndefined)(unitProp) && value ? unitProp : ''; var result = "".concat(value).concat(unit); return model_Property.prototype.getFullValue.apply(this, [result]); }; return PropertyNumber; }(model_Property)); /* harmony default export */ const model_PropertyNumber = (PropertyNumber); ;// CONCATENATED MODULE: ./src/style_manager/model/PropertySlider.ts var PropertySlider_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var PropertySlider_assign = ( false) || function () { PropertySlider_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return PropertySlider_assign.apply(this, arguments); }; var PropertySlider = /** @class */ (function (_super) { PropertySlider_extends(PropertySlider, _super); function PropertySlider() { return _super !== null && _super.apply(this, arguments) || this; } PropertySlider.prototype.defaults = function () { return PropertySlider_assign(PropertySlider_assign({}, model_PropertyNumber.getDefaults()), { showInput: 1 }); }; return PropertySlider; }(model_PropertyNumber)); /* harmony default export */ const model_PropertySlider = (PropertySlider); ;// CONCATENATED MODULE: ./src/style_manager/view/PropertySliderView.ts var PropertySliderView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var PropertySliderView_assign = ( false) || function () { PropertySliderView_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return PropertySliderView_assign.apply(this, arguments); }; var PropertySliderView = /** @class */ (function (_super) { PropertySliderView_extends(PropertySliderView, _super); function PropertySliderView() { return _super !== null && _super.apply(this, arguments) || this; } PropertySliderView.prototype.events = function () { return PropertySliderView_assign(PropertySliderView_assign({}, view_PropertyNumberView.prototype.events()), { 'change [type=range]': 'inputValueChanged', 'input [type=range]': 'inputValueChangedSoft', change: '' }); }; PropertySliderView.prototype.templateInput = function (model) { var ppfx = this.ppfx; return "\n <div class=\"".concat(ppfx, "field ").concat(ppfx, "field-range\">\n <input type=\"range\" min=\"").concat(model.get('min'), "\" max=\"").concat(model.get('max'), "\" step=\"").concat(model.get('step'), "\"/>\n </div>\n "); }; PropertySliderView.prototype.getSliderEl = function () { if (!this.slider) { this.slider = this.el.querySelector('input[type=range]'); } return this.slider; }; PropertySliderView.prototype.inputValueChanged = function (ev) { ev.stopPropagation(); this.model.upValue(this.getSliderEl().value); }; PropertySliderView.prototype.inputValueChangedSoft = function (ev) { ev.stopPropagation(); this.model.upValue(this.getSliderEl().value, { partial: true }); }; PropertySliderView.prototype.setValue = function (value) { var model = this.model; var parsed = model.parseValue(value); // @ts-ignore this.getSliderEl().value = value === '' ? model.getDefaultValue() : parseFloat(parsed.value); view_PropertyNumberView.prototype.setValue.apply(this, arguments); }; PropertySliderView.prototype.onRender = function () { view_PropertyNumberView.prototype.onRender.apply(this, arguments); // @ts-ignore if (!this.model.get('showInput')) { this.inputInst.el.style.display = 'none'; } }; PropertySliderView.prototype.clearCached = function () { view_PropertyNumberView.prototype.clearCached.apply(this, arguments); delete this.slider; }; return PropertySliderView; }(view_PropertyNumberView)); /* harmony default export */ const view_PropertySliderView = (PropertySliderView); ;// CONCATENATED MODULE: ./src/style_manager/model/Properties.ts var Properties_TypeableCollectionExt = common/* Collection */.FE.extend(model_TypeableCollection); var Properties = Properties_TypeableCollectionExt.extend({ extendViewApi: 1, init: function () { var _a = this, opts = _a.opts, em = _a.em; var sm = opts.module || (em === null || em === void 0 ? void 0 : em.get('StyleManager')); if (sm) { sm.__listenAdd(this, sm.events.propertyAdd); sm.__listenRemove(this, sm.events.propertyRemove); } }, types: [ { id: 'stack', model: model_PropertyStack, view: view_PropertyStackView, isType: function (value) { if (value && value.type == 'stack') { return value; } }, }, { id: 'composite', model: model_PropertyComposite, view: view_PropertyCompositeView, isType: function (value) { if (value && value.type == 'composite') { return value; } }, }, { id: 'file', model: model_Property, view: view_PropertyFileView, isType: function (value) { if (value && value.type == 'file') { return value; } }, }, { id: 'color', model: model_Property, view: view_PropertyColorView, isType: function (value) { if (value && value.type == 'color') { return value; } }, }, { id: 'select', model: model_PropertySelect, view: view_PropertySelectView, isType: function (value) { if (value && value.type == 'select') { return value; } }, }, { id: 'radio', model: model_PropertyRadio, view: view_PropertyRadioView, isType: function (value) { if (value && value.type == 'radio') { return value; } }, }, { id: 'slider', model: model_PropertySlider, view: view_PropertySliderView, isType: function (value) { if (value && value.type == 'slider') { return value; } }, }, { id: 'integer', model: model_PropertyNumber, view: view_PropertyNumberView, isType: function (value) { if (value && value.type == 'integer') { return value; } }, }, { id: 'number', model: model_PropertyNumber, view: view_PropertyNumberView, isType: function (value) { if (value && value.type == 'number') { return value; } }, }, { id: 'base', model: model_Property, view: view_PropertyView, isType: function (value) { value.type = 'base'; return value; }, }, ], }); /* harmony default export */ const model_Properties = (Properties); ;// CONCATENATED MODULE: ./src/style_manager/model/Sector.ts var Sector_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var Sector_assign = ( false) || function () { Sector_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return Sector_assign.apply(this, arguments); }; var Sector_rest = ( false) || 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 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; var Sector_spreadArray = ( false) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; /** * * [Property]: property.html * * @typedef Sector * @property {String} id Sector id, eg. `typography` * @property {String} name Sector name, eg. `Typography` * @property {Boolean} [open=true] Indicates the open state. * @property {Array<Object>} [properties=[]] Indicate an array of Property defintions. */ var Sector = /** @class */ (function (_super) { Sector_extends(Sector, _super); /** * @hideconstructor */ function Sector(prp, opts) { if (opts === void 0) { opts = {}; } var _this = _super.call(this, prp) || this; var em = opts.em; _this.em = em; var o = prp || {}; var builded = _this.buildProperties(o.buildProps); var name = _this.get('name') || ''; var props = []; !_this.get('id') && _this.set('id', name.replace(/ /g, '_').toLowerCase()); if (!builded) { props = _this.get('properties') .map(function (prop) { return ((0,index_all.isString)(prop) ? _this.buildProperties(prop)[0] : prop); }) .filter(Boolean); } else { props = _this.extendProperties(builded); } props = props.map(function (prop) { return _this.checkExtend(prop); }); var propsModel = new model_Properties(props, { em: em }); propsModel.sector = _this; _this.set('properties', propsModel); return _this; } Sector.prototype.defaults = function () { return { id: '', name: '', open: true, visible: true, extendBuilded: true, properties: [], }; }; Object.defineProperty(Sector.prototype, "properties", { get: function () { return this.get('properties'); }, enumerable: false, configurable: true }); /** * Get sector id. * @returns {String} */ Sector.prototype.getId = function () { return this.get('id'); }; /** * Get sector name. * @returns {String} */ Sector.prototype.getName = function () { var _a; var id = this.getId(); return ((_a = this.em) === null || _a === void 0 ? void 0 : _a.t("styleManager.sectors.".concat(id))) || this.get('name'); }; /** * Update sector name. * @param {String} value New sector name */ Sector.prototype.setName = function (value) { return this.set('name', value); }; /** * Check if the sector is open * @returns {Boolean} */ Sector.prototype.isOpen = function () { return !!this.get('open'); }; /** * Update Sector open state * @param {Boolean} value */ Sector.prototype.setOpen = function (value) { return this.set('open', value); }; /** * Check if the sector is visible * @returns {Boolean} */ Sector.prototype.isVisible = function () { return !!this.get('visible'); }; /** * Get sector properties. * @param {Object} [opts={}] Options * @param {Boolean} [opts.withValue=false] Get only properties with value * @param {Boolean} [opts.withParentValue=false] Get only properties with parent value * @returns {Array<[Property]>} */ Sector.prototype.getProperties = function (opts) { if (opts === void 0) { opts = {}; } var props = this.get('properties'); var res = (props.models ? Sector_spreadArray([], props.models, true) : props); return res.filter(function (prop) { var result = true; if (opts.withValue) { result = prop.hasValue({ noParent: true }); } if (opts.withParentValue) { var hasVal = prop.hasValue({ noParent: true }); result = !hasVal && prop.hasValue(); } return result; }); }; Sector.prototype.getProperty = function (id) { return this.getProperties().filter(function (prop) { return prop.get('id') === id; })[0] || undefined; }; Sector.prototype.addProperty = function (property, opts) { // @ts-ignore return this.get('properties').add(this.checkExtend(property), opts); }; /** * Extend properties * @param {Array<Object>} props Start properties * @param {Array<Object>} moProps Model props * @param {Boolean} ex Returns the same amount of passed model props * @return {Array<Object>} Final props * @private */ Sector.prototype.extendProperties = function (props, moProps, ex) { if (ex === void 0) { ex = false; } var pLen = props.length; var mProps = moProps || this.get('properties'); var ext = this.get('extendBuilded'); var isolated = []; for (var i = 0, len = mProps.length; i < len; i++) { var mProp = mProps[i]; var found = 0; for (var j = 0; j < pLen; j++) { var prop = props[j]; if (mProp.property == prop.property || mProp.id == prop.property) { // @ts-ignore Check for nested properties var mPProps = mProp.properties; if (mPProps && mPProps.length) { // @ts-ignore mProp.properties = this.extendProperties(prop.properties || [], mPProps, 1); } props[j] = ext ? (0,index_all.extend)(prop, mProp) : mProp; isolated[j] = props[j]; found = 1; continue; } } if (!found) { props.push(mProp); isolated.push(mProp); } } return ex ? isolated.filter(function (i) { return i; }) : props; }; Sector.prototype.checkExtend = function (prop) { var _a = ((0,index_all.isString)(prop) ? { extend: prop } : prop) || {}, extend = _a.extend, rest = Sector_rest(_a, ["extend"]); if (extend) { return Sector_assign(Sector_assign({}, (this.buildProperties([extend])[0] || {})), rest); } else { return prop; } }; /** * Build properties * @param {Array<string>} propr Array of props as sting * @return {Array<Object>} * @private */ Sector.prototype.buildProperties = function (props) { var _a; var buildP = props || []; if (!buildP.length) return []; var builtIn = (_a = this.em) === null || _a === void 0 ? void 0 : _a.get('StyleManager').builtIn; return builtIn === null || builtIn === void 0 ? void 0 : builtIn.build(buildP); }; return Sector; }(common/* Model */.Hn)); /* harmony default export */ const model_Sector = (Sector); ;// CONCATENATED MODULE: ./src/style_manager/model/Sectors.ts var Sectors_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var Sectors_assign = ( false) || function () { Sectors_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return Sectors_assign.apply(this, arguments); }; var Sectors = /** @class */ (function (_super) { Sectors_extends(Sectors, _super); function Sectors() { return _super !== null && _super.apply(this, arguments) || this; } Sectors.prototype.initialize = function (prop, opts) { if (opts === void 0) { opts = {}; } var module = opts.module, em = opts.em; this.em = em; this.module = module; this.listenTo(this, 'reset', this.onReset); }; /** @ts-ignore */ Sectors.prototype.model = function (props, opts) { if (opts === void 0) { opts = {}; } // @ts-ignore var em = opts.collection.em; return new model_Sector(props, Sectors_assign(Sectors_assign({}, opts), { em: em })); }; Sectors.prototype.onReset = function (models, opts) { if (opts === void 0) { opts = {}; } var prev = opts.previousModels || []; // @ts-ignore prev.forEach(function (sect) { return sect.get('properties').reset(); }); }; return Sectors; }(common/* Collection */.FE)); /* harmony default export */ const model_Sectors = (Sectors); ;// CONCATENATED MODULE: ./src/style_manager/model/PropertyFactory.ts var PropertyFactory_assign = ( false) || function () { PropertyFactory_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return PropertyFactory_assign.apply(this, arguments); }; var PropertyFactory_rest = ( false) || 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 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; var PropertyFactory_spreadArray = ( false) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var getOptions = function (items) { return items.map(function (item) { return ({ id: item }); }); }; var PropertyFactory = /** @class */ (function () { function PropertyFactory() { this.props = {}; this.typeNumber = 'number'; this.typeColor = 'color'; this.typeRadio = 'radio'; this.typeSelect = 'select'; this.typeFile = 'file'; this.typeSlider = 'slider'; this.typeComposite = 'composite'; this.typeStack = 'stack'; this.unitsSize = ['px', '%', 'em', 'rem', 'vh', 'vw']; this.unitsSizeNoPerc = ['px', 'em', 'rem', 'vh', 'vw']; this.unitsTime = ['s', 'ms']; this.unitsAngle = ['deg', 'rad', 'grad']; this.fixedValues = ['initial', 'inherit', 'auto']; var ss = ', sans-serif'; var optsFlex = ['flex-start', 'flex-end', 'center']; var optsFlexAlign = PropertyFactory_spreadArray(PropertyFactory_spreadArray([], optsFlex, true), ['baseline', 'stretch'], false); this.optsBgSize = getOptions(['auto', 'cover', 'contain']); this.optsBgAttach = getOptions(['scroll', 'fixed', 'local']); this.optsBgRepeat = getOptions(['repeat', 'repeat-x', 'repeat-y', 'no-repeat']); this.optsWrap = getOptions(['nowrap', 'wrap', 'wrap-reverse']); this.optsOverflow = getOptions(['visible', 'hidden', 'scroll', 'auto']); this.optsDir = getOptions(['row', 'row-reverse', 'column', 'column-reverse']); this.opstDisplay = getOptions(['block', 'inline', 'inline-block', 'flex', 'none']); this.optsTransitFn = getOptions(['linear', 'ease', 'ease-in', 'ease-out', 'ease-in-out']); this.optsCursor = getOptions(['auto', 'pointer', 'copy', 'crosshair', 'grab', 'grabbing', 'help', 'move', 'text']); this.optsFloat = getOptions(['none', 'left', 'right']); this.optsPos = getOptions(['static', 'relative', 'absolute', 'fixed']); this.optsTextAlign = getOptions(['left', 'center', 'right', 'justify']); this.optsFlexAlign = getOptions(optsFlexAlign); this.optsJustCont = getOptions(PropertyFactory_spreadArray(PropertyFactory_spreadArray([], optsFlex, true), ['space-between', 'space-around', 'space-evenly'], false)); this.optsAlignCont = getOptions(PropertyFactory_spreadArray(PropertyFactory_spreadArray([], optsFlex, true), ['space-between', 'space-around', 'stretch'], false)); this.optsAlignSelf = getOptions(PropertyFactory_spreadArray(['auto'], optsFlexAlign, true)); this.optsTransitProp = getOptions([ 'all', 'width', 'height', 'background-color', 'transform', 'box-shadow', 'opacity', ]); this.optsBorderStyle = getOptions([ 'none', 'solid', 'dotted', 'dashed', 'double', 'groove', 'ridge', 'inset', 'outset', ]); this.optsBgPos = getOptions([ 'left top', 'left center', 'left bottom', 'right top', 'right center', 'right bottom', 'center top', 'center center', 'center bottom', ]); this.optsWeight = [ { id: '100', label: 'Thin' }, { id: '200', label: 'Extra-Light' }, { id: '300', label: 'Light' }, { id: '400', label: 'Normal' }, { id: '500', label: 'Medium' }, { id: '600', label: 'Semi-Bold' }, { id: '700', label: 'Bold' }, { id: '800', label: 'Extra-Bold' }, { id: '900', label: 'Ultra-Bold' }, ]; this.optsShadowType = [ { id: '', label: 'Outside' }, { id: 'inset', label: 'Inside' }, ]; this.optsFonts = [ 'Arial, Helvetica' + ss, 'Arial Black, Gadget' + ss, 'Brush Script MT' + ss, 'Comic Sans MS, cursive' + ss, 'Courier New, Courier, monospace', 'Georgia, serif', 'Helvetica' + ss, 'Impact, Charcoal' + ss, 'Lucida Sans Unicode, Lucida Grande' + ss, 'Tahoma, Geneva' + ss, 'Times New Roman, Times, serif', 'Trebuchet MS, Helvetica' + ss, 'Verdana, Geneva' + ss, ].map(function (font) { return { id: font, label: font.split(',')[0] }; }); // Fixed values this.fixedFontSizes = [ 'medium', 'xx-small', 'x-small', 'small', 'large', 'x-large', 'xx-large', 'smaller', 'larger', 'length', 'initial', 'inherit', ]; this.fixedLetSpace = ['normal', 'initial', 'inherit']; this.requireFlex = { display: ['flex'] }; this.init(); } PropertyFactory.prototype.__sub = function (items) { var _this = this; return function () { return items.map(function (p) { if ((0,index_all.isString)(p)) return _this.get(p); var extend = p.extend, rest = PropertyFactory_rest(p, ["extend"]); return PropertyFactory_assign(PropertyFactory_assign({}, _this.get(extend)), rest); }); }; }; PropertyFactory.prototype.init = function () { var _this = this; var _a = this, fixedValues = _a.fixedValues, requireFlex = _a.requireFlex, typeNumber = _a.typeNumber; this.props = {}; // Build default built-in properties (the order, in the array here below, matters) // [propertyName, propertyDefinition, extendFromProperty] var propsToCreate = [ // Number types ['text-shadow-h', { type: typeNumber, default: '0', units: this.unitsSizeNoPerc }], ['top', { default: 'auto', units: this.unitsSize, fixedValues: fixedValues }, 'text-shadow-h'], ['right', {}, 'top'], ['bottom', {}, 'top'], ['left', {}, 'top'], ['margin-top', { default: '0' }, 'top'], ['margin-right', {}, 'margin-top'], ['margin-bottom', {}, 'margin-top'], ['margin-left', {}, 'margin-top'], ['padding-top', { min: 0 }, 'margin-top'], ['padding-right', {}, 'padding-top'], ['padding-bottom', {}, 'padding-top'], ['padding-left', {}, 'padding-top'], ['width', { min: 0 }, 'top'], ['min-width', {}, 'width'], ['max-width', {}, 'width'], ['height', {}, 'width'], ['min-height', {}, 'width'], ['max-height', {}, 'width'], ['flex-basis', { requiresParent: requireFlex }, 'width'], ['font-size', { default: 'medium', fixedValues: this.fixedFontSizes }, 'width'], ['letter-spacing', { default: 'normal', fixedValues: this.fixedLetSpace }, 'top'], ['line-height', {}, 'letter-spacing'], ['text-shadow-v', {}, 'text-shadow-h'], ['text-shadow-blur', { min: 0 }, 'text-shadow-h'], ['border-radius-c', { property: 'border-radius', fixedValues: undefined }, 'padding-top'], ['border-top-left-radius', {}, 'border-radius-c'], ['border-top-right-radius', {}, 'border-radius-c'], ['border-bottom-left-radius', {}, 'border-radius-c'], ['border-bottom-right-radius', {}, 'border-radius-c'], ['border-width', { units: this.unitsSizeNoPerc }, 'border-radius-c'], ['box-shadow-h', {}, 'text-shadow-h'], ['box-shadow-v', {}, 'text-shadow-h'], ['box-shadow-blur', { default: '5px' }, 'text-shadow-blur'], ['box-shadow-spread', {}, 'text-shadow-h'], ['transition-duration', { default: '2s', units: this.unitsTime }, 'border-radius-c'], ['perspective', {}, 'border-radius-c'], ['order', { type: typeNumber, default: '0', requiresParent: requireFlex }], ['flex-grow', {}, 'order'], ['flex-shrink', { default: '1' }, 'order'], // Radio types ['float', { type: this.typeRadio, default: 'none', options: this.optsFloat }], ['position', { default: 'static', options: this.optsPos }, 'float'], ['text-align', { default: 'left', options: this.optsTextAlign }, 'float'], // Color types ['color', { type: this.typeColor, default: 'black', full: true }], ['text-shadow-color', {}, 'color'], ['border-color', {}, 'color'], ['box-shadow-color', {}, 'color'], ['background-color', { default: 'none' }, 'color'], // File type [ 'background-image', { type: this.typeFile, functionName: 'url', default: 'none', full: true, }, ], // Slider type ['opacity', { type: this.typeSlider, default: '1', min: 0, max: 1, step: 0.01, full: true }], // Select types ['display', { type: this.typeSelect, default: 'block', options: this.opstDisplay }], ['flex-direction', { default: 'row', options: this.optsDir, requires: requireFlex }, 'display'], ['flex-wrap', { default: 'nowrap', options: this.optsWrap }, 'flex-direction'], ['justify-content', { default: 'flex-start', options: this.optsJustCont }, 'flex-wrap'], ['align-items', { default: 'stretch', options: this.optsFlexAlign }, 'flex-wrap'], ['align-content', { options: this.optsAlignCont }, 'align-items'], [ 'align-self', { default: 'auto', options: this.optsAlignSelf, requiresParent: requireFlex, }, 'display', ], ['font-family', { default: 'Arial, Helvetica, sans-serif', options: this.optsFonts }, 'display'], ['font-weight', { default: '400', options: this.optsWeight }, 'display'], ['border-style', { default: 'solid', options: this.optsBorderStyle }, 'display'], ['box-shadow-type', { default: '', options: this.optsShadowType }, 'display'], ['background-repeat', { default: 'repeat', options: this.optsBgRepeat }, 'display'], ['background-position', { default: 'left top', options: this.optsBgPos }, 'display'], ['background-attachment', { default: 'scroll', options: this.optsBgAttach }, 'display'], ['background-size', { default: 'auto', options: this.optsBgSize }, 'display'], ['transition-property', { default: 'width', options: this.optsTransitProp }, 'display'], ['transition-timing-function', { default: 'ease', options: this.optsTransitFn }, 'display'], ['cursor', { default: 'auto', options: this.optsCursor }, 'display'], ['overflow', { default: 'visible', options: this.optsOverflow }, 'display'], ['overflow-x', {}, 'overflow'], ['overflow-y', {}, 'overflow'], // Composite types [ 'margin', { type: this.typeComposite, properties: this.__sub([ { extend: 'margin-top', id: 'margin-top-sub' }, { extend: 'margin-right', id: 'margin-right-sub' }, { extend: 'margin-bottom', id: 'margin-bottom-sub' }, { extend: 'margin-left', id: 'margin-left-sub' }, ]), }, ], [ 'padding', { properties: this.__sub([ { extend: 'padding-top', id: 'padding-top-sub' }, { extend: 'padding-right', id: 'padding-right-sub' }, { extend: 'padding-bottom', id: 'padding-bottom-sub' }, { extend: 'padding-left', id: 'padding-left-sub' }, ]), }, 'margin', ], [ 'border', { properties: this.__sub([ { extend: 'border-width', id: 'border-width-sub' }, { extend: 'border-style', id: 'border-style-sub' }, { extend: 'border-color', id: 'border-color-sub' }, ]), }, 'margin', ], [ 'border-radius', { properties: this.__sub([ { extend: 'border-top-left-radius', id: 'border-top-left-radius-sub', }, { extend: 'border-top-right-radius', id: 'border-top-right-radius-sub', }, { extend: 'border-bottom-right-radius', id: 'border-bottom-right-radius-sub', }, { extend: 'border-bottom-left-radius', id: 'border-bottom-left-radius-sub', }, ]), }, 'margin', ], // Stack types [ 'transition', { type: this.typeStack, properties: this.__sub([ { extend: 'transition-property', id: 'transition-property-sub' }, { extend: 'transition-duration', id: 'transition-duration-sub' }, { extend: 'transition-timing-function', id: 'transition-timing-function-sub', }, ]), }, ], [ 'box-shadow', { preview: true, layerLabel: function (l, _a) { var values = _a.values; var x = values['box-shadow-h']; var y = values['box-shadow-v']; var blur = values['box-shadow-blur']; var spread = values['box-shadow-spread']; return "".concat(x, " ").concat(y, " ").concat(blur, " ").concat(spread); }, properties: this.__sub([ 'box-shadow-h', 'box-shadow-v', 'box-shadow-blur', 'box-shadow-spread', 'box-shadow-color', 'box-shadow-type', ]), }, 'transition', ], [ 'text-shadow', { default: 'none', layerLabel: function (l, _a) { var values = _a.values; var x = values['text-shadow-h']; var y = values['text-shadow-v']; var blur = values['text-shadow-blur']; return "".concat(x, " ").concat(y, " ").concat(blur); }, properties: this.__sub(['text-shadow-h', 'text-shadow-v', 'text-shadow-blur', 'text-shadow-color']), }, 'box-shadow', ], [ 'background', { detached: true, layerLabel: function (l, _a) { var values = _a.values; var repeat = values['background-repeat-sub'] || ''; var pos = values['background-position-sub'] || ''; var att = values['background-attachment-sub'] || ''; var size = values['background-size-sub'] || ''; return [repeat, pos, att, size].join(' '); }, properties: this.__sub([ { extend: 'background-image', id: 'background-image-sub' }, { extend: 'background-repeat', id: 'background-repeat-sub' }, { extend: 'background-position', id: 'background-position-sub' }, { extend: 'background-attachment', id: 'background-attachment-sub', }, { extend: 'background-size', id: 'background-size-sub' }, ]), }, 'box-shadow', ], [ 'transform', { type: 'stack', layerSeparator: ' ', fromStyle: function (style, _a) { var property = _a.property, name = _a.name; var filter = (style[name] || ''); var sep = property.getLayerSeparator(); return filter ? filter.split(sep).map(function (input) { var _a = property.__parseFn(input), name = _a.name, value = _a.value; return { 'transform-type': name, 'transform-value': value, }; }) : []; }, toStyle: function (values, _a) { var _b; var name = _a.name; return _b = {}, _b[name] = "".concat(values['transform-type'], "(").concat(values['transform-value'], ")"), _b; }, properties: [ { property: 'transform-type', name: 'Type', type: this.typeSelect, default: 'rotateZ', full: true, options: [ { id: 'scaleX', propValue: { units: [''], step: 0.01 } }, { id: 'scaleY', propValue: { units: [''], step: 0.01 } }, { id: 'scaleZ', propValue: { units: [''], step: 0.01 } }, { id: 'rotateX', propValue: { units: this.unitsAngle, step: 1 }, }, { id: 'rotateY', propValue: { units: this.unitsAngle, step: 1 }, }, { id: 'rotateZ', propValue: { units: this.unitsAngle, step: 1 }, }, { id: 'translateX', propValue: { units: this.unitsSize, step: 1 }, }, { id: 'translateY', propValue: { units: this.unitsSize, step: 1 }, }, ], onChange: function (_a) { var property = _a.property, to = _a.to; if (to.value) { var option = property.getOption(); var props = PropertyFactory_assign({}, (option.propValue || {})); var propToUp = property.getParent().getProperty('transform-value'); var unit = propToUp.getUnit(); if (!unit || (props === null || props === void 0 ? void 0 : props.units.indexOf(unit)) < 0) { props.unit = (props === null || props === void 0 ? void 0 : props.units[0]) || ''; } propToUp.up(props); } }, }, { property: 'transform-value', type: this.typeNumber, default: '0', full: true, }, ], }, ], ]; propsToCreate.forEach(function (_a) { var prop = _a[0], def = _a[1], from = _a[2]; _this.add(prop, def || {}, { from: from }); }); return this; }; PropertyFactory.prototype.add = function (property, def, opts) { if (def === void 0) { def = {}; } if (opts === void 0) { opts = {}; } var from = opts.from || ''; var fromRes = this.props[from || property] || {}; var result = PropertyFactory_assign(PropertyFactory_assign(PropertyFactory_assign({}, fromRes), { property: property }), def); if (result.properties && (0,index_all.isFunction)(result.properties)) { result.properties = result.properties(); } this.props[property] = result; return result; }; PropertyFactory.prototype.get = function (prop) { return this.props[prop]; }; /** * Build props object by their name * @param {Array<string>|string} props Array of properties name * @return {Array<Object>} */ PropertyFactory.prototype.build = function (props) { var _this = this; var result = []; var propsArr = (0,index_all.isString)(props) ? [props] : props; propsArr.forEach(function (prop) { result.push(_this.get(prop) || { property: prop }); }); return result; }; return PropertyFactory; }()); /* harmony default export */ const model_PropertyFactory = (PropertyFactory); ;// CONCATENATED MODULE: ./src/style_manager/view/SectorView.ts var SectorView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var SectorView_makeTemplateObject = ( false) || function (cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; }; var SectorView = /** @class */ (function (_super) { SectorView_extends(SectorView, _super); function SectorView(o) { var _this = _super.call(this, o) || this; var config = o.config || {}; var model = _this.model; // @ts-ignore var em = config.em; _this.config = config; _this.em = em; _this.pfx = config.stylePrefix || ''; _this.listenTo(model, 'destroy remove', _this.remove); _this.listenTo(model, 'change:open', _this.updateOpen); _this.listenTo(model, 'change:visible', _this.updateVisibility); return _this; } SectorView.prototype.template = function (_a) { var _b; var pfx = _a.pfx, label = _a.label; var icons = (_b = this.em) === null || _b === void 0 ? void 0 : _b.getConfig().icons; var iconCaret = (icons === null || icons === void 0 ? void 0 : icons.caret) || ''; var clsPfx = "".concat(pfx, "sector-"); return html(SectorView_templateObject_1 || (SectorView_templateObject_1 = SectorView_makeTemplateObject(["\n <div class=\"", "title\" data-sector-title>\n <div class=\"", "caret\">$", "</div>\n <div class=\"", "label\">", "</div>\n </div>\n "], ["\n <div class=\"", "title\" data-sector-title>\n <div class=\"", "caret\">$", "</div>\n <div class=\"", "label\">", "</div>\n </div>\n "])), clsPfx, clsPfx, iconCaret, clsPfx, label); }; SectorView.prototype.events = function () { return { 'click [data-sector-title]': 'toggle', }; }; SectorView.prototype.updateOpen = function () { var _a = this, $el = _a.$el, model = _a.model, pfx = _a.pfx; var isOpen = model.isOpen(); $el[isOpen ? 'addClass' : 'removeClass']("".concat(pfx, "open")); this.getPropertiesEl().style.display = isOpen ? '' : 'none'; }; SectorView.prototype.updateVisibility = function () { this.el.style.display = this.model.isVisible() ? '' : 'none'; }; SectorView.prototype.getPropertiesEl = function () { var _a = this, $el = _a.$el, pfx = _a.pfx; return $el.find(".".concat(pfx, "properties")).get(0); }; SectorView.prototype.toggle = function () { var model = this.model; model.setOpen(!model.get('open')); }; SectorView.prototype.renderProperties = function () { var _a = this, model = _a.model, config = _a.config; var objs = model.get('properties'); if (objs) { // @ts-ignore var view = new view_PropertiesView({ collection: objs, config: config }); this.$el.append(view.render().el); } }; SectorView.prototype.render = function () { var _a = this, pfx = _a.pfx, model = _a.model, $el = _a.$el; var id = model.getId(); var label = model.getName(); $el.html(this.template({ pfx: pfx, label: label })); this.renderProperties(); $el.attr('class', "".concat(pfx, "sector ").concat(pfx, "sector__").concat(id, " no-select")); this.updateOpen(); return this; }; return SectorView; }(common/* View */.G7)); /* harmony default export */ const view_SectorView = (SectorView); var SectorView_templateObject_1; ;// CONCATENATED MODULE: ./src/style_manager/view/SectorsView.ts var SectorsView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var SectorsView = /** @class */ (function (_super) { SectorsView_extends(SectorsView, _super); function SectorsView(o) { if (o === void 0) { o = {}; } var _this = // @ts-ignore _super.call(this, o) || this; var module = o.module, config = o.config; var coll = _this.collection; _this.pfx = (config === null || config === void 0 ? void 0 : config.stylePrefix) || ''; _this.ppfx = (config === null || config === void 0 ? void 0 : config.pStylePrefix) || ''; _this.config = config; _this.module = module; _this.listenTo(coll, 'add', _this.addTo); _this.listenTo(coll, 'reset', _this.render); return _this; } SectorsView.prototype.remove = function () { var _this = this; common/* View */.G7.prototype.remove.apply(this, arguments); ['config', 'module', 'em'].forEach(function (i) { // @ts-ignore return (_this[i] = {}); }); return this; }; SectorsView.prototype.addTo = function (model, c, opts) { if (opts === void 0) { opts = {}; } this.addToCollection(model, null, opts); }; SectorsView.prototype.addToCollection = function (model, fragmentEl, opts) { if (opts === void 0) { opts = {}; } var _a = this, config = _a.config, el = _a.el; var appendTo = fragmentEl || el; var rendered = new view_SectorView({ model: model, config: config }).render().el; (0,dom/* appendAtIndex */.$Q)(appendTo, rendered, opts.at); return rendered; }; SectorsView.prototype.render = function () { var _this = this; var _a = this, $el = _a.$el, pfx = _a.pfx, ppfx = _a.ppfx; $el.empty(); var frag = document.createDocumentFragment(); this.collection.each(function (model) { return _this.addToCollection(model, frag); }); $el.append(frag); $el.addClass("".concat(pfx, "sectors ").concat(ppfx, "one-bg ").concat(ppfx, "two-color")); return this; }; return SectorsView; }(common/* View */.G7)); /* harmony default export */ const view_SectorsView = (SectorsView); ;// CONCATENATED MODULE: ./src/style_manager/index.ts /** * With Style Manager you build categories (called sectors) of CSS properties which could be used to customize the style of components. * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/GrapesJS/grapesjs/blob/master/src/style_manager/config/config.ts) * ```js * const editor = grapesjs.init({ * styleManager: { * // options * } * }) * ``` * * Once the editor is instantiated you can use its API and listen to its events. Before using these methods, you should get the module from the instance. * * ```js * // Listen to events * editor.on('style:sector:add', (sector) => { ... }); * * // Use the API * const styleManager = editor.StyleManager; * styleManager.addSector(...); * ``` * ## Available Events * * `style:sector:add` - Sector added. The [Sector] is passed as an argument to the callback. * * `style:sector:remove` - Sector removed. The [Sector] is passed as an argument to the callback. * * `style:sector:update` - Sector updated. The [Sector] and the object containing changes are passed as arguments to the callback. * * `style:property:add` - Property added. The [Property] is passed as an argument to the callback. * * `style:property:remove` - Property removed. The [Property] is passed as an argument to the callback. * * `style:property:update` - Property updated. The [Property] and the object containing changes are passed as arguments to the callback. * * `style:target` - Target selection changed. The target (or `null` in case the target is deselected) is passed as an argument to the callback. * <!-- * * `styleManager:update:target` - The target (Component or CSSRule) is changed * * `styleManager:change` - Triggered on style property change from new selected component, the view of the property is passed as an argument to the callback * * `styleManager:change:{propertyName}` - As above but for a specific style property * --> * * ## Methods * * [getConfig](#getconfig) * * [addSector](#addsector) * * [getSector](#getsector) * * [getSectors](#getsectors) * * [removeSector](#removesector) * * [addProperty](#addproperty) * * [getProperty](#getproperty) * * [getProperties](#getproperties) * * [removeProperty](#removeproperty) * * [select](#select) * * [getSelected](#getselected) * * [getSelectedAll](#getselectedall) * * [getSelectedParents](#getselectedparents) * * [addStyleTargets](#addstyletargets) * * [getBuiltIn](#getbuiltin) * * [getBuiltInAll](#getbuiltinall) * * [addBuiltIn](#addbuiltin) * * [addType](#addtype) * * [getType](#gettype) * * [getTypes](#gettypes) * * [Sector]: sector.html * [CssRule]: css_rule.html * [Component]: component.html * [Property]: property.html * * @module docsjs.StyleManager */ var style_manager_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var style_manager_assign = ( false) || function () { style_manager_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return style_manager_assign.apply(this, arguments); }; var style_manager_spreadArray = ( false) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var style_manager_evAll = 'style'; var style_manager_evPfx = "".concat(style_manager_evAll, ":"); var evSector = "".concat(style_manager_evPfx, "sector"); var evSectorAdd = "".concat(evSector, ":add"); var evSectorRemove = "".concat(evSector, ":remove"); var evSectorUpdate = "".concat(evSector, ":update"); var evProp = "".concat(style_manager_evPfx, "property"); var evPropAdd = "".concat(evProp, ":add"); var evPropRemove = "".concat(evProp, ":remove"); var evPropUp = "".concat(evProp, ":update"); var evLayerSelect = "".concat(style_manager_evPfx, "layer:select"); var evTarget = "".concat(style_manager_evPfx, "target"); var style_manager_evCustom = "".concat(style_manager_evPfx, "custom"); var propDef = function (value) { return value || value === 0; }; var stylesEvents = { all: style_manager_evAll, sectorAdd: evSectorAdd, sectorRemove: evSectorRemove, sectorUpdate: evSectorUpdate, propertyAdd: evPropAdd, propertyRemove: evPropRemove, propertyUpdate: evPropUp, layerSelect: evLayerSelect, target: evTarget, custom: style_manager_evCustom, }; var StyleManager = /** @class */ (function (_super) { style_manager_extends(StyleManager, _super); /** * Get configuration object * @name getConfig * @function * @return {Object} */ /** * Initialize module. Automatically called with a new instance of the editor * @param {Object} config Configurations * @private */ function StyleManager(em) { var _this = _super.call(this, em, 'StyleManager', new model_Sectors([], { em: em }), stylesEvents, style_manager_config_config) || this; _this.Sector = model_Sector; _this.storageKey = ''; (0,index_all.bindAll)(_this, '__clearStateTarget'); var c = _this.config; var ppfx = c.pStylePrefix; if (ppfx) c.stylePrefix = ppfx + c.stylePrefix; _this.builtIn = new model_PropertyFactory(); _this.properties = new model_Properties([], { em: em, module: _this }); _this.sectors = _this.all; // TODO check if (module: this) is required var model = new common/* Model */.Hn({ targets: [] }); _this.model = model; // Triggers for the selection refresh and properties var ev = 'component:toggled component:update:classes change:state change:device frame:resized selector:type'; _this.upAll = (0,index_all.debounce)(function () { return _this.__upSel(); }, 0); model.listenTo(em, ev, _this.upAll); // Clear state target on any component selection change, without debounce (#4208) model.listenTo(em, 'component:toggled', _this.__clearStateTarget); // Triggers only for properties (avoid selection refresh) var upProps = (0,index_all.debounce)(function () { _this.__upProps(); _this.__trgCustom(); }, 0); model.listenTo(em, 'styleable:change undo redo', upProps); // Triggers only custom event var trgCustom = (0,index_all.debounce)(function () { return _this.__trgCustom(); }, 0); model.listenTo(em, "".concat(evLayerSelect, " ").concat(evTarget), trgCustom); // Other listeners model.on('change:lastTarget', function () { return em.trigger(evTarget, _this.getSelected()); }); return _this; } StyleManager.prototype.__upSel = function () { this.select(this.em.getSelectedAll()); }; StyleManager.prototype.__trgCustom = function (opts) { if (opts === void 0) { opts = {}; } this.__ctn = this.__ctn || opts.container; this.em.trigger(this.events.custom, { container: this.__ctn }); }; StyleManager.prototype.__trgEv = function (event) { var _a; var data = []; for (var _i = 1; _i < arguments.length; _i++) { data[_i - 1] = arguments[_i]; } (_a = this.em).trigger.apply(_a, style_manager_spreadArray([event], data, false)); }; StyleManager.prototype.__clearStateTarget = function () { var _this = this; var em = this.em; var stateTarget = this.__getStateTarget(); stateTarget && (em === null || em === void 0 ? void 0 : em.skip(function () { em.Css.remove(stateTarget); _this.model.set({ stateTarget: null }); })); }; StyleManager.prototype.onLoad = function () { // Use silent as sectors' view will be created and rendered on StyleManager.render this.sectors.add(this.config.sectors, { silent: true }); }; StyleManager.prototype.postRender = function () { this.__appendTo(); }; /** * Add new sector. If the sector with the same id already exists, that one will be returned. * @param {String} id Sector id * @param {Object} sector Sector definition. Check the [available properties](sector.html#properties) * @param {Object} [options={}] Options * @param {Number} [options.at] Position index (by default, will be appended at the end). * @returns {[Sector]} Added Sector * @example * const sector = styleManager.addSector('mySector',{ * name: 'My sector', * open: true, * properties: [{ name: 'My property'}] * }, { at: 0 }); * // With `at: 0` we place the new sector at the beginning of the list * */ StyleManager.prototype.addSector = function (id, sector, options) { if (options === void 0) { options = {}; } var result = this.getSector(id); if (!result) { sector.id = id; result = this.sectors.add(sector, options); } return result; }; /** * Get sector by id. * @param {String} id Sector id * @returns {[Sector]|null} * @example * const sector = styleManager.getSector('mySector'); * */ StyleManager.prototype.getSector = function (id, opts) { if (opts === void 0) { opts = {}; } var res = this.sectors.where({ id: id })[0]; !res && opts.warn && this._logNoSector(id); return res || null; }; /** * Get all sectors. * @param {Object} [opts={}] Options * @param {Boolean} [opts.visible] Returns only visible sectors * @returns {Array<[Sector]>} * @example * const sectors = styleManager.getSectors(); * */ StyleManager.prototype.getSectors = function (opts) { if (opts === void 0) { opts = {}; } var sectors = this.sectors; var res = sectors && sectors.models ? (opts.array ? style_manager_spreadArray([], sectors.models, true) : sectors) : []; return (opts.visible ? res.filter(function (s) { return s.isVisible(); }) : res); }; /** * Remove sector by id. * @param {String} id Sector id * @returns {[Sector]} Removed sector * @example * const removed = styleManager.removeSector('mySector'); */ StyleManager.prototype.removeSector = function (id) { return this.getSectors().remove(this.getSector(id, { warn: true })); }; /** * Add new property to the sector. * @param {String} sectorId Sector id. * @param {Object} property Property definition. Check the [base available properties](property.html#properties) + others based on the `type` of your property. * @param {Object} [opts={}] Options * @param {Number} [opts.at] Position index (by default, will be appended at the end). * @returns {[Property]|null} Added property or `null` in case the sector doesn't exist. * @example * const property = styleManager.addProperty('mySector', { * label: 'Minimum height', * property: 'min-height', * type: 'select', * default: '100px', * options: [ * { id: '100px', label: '100' }, * { id: '200px', label: '200' }, * ], * }, { at: 0 }); */ StyleManager.prototype.addProperty = function (sectorId, property, opts) { if (opts === void 0) { opts = {}; } var sector = this.getSector(sectorId, { warn: true }); var prop = null; if (sector) prop = sector.addProperty(property, opts); return prop; }; /** * Get the property. * @param {String} sectorId Sector id. * @param {String} id Property id. * @returns {[Property]|undefined} * @example * const property = styleManager.getProperty('mySector', 'min-height'); */ StyleManager.prototype.getProperty = function (sectorId, id) { var sector = this.getSector(sectorId, { warn: true }); var prop; if (sector) { prop = sector.properties.filter(function (prop) { return prop.get('property') === id || prop.get('id') === id; })[0]; } return prop; }; /** * Get all properties of the sector. * @param {String} sectorId Sector id. * @returns {Collection<[Property]>|undefined} Collection of properties * @example * const properties = styleManager.getProperties('mySector'); */ StyleManager.prototype.getProperties = function (sectorId) { var props; var sector = this.getSector(sectorId, { warn: true }); if (sector) props = sector.properties; return props; }; /** * Remove the property. * @param {String} sectorId Sector id. * @param {String} id Property id. * @returns {[Property]|null} Removed property * @example * const property = styleManager.removeProperty('mySector', 'min-height'); */ StyleManager.prototype.removeProperty = function (sectorId, id) { var props = this.getProperties(sectorId); return props ? props.remove(this.getProperty(sectorId, id)) : null; }; /** * Select new target. * The target could be a Component, CSSRule, or a CSS selector string. * @param {[Component]|[CSSRule]|String} target * @returns {Array<[Component]|[CSSRule]>} Array containing selected Components or CSSRules * @example * // Select the first button in the current page * const wrapperCmp = editor.Pages.getSelected().getMainComponent(); * const btnCmp = wrapperCmp.find('button')[0]; * btnCmp && styleManager.select(btnCmp); * * // Set as a target the CSS selector * styleManager.select('.btn > span'); */ StyleManager.prototype.select = function (target, opts) { var _this = this; if (opts === void 0) { opts = {}; } var em = this.em; var trgs = (0,index_all.isArray)(target) ? target : [target]; var stylable = opts.stylable; var cssc = em.Css; var targets = []; trgs.filter(Boolean).forEach(function (target) { var model = target; if ((0,index_all.isString)(target)) { var rule = cssc.getRule(target) || cssc.setRule(target); !(0,index_all.isUndefined)(stylable) && rule.set({ stylable: stylable }); model = rule; } targets.push(model); }); var component = opts.component || targets.filter(function (t) { return (0,mixins.isComponent)(t); }).reverse()[0]; targets = targets.map(function (t) { return _this.getModelToStyle(t); }); var state = em.getState(); var lastTarget = targets.slice().reverse()[0]; var lastTargetParents = this.getParentRules(lastTarget, { state: state, // @ts-ignore component: component, }); var stateTarget = this.__getStateTarget(); // Handle the creation and update of the state rule, if enabled. em.skip(function () { var _a; // @ts-ignore if (state && ((_a = lastTarget === null || lastTarget === void 0 ? void 0 : lastTarget.getState) === null || _a === void 0 ? void 0 : _a.call(lastTarget))) { var style = lastTarget.getStyle(); if (!stateTarget) { stateTarget = cssc.getAll().add({ selectors: 'gjs-selected', style: style, shallow: true, important: true, }); } else { stateTarget.setStyle(style); } } else if (stateTarget) { cssc.remove(stateTarget); stateTarget = undefined; } }); this.model.set({ targets: targets, lastTarget: lastTarget, lastTargetParents: lastTargetParents, stateTarget: stateTarget, component: component, }); this.__upProps(opts); return targets; }; /** * Get the last selected target. * By default, the Style Manager shows styles of the last selected target. * @returns {[Component]|[CSSRule]|null} */ StyleManager.prototype.getSelected = function () { return this.model.get('lastTarget'); }; /** * Get the array of selected targets. * @returns {Array<[Component]|[CSSRule]>} */ StyleManager.prototype.getSelectedAll = function () { return this.model.get('targets'); }; /** * Get parent rules of the last selected target. * @returns {Array<[CSSRule]>} */ StyleManager.prototype.getSelectedParents = function () { return this.model.get('lastTargetParents') || []; }; StyleManager.prototype.__getStateTarget = function () { return this.model.get('stateTarget'); }; /** * Update selected targets with a custom style. * @param {Object} style Style object * @param {Object} [opts={}] Options * @example * styleManager.addStyleTargets({ color: 'red' }); */ StyleManager.prototype.addStyleTargets = function (style, opts) { this.getSelectedAll().map(function (t) { return t.addStyle(style, opts); }); var target = this.getSelected(); // Trigger style changes on selected components target && this.__emitCmpStyleUpdate(style); // Update state rule var targetState = this.__getStateTarget(); target && (targetState === null || targetState === void 0 ? void 0 : targetState.setStyle(target.getStyle(), opts)); }; /** * Return built-in property definition * @param {String} prop Property name. * @returns {Object|null} Property definition. * @example * const widthPropDefinition = styleManager.getBuiltIn('width'); */ StyleManager.prototype.getBuiltIn = function (prop) { return this.builtIn.get(prop); }; /** * Get all the available built-in property definitions. * @returns {Object} */ StyleManager.prototype.getBuiltInAll = function () { return this.builtIn.props; }; /** * Add built-in property definition. * If the property exists already, it will extend it. * @param {String} prop Property name. * @param {Object} definition Property definition. * @returns {Object} Added property definition. * @example * const sector = styleManager.addBuiltIn('new-property', { * type: 'select', * default: 'value1', * options: [{ id: 'value1', label: 'Some label' }, ...], * }) */ StyleManager.prototype.addBuiltIn = function (prop, definition) { return this.builtIn.add(prop, definition); }; /** * Get what to style inside Style Manager. If you select the component * without classes the entity is the Component itself and all changes will * go inside its 'style' property. Otherwise, if the selected component has * one or more classes, the function will return the corresponding CSS Rule * @param {Model} model * @return {Model} * @private */ StyleManager.prototype.getModelToStyle = function (model, options) { if (options === void 0) { options = {}; } var em = this.em; var skipAdd = options.skipAdd; if (em && (model === null || model === void 0 ? void 0 : model.toHTML)) { var config = em.getConfig(); var um = em.UndoManager; var cssC = em.Css; var sm = em.Selectors; var smConf = sm ? sm.getConfig() : {}; var state = !config.devicePreviewMode ? em.get('state') : ''; var classes = model.get('classes'); var valid = classes.getStyleable(); var hasClasses = valid.length; var useClasses = !smConf.componentFirst || options.useClasses; var addOpts = { noCount: 1 }; var opts = { state: state, addOpts: addOpts }; var rule = void 0; // I stop undo manager here as after adding the CSSRule (generally after // selecting the component) and calling undo() it will remove the rule from // the collection, therefore updating it in style manager will not affect it // #268 um.stop(); if (hasClasses && useClasses) { var deviceW = em.getCurrentMedia(); rule = cssC.get(valid, state, deviceW); if (!rule && !skipAdd) { rule = cssC.add(valid, state, deviceW, {}, addOpts); } } else if (config.avoidInlineStyle) { var id = model.getId(); rule = cssC.getIdRule(id, opts); !rule && !skipAdd && (rule = cssC.setIdRule(id, {}, opts)); if (model.is('wrapper')) { // @ts-ignore rule.set('wrapper', 1, addOpts); } } rule && (model = rule); um.start(); } return model; }; StyleManager.prototype.getParentRules = function (target, _a) { var _b = _a === void 0 ? {} : _a, state = _b.state, component = _b.component; var em = this.em; var result = []; if (em && target) { var sel = component; var cssC = em.Css; var cssGen = em.CodeManager.getGenerator('css'); // @ts-ignore var cmp = target.toHTML ? target : target.getComponent(); var optsSel = { combination: true, array: true }; var cmpRules = []; var otherRules = []; var rules = []; // Componente related rule if (cmp) { cmpRules = cssC.getRules("#".concat(cmp.getId())); otherRules = sel ? cssC.getRules(sel.getSelectors().getFullName(optsSel)) : []; rules = otherRules.concat(cmpRules); } else { cmpRules = sel ? cssC.getRules("#".concat(sel.getId())) : []; otherRules = cssC.getRules(target.getSelectors().getFullName(optsSel)); rules = cmpRules.concat(otherRules); } var all = rules .filter(function (rule) { return (!(0,index_all.isUndefined)(state) ? rule.get('state') === state : 1); }) .sort(cssGen.sortRules) .reverse(); // Slice removes rules not related to the current device result = all.slice(all.indexOf(target) + 1); } return result; }; /** * Add new property type * @param {string} id Type ID * @param {Object} definition Definition of the type. * @example * styleManager.addType('my-custom-prop', { * // Create UI * create({ props, change }) { * const el = document.createElement('div'); * el.innerHTML = '<input type="range" class="my-input" min="10" max="50"/>'; * const inputEl = el.querySelector('.my-input'); * inputEl.addEventListener('change', event => change({ event })); * inputEl.addEventListener('input', event => change({ event, partial: true })); * return el; * }, * // Propagate UI changes up to the targets * emit({ props, updateStyle }, { event, partial }) { * const { value } = event.target; * updateStyle(`${value}px`, { partial }); * }, * // Update UI (eg. when the target is changed) * update({ value, el }) { * el.querySelector('.my-input').value = parseInt(value, 10); * }, * // Clean the memory from side effects if necessary (eg. global event listeners, etc.) * destroy() {} *}) */ StyleManager.prototype.addType = function (id, definition) { this.properties.addType(id, definition); }; /** * Get type * @param {string} id Type ID * @return {Object} Type definition */ StyleManager.prototype.getType = function (id) { return this.properties.getType(id); }; /** * Get all types * @return {Array} */ StyleManager.prototype.getTypes = function () { return this.properties.getTypes(); }; /** * Create new UI property from type (Experimental) * @param {string} id Type ID * @param {Object} [options={}] Options * @param {Object} [options.model={}] Custom model object * @param {Object} [options.view={}] Custom view object * @return {PropertyView} * @private * @example * const propView = styleManager.createType('number', { * model: {units: ['px', 'rem']} * }); * propView.render(); * propView.model.on('change:value', ...); * someContainer.appendChild(propView.el); */ StyleManager.prototype.createType = function (id, _a) { var _b = _a === void 0 ? {} : _a, _c = _b.model, model = _c === void 0 ? {} : _c, _d = _b.view, view = _d === void 0 ? {} : _d; var config = this.config; var type = this.getType(id); if (type) { return new type.view(style_manager_assign({ model: new type.model(model), config: config }, view)); } }; /** * Render sectors and properties * @return {HTMLElement} * @private * */ StyleManager.prototype.render = function () { var _a = this, config = _a.config, em = _a.em, SectView = _a.SectView; var el = SectView && SectView.el; this.SectView = new view_SectorsView({ el: el, em: em, config: config, module: this, collection: this.sectors, }); return this.SectView.render().el; }; StyleManager.prototype._logNoSector = function (sectorId) { var em = this.em; em && em.logWarning("'".concat(sectorId, "' sector not found")); }; StyleManager.prototype.__emitCmpStyleUpdate = function (style, opts) { if (opts === void 0) { opts = {}; } var em = this.em; var event = 'component:styleUpdate'; // Ignore partial updates if (!style.__p) { var cmp = opts.components || em.getSelectedAll(); var cmps = Array.isArray(cmp) ? cmp : [cmp]; var newStyle = style_manager_assign({}, style); delete newStyle.__p; var styleKeys_1 = Object.keys(newStyle); var optsToPass_1 = { style: newStyle }; cmps.forEach(function (component) { em.trigger(event, component, optsToPass_1); styleKeys_1.forEach(function (key) { return em.trigger("".concat(event, ":").concat(key), component, optsToPass_1); }); }); } }; StyleManager.prototype.__upProps = function (opts) { var _this = this; if (opts === void 0) { opts = {}; } var lastTarget = this.getSelected(); if (!lastTarget) return; var sectors = this.sectors; var component = this.model.get('component'); var lastTargetParents = this.getSelectedParents(); var style = lastTarget.getStyle(); var parentStyles = lastTargetParents.map(function (p) { return ({ target: p, style: p.getStyle(), }); }); sectors.map(function (sector) { sector.getProperties().map(function (prop) { _this.__upProp(prop, style, parentStyles, opts); }); }); // Update sectors/properties visibility sectors.forEach(function (sector) { var props = sector.getProperties(); props.forEach(function (prop) { var isVisible = prop.__checkVisibility({ target: lastTarget, component: component, // @ts-ignore sectors: sectors, }); prop.set('visible', isVisible); }); var sectorVisible = props.some(function (p) { return p.isVisible(); }); sector.set('visible', sectorVisible); }); }; StyleManager.prototype.__upProp = function (prop, style, parentStyles, opts) { var _this = this; var name = prop.getName(); var value = style[name]; var hasVal = propDef(value); var isStack = prop.getType() === 'stack'; var isComposite = prop.getType() === 'composite'; var opt = style_manager_assign(style_manager_assign({}, opts), { __up: true }); var canUpdate = !isComposite && !isStack; var newLayers = isStack ? prop.__getLayersFromStyle(style) : []; var newProps = isComposite ? prop.__getPropsFromStyle(style) : {}; var newValue = hasVal ? value : null; var parentTarget = null; if ((isStack && newLayers === null) || (isComposite && newProps === null)) { var method_1 = isStack ? '__getLayersFromStyle' : '__getPropsFromStyle'; var parentItem = parentStyles.filter(function (p) { return prop[method_1](p.style) !== null; })[0]; if (parentItem) { newValue = parentItem.style[name]; parentTarget = parentItem.target; var val = prop[method_1](parentItem.style); if (isStack) { newLayers = val; } else { newProps = val; } } } else if (!hasVal) { newValue = null; var parentItem = parentStyles.filter(function (p) { return propDef(p.style[name]); })[0]; if (parentItem) { newValue = parentItem.style[name]; parentTarget = parentItem.target; } } prop.__setParentTarget(parentTarget); canUpdate && prop.__getFullValue() !== newValue && prop.upValue(newValue, opt); isStack && prop.__setLayers(newLayers || []); if (isComposite) { var props = prop.getProperties(); // Detached has to be treathed as separate properties if (prop.isDetached()) { var newStyle_1 = prop.__getPropsFromStyle(style, { byName: true }) || {}; var newParentStyles_1 = parentStyles.map(function (p) { return (style_manager_assign(style_manager_assign({}, p), { style: prop.__getPropsFromStyle(p.style, { byName: true }) || {} })); }); props.map(function (pr) { return _this.__upProp(pr, newStyle_1, newParentStyles_1, opts); }); } else { prop.__setProperties(newProps || {}, opt); prop.getProperties().map(function (pr) { return pr.__setParentTarget(parentTarget); }); } } }; StyleManager.prototype.destroy = function () { var _a; [this.properties, this.sectors].forEach(function (coll) { coll.reset(); coll.stopListening(); }); (_a = this.SectView) === null || _a === void 0 ? void 0 : _a.remove(); this.model.stopListening(); this.upAll.cancel(); }; return StyleManager; }(ItemManagerModule)); /* harmony default export */ const style_manager = (StyleManager); ;// CONCATENATED MODULE: ./src/editor/model/Editor.ts var Editor_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var Editor_assign = ( false) || function () { Editor_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return Editor_assign.apply(this, arguments); }; var Editor_awaiter = ( false) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var Editor_generator = ( false) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var Editor_rest = ( false) || 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 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; var Editor_spreadArray = ( false) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; (backbone_default()).$ = cash_dom["default"]; var deps = [ utils, i18n, keymaps, undo_manager, storage_manager, device_manager, parser, style_manager, selector_manager, modal_dialog, code_manager, panels, rich_text_editor, trait_manager, src_navigator, canvas, commands, block_manager, ]; var storableDeps = [ asset_manager, css_composer, pages, dom_components, ]; extender({ $: cash_dom["default"] }); var logs = { debug: console.log, info: console.info, warning: console.warn, error: console.error, }; var EditorModel = /** @class */ (function (_super) { Editor_extends(EditorModel, _super); function EditorModel(conf) { if (conf === void 0) { conf = {}; } var _this = _super.call(this) || this; _this.__skip = false; _this.defaultRunning = false; _this.destroyed = false; _this._config = conf; var config = _this.config; _this.set('Config', conf); _this.set('modules', []); _this.set('toLoad', []); _this.set('storables', []); _this.set('selected', new model_Selected()); _this.set('dmode', config.dragMode); var el = config.el, log = config.log; var toLog = log === true ? (0,index_all.keys)(logs) : (0,index_all.isArray)(log) ? log : []; (0,index_all.bindAll)(_this, 'initBaseColorPicker'); if (el && config.fromElement) { config.components = el.innerHTML; } _this.attrsOrig = el ? (0,index_all.toArray)(el.attributes).reduce(function (res, next) { res[next.nodeName] = next.nodeValue; return res; }, {}) : ''; // Move components to pages if (config.components && !config.pageManager) { config.pageManager = { pages: [{ component: config.components }] }; } // Load modules deps.forEach(function (constr) { return _this.loadModule(constr); }); storableDeps.forEach(function (constr) { return _this.loadStorableModule(constr); }); _this.on('change:componentHovered', _this.componentHovered, _this); _this.on('change:changesCount', _this.updateChanges, _this); _this.on('change:readyLoad change:readyCanvas', _this._checkReady, _this); toLog.forEach(function (e) { return _this.listenLog(e); }); // Deprecations [{ from: 'change:selectedComponent', to: 'component:toggled' }].forEach(function (event) { var eventFrom = event.from; var eventTo = event.to; _this.listenTo(_this, eventFrom, function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } _this.trigger.apply(_this, Editor_spreadArray([eventTo], args, false)); _this.logWarning("The event '".concat(eventFrom, "' is deprecated, replace it with '").concat(eventTo, "'")); }); }); return _this; } EditorModel.prototype.defaults = function () { return { editing: 0, selected: 0, clipboard: null, dmode: 0, componentHovered: null, previousModel: null, changesCount: 0, storables: [], modules: [], toLoad: [], opened: {}, device: '', }; }; Object.defineProperty(EditorModel.prototype, "storables", { get: function () { return this.get('storables'); }, enumerable: false, configurable: true }); Object.defineProperty(EditorModel.prototype, "modules", { get: function () { return this.get('modules'); }, enumerable: false, configurable: true }); Object.defineProperty(EditorModel.prototype, "toLoad", { get: function () { return this.get('toLoad'); }, enumerable: false, configurable: true }); Object.defineProperty(EditorModel.prototype, "selected", { get: function () { return this.get('selected'); }, enumerable: false, configurable: true }); Object.defineProperty(EditorModel.prototype, "shallow", { get: function () { return this.get('shallow'); }, enumerable: false, configurable: true }); Object.defineProperty(EditorModel.prototype, "I18n", { get: function () { return this.get('I18n'); }, enumerable: false, configurable: true }); Object.defineProperty(EditorModel.prototype, "Utils", { get: function () { return this.get('Utils'); }, enumerable: false, configurable: true }); Object.defineProperty(EditorModel.prototype, "Commands", { get: function () { return this.get('Commands'); }, enumerable: false, configurable: true }); Object.defineProperty(EditorModel.prototype, "Keymaps", { get: function () { return this.get('Keymaps'); }, enumerable: false, configurable: true }); Object.defineProperty(EditorModel.prototype, "Modal", { get: function () { return this.get('Modal'); }, enumerable: false, configurable: true }); Object.defineProperty(EditorModel.prototype, "Panels", { get: function () { return this.get('Panels'); }, enumerable: false, configurable: true }); Object.defineProperty(EditorModel.prototype, "CodeManager", { get: function () { return this.get('CodeManager'); }, enumerable: false, configurable: true }); Object.defineProperty(EditorModel.prototype, "UndoManager", { get: function () { return this.get('UndoManager'); }, enumerable: false, configurable: true }); Object.defineProperty(EditorModel.prototype, "RichTextEditor", { get: function () { return this.get('RichTextEditor'); }, enumerable: false, configurable: true }); Object.defineProperty(EditorModel.prototype, "Canvas", { get: function () { return this.get('Canvas'); }, enumerable: false, configurable: true }); Object.defineProperty(EditorModel.prototype, "Editor", { get: function () { return this.get('Editor'); }, enumerable: false, configurable: true }); Object.defineProperty(EditorModel.prototype, "Components", { get: function () { return this.get('DomComponents'); }, enumerable: false, configurable: true }); Object.defineProperty(EditorModel.prototype, "Css", { get: function () { return this.get('CssComposer'); }, enumerable: false, configurable: true }); Object.defineProperty(EditorModel.prototype, "Blocks", { get: function () { return this.get('BlockManager'); }, enumerable: false, configurable: true }); Object.defineProperty(EditorModel.prototype, "Selectors", { get: function () { return this.get('SelectorManager'); }, enumerable: false, configurable: true }); Object.defineProperty(EditorModel.prototype, "Storage", { get: function () { return this.get('StorageManager'); }, enumerable: false, configurable: true }); Object.defineProperty(EditorModel.prototype, "Traits", { get: function () { return this.get('TraitManager'); }, enumerable: false, configurable: true }); Object.defineProperty(EditorModel.prototype, "Parser", { get: function () { return this.get('Parser'); }, enumerable: false, configurable: true }); Object.defineProperty(EditorModel.prototype, "Layers", { get: function () { return this.get('LayerManager'); }, enumerable: false, configurable: true }); Object.defineProperty(EditorModel.prototype, "Assets", { get: function () { return this.get('AssetManager'); }, enumerable: false, configurable: true }); Object.defineProperty(EditorModel.prototype, "Devices", { get: function () { return this.get('DeviceManager'); }, enumerable: false, configurable: true }); Object.defineProperty(EditorModel.prototype, "Pages", { get: function () { return this.get('PageManager'); }, enumerable: false, configurable: true }); Object.defineProperty(EditorModel.prototype, "Styles", { get: function () { return this.get('StyleManager'); }, enumerable: false, configurable: true }); EditorModel.prototype._checkReady = function () { if (this.get('readyLoad') && this.get('readyCanvas') && !this.get('ready')) { this.set('ready', true); } }; EditorModel.prototype.getContainer = function () { return this.config.el; }; EditorModel.prototype.listenLog = function (event) { //@ts-ignore this.listenTo(this, "log:".concat(event), logs[event]); }; Object.defineProperty(EditorModel.prototype, "config", { get: function () { return this._config; }, enumerable: false, configurable: true }); /** * Get configurations * @param {string} [prop] Property name * @return {any} Returns the configuration object or * the value of the specified property */ EditorModel.prototype.getConfig = function (prop) { var config = this.config; // @ts-ignore return (0,index_all.isUndefined)(prop) ? config : config[prop]; }; /** * Should be called once all modules and plugins are loaded * @private */ EditorModel.prototype.loadOnStart = function () { var _this = this; var _a = this.config, projectData = _a.projectData, headless = _a.headless; var sm = this.get('StorageManager'); // In `onLoad`, the module will try to load the data from its configurations. this.toLoad.reverse().forEach(function (mdl) { return mdl.onLoad(); }); // Stuff to do post load var postLoad = function () { _this.modules.forEach(function (mdl) { return mdl.postLoad && mdl.postLoad(_this); }); _this.set('readyLoad', 1); }; if (headless) { projectData && this.loadData(projectData); postLoad(); } else { // Defer for storage load events. this._storageTimeout = setTimeout(function () { return Editor_awaiter(_this, void 0, void 0, function () { var error_1; return Editor_generator(this, function (_a) { switch (_a.label) { case 0: if (!projectData) return [3 /*break*/, 1]; this.loadData(projectData); return [3 /*break*/, 5]; case 1: if (!(sm === null || sm === void 0 ? void 0 : sm.canAutoload())) return [3 /*break*/, 5]; _a.label = 2; case 2: _a.trys.push([2, 4, , 5]); return [4 /*yield*/, this.load()]; case 3: _a.sent(); return [3 /*break*/, 5]; case 4: error_1 = _a.sent(); this.logError(error_1); return [3 /*break*/, 5]; case 5: postLoad(); return [2 /*return*/]; } }); }); }); } // Create shallow editor. // Here we can create components/styles without altering/triggering the main EditorModel var shallow = new EditorModel({ noticeOnUnload: false, storageManager: false, undoManager: false, }); // We only need to load a few modules shallow.Pages.onLoad(); shallow.Canvas.postLoad(); this.set('shallow', shallow); }; /** * Set the alert before unload in case it's requested * and there are unsaved changes * @private */ EditorModel.prototype.updateChanges = function () { var _this = this; var stm = this.get('StorageManager'); var changes = this.getDirtyCount(); this.updateItr && clearTimeout(this.updateItr); this.updateItr = setTimeout(function () { return _this.trigger('update'); }); if (this.config.noticeOnUnload) { window.onbeforeunload = changes ? function () { return true; } : null; } if (stm.isAutosave() && changes >= stm.getStepsBeforeSave()) { this.store().catch(function (err) { return _this.logError(err); }); } }; /** * Load generic module */ EditorModel.prototype.loadModule = function (InitModule) { var Mod = new InitModule(this); this.set(Mod.name, Mod); Mod.onLoad && this.toLoad.push(Mod); this.modules.push(Mod); return Mod; }; EditorModel.prototype.loadStorableModule = function (InitModule) { var Mod = this.loadModule(InitModule); this.storables.push(Mod); return Mod; }; /** * Initialize editor model and set editor instance * @param {Editor} editor Editor instance * @return {this} * @public */ EditorModel.prototype.init = function (editor, opts) { if (opts === void 0) { opts = {}; } if (this.destroyed) { this.initialize(opts); this.destroyed = false; } this.set('Editor', editor); }; EditorModel.prototype.getEditor = function () { return this.get('Editor'); }; /** * This method handles updates on the editor and tries to store them * if requested and if the changesCount is exceeded * @param {Object} model * @param {any} val Value * @param {Object} opt Options * @private * */ EditorModel.prototype.handleUpdates = function (model, val, opt) { var _this = this; if (opt === void 0) { opt = {}; } // Component has been added temporarily - do not update storage or record changes if (this.__skip || opt.temporary || opt.noCount || opt.avoidStore || !this.get('ready')) { return; } this.timedInterval && clearTimeout(this.timedInterval); this.timedInterval = setTimeout(function () { var curr = _this.getDirtyCount() || 0; var unset = opt.unset, opts = Editor_rest(opt, ["unset"]); _this.set('changesCount', curr + 1, opts); }, 0); }; EditorModel.prototype.changesUp = function (opts) { this.handleUpdates(0, 0, opts); }; /** * Callback on component hover * @param {Object} Model * @param {Mixed} New value * @param {Object} Options * @private * */ EditorModel.prototype.componentHovered = function (editor, component, options) { var prev = this.previous('componentHovered'); prev && this.trigger('component:unhovered', prev, options); component && this.trigger('component:hovered', component, options); }; /** * Returns model of the selected component * @return {Component|null} * @public */ EditorModel.prototype.getSelected = function () { return this.selected.lastComponent(); }; /** * Returns an array of all selected components * @return {Array} * @public */ EditorModel.prototype.getSelectedAll = function () { return this.selected.allComponents(); }; /** * Select a component * @param {Component|HTMLElement} el Component to select * @param {Object} [opts={}] Options, optional * @public */ EditorModel.prototype.setSelected = function (el, opts) { var _this = this; if (opts === void 0) { opts = {}; } var event = opts.event; var ctrlKey = event && (event.ctrlKey || event.metaKey); var shiftKey = (event || {}).shiftKey; var els = ((0,index_all.isArray)(el) ? el : [el]).map(function (el) { return (0,mixins.getModel)(el, cash_dom["default"]); }); var selected = this.getSelectedAll(); var mltSel = this.getConfig().multipleSelection; var added; // If an array is passed remove all selected // expect those yet to be selected var multiple = (0,index_all.isArray)(el); multiple && this.removeSelected(selected.filter(function (s) { return !(0,index_all.contains)(els, s); })); els.forEach(function (el) { var model = (0,mixins.getModel)(el, undefined); if (model) { _this.trigger('component:select:before', model, opts); // Check for valid selectable if (!model.get('selectable') || opts.abort) { if (opts.useValid) { var parent_1 = model.parent(); while (parent_1 && !parent_1.get('selectable')) parent_1 = parent_1.parent(); model = parent_1; } else { return; } } } // Hanlde multiple selection if (ctrlKey && mltSel) { return _this.toggleSelected(model); } else if (shiftKey && mltSel) { _this.clearSelection(_this.get('Canvas').getWindow()); var coll_1 = model.collection; var index_1 = model.index(); var min_1, max_1; // Fin min and max siblings _this.getSelectedAll().forEach(function (sel) { var selColl = sel.collection; var selIndex = sel.index(); if (selColl === coll_1) { if (selIndex < index_1) { // First model BEFORE the selected one min_1 = (0,index_all.isUndefined)(min_1) ? selIndex : Math.max(min_1, selIndex); } else if (selIndex > index_1) { // First model AFTER the selected one max_1 = (0,index_all.isUndefined)(max_1) ? selIndex : Math.min(max_1, selIndex); } } }); if (!(0,index_all.isUndefined)(min_1)) { while (min_1 !== index_1) { _this.addSelected(coll_1.at(min_1)); min_1++; } } if (!(0,index_all.isUndefined)(max_1)) { while (max_1 !== index_1) { _this.addSelected(coll_1.at(max_1)); max_1--; } } return _this.addSelected(model); } !multiple && _this.removeSelected(selected.filter(function (s) { return s !== model; })); _this.addSelected(model, opts); added = model; }); }; /** * Add component to selection * @param {Component|HTMLElement} el Component to select * @param {Object} [opts={}] Options, optional * @public */ EditorModel.prototype.addSelected = function (el, opts) { var _this = this; if (opts === void 0) { opts = {}; } var model = (0,mixins.getModel)(el, cash_dom["default"]); var models = (0,index_all.isArray)(model) ? model : [model]; models.forEach(function (model) { var selected = _this.selected; if (!model || !model.get('selectable') || // Avoid selecting children of selected components model.parents().some(function (parent) { return selected.hasComponent(parent); })) { return; } opts.forceChange && _this.removeSelected(model, opts); // Remove from selection, children of the component to select var toDeselect = selected.allComponents().filter(function (cmp) { return (0,index_all.contains)(cmp.parents(), model); }); toDeselect.forEach(function (cmp) { return _this.removeSelected(cmp, opts); }); selected.addComponent(model, opts); _this.trigger('component:select', model, opts); _this.Canvas.addSpot({ type: CanvasSpot/* CanvasSpotBuiltInTypes */.q.Select, component: model, }); }); }; /** * Remove component from selection * @param {Component|HTMLElement} el Component to select * @param {Object} [opts={}] Options, optional * @public */ EditorModel.prototype.removeSelected = function (el, opts) { var _this = this; if (opts === void 0) { opts = {}; } var component = (0,mixins.getModel)(el, cash_dom["default"]); this.selected.removeComponent(component, opts); var cmps = (0,index_all.isArray)(component) ? component : [component]; cmps.forEach(function (component) { return _this.Canvas.removeSpots({ type: CanvasSpot/* CanvasSpotBuiltInTypes */.q.Select, component: component, }); }); }; /** * Toggle component selection * @param {Component|HTMLElement} el Component to select * @param {Object} [opts={}] Options, optional * @public */ EditorModel.prototype.toggleSelected = function (el, opts) { var _this = this; if (opts === void 0) { opts = {}; } var model = (0,mixins.getModel)(el, cash_dom["default"]); var models = (0,index_all.isArray)(model) ? model : [model]; models.forEach(function (model) { if (_this.selected.hasComponent(model)) { _this.removeSelected(model, opts); } else { _this.addSelected(model, opts); } }); }; /** * Hover a component * @param {Component|HTMLElement} cmp Component to select * @param {Object} [opts={}] Options, optional * @private */ EditorModel.prototype.setHovered = function (cmp, opts) { var _this = this; if (opts === void 0) { opts = {}; } var upHovered = function (cmp, opts) { var _a = _this, config = _a.config, Canvas = _a.Canvas; var current = _this.getHovered(); var selectedAll = _this.getSelectedAll(); var typeHover = CanvasSpot/* CanvasSpotBuiltInTypes */.q.Hover; var typeSpacing = CanvasSpot/* CanvasSpotBuiltInTypes */.q.Spacing; _this.set('componentHovered', cmp || null, opts); if (current) { Canvas.removeSpots({ type: typeHover, component: current }); Canvas.removeSpots({ type: typeSpacing, component: current }); } if (cmp) { Canvas.addSpot({ type: typeHover, component: cmp }); if (!selectedAll.includes(cmp) || config.showOffsetsSelected) { Canvas.addSpot({ type: typeSpacing, component: cmp }); } } }; if (!cmp) { return upHovered(); } var ev = 'component:hover'; var model = (0,mixins.getModel)(cmp, undefined); if (!model) return; opts.forceChange && upHovered(); this.trigger("".concat(ev, ":before"), model, opts); // Check for valid hoverable if (!model.get('hoverable')) { if (opts.useValid && !opts.abort) { var parent_2 = model.parent(); while (parent_2 && !parent_2.get('hoverable')) parent_2 = parent_2.parent(); model = parent_2; } else { return; } } if (!opts.abort) { upHovered(model, opts); this.trigger(ev, model, opts); } }; EditorModel.prototype.getHovered = function () { return this.get('componentHovered'); }; /** * Set components inside editor's canvas. This method overrides actual components * @param {Object|string} components HTML string or components model * @param {Object} opt the options object to be used by the [setComponents]{@link setComponents} method * @return {this} * @public */ EditorModel.prototype.setComponents = function (components, opt) { if (opt === void 0) { opt = {}; } return this.Components.setComponents(components, opt); }; /** * Returns components model from the editor's canvas * @return {Components} * @private */ EditorModel.prototype.getComponents = function () { var cmp = this.Components; var cm = this.CodeManager; if (!cmp || !cm) return; var wrp = cmp.getComponents(); return cm.getCode(wrp, 'json'); }; /** * Set style inside editor's canvas. This method overrides actual style * @param {Object|string} style CSS string or style model * @param {Object} opt the options object to be used by the `CssRules.add` method * @return {this} * @public */ EditorModel.prototype.setStyle = function (style, opt) { if (opt === void 0) { opt = {}; } var cssc = this.Css; cssc.clear(opt); cssc.getAll().add(style, opt); return this; }; /** * Add styles to the editor * @param {Array<Object>|Object|string} style CSS string or style model * @returns {Array<CssRule>} * @public */ EditorModel.prototype.addStyle = function (style, opts) { if (opts === void 0) { opts = {}; } var res = this.getStyle().add(style, opts); return (0,index_all.isArray)(res) ? res : [res]; }; /** * Returns rules/style model from the editor's canvas * @return {Rules} * @private */ EditorModel.prototype.getStyle = function () { return this.Css.getAll(); }; /** * Change the selector state * @param {String} value State value * @returns {this} */ EditorModel.prototype.setState = function (value) { this.set('state', value); return this; }; /** * Get the current selector state * @returns {String} */ EditorModel.prototype.getState = function () { return this.get('state') || ''; }; /** * Returns HTML built inside canvas * @param {Object} [opts={}] Options * @returns {string} HTML string * @public */ EditorModel.prototype.getHtml = function (opts) { if (opts === void 0) { opts = {}; } var config = this.config; var optsHtml = config.optsHtml; var js = config.jsInHtml ? this.getJs(opts) : ''; var cmp = opts.component || this.Components.getComponent(); var html = cmp ? this.CodeManager.getCode(cmp, 'html', Editor_assign(Editor_assign({}, optsHtml), opts)) : ''; html += js ? "<script>".concat(js, "</script>") : ''; return html; }; /** * Returns CSS built inside canvas * @param {Object} [opts={}] Options * @returns {string} CSS string * @public */ EditorModel.prototype.getCss = function (opts) { if (opts === void 0) { opts = {}; } var config = this.config; var optsCss = config.optsCss; var avoidProt = opts.avoidProtected; var keepUnusedStyles = !(0,index_all.isUndefined)(opts.keepUnusedStyles) ? opts.keepUnusedStyles : config.keepUnusedStyles; var cssc = this.Css; var wrp = opts.component || this.Components.getComponent(); var protCss = !avoidProt ? config.protectedCss : ''; var css = wrp && this.CodeManager.getCode(wrp, 'css', Editor_assign(Editor_assign({ cssc: cssc, keepUnusedStyles: keepUnusedStyles }, optsCss), opts)); return wrp ? (opts.json ? css : protCss + css) : ''; }; /** * Returns JS of all components * @return {string} JS string * @public */ EditorModel.prototype.getJs = function (opts) { if (opts === void 0) { opts = {}; } var wrp = opts.component || this.Components.getWrapper(); return wrp ? this.CodeManager.getCode(wrp, 'js').trim() : ''; }; /** * Store data to the current storage. * @public */ EditorModel.prototype.store = function (options) { return Editor_awaiter(this, void 0, void 0, function () { var data; return Editor_generator(this, function (_a) { switch (_a.label) { case 0: data = this.storeData(); return [4 /*yield*/, this.Storage.store(data, options)]; case 1: _a.sent(); this.clearDirtyCount(); return [2 /*return*/, data]; } }); }); }; /** * Load data from the current storage. * @public */ EditorModel.prototype.load = function (options, loadOptions) { if (loadOptions === void 0) { loadOptions = {}; } return Editor_awaiter(this, void 0, void 0, function () { var result; return Editor_generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.Storage.load(options)]; case 1: result = _a.sent(); this.loadData(result); // Wait in order to properly update the dirty counter (#5385) return [4 /*yield*/, (0,mixins.wait)()]; case 2: // Wait in order to properly update the dirty counter (#5385) _a.sent(); if (loadOptions.clear) { this.UndoManager.clear(); this.clearDirtyCount(); } return [2 /*return*/, result]; } }); }); }; EditorModel.prototype.storeData = function () { var result = {}; // Sync content if there is an active RTE var editingCmp = this.getEditing(); editingCmp && editingCmp.trigger('sync:content', { noCount: true }); this.storables.forEach(function (m) { result = Editor_assign(Editor_assign({}, result), m.store(1)); }); return JSON.parse(JSON.stringify(result)); }; EditorModel.prototype.loadData = function (data) { if (data === void 0) { data = {}; } if (!(0,mixins.isEmptyObj)(data)) { this.storables.forEach(function (module) { return module.clear(); }); this.storables.forEach(function (module) { return module.load(data); }); } return data; }; /** * Returns device model by name * @return {Device|null} * @private */ EditorModel.prototype.getDeviceModel = function () { var name = this.get('device'); return this.Devices.get(name); }; /** * Run default command if setted * @param {Object} [opts={}] Options * @private */ EditorModel.prototype.runDefault = function (opts) { if (opts === void 0) { opts = {}; } var command = this.get('Commands').get(this.config.defaultCommand); if (!command || this.defaultRunning) return; command.stop(this, this, opts); command.run(this, this, opts); this.defaultRunning = true; }; /** * Stop default command * @param {Object} [opts={}] Options * @private */ EditorModel.prototype.stopDefault = function (opts) { if (opts === void 0) { opts = {}; } var commands = this.get('Commands'); var command = commands.get(this.config.defaultCommand); if (!command || !this.defaultRunning) return; command.stop(this, this, opts); this.defaultRunning = false; }; /** * Update canvas dimensions and refresh data useful for tools positioning * @public */ EditorModel.prototype.refreshCanvas = function (opts) { if (opts === void 0) { opts = {}; } this.set('canvasOffset', null); this.set('canvasOffset', this.Canvas.getOffset()); opts.tools && this.trigger('canvas:updateTools'); }; /** * Clear all selected stuf inside the window, sometimes is useful to call before * doing some dragging opearation * @param {Window} win If not passed the current one will be used * @private */ EditorModel.prototype.clearSelection = function (win) { var _a; var w = win || window; (_a = w.getSelection()) === null || _a === void 0 ? void 0 : _a.removeAllRanges(); }; /** * Get the current media text * @return {string} */ EditorModel.prototype.getCurrentMedia = function () { var config = this.config; var device = this.getDeviceModel(); var condition = config.mediaCondition; var preview = config.devicePreviewMode; var width = device && device.get('widthMedia'); return device && width && !preview ? "(".concat(condition, ": ").concat(width, ")") : ''; }; /** * Return the component wrapper * @return {Component} */ EditorModel.prototype.getWrapper = function () { return this.Components.getWrapper(); }; EditorModel.prototype.setCurrentFrame = function (frameView) { return this.set('currentFrame', frameView); }; EditorModel.prototype.getCurrentFrame = function () { return this.get('currentFrame'); }; EditorModel.prototype.getCurrentFrameModel = function () { var _a; return (_a = (this.getCurrentFrame() || {})) === null || _a === void 0 ? void 0 : _a.model; }; EditorModel.prototype.getIcon = function (icon) { var icons = this.config.icons || {}; return icons[icon] || ''; }; /** * Return the count of changes made to the content and not yet stored. * This count resets at any `store()` * @return {number} */ EditorModel.prototype.getDirtyCount = function () { return this.get('changesCount'); }; EditorModel.prototype.clearDirtyCount = function () { return this.set('changesCount', 0); }; EditorModel.prototype.getZoomDecimal = function () { return this.Canvas.getZoomDecimal(); }; EditorModel.prototype.getZoomMultiplier = function () { return this.Canvas.getZoomMultiplier(); }; EditorModel.prototype.setDragMode = function (value) { return this.set('dmode', value); }; EditorModel.prototype.getDragMode = function (component) { var mode = (component === null || component === void 0 ? void 0 : component.getDragMode()) || this.get('dmode'); return mode || ''; }; EditorModel.prototype.t = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var i18n = this.get('I18n'); return i18n === null || i18n === void 0 ? void 0 : i18n.t.apply(i18n, args); }; /** * Returns true if the editor is in absolute mode * @returns {Boolean} */ EditorModel.prototype.inAbsoluteMode = function (component) { return this.getDragMode(component) === 'absolute'; }; /** * Destroy editor */ EditorModel.prototype.destroyAll = function () { var _this = this; var _a = this, config = _a.config, view = _a.view; var editor = this.getEditor(); // @ts-ignore var _b = (config.grapesjs || {}).editors, editors = _b === void 0 ? [] : _b; var shallow = this.get('shallow'); this._storageTimeout && clearTimeout(this._storageTimeout); shallow === null || shallow === void 0 ? void 0 : shallow.destroyAll(); this.stopListening(); this.stopDefault(); this.modules .slice() .reverse() .forEach(function (mod) { return mod.destroy(); }); view && view.remove(); this.clear({ silent: true }); this.destroyed = true; ['_config', 'view', '_previousAttributes', '_events', '_listeners'].forEach( //@ts-ignore function (i) { return (_this[i] = {}); }); editors.splice(editors.indexOf(editor), 1); //@ts-ignore (0,mixins.hasWin)() && (0,cash_dom["default"])(config.el).empty().attr(this.attrsOrig); }; EditorModel.prototype.getEditing = function () { var res = this.get('editing'); return (res && res.model) || undefined; }; EditorModel.prototype.setEditing = function (value) { this.set('editing', value); return this; }; EditorModel.prototype.isEditing = function () { return !!this.get('editing'); }; EditorModel.prototype.log = function (msg, opts) { if (opts === void 0) { opts = {}; } var ns = opts.ns, _a = opts.level, level = _a === void 0 ? 'debug' : _a; this.trigger('log', msg, opts); level && this.trigger("log:".concat(level), msg, opts); if (ns) { var logNs = "log-".concat(ns); this.trigger(logNs, msg, opts); level && this.trigger("".concat(logNs, ":").concat(level), msg, opts); } }; EditorModel.prototype.logInfo = function (msg, opts) { this.log(msg, Editor_assign(Editor_assign({}, opts), { level: 'info' })); }; EditorModel.prototype.logWarning = function (msg, opts) { this.log(msg, Editor_assign(Editor_assign({}, opts), { level: 'warning' })); }; EditorModel.prototype.logError = function (msg, opts) { this.log(msg, Editor_assign(Editor_assign({}, opts), { level: 'error' })); }; EditorModel.prototype.initBaseColorPicker = function (el, opts) { if (opts === void 0) { opts = {}; } var config = this.config; var _a = config.colorPicker, colorPicker = _a === void 0 ? {} : _a; var elToAppend = config.el; var ppfx = config.stylePrefix; //@ts-ignore return (0,cash_dom["default"])(el).spectrum(Editor_assign(Editor_assign({ containerClassName: "".concat(ppfx, "one-bg ").concat(ppfx, "two-color"), appendTo: elToAppend || 'body', maxSelectionSize: 8, showPalette: true, palette: [], showAlpha: true, chooseText: 'Ok', cancelText: '⨯' }, opts), colorPicker)); }; /** * Execute actions without triggering the storage and undo manager. * @param {Function} clb * @private */ EditorModel.prototype.skip = function (clb) { this.__skip = true; var um = this.UndoManager; um ? um.skip(clb) : clb(); this.__skip = false; }; /** * Set/get data from the HTMLElement * @param {HTMLElement} el * @param {string} name Data name * @param {any} value Date value * @return {any} * @private */ EditorModel.prototype.data = function (el, name, value) { var varName = '_gjs-data'; if (!el[varName]) { el[varName] = {}; } if ((0,index_all.isUndefined)(value)) { return el[varName][name]; } else { el[varName][name] = value; } }; return EditorModel; }(common/* Model */.Hn)); /* harmony default export */ const model_Editor = (EditorModel); ;// CONCATENATED MODULE: ./src/editor/view/EditorView.ts var view_EditorView_extends = ( false) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var EditorView_EditorView = /** @class */ (function (_super) { view_EditorView_extends(EditorView, _super); function EditorView(model) { var _this = _super.call(this, { model: model }) || this; //const { model } = this; var _a = model.attributes, Panels = _a.Panels, UndoManager = _a.UndoManager; model.view = _this; model.once('change:ready', function () { Panels.active(); Panels.disableButtons(); UndoManager.clear(); setTimeout(function () { model.trigger('load', model.get('Editor')); model.clearDirtyCount(); }); }); return _this; } EditorView.prototype.render = function () { var _this = this; var _a = this, $el = _a.$el, model = _a.model; var _b = model.attributes, Panels = _b.Panels, Canvas = _b.Canvas; var config = model.config, modules = model.modules; var pfx = config.stylePrefix; var classNames = ["".concat(pfx, "editor")]; !config.customUI && classNames.push("".concat(pfx, "one-bg ").concat(pfx, "two-color")); // @ts-ignore var contEl = (0,cash_dom["default"])(config.el || "body ".concat(config.container)); config.cssIcons && (0,mixins.appendStyles)(config.cssIcons, { unique: true, prepand: true }); $el.empty(); // @ts-ignore if (config.width) contEl.css('width', config.width); // @ts-ignore if (config.height) contEl.css('height', config.height); $el.append(Canvas.render()); $el.append(Panels.render()); // Load shallow editor var shallow = model.get('shallow'); var shallowCanvasEl = shallow.get('Canvas').render(); shallowCanvasEl.style.display = 'none'; $el.append(shallowCanvasEl); $el.attr('class', classNames.join(' ')); // @ts-ignore contEl.addClass("".concat(pfx, "editor-cont")).empty().append($el); modules.forEach(function (md) { return md.postRender && md.postRender(_this); }); return this; }; return EditorView; }(common/* View */.G7)); /* harmony default export */ const view_EditorView = (EditorView_EditorView); ;// CONCATENATED MODULE: ./src/editor/index.ts var editor_assign = ( false) || function () { editor_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return editor_assign.apply(this, arguments); }; var editor_awaiter = ( false) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var editor_generator = ( false) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var editor_spreadArray = ( false) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var Editor = /** @class */ (function () { function Editor(config, opts) { if (config === void 0) { config = {}; } if (opts === void 0) { opts = {}; } var _a; /** * Print safe HTML by using ES6 tagged template strings. * @param {Array<String>} literals * @param {Array<String>} substs * @returns {String} * @example * const unsafeStr = '<script>....</script>'; * const safeStr = '<b>Hello</b>'; * // Use `$${var}` to avoid escaping * const strHtml = editor.html`Escaped ${unsafeStr} unescaped $${safeStr}`; */ this.html = html; this.config = editor_assign(editor_assign(editor_assign({}, config_config), config), { pStylePrefix: (_a = config.stylePrefix) !== null && _a !== void 0 ? _a : config_config.stylePrefix }); this.em = new model_Editor(this.config); this.$ = opts.$; this.em.init(this); this.editor = this.em; } Object.defineProperty(Editor.prototype, "Config", { get: function () { return this.em.config; }, enumerable: false, configurable: true }); Object.defineProperty(Editor.prototype, "I18n", { get: function () { return this.em.I18n; }, enumerable: false, configurable: true }); Object.defineProperty(Editor.prototype, "Utils", { get: function () { return this.em.Utils; }, enumerable: false, configurable: true }); Object.defineProperty(Editor.prototype, "Commands", { get: function () { return this.em.Commands; }, enumerable: false, configurable: true }); Object.defineProperty(Editor.prototype, "Keymaps", { get: function () { return this.em.Keymaps; }, enumerable: false, configurable: true }); Object.defineProperty(Editor.prototype, "Modal", { get: function () { return this.em.Modal; }, enumerable: false, configurable: true }); Object.defineProperty(Editor.prototype, "Panels", { get: function () { return this.em.Panels; }, enumerable: false, configurable: true }); Object.defineProperty(Editor.prototype, "Canvas", { get: function () { return this.em.Canvas; }, enumerable: false, configurable: true }); Object.defineProperty(Editor.prototype, "Parser", { get: function () { return this.em.Parser; }, enumerable: false, configurable: true }); Object.defineProperty(Editor.prototype, "CodeManager", { get: function () { return this.em.CodeManager; }, enumerable: false, configurable: true }); Object.defineProperty(Editor.prototype, "UndoManager", { get: function () { return this.em.UndoManager; }, enumerable: false, configurable: true }); Object.defineProperty(Editor.prototype, "RichTextEditor", { get: function () { return this.em.RichTextEditor; }, enumerable: false, configurable: true }); Object.defineProperty(Editor.prototype, "Pages", { get: function () { return this.em.Pages; }, enumerable: false, configurable: true }); Object.defineProperty(Editor.prototype, "Components", { get: function () { return this.em.Components; }, enumerable: false, configurable: true }); Object.defineProperty(Editor.prototype, "DomComponents", { get: function () { return this.em.Components; }, enumerable: false, configurable: true }); Object.defineProperty(Editor.prototype, "Layers", { get: function () { return this.em.Layers; }, enumerable: false, configurable: true }); Object.defineProperty(Editor.prototype, "LayerManager", { get: function () { return this.em.Layers; }, enumerable: false, configurable: true }); Object.defineProperty(Editor.prototype, "Css", { get: function () { return this.em.Css; }, enumerable: false, configurable: true }); Object.defineProperty(Editor.prototype, "CssComposer", { get: function () { return this.em.Css; }, enumerable: false, configurable: true }); Object.defineProperty(Editor.prototype, "Storage", { get: function () { return this.em.Storage; }, enumerable: false, configurable: true }); Object.defineProperty(Editor.prototype, "StorageManager", { get: function () { return this.em.Storage; }, enumerable: false, configurable: true }); Object.defineProperty(Editor.prototype, "Assets", { get: function () { return this.em.Assets; }, enumerable: false, configurable: true }); Object.defineProperty(Editor.prototype, "AssetManager", { get: function () { return this.em.Assets; }, enumerable: false, configurable: true }); Object.defineProperty(Editor.prototype, "Blocks", { get: function () { return this.em.Blocks; }, enumerable: false, configurable: true }); Object.defineProperty(Editor.prototype, "BlockManager", { get: function () { return this.em.Blocks; }, enumerable: false, configurable: true }); Object.defineProperty(Editor.prototype, "Traits", { get: function () { return this.em.Traits; }, enumerable: false, configurable: true }); Object.defineProperty(Editor.prototype, "TraitManager", { get: function () { return this.em.Traits; }, enumerable: false, configurable: true }); Object.defineProperty(Editor.prototype, "Selectors", { get: function () { return this.em.Selectors; }, enumerable: false, configurable: true }); Object.defineProperty(Editor.prototype, "SelectorManager", { get: function () { return this.em.Selectors; }, enumerable: false, configurable: true }); Object.defineProperty(Editor.prototype, "Styles", { get: function () { return this.em.Styles; }, enumerable: false, configurable: true }); Object.defineProperty(Editor.prototype, "StyleManager", { get: function () { return this.em.Styles; }, enumerable: false, configurable: true }); Object.defineProperty(Editor.prototype, "Devices", { get: function () { return this.em.Devices; }, enumerable: false, configurable: true }); Object.defineProperty(Editor.prototype, "DeviceManager", { get: function () { return this.em.Devices; }, enumerable: false, configurable: true }); Object.defineProperty(Editor.prototype, "EditorModel", { get: function () { return this.em; }, enumerable: false, configurable: true }); /** * Returns configuration object * @returns {any} Returns the configuration object or the value of the specified property */ Editor.prototype.getConfig = function (prop) { return this.em.getConfig(prop); }; /** * Returns HTML built inside canvas * @param {Object} [opts={}] Options * @param {Component} [opts.component] Return the HTML of a specific Component * @param {Boolean} [opts.cleanId=false] Remove unnecessary IDs (eg. those created automatically) * @returns {string} HTML string */ Editor.prototype.getHtml = function (opts) { return this.em.getHtml(opts); }; /** * Returns CSS built inside canvas * @param {Object} [opts={}] Options * @param {Component} [opts.component] Return the CSS of a specific Component * @param {Boolean} [opts.json=false] Return an array of CssRules instead of the CSS string * @param {Boolean} [opts.avoidProtected=false] Don't include protected CSS * @param {Boolean} [opts.onlyMatched=false] Return only rules matched by the passed component. * @param {Boolean} [opts.keepUnusedStyles=false] Force keep all defined rules. Toggle on in case output looks different inside/outside of the editor. * @returns {String|Array<CssRule>} CSS string or array of CssRules */ Editor.prototype.getCss = function (opts) { return this.em.getCss(opts); }; /** * Returns JS of all components * @param {Object} [opts={}] Options * @param {Component} [opts.component] Get the JS of a specific component * @returns {String} JS string */ Editor.prototype.getJs = function (opts) { return this.em.getJs(opts); }; /** * Return the complete tree of components. Use `getWrapper` to include also the wrapper * @return {Components} */ Editor.prototype.getComponents = function () { return this.Components.getComponents(); }; /** * Return the wrapper and its all components * @return {Component} */ Editor.prototype.getWrapper = function () { return this.Components.getWrapper(); }; /** * Set components inside editor's canvas. This method overrides actual components * @param {Array<Object>|Object|string} components HTML string or components model * @param {Object} opt the options object to be used by the [setComponents]{@link em#setComponents} method * @return {this} * @example * editor.setComponents('<div class="cls">New component</div>'); * // or * editor.setComponents({ * type: 'text', * classes:['cls'], * content: 'New component' * }); */ Editor.prototype.setComponents = function (components, opt) { if (opt === void 0) { opt = {}; } this.em.setComponents(components, opt); return this; }; /** * Add components * @param {Array<Object>|Object|string} components HTML string or components model * @param {Object} opts Options * @param {Boolean} [opts.avoidUpdateStyle=false] If the HTML string contains styles, * by default, they will be created and, if already exist, updated. When this option * is true, styles already created will not be updated. * @return {Array<Component>} * @example * editor.addComponents('<div class="cls">New component</div>'); * // or * editor.addComponents({ * type: 'text', * classes:['cls'], * content: 'New component' * }); */ Editor.prototype.addComponents = function (components, opts) { return this.getWrapper().append(components, opts); }; /** * Returns style in JSON format object * @return {Object} */ Editor.prototype.getStyle = function () { return this.em.Css.getAll(); }; /** * Set style inside editor's canvas. This method overrides actual style * @param {Array<Object>|Object|string} style CSS string or style model * @return {this} * @example * editor.setStyle('.cls{color: red}'); * //or * editor.setStyle({ * selectors: ['cls'], * style: { color: 'red' } * }); */ Editor.prototype.setStyle = function (style, opt) { if (opt === void 0) { opt = {}; } this.em.setStyle(style, opt); return this; }; /** * Add styles to the editor * @param {Array<Object>|Object|string} style CSS string or style model * @returns {Array<CssRule>} Array of created CssRule instances * @example * editor.addStyle('.cls{color: red}'); */ Editor.prototype.addStyle = function (style, opts) { if (opts === void 0) { opts = {}; } return this.em.addStyle(style, opts); }; /** * Returns the last selected component, if there is one * @return {Model} */ Editor.prototype.getSelected = function () { return this.em.getSelected(); }; /** * Returns an array of all selected components * @return {Array} */ Editor.prototype.getSelectedAll = function () { return this.em.getSelectedAll(); }; /** * Get a stylable entity from the selected component. * If you select a component without classes the entity is the Component * itself and all changes will go inside its 'style' attribute. Otherwise, * if the selected component has one or more classes, the function will * return the corresponding CSS Rule * @return {Model} */ Editor.prototype.getSelectedToStyle = function () { var selected = this.em.getSelected(); if (selected) { return this.StyleManager.getModelToStyle(selected); } }; /** * Select a component * @param {Component|HTMLElement} el Component to select * @param {Object} [opts] Options * @param {Boolean} [opts.scroll] Scroll canvas to the selected element * @return {this} * @example * // Select dropped block * editor.on('block:drag:stop', function(model) { * editor.select(model); * }); */ Editor.prototype.select = function (el, opts) { this.em.setSelected(el, opts); return this; }; /** * Add component to selection * @param {Component|HTMLElement|Array} el Component to select * @return {this} * @example * editor.selectAdd(model); */ // selectAdd(el: Parameters<EditorModel['addSelected']>[0]) { Editor.prototype.selectAdd = function (el) { this.em.addSelected(el); return this; }; /** * Remove component from selection * @param {Component|HTMLElement|Array} el Component to select * @return {this} * @example * editor.selectRemove(model); */ Editor.prototype.selectRemove = function (el) { this.em.removeSelected(el); return this; }; /** * Toggle component selection * @param {Component|HTMLElement|Array} el Component to select * @return {this} * @example * editor.selectToggle(model); */ Editor.prototype.selectToggle = function (el) { this.em.toggleSelected(el); return this; }; /** * Returns, if active, the Component enabled in rich text editing mode. * @returns {Component|null} * @example * const textComp = editor.getEditing(); * if (textComp) { * console.log('HTML: ', textComp.toHTML()); * } */ Editor.prototype.getEditing = function () { return this.em.getEditing(); }; /** * Set device to the editor. If the device exists it will * change the canvas to the proper width * @param {string} name Name of the device * @return {this} * @example * editor.setDevice('Tablet'); */ Editor.prototype.setDevice = function (name) { this.em.set('device', name); return this; }; /** * Return the actual active device * @return {string} Device name * @example * var device = editor.getDevice(); * console.log(device); * // 'Tablet' */ Editor.prototype.getDevice = function () { return this.em.get('device'); }; /** * Execute command * @param {string} id Command ID * @param {Object} options Custom options * @return {*} The return is defined by the command * @example * editor.runCommand('myCommand', {someValue: 1}); */ Editor.prototype.runCommand = function (id, options) { if (options === void 0) { options = {}; } return this.Commands.run(id, options); }; /** * Stop the command if stop method was provided * @param {string} id Command ID * @param {Object} options Custom options * @return {*} The return is defined by the command * @example * editor.stopCommand('myCommand', {someValue: 1}); */ Editor.prototype.stopCommand = function (id, options) { if (options === void 0) { options = {}; } return this.Commands.stop(id, options); }; /** * Store data to the current storage. * This will reset the counter of changes (`editor.getDirtyCount()`). * @param {Object} [options] Storage options. * @returns {Object} Stored data. * @example * const storedData = await editor.store(); */ Editor.prototype.store = function (options) { return editor_awaiter(this, void 0, void 0, function () { return editor_generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.em.store(options)]; case 1: return [2 /*return*/, _a.sent()]; } }); }); }; /** * Load data from the current storage. * @param {Object} [options] Storage options. * @param {Object} [loadOptions={}] Load options. * @param {Boolean} [loadOptions.clear=false] Clear the editor state (eg. dirty counter, undo manager, etc.). * @returns {Object} Loaded data. * @example * const data = await editor.load(); */ Editor.prototype.load = function (options, loadOptions) { if (loadOptions === void 0) { loadOptions = {}; } return editor_awaiter(this, void 0, void 0, function () { return editor_generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.em.load(options, loadOptions)]; case 1: return [2 /*return*/, _a.sent()]; } }); }); }; /** * Get the JSON project data, which could be stored and loaded back with `editor.loadProjectData(json)` * @returns {Object} * @example * console.log(editor.getProjectData()); * // { pages: [...], styles: [...], ... } */ Editor.prototype.getProjectData = function () { return this.em.storeData(); }; /** * Load data from the JSON project * @param {Object} data Project to load * @example * editor.loadProjectData({ pages: [...], styles: [...], ... }) */ Editor.prototype.loadProjectData = function (data) { return this.em.loadData(data); }; Editor.prototype.storeData = function () { return this.em.storeData(); }; Editor.prototype.loadData = function (data) { return this.em.loadData(data); }; /** * Returns container element. The one which was indicated as 'container' * on init method * @return {HTMLElement} */ Editor.prototype.getContainer = function () { return this.config.el; }; /** * Return the count of changes made to the content and not yet stored. * This count resets at any `store()` * @return {number} */ Editor.prototype.getDirtyCount = function () { return this.em.getDirtyCount(); }; /** * Reset the counter of changes. */ Editor.prototype.clearDirtyCount = function () { return this.em.clearDirtyCount(); }; /** * Update editor dimension offsets * * This method could be useful when you update, for example, some position * of the editor element (eg. canvas, panels, etc.) with CSS, where without * refresh you'll get misleading position of tools * @param {Object} [options] Options * @param {Boolean} [options.tools=false] Update the position of tools (eg. rich text editor, component highlighter, etc.) */ Editor.prototype.refresh = function (opts) { this.em.refreshCanvas(opts); }; /** * Replace the built-in Rich Text Editor with a custom one. * @param {Object} obj Custom RTE Interface * @example * editor.setCustomRte({ * // Function for enabling custom RTE * // el is the HTMLElement of the double clicked Text Component * // rte is the same instance you have returned the first time you call * // enable(). This is useful if need to check if the RTE is already enabled so * // ion this case you'll need to return the RTE and the end of the function * enable: function(el, rte) { * rte = new MyCustomRte(el, {}); // this depends on the Custom RTE API * ... * return rte; // return the RTE instance * } * * // Disable the editor, called for example when you unfocus the Text Component * disable: function(el, rte) { * rte.blur(); // this depends on the Custom RTE API * } * * // Called when the Text Component is focused again. If you returned the RTE instance * // from the enable function, the enable won't be called again instead will call focus, * // in this case to avoid double binding of the editor * focus: function (el, rte) { * rte.focus(); // this depends on the Custom RTE API * } * }); */ Editor.prototype.setCustomRte = function (obj) { this.RichTextEditor.customRte = obj; }; /** * Replace the default CSS parser with a custom one. * The parser function receives a CSS string as a parameter and expects * an array of CSSRule objects as a result. If you need to remove the * custom parser, pass `null` as the argument * @param {Function|null} parser Parser function * @return {this} * @example * editor.setCustomParserCss(css => { * const result = []; * // ... parse the CSS string * result.push({ * selectors: '.someclass, div .otherclass', * style: { color: 'red' } * }) * // ... * return result; * }); */ Editor.prototype.setCustomParserCss = function (parser) { this.Parser.getConfig().parserCss = parser; return this; }; /** * Change the global drag mode of components. * To get more about this feature read: https://github.com/GrapesJS/grapesjs/issues/1936 * @param {String} value Drag mode, options: 'absolute' | 'translate' * @returns {this} */ Editor.prototype.setDragMode = function (value) { this.em.setDragMode(value); return this; }; /** * Trigger event log message * @param {*} msg Message to log * @param {Object} [opts={}] Custom options * @param {String} [opts.ns=''] Namespace of the log (eg. to use in plugins) * @param {String} [opts.level='debug'] Level of the log, `debug`, `info`, `warning`, `error` * @return {this} * @example * editor.log('Something done!', { ns: 'from-plugin-x', level: 'info' }); * // This will trigger following events * // `log`, `log:info`, `log-from-plugin-x`, `log-from-plugin-x:info` * // Callbacks of those events will always receive the message and * // options, as arguments, eg: * // editor.on('log:info', (msg, opts) => console.info(msg, opts)) */ Editor.prototype.log = function (msg, opts) { if (opts === void 0) { opts = {}; } this.em.log(msg, opts); return this; }; /** * Translate label * @param {String} key Label to translate * @param {Object} [opts] Options for the translation * @param {Object} [opts.params] Params for the translation * @param {Boolean} [opts.noWarn] Avoid warnings in case of missing resources * @returns {String} * @example * editor.t('msg'); * // use params * editor.t('msg2', { params: { test: 'hello' } }); * // custom local * editor.t('msg2', { params: { test: 'hello' } l: 'it' }); */ Editor.prototype.t = function () { var _a; var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return (_a = this.em).t.apply(_a, args); }; /** * Attach event * @param {string} event Event name * @param {Function} callback Callback function * @return {this} */ Editor.prototype.on = function (event, callback) { this.em.on(event, callback); return this; }; /** * Attach event and detach it after the first run * @param {string} event Event name * @param {Function} callback Callback function * @return {this} */ Editor.prototype.once = function (event, callback) { this.em.once(event, callback); return this; }; /** * Detach event * @param {string} event Event name * @param {Function} callback Callback function * @return {this} */ Editor.prototype.off = function (event, callback) { this.em.off(event, callback); return this; }; /** * Trigger event * @param {string} event Event to trigger * @return {this} */ Editor.prototype.trigger = function (event) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } this.em.trigger.apply(this.em, editor_spreadArray([event], args, true)); return this; }; /** * Destroy the editor */ Editor.prototype.destroy = function () { if (!this.em) return; this.em.destroyAll(); this.editorView = undefined; }; /** * Returns editor element * @return {HTMLElement} * @private */ Editor.prototype.getEl = function () { var _a; return (_a = this.editorView) === null || _a === void 0 ? void 0 : _a.el; }; /** * Returns editor model * @return {Model} * @private */ Editor.prototype.getModel = function () { return this.em; }; /** * Render editor * @return {HTMLElement} */ Editor.prototype.render = function () { var _a; (_a = this.editorView) === null || _a === void 0 ? void 0 : _a.remove(); this.editorView = new view_EditorView(this.em); return this.editorView.render().el; }; /** * Trigger a callback once the editor is loaded and rendered. * The callback will be executed immediately if the method is called on the already rendered editor. * @param {Function} clb Callback to trigger * @example * editor.onReady(() => { * // perform actions * }); */ Editor.prototype.onReady = function (clb) { this.em.get('ready') ? clb(this) : this.em.on('load', clb); }; return Editor; }()); /* harmony default export */ const src_editor = (Editor); ;// CONCATENATED MODULE: ./src/plugin_manager/index.ts var getPluginById = function (pluginId, plugins) { var result = plugins.get(pluginId); // Try to search in global context if (!result) { var wplg = (0,mixins.getGlobal)()[pluginId]; result = (wplg === null || wplg === void 0 ? void 0 : wplg.default) || wplg; } return result; }; var getPlugin = function (plugin, plugins) { return (0,index_all.isString)(plugin) ? getPluginById(plugin, plugins) : (plugin === null || plugin === void 0 ? void 0 : plugin.default) || plugin; }; var logPluginWarn = function (editor, plugin) { editor.getModel().logWarning("Plugin ".concat(plugin, " not found"), { context: 'plugins', plugin: plugin, }); }; var PluginManager = /** @class */ (function () { function PluginManager() { this.plugins = {}; } /** * Add new plugin. Plugins could not be overwritten * @param {string} id Plugin ID * @param {Function} plugin Function which contains all plugin logic * @return {Function} The plugin function * @deprecated Don't use named plugins, create plugins as simple functions. More about [Plugins](https://grapesjs.com/docs/modules/Plugins.html) * @example * PluginManager.add('some-plugin', function(editor) { * editor.Commands.add('new-command', { * run: function(editor, senderBtn){ * console.log('Executed new-command'); * } * }) * }); */ PluginManager.prototype.add = function (id, plugin) { var plg = this.get(id); if (plg) { return plg; } // @ts-ignore this.plugins[id] = plugin; return plugin; }; /** * Returns plugin by ID * @param {string} id Plugin ID * @return {Function|undefined} Plugin * @example * var plugin = PluginManager.get('some-plugin'); * plugin(editor); */ PluginManager.prototype.get = function (id) { return this.plugins[id]; }; /** * Returns object with all plugins */ PluginManager.prototype.getAll = function () { return this.plugins; }; return PluginManager; }()); /* harmony default export */ const plugin_manager = (PluginManager); ;// CONCATENATED MODULE: ./src/utils/polyfills.ts /** * File made for IE/Edge support * https://github.com/GrapesJS/grapesjs/issues/214 */ /* harmony default export */ const polyfills = (function () { /** * Check if IE/Edge * @return {Boolean} */ var isIE = function () { var match; var agent = window.navigator.userAgent; var rules = [ ['edge', /Edge\/([0-9\._]+)/], ['ie', /MSIE\s(7\.0)/], ['ie', /MSIE\s([0-9\.]+);.*Trident\/[4-7].0/], ['ie', /Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/], ]; for (var i = 0; i < rules.length; i++) { var rule = rules[i]; match = rule[1].exec(agent); if (match) break; } return !!match; }; if ((0,mixins.hasWin)() && isIE()) { var originalCreateHTMLDocument_1 = DOMImplementation.prototype.createHTMLDocument; DOMImplementation.prototype.createHTMLDocument = function (title) { if (!title) title = ''; return originalCreateHTMLDocument_1.apply(document.implementation, [title]); }; } }); ;// CONCATENATED MODULE: ./src/index.ts var src_assign = ( false) || function () { src_assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return src_assign.apply(this, arguments); }; polyfills(); var plugins = new plugin_manager(); var editors = []; var usePlugin = function (plugin, opts) { var pluginResult = getPlugin(plugin, plugins); return function (editor) { if (pluginResult) { pluginResult(editor, opts || {}); } else { logPluginWarn(editor, plugin); } }; }; var grapesjs = { $: cash_dom["default"], editors: editors, plugins: plugins, usePlugin: usePlugin, // @ts-ignore Will be replaced on build version: '0.21.6', /** * Initialize the editor with passed options * @param {Object} config Configuration object * @param {string|HTMLElement} config.container Selector which indicates where render the editor * @param {Boolean} [config.autorender=true] If true, auto-render the content * @param {Array} [config.plugins=[]] Array of plugins to execute on start * @param {Object} [config.pluginsOpts={}] Custom options for plugins * @param {Boolean} [config.headless=false] Init headless editor * @return {Editor} Editor instance * @example * var editor = grapesjs.init({ * container: '#myeditor', * components: '<article class="hello">Hello world</article>', * style: '.hello{color: red}', * }) */ init: function (config) { if (config === void 0) { config = {}; } var headless = config.headless; var els = config.container; if (!els && !headless) throw new Error("'container' is required"); var initConfig = src_assign(src_assign({ autorender: true, plugins: [], pluginsOpts: {} }, config), { grapesjs: this, el: headless ? undefined : (0,index_all.isElement)(els) ? els : document.querySelector(els) }); var editor = new src_editor(initConfig, { $: cash_dom["default"] }); var em = editor.getModel(); // Load plugins initConfig.plugins.forEach(function (pluginId) { var plugin = getPlugin(pluginId, plugins); var plgOptions = initConfig.pluginsOpts[pluginId] || {}; if (plugin) { plugin(editor, plgOptions); } else { logPluginWarn(editor, pluginId); } }); // Execute `onLoad` on modules once all plugins are initialized. // A plugin might have extended/added some custom type so this // is a good point to load stuff like components, css rules, etc. em.loadOnStart(); initConfig.autorender && !headless && editor.render(); editors.push(editor); return editor; }, }; /* harmony default export */ const src_0 = (grapesjs); })(); var __webpack_exports__default = __nested_webpack_exports__.ZP; var __webpack_exports__grapesjs = __nested_webpack_exports__.kr; var __webpack_exports__usePlugin = __nested_webpack_exports__.j7; //# sourceMappingURL=grapes.mjs.map /***/ }) /******/ }); /************************************************************************/ /******/ // The module cache /******/ var __webpack_module_cache__ = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ var cachedModule = __webpack_module_cache__[moduleId]; /******/ if (cachedModule !== undefined) { /******/ return cachedModule.exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = __webpack_module_cache__[moduleId] = { /******/ id: moduleId, /******/ loaded: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = __webpack_modules__; /******/ /************************************************************************/ /******/ /* webpack/runtime/chunk loaded */ /******/ (() => { /******/ var deferred = []; /******/ __webpack_require__.O = (result, chunkIds, fn, priority) => { /******/ if(chunkIds) { /******/ priority = priority || 0; /******/ for(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1]; /******/ deferred[i] = [chunkIds, fn, priority]; /******/ return; /******/ } /******/ var notFulfilled = Infinity; /******/ for (var i = 0; i < deferred.length; i++) { /******/ var [chunkIds, fn, priority] = deferred[i]; /******/ var fulfilled = true; /******/ for (var j = 0; j < chunkIds.length; j++) { /******/ if ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(__webpack_require__.O).every((key) => (__webpack_require__.O[key](chunkIds[j])))) { /******/ chunkIds.splice(j--, 1); /******/ } else { /******/ fulfilled = false; /******/ if(priority < notFulfilled) notFulfilled = priority; /******/ } /******/ } /******/ if(fulfilled) { /******/ deferred.splice(i--, 1) /******/ var r = fn(); /******/ if (r !== undefined) result = r; /******/ } /******/ } /******/ return result; /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/compat get default export */ /******/ (() => { /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = (module) => { /******/ var getter = module && module.__esModule ? /******/ () => (module['default']) : /******/ () => (module); /******/ __webpack_require__.d(getter, { a: getter }); /******/ return getter; /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/define property getters */ /******/ (() => { /******/ // define getter functions for harmony exports /******/ __webpack_require__.d = (exports, definition) => { /******/ for(var key in definition) { /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); /******/ } /******/ } /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/global */ /******/ (() => { /******/ __webpack_require__.g = (function() { /******/ if (typeof globalThis === 'object') return globalThis; /******/ try { /******/ return this || new Function('return this')(); /******/ } catch (e) { /******/ if (typeof window === 'object') return window; /******/ } /******/ })(); /******/ })(); /******/ /******/ /* webpack/runtime/hasOwnProperty shorthand */ /******/ (() => { /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) /******/ })(); /******/ /******/ /* webpack/runtime/make namespace object */ /******/ (() => { /******/ // define __esModule on exports /******/ __webpack_require__.r = (exports) => { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/node module decorator */ /******/ (() => { /******/ __webpack_require__.nmd = (module) => { /******/ module.paths = []; /******/ if (!module.children) module.children = []; /******/ return module; /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/jsonp chunk loading */ /******/ (() => { /******/ // no baseURI /******/ /******/ // object to store loaded and loading chunks /******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched /******/ // [resolve, reject, Promise] = chunk loading, 0 = chunk loaded /******/ var installedChunks = { /******/ "/js/app": 0, /******/ "css/app": 0 /******/ }; /******/ /******/ // no chunk on demand loading /******/ /******/ // no prefetching /******/ /******/ // no preloaded /******/ /******/ // no HMR /******/ /******/ // no HMR manifest /******/ /******/ __webpack_require__.O.j = (chunkId) => (installedChunks[chunkId] === 0); /******/ /******/ // install a JSONP callback for chunk loading /******/ var webpackJsonpCallback = (parentChunkLoadingFunction, data) => { /******/ var [chunkIds, moreModules, runtime] = data; /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0; /******/ if(chunkIds.some((id) => (installedChunks[id] !== 0))) { /******/ for(moduleId in moreModules) { /******/ if(__webpack_require__.o(moreModules, moduleId)) { /******/ __webpack_require__.m[moduleId] = moreModules[moduleId]; /******/ } /******/ } /******/ if(runtime) var result = runtime(__webpack_require__); /******/ } /******/ if(parentChunkLoadingFunction) parentChunkLoadingFunction(data); /******/ for(;i < chunkIds.length; i++) { /******/ chunkId = chunkIds[i]; /******/ if(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) { /******/ installedChunks[chunkId][0](); /******/ } /******/ installedChunks[chunkId] = 0; /******/ } /******/ return __webpack_require__.O(result); /******/ } /******/ /******/ var chunkLoadingGlobal = self["webpackChunkbluewater"] = self["webpackChunkbluewater"] || []; /******/ chunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0)); /******/ chunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal)); /******/ })(); /******/ /******/ /* webpack/runtime/nonce */ /******/ (() => { /******/ __webpack_require__.nc = undefined; /******/ })(); /******/ /************************************************************************/ /******/ /******/ // startup /******/ // Load entry module and return exports /******/ // This entry module depends on other loaded chunks and execution need to be delayed /******/ __webpack_require__.O(undefined, ["css/app"], () => (__webpack_require__("./resources/js/app.js"))) /******/ var __webpack_exports__ = __webpack_require__.O(undefined, ["css/app"], () => (__webpack_require__("./resources/css/app.css"))) /******/ __webpack_exports__ = __webpack_require__.O(__webpack_exports__); /******/ /******/ })() ;
| ver. 1.4 |
Github
|
.
| PHP 8.1.29 | Генерация страницы: 0.15 |
proxy
|
phpinfo
|
Настройка