UNPKG

72.4 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, '__esModule', { value: true });
4
5function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
6
7var _globalThis = _interopDefault(require('szfe-tools/lib/globalThis'));
8var _flatten = _interopDefault(require('szfe-tools/lib/flatten'));
9var _get = _interopDefault(require('szfe-tools/lib/get'));
10var _run = _interopDefault(require('szfe-tools/lib/run'));
11var _debounce = _interopDefault(require('szfe-tools/lib/debounce'));
12var React = require('react');
13var React__default = _interopDefault(React);
14var reactDom = require('react-dom');
15var _isFunction = _interopDefault(require('szfe-tools/lib/isFunction'));
16var createContext$1 = _interopDefault(require('create-react-context'));
17var _EventBus = _interopDefault(require('szfe-tools/lib/EventBus'));
18var _nextTick = _interopDefault(require('szfe-tools/lib/nextTick'));
19var _isString = _interopDefault(require('szfe-tools/lib/isString'));
20var _memoize = _interopDefault(require('szfe-tools/lib/memoize'));
21var _isUndefined = _interopDefault(require('szfe-tools/lib/isUndefined'));
22var _isObject = _interopDefault(require('szfe-tools/lib/isObject'));
23var hoistStatics = _interopDefault(require('hoist-non-react-statics'));
24var _value = _interopDefault(require('szfe-tools/lib/value'));
25var _isArray = _interopDefault(require('szfe-tools/lib/isArray'));
26var NodeKey = _interopDefault(require('react-node-key'));
27var _isExist = _interopDefault(require('szfe-tools/lib/isExist'));
28
29function ownKeys(object, enumerableOnly) {
30 var keys = Object.keys(object);
31
32 if (Object.getOwnPropertySymbols) {
33 var symbols = Object.getOwnPropertySymbols(object);
34
35 if (enumerableOnly) {
36 symbols = symbols.filter(function (sym) {
37 return Object.getOwnPropertyDescriptor(object, sym).enumerable;
38 });
39 }
40
41 keys.push.apply(keys, symbols);
42 }
43
44 return keys;
45}
46
47function _objectSpread2(target) {
48 for (var i = 1; i < arguments.length; i++) {
49 var source = arguments[i] != null ? arguments[i] : {};
50
51 if (i % 2) {
52 ownKeys(Object(source), true).forEach(function (key) {
53 _defineProperty(target, key, source[key]);
54 });
55 } else if (Object.getOwnPropertyDescriptors) {
56 Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
57 } else {
58 ownKeys(Object(source)).forEach(function (key) {
59 Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
60 });
61 }
62 }
63
64 return target;
65}
66
67function _classCallCheck(instance, Constructor) {
68 if (!(instance instanceof Constructor)) {
69 throw new TypeError("Cannot call a class as a function");
70 }
71}
72
73function _defineProperties(target, props) {
74 for (var i = 0; i < props.length; i++) {
75 var descriptor = props[i];
76 descriptor.enumerable = descriptor.enumerable || false;
77 descriptor.configurable = true;
78 if ("value" in descriptor) descriptor.writable = true;
79 Object.defineProperty(target, descriptor.key, descriptor);
80 }
81}
82
83function _createClass(Constructor, protoProps, staticProps) {
84 if (protoProps) _defineProperties(Constructor.prototype, protoProps);
85 if (staticProps) _defineProperties(Constructor, staticProps);
86 return Constructor;
87}
88
89function _defineProperty(obj, key, value) {
90 if (key in obj) {
91 Object.defineProperty(obj, key, {
92 value: value,
93 enumerable: true,
94 configurable: true,
95 writable: true
96 });
97 } else {
98 obj[key] = value;
99 }
100
101 return obj;
102}
103
104function _extends() {
105 _extends = Object.assign || function (target) {
106 for (var i = 1; i < arguments.length; i++) {
107 var source = arguments[i];
108
109 for (var key in source) {
110 if (Object.prototype.hasOwnProperty.call(source, key)) {
111 target[key] = source[key];
112 }
113 }
114 }
115
116 return target;
117 };
118
119 return _extends.apply(this, arguments);
120}
121
122function _inherits(subClass, superClass) {
123 if (typeof superClass !== "function" && superClass !== null) {
124 throw new TypeError("Super expression must either be null or a function");
125 }
126
127 subClass.prototype = Object.create(superClass && superClass.prototype, {
128 constructor: {
129 value: subClass,
130 writable: true,
131 configurable: true
132 }
133 });
134 if (superClass) _setPrototypeOf(subClass, superClass);
135}
136
137function _getPrototypeOf(o) {
138 _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
139 return o.__proto__ || Object.getPrototypeOf(o);
140 };
141 return _getPrototypeOf(o);
142}
143
144function _setPrototypeOf(o, p) {
145 _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
146 o.__proto__ = p;
147 return o;
148 };
149
150 return _setPrototypeOf(o, p);
151}
152
153function _isNativeReflectConstruct() {
154 if (typeof Reflect === "undefined" || !Reflect.construct) return false;
155 if (Reflect.construct.sham) return false;
156 if (typeof Proxy === "function") return true;
157
158 try {
159 Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
160 return true;
161 } catch (e) {
162 return false;
163 }
164}
165
166function _objectWithoutPropertiesLoose(source, excluded) {
167 if (source == null) return {};
168 var target = {};
169 var sourceKeys = Object.keys(source);
170 var key, i;
171
172 for (i = 0; i < sourceKeys.length; i++) {
173 key = sourceKeys[i];
174 if (excluded.indexOf(key) >= 0) continue;
175 target[key] = source[key];
176 }
177
178 return target;
179}
180
181function _objectWithoutProperties(source, excluded) {
182 if (source == null) return {};
183
184 var target = _objectWithoutPropertiesLoose(source, excluded);
185
186 var key, i;
187
188 if (Object.getOwnPropertySymbols) {
189 var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
190
191 for (i = 0; i < sourceSymbolKeys.length; i++) {
192 key = sourceSymbolKeys[i];
193 if (excluded.indexOf(key) >= 0) continue;
194 if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
195 target[key] = source[key];
196 }
197 }
198
199 return target;
200}
201
202function _assertThisInitialized(self) {
203 if (self === void 0) {
204 throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
205 }
206
207 return self;
208}
209
210function _possibleConstructorReturn(self, call) {
211 if (call && (typeof call === "object" || typeof call === "function")) {
212 return call;
213 } else if (call !== void 0) {
214 throw new TypeError("Derived constructors may only return object or undefined");
215 }
216
217 return _assertThisInitialized(self);
218}
219
220function _createSuper(Derived) {
221 var hasNativeReflectConstruct = _isNativeReflectConstruct();
222
223 return function _createSuperInternal() {
224 var Super = _getPrototypeOf(Derived),
225 result;
226
227 if (hasNativeReflectConstruct) {
228 var NewTarget = _getPrototypeOf(this).constructor;
229
230 result = Reflect.construct(Super, arguments, NewTarget);
231 } else {
232 result = Super.apply(this, arguments);
233 }
234
235 return _possibleConstructorReturn(this, result);
236 };
237}
238
239function _slicedToArray(arr, i) {
240 return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
241}
242
243function _toArray(arr) {
244 return _arrayWithHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableRest();
245}
246
247function _toConsumableArray(arr) {
248 return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
249}
250
251function _arrayWithoutHoles(arr) {
252 if (Array.isArray(arr)) return _arrayLikeToArray(arr);
253}
254
255function _arrayWithHoles(arr) {
256 if (Array.isArray(arr)) return arr;
257}
258
259function _iterableToArray(iter) {
260 if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
261}
262
263function _iterableToArrayLimit(arr, i) {
264 var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
265
266 if (_i == null) return;
267 var _arr = [];
268 var _n = true;
269 var _d = false;
270
271 var _s, _e;
272
273 try {
274 for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
275 _arr.push(_s.value);
276
277 if (i && _arr.length === i) break;
278 }
279 } catch (err) {
280 _d = true;
281 _e = err;
282 } finally {
283 try {
284 if (!_n && _i["return"] != null) _i["return"]();
285 } finally {
286 if (_d) throw _e;
287 }
288 }
289
290 return _arr;
291}
292
293function _unsupportedIterableToArray(o, minLen) {
294 if (!o) return;
295 if (typeof o === "string") return _arrayLikeToArray(o, minLen);
296 var n = Object.prototype.toString.call(o).slice(8, -1);
297 if (n === "Object" && o.constructor) n = o.constructor.name;
298 if (n === "Map" || n === "Set") return Array.from(o);
299 if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
300}
301
302function _arrayLikeToArray(arr, len) {
303 if (len == null || len > arr.length) len = arr.length;
304
305 for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
306
307 return arr2;
308}
309
310function _nonIterableSpread() {
311 throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
312}
313
314function _nonIterableRest() {
315 throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
316}
317
318// 值类型判断 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
319var isRegExp = function isRegExp(val) {
320 return val instanceof RegExp;
321}; // 值类型判断 -------------------------------------------------------------
322
323var aliveScopeContext = createContext$1();
324var AliveScopeProvider = aliveScopeContext.Provider,
325 AliveScopeConsumer = aliveScopeContext.Consumer; // KeepAlive 组件的上下文,实现缓存生命周期功能
326var aliveNodeContext = createContext$1();
327var AliveNodeProvider = aliveNodeContext.Provider,
328 AliveNodeConsumer = aliveNodeContext.Consumer;
329
330var eventBus = new _EventBus();
331var FakeScopeProvider = /*#__PURE__*/function (_Component) {
332 _inherits(FakeScopeProvider, _Component);
333
334 var _super = _createSuper(FakeScopeProvider);
335
336 function FakeScopeProvider(props) {
337 var _this;
338
339 _classCallCheck(this, FakeScopeProvider);
340
341 _this = _super.call(this, props);
342 FakeScopeProvider.currentContextValue = props.value;
343 return _this;
344 }
345
346 _createClass(FakeScopeProvider, [{
347 key: "shouldComponentUpdate",
348 value: function shouldComponentUpdate(nextProps) {
349 if (nextProps.value !== this.props.value) {
350 FakeScopeProvider.currentContextValue = nextProps.value;
351 eventBus.emit('update', nextProps.value);
352 }
353
354 return nextProps.children !== this.props.children || nextProps.value !== this.props.value;
355 }
356 }, {
357 key: "render",
358 value: function render() {
359 var children = this.props.children;
360 return children;
361 }
362 }]);
363
364 return FakeScopeProvider;
365}(React.Component);
366
367_defineProperty(FakeScopeProvider, "eventBus", eventBus);
368
369_defineProperty(FakeScopeProvider, "currentContextValue", undefined);
370
371var FakeScopeConsumer = /*#__PURE__*/function (_PureComponent) {
372 _inherits(FakeScopeConsumer, _PureComponent);
373
374 var _super2 = _createSuper(FakeScopeConsumer);
375
376 function FakeScopeConsumer(props) {
377 var _this2;
378
379 _classCallCheck(this, FakeScopeConsumer);
380
381 _this2 = _super2.call(this, props);
382
383 _defineProperty(_assertThisInitialized(_this2), "state", {
384 context: FakeScopeProvider.currentContextValue
385 });
386
387 _defineProperty(_assertThisInitialized(_this2), "updateListener", _debounce(function (nextContextValue) {
388 _this2.setState({
389 context: nextContextValue
390 });
391 }));
392
393 eventBus.on('update', _this2.updateListener);
394 return _this2;
395 }
396
397 _createClass(FakeScopeConsumer, [{
398 key: "componentWillUnmount",
399 value: function componentWillUnmount() {
400 eventBus.off('update', this.updateListener);
401 }
402 }, {
403 key: "render",
404 value: function render() {
405 var children = this.props.children;
406 var context = this.state.context;
407 return _run(children, undefined, context);
408 }
409 }]);
410
411 return FakeScopeConsumer;
412}(React.PureComponent);
413
414var _excluded = ["children"];
415var _filehash = "qj9A";
416var useScopeContext = function useScopeContext() {
417 if (!_isFunction(React.useContext)) {
418 return {};
419 }
420
421 var scopeReactContext = React.useContext(aliveScopeContext);
422
423 if (scopeReactContext) {
424 return scopeReactContext;
425 }
426
427 var _useState = React.useState(FakeScopeProvider.currentContextValue),
428 _useState2 = _slicedToArray(_useState, 2),
429 context = _useState2[0],
430 setContext = _useState2[1];
431
432 React.useEffect(function () {
433 var updateListener = _debounce(setContext);
434
435 eventBus.on('update', updateListener);
436 return function () {
437 return eventBus.off('update', updateListener);
438 };
439 }, []);
440 return context;
441};
442var AliveScopeProvider$1 = function AliveScopeProvider$1(_ref) {
443 var children = _ref.children,
444 props = _objectWithoutProperties(_ref, _excluded);
445
446 return /*#__PURE__*/React__default.createElement(AliveScopeProvider, _extends({}, props, {
447 _nk: "".concat(_filehash, "11")
448 }), /*#__PURE__*/React__default.createElement(FakeScopeProvider, _extends({}, props, {
449 _nk: "".concat(_filehash, "21")
450 }), children));
451};
452var AliveScopeConsumer$1 = function AliveScopeConsumer$1(_ref2) {
453 var children = _ref2.children;
454 return /*#__PURE__*/React__default.createElement(AliveScopeConsumer, {
455 _nk: "".concat(_filehash, "31")
456 }, function (reactContext) {
457 return !!reactContext ? _run(children, undefined, reactContext) : /*#__PURE__*/React__default.createElement(FakeScopeConsumer, {
458 _nk: "".concat(_filehash, "41")
459 }, children);
460 });
461};
462
463function Suspender(_ref) {
464 var freeze = _ref.freeze,
465 children = _ref.children;
466 var promiseCache = React.useRef({}).current;
467
468 if (freeze && !promiseCache.promise) {
469 promiseCache.promise = new Promise(function (res) {
470 promiseCache.resolve = res;
471 });
472 throw promiseCache.promise;
473 } else if (freeze) {
474 throw promiseCache.promise;
475 } else if (promiseCache.promise) {
476 promiseCache.resolve();
477 promiseCache.promise = undefined;
478 }
479
480 return React__default.createElement(React.Fragment, null, children);
481}
482
483function Freeze(_ref2) {
484 var freeze = _ref2.freeze,
485 children = _ref2.children,
486 _ref2$placeholder = _ref2.placeholder,
487 placeholder = _ref2$placeholder === void 0 ? null : _ref2$placeholder;
488 return React__default.createElement(React.Suspense, {
489 fallback: placeholder
490 }, React__default.createElement(Suspender, {
491 freeze: freeze
492 }, children));
493}
494
495var fixedContext = [];
496var updateListenerCache = new Map();
497var eventBus$1 = new _EventBus();
498var fixContext = _memoize(function (ctx) {
499 // 排除 KeepAlive 功能的上下文
500 if ([aliveScopeContext, aliveNodeContext].includes(ctx)) {
501 return;
502 }
503
504 fixedContext.push(ctx);
505 setTimeout(function () {
506 return eventBus$1.emit('update');
507 });
508});
509var createContext = function createContext(defaultValue, calculateChangedBits) {
510 var ctx = createContext$1(defaultValue, calculateChangedBits);
511 fixContext(ctx);
512 return ctx;
513};
514
515var tryFixCtx = _memoize(function (type) {
516 // 尝试读取 Provider 或 Consumer 中的 context 静态属性
517 var ctx = _get(type, '_context') || _get(type, 'context'); // 16.3.0 版本为 context,之后为 _context
518 // 判断是否为 ReactContext 类型
519
520
521 if (_get(ctx, '$$typeof') === _get(aliveScopeContext, '$$typeof')) {
522 fixContext(ctx);
523 }
524});
525
526var override = function override(configs) {
527 configs.forEach(function (_ref) {
528 var _ref2 = _toArray(_ref),
529 host = _ref2[0],
530 methods = _ref2.slice(1);
531
532 methods.forEach(function (method) {
533 if (!_isFunction(_get(host, method)) || _get(host, [method, '_overridden'])) {
534 return;
535 }
536
537 var originMethod = host[method].bind(host);
538
539 host[method] = function (type) {
540 if (!_isString(type)) {
541 tryFixCtx(type);
542 }
543
544 for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
545 args[_key - 1] = arguments[_key];
546 }
547
548 return originMethod.apply(void 0, [type].concat(args));
549 };
550
551 host[method]._overridden = true;
552 });
553 });
554};
555/**
556 * 通过覆写 React.createElement 方法来探测 Provider 或 Consumer 的创建,并攫取其中 context 主动进行修复
557 * TODO:同时兼容 React 17+,目前仅默认兼容 React.createElement 方法
558 * React 17+ 为 require('react/jsx-runtime') 或 require('react/jsx-dev-runtime') 的 jsx、jsxs、jsxDEV 方法
559 * 但由于无法动态 require,暂未想到方式同时兼容
560 * 若需兼容 17+,目前手法为
561 *
562 * autoFixContext(
563 * [require('react/jsx-runtime'), 'jsx', 'jsxs', 'jsxDEV'],
564 * [require('react/jsx-dev-runtime'), 'jsx', 'jsxs', 'jsxDEV']
565 * )
566 *
567 * Note: 需注意 16.2.x 及以下版本不支持此方法
568 */
569
570
571var autoFixContext = function autoFixContext() {
572 try {
573 for (var _len2 = arguments.length, configs = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
574 configs[_key2] = arguments[_key2];
575 }
576
577 override(configs);
578 } catch (err) {
579 console.warn('activation override failed:', err);
580 }
581};
582autoFixContext([React__default, 'createElement']);
583
584var _filehash$1 = "lqEk";
585
586var ProviderBridge = /*#__PURE__*/function (_PureComponent) {
587 _inherits(ProviderBridge, _PureComponent);
588
589 var _super = _createSuper(ProviderBridge);
590
591 function ProviderBridge(props) {
592 var _this;
593
594 _classCallCheck(this, ProviderBridge);
595
596 _this = _super.call(this, props);
597
598 _defineProperty(_assertThisInitialized(_this), "unmount", null);
599
600 var ctxValues = props.value;
601
602 if (ctxValues.length === 0) {
603 _this.state = {
604 ctxValue: null
605 };
606 return _possibleConstructorReturn(_this);
607 }
608
609 var _ctxValues = _slicedToArray(ctxValues, 1),
610 _ctxValues$ = _ctxValues[0],
611 ctx = _ctxValues$.ctx,
612 value = _ctxValues$.value,
613 onUpdate = _ctxValues$.onUpdate;
614
615 _this.state = {
616 ctxValue: value
617 };
618 _this.unmount = onUpdate(function (value) {
619 _this.setState({
620 ctxValue: value
621 });
622 });
623 return _this;
624 }
625
626 _createClass(ProviderBridge, [{
627 key: "componentWillUnmount",
628 value: function componentWillUnmount() {
629 _run(this.unmount);
630 } // componentDidCatch(error) {
631 // console.error('ProviderBridge Error', error)
632 // }
633
634 }, {
635 key: "render",
636 value: function render() {
637 var _this$props = this.props,
638 ctxValues = _this$props.value,
639 children = _this$props.children;
640
641 if (ctxValues.length === 0) {
642 return children;
643 }
644
645 var ctxValue = this.state.ctxValue;
646
647 var _ctxValues2 = _toArray(ctxValues),
648 ctx = _ctxValues2[0].ctx,
649 restValues = _ctxValues2.slice(1);
650
651 var Provider = ctx.Provider;
652 var nextChildren = !_isUndefined(ctxValue) ? /*#__PURE__*/React__default.createElement(Provider, {
653 value: ctxValue,
654 _nk: "".concat(_filehash$1, "11")
655 }, children) : children; // 递归 ProviderBridge 修复多个上下文
656 // 此处未考虑待修复上下文顺序问题,按先来后到顺序处理,但理论上不应存在顺序问题
657
658 return restValues.length > 0 ? /*#__PURE__*/React__default.createElement(ProviderBridge, {
659 value: restValues,
660 _nk: "".concat(_filehash$1, "21")
661 }, nextChildren) : nextChildren;
662 }
663 }]);
664
665 return ProviderBridge;
666}(React.PureComponent);
667
668var ConsumerWrapper = /*#__PURE__*/function (_Component) {
669 _inherits(ConsumerWrapper, _Component);
670
671 var _super = _createSuper(ConsumerWrapper);
672
673 function ConsumerWrapper(props) {
674 var _this;
675
676 _classCallCheck(this, ConsumerWrapper);
677
678 _this = _super.call(this, props);
679
680 _defineProperty(_assertThisInitialized(_this), "updateListener", null);
681
682 _defineProperty(_assertThisInitialized(_this), "ctxInfo", null);
683
684 var value = props.value,
685 ctx = props.ctx,
686 id = props.id;
687
688 if (_isUndefined(value)) {
689 return _possibleConstructorReturn(_this);
690 } // 因 Consumer 探测器存在于 KeepAlive 外层故会随着 KeepAlive 卸载
691 // componentWillUnmount 中保留了已生成的更新监听器
692 // 此处重新挂载后恢复与对应 Keeper 中 ProviderBridge 的联系
693
694
695 _this.updateListener = _get(updateListenerCache.get(ctx), id, new Map());
696 _this.ctxInfo = {
697 ctx: ctx,
698 value: value,
699 // 注册上下文更新的监听,保证上下文更新时 Keeper 中 ProviderBridge 内容的同步
700 onUpdate: function onUpdate(updator) {
701 _this.updateListener.set(updator, updator); // 返回更新监听器的注销方法
702
703
704 return function () {
705 return _this.updateListener["delete"](updator);
706 };
707 }
708 };
709 return _this;
710 }
711
712 _createClass(ConsumerWrapper, [{
713 key: "componentWillUnmount",
714 value: function componentWillUnmount() {
715 var _this$props = this.props,
716 value = _this$props.value,
717 ctx = _this$props.ctx,
718 id = _this$props.id;
719
720 if (_isUndefined(value)) {
721 return;
722 } // 因 Consumer 探测器存在于 KeepAlive 外层故会随着 KeepAlive 卸载
723 // 此处保留其中已生成的更新监听器,用以在重新挂载后保持与对应 Keeper 中 ProviderBridge 的联系
724
725
726 updateListenerCache.set(ctx, _objectSpread2(_objectSpread2({}, _get(updateListenerCache.get(ctx), undefined, {})), {}, _defineProperty({}, id, this.updateListener)));
727 } // 利用 shouldComponentUpdate 尽早将上下文更新的咨询通知到对应 Keeper 中 ProviderBridge
728 // TODO: 改用 componentWillReceiveProps 更早地进行更新,需注意与 getDerivedStateFromProps 新生命周期的兼容及可能存在的死循环问题
729
730 }, {
731 key: "shouldComponentUpdate",
732 value: function shouldComponentUpdate(_ref) {
733 var value = _ref.value;
734 var prevValue = this.props.prevValue;
735 var shouldUpdate = prevValue !== value;
736
737 if (shouldUpdate) {
738 _run(this.updateListener, 'forEach', function (fn) {
739 return fn(value);
740 });
741 }
742
743 return shouldUpdate;
744 }
745 }, {
746 key: "render",
747 value: function render() {
748 var _this2 = this;
749
750 var _this$props2 = this.props,
751 value = _this$props2.value,
752 renderWrapper = _this$props2.renderWrapper,
753 renderContent = _this$props2.renderContent,
754 id = _this$props2.id;
755 return renderWrapper(function (ctx$$) {
756 return renderContent(_isUndefined(value) ? ctx$$ : [].concat(_toConsumableArray(ctx$$), [_this2.ctxInfo]));
757 });
758 }
759 }]);
760
761 return ConsumerWrapper;
762}(React.Component);
763
764var _filehash$2 = "SsUr";
765var fixedContextSnapshot = {}; // 对 ConsumerWrapper 的递归结构,会在 devtool 中生成较深的嵌套结构,可用 hooks 消除嵌套结构
766
767var RecursiveConsumerBridge = /*#__PURE__*/function (_PureComponent) {
768 _inherits(RecursiveConsumerBridge, _PureComponent);
769
770 var _super = _createSuper(RecursiveConsumerBridge);
771
772 function RecursiveConsumerBridge(props) {
773 var _this;
774
775 _classCallCheck(this, RecursiveConsumerBridge);
776
777 _this = _super.call(this, props);
778
779 _defineProperty(_assertThisInitialized(_this), "renderWrapper", function (renderChildren) {
780 var id = _this.props.id;
781 var renderWrapper = fixedContextSnapshot[id].reduce(function (render, ctx) {
782 var Consumer = ctx.Consumer;
783
784 var renderWrapper = function renderWrapper(renderContent) {
785 return /*#__PURE__*/React__default.createElement(Consumer, {
786 _nk: "".concat(_filehash$2, "11")
787 }, function (value) {
788 return /*#__PURE__*/React__default.createElement(ConsumerWrapper, {
789 value: value,
790 ctx: ctx,
791 renderWrapper: render,
792 renderContent: renderContent,
793 id: id,
794 _nk: "".concat(_filehash$2, "21")
795 });
796 });
797 };
798
799 return renderWrapper;
800 }, function (renderContent) {
801 return renderContent([]);
802 });
803 return renderWrapper(renderChildren);
804 });
805
806 var _id = props.id;
807
808 if (!fixedContextSnapshot[_id]) {
809 fixedContextSnapshot[_id] = _toConsumableArray(fixedContext);
810 }
811
812 return _this;
813 }
814
815 _createClass(RecursiveConsumerBridge, [{
816 key: "render",
817 value: function render() {
818 var renderChildren = this.props.children;
819 return this.renderWrapper(renderChildren);
820 }
821 }]);
822
823 return RecursiveConsumerBridge;
824}(React.PureComponent); // 若支持 Hooks,就不需要递归了,相关实现解释可参考 ConsumerWrapper
825
826var _filehash$3 = "46lG";
827// 兼容性检测
828var isSupported = _isFunction(React.lazy) && !_isUndefined(React.Suspense);
829
830var SusNotSupported = function SusNotSupported(_ref) {
831 var children = _ref.children;
832 return _run(children);
833};
834
835var Lazy = isSupported ? /*#__PURE__*/React.lazy(function () {
836 return new Promise(function () {
837 return null;
838 });
839}) : function () {
840 return null;
841};
842
843var FallbackListener = /*#__PURE__*/function (_Component) {
844 _inherits(FallbackListener, _Component);
845
846 var _super = _createSuper(FallbackListener);
847
848 function FallbackListener() {
849 _classCallCheck(this, FallbackListener);
850
851 return _super.apply(this, arguments);
852 }
853
854 _createClass(FallbackListener, [{
855 key: "componentDidMount",
856 value: function componentDidMount() {
857 _run(this.props, 'onStart');
858 }
859 }, {
860 key: "componentWillUnmount",
861 value: function componentWillUnmount() {
862 _run(this.props, 'onEnd');
863 }
864 }, {
865 key: "render",
866 value: function render() {
867 return null;
868 }
869 }]);
870
871 return FallbackListener;
872}(React.Component);
873
874function SuspenseBridge(_ref2) {
875 var children = _ref2.children,
876 sus$$ = _ref2.sus$$;
877 return (
878 /*#__PURE__*/
879 // 捕获 Keeper 内部可能存在的 lazy,并触发对应 KeepAlive 位置上的 LazyBridge
880 React__default.createElement(React.Suspense, {
881 fallback: /*#__PURE__*/React__default.createElement(FallbackListener, {
882 onStart: sus$$.onSuspenseStart,
883 onEnd: sus$$.onSuspenseEnd,
884 _nk: "".concat(_filehash$3, "21")
885 }),
886 _nk: "".concat(_filehash$3, "11")
887 }, children)
888 );
889}
890
891var LazyBridge = isSupported ? /*#__PURE__*/function (_Component2) {
892 _inherits(LazyBridge, _Component2);
893
894 var _super2 = _createSuper(LazyBridge);
895
896 function LazyBridge() {
897 var _this;
898
899 _classCallCheck(this, LazyBridge);
900
901 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
902 args[_key] = arguments[_key];
903 }
904
905 _this = _super2.call.apply(_super2, [this].concat(args));
906
907 _defineProperty(_assertThisInitialized(_this), "state", {
908 suspense: false
909 });
910
911 _defineProperty(_assertThisInitialized(_this), "onSuspenseStart", function () {
912 _this.setState({
913 suspense: true
914 });
915 });
916
917 _defineProperty(_assertThisInitialized(_this), "onSuspenseEnd", function () {
918 _this.setState({
919 suspense: false
920 });
921 });
922
923 _defineProperty(_assertThisInitialized(_this), "sus$$", {
924 onSuspenseStart: _this.onSuspenseStart,
925 onSuspenseEnd: _this.onSuspenseEnd
926 });
927
928 return _this;
929 }
930
931 _createClass(LazyBridge, [{
932 key: "render",
933 value: function render() {
934 var children = this.props.children;
935 return /*#__PURE__*/React__default.createElement(React.Fragment, null, _run(children, undefined, this.sus$$), this.state.suspense && /*#__PURE__*/React__default.createElement(Lazy, {
936 _nk: "".concat(_filehash$3, "31")
937 }));
938 }
939 }]);
940
941 return LazyBridge;
942}(React.Component) : SusNotSupported;
943var SuspenseBridge$1 = isSupported ? SuspenseBridge : SusNotSupported;
944
945var ErrorBoundaryBridge = /*#__PURE__*/function (_Component) {
946 _inherits(ErrorBoundaryBridge, _Component);
947
948 var _super = _createSuper(ErrorBoundaryBridge);
949
950 function ErrorBoundaryBridge() {
951 _classCallCheck(this, ErrorBoundaryBridge);
952
953 return _super.apply(this, arguments);
954 }
955
956 _createClass(ErrorBoundaryBridge, [{
957 key: "componentDidCatch",
958 value: // Error Boundary 透传至对应 KeepAlive 实例位置
959 function componentDidCatch(error) {
960 var throwError = this.props.error$$;
961
962 _run(throwError, undefined, error, function () {
963 _run(throwError, undefined, null);
964 });
965 }
966 }, {
967 key: "render",
968 value: function render() {
969 return this.props.children;
970 }
971 }]);
972
973 return ErrorBoundaryBridge;
974}(React.Component);
975
976_defineProperty(ErrorBoundaryBridge, "getDerivedStateFromError", function () {
977 return null;
978});
979var ErrorThrower = /*#__PURE__*/function (_Component2) {
980 _inherits(ErrorThrower, _Component2);
981
982 var _super2 = _createSuper(ErrorThrower);
983
984 function ErrorThrower() {
985 var _this;
986
987 _classCallCheck(this, ErrorThrower);
988
989 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
990 args[_key] = arguments[_key];
991 }
992
993 _this = _super2.call.apply(_super2, [this].concat(args));
994
995 _defineProperty(_assertThisInitialized(_this), "state", {
996 error: null
997 });
998
999 _defineProperty(_assertThisInitialized(_this), "throwError", function (error, cb) {
1000 return _this.setState({
1001 error: error
1002 }, cb);
1003 });
1004
1005 return _this;
1006 }
1007
1008 _createClass(ErrorThrower, [{
1009 key: "render",
1010 value: function render() {
1011 if (this.state.error) {
1012 throw this.state.error;
1013 }
1014
1015 return _run(this.props.children, undefined, this.throwError);
1016 }
1017 }]);
1018
1019 return ErrorThrower;
1020}(React.Component);
1021
1022var _filehash$4 = "lajT";
1023function Bridge(_ref) {
1024 var id = _ref.id,
1025 children = _ref.children,
1026 bridgeProps = _ref.bridgeProps;
1027 var sus$$ = bridgeProps.sus$$,
1028 ctx$$ = bridgeProps.ctx$$,
1029 error$$ = bridgeProps.error$$;
1030 return (
1031 /*#__PURE__*/
1032
1033 /* 由内向外透传 componentDidCatch 捕获的 error */
1034 React__default.createElement(ErrorBoundaryBridge, {
1035 error$$: error$$,
1036 _nk: "".concat(_filehash$4, "11")
1037 }, /*#__PURE__*/React__default.createElement(SuspenseBridge$1, {
1038 sus$$: sus$$,
1039 _nk: "".concat(_filehash$4, "21")
1040 }, /*#__PURE__*/React__default.createElement(ProviderBridge, {
1041 id: id,
1042 value: ctx$$,
1043 _nk: "".concat(_filehash$4, "31")
1044 }, children)))
1045 );
1046} // 用于 KeepAlive 中,实现 KeepAlive 向外或向内的桥接代理
1047
1048function Acceptor(_ref2) {
1049 var id = _ref2.id,
1050 children = _ref2.children;
1051 return (
1052 /*#__PURE__*/
1053
1054 /* 由内向外透传 componentDidCatch 捕获的 error */
1055 React__default.createElement(ErrorThrower, {
1056 _nk: "".concat(_filehash$4, "41")
1057 }, function (error$$) {
1058 return (
1059 /*#__PURE__*/
1060
1061 /* 由内向外透传 lazy 行为 */
1062 React__default.createElement(LazyBridge, {
1063 _nk: "".concat(_filehash$4, "51")
1064 }, function (sus$$) {
1065 return (
1066 /*#__PURE__*/
1067
1068 /* 由外向内透传可能被捕获的 Provider 数据 */
1069 React__default.createElement(RecursiveConsumerBridge, {
1070 id: id,
1071 _nk: "".concat(_filehash$4, "61")
1072 }, function (ctx$$) {
1073 return _run(children, undefined, {
1074 bridgeProps: {
1075 sus$$: sus$$,
1076 ctx$$: ctx$$,
1077 error$$: error$$
1078 }
1079 });
1080 })
1081 );
1082 })
1083 );
1084 })
1085 );
1086}
1087
1088var _excluded$1 = ["forwardedRef"];
1089var _filehash$5 = "XKTv";
1090var LIFECYCLE_ACTIVATE = 'componentDidActivate';
1091var LIFECYCLE_UNACTIVATE = 'componentWillUnactivate';
1092var withActivation = function withActivation(WrappedComponent) {
1093 var HOC = /*#__PURE__*/function (_Component) {
1094 _inherits(HOC, _Component);
1095
1096 var _super = _createSuper(HOC);
1097
1098 function HOC() {
1099 var _this;
1100
1101 _classCallCheck(this, HOC);
1102
1103 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
1104 args[_key] = arguments[_key];
1105 }
1106
1107 _this = _super.call.apply(_super, [this].concat(args));
1108
1109 _defineProperty(_assertThisInitialized(_this), "drop", null);
1110
1111 return _this;
1112 }
1113
1114 _createClass(HOC, [{
1115 key: "componentWillUnmount",
1116 value: function componentWillUnmount() {
1117 _run(this.drop);
1118 }
1119 }, {
1120 key: "render",
1121 value: function render() {
1122 var _this2 = this;
1123
1124 var _this$props = this.props,
1125 forwardedRef = _this$props.forwardedRef,
1126 props = _objectWithoutProperties(_this$props, _excluded$1);
1127
1128 return /*#__PURE__*/React__default.createElement(AliveNodeConsumer, {
1129 _nk: "".concat(_filehash$5, "11")
1130 }, function () {
1131 var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
1132 attach = _ref.attach;
1133
1134 return /*#__PURE__*/React__default.createElement(WrappedComponent, _extends({
1135 ref: function ref(_ref2) {
1136 if ([LIFECYCLE_ACTIVATE, LIFECYCLE_UNACTIVATE].every(function (lifecycleName) {
1137 return !_isFunction(_get(_ref2, lifecycleName));
1138 })) {
1139 return;
1140 }
1141
1142 _this2.drop = _run(attach, undefined, _ref2); // 以下保持 ref 功能
1143
1144 if (_isUndefined(forwardedRef)) {
1145 return;
1146 }
1147
1148 if (_isObject(forwardedRef) && 'current' in forwardedRef) {
1149 forwardedRef.current = _ref2;
1150 return;
1151 }
1152
1153 _run(forwardedRef, undefined, _ref2);
1154 }
1155 }, props, {
1156 _nk: "".concat(_filehash$5, "21")
1157 }));
1158 });
1159 }
1160 }]);
1161
1162 return HOC;
1163 }(React.Component); // 由于 KeepAlive 内组件渲染与实际内容落后一个节拍
1164 // 将导致真实节点的 componentDidMount 无法及时获取到 KeepAlive 中内容的 ref 值
1165 // 此处对使用了 withActivation HOC 的组件 componentDidMount 做 nextTick 延时处理
1166 // 修复上述问题
1167
1168
1169 if (_isFunction(WrappedComponent.prototype.componentDidMount)) {
1170 WrappedComponent.prototype._componentDidMount = WrappedComponent.prototype.componentDidMount;
1171
1172 WrappedComponent.prototype.componentDidMount = function componentDidMount() {
1173 var _this3 = this;
1174
1175 _nextTick(function () {
1176 return WrappedComponent.prototype._componentDidMount.call(_this3);
1177 });
1178 };
1179 }
1180
1181 if (_isFunction(React.forwardRef)) {
1182 var ForwardedRefHOC = /*#__PURE__*/React.forwardRef(function (props, ref) {
1183 return /*#__PURE__*/React__default.createElement(HOC, _extends({}, props, {
1184 forwardedRef: ref,
1185 _nk: "".concat(_filehash$5, "31")
1186 }));
1187 });
1188 return hoistStatics(ForwardedRefHOC, WrappedComponent);
1189 } else {
1190 return hoistStatics(HOC, WrappedComponent);
1191 }
1192};
1193
1194var useActivation = function useActivation(funcName, func) {
1195 // 兼容性判断
1196 if ([React.useRef, React.useContext, React.useEffect].some(function (fn) {
1197 return !_isFunction(fn);
1198 })) {
1199 return;
1200 }
1201
1202 var ctxValue = React.useContext(aliveNodeContext); // 未处于 KeepAlive 中
1203
1204 if (!ctxValue) {
1205 return;
1206 }
1207
1208 var _useRef = React.useRef({}),
1209 ref = _useRef.current;
1210
1211 var attach = ctxValue.attach;
1212 ref[funcName] = func;
1213 ref.drop = attach(ref);
1214 React.useEffect(function () {
1215 return function () {
1216 return _run(ref.drop);
1217 };
1218 }, []);
1219};
1220
1221var useActivate = useActivation.bind(null, LIFECYCLE_ACTIVATE);
1222var useUnactivate = useActivation.bind(null, LIFECYCLE_UNACTIVATE);
1223
1224var _excluded$2 = ["id"];
1225var _filehash$6 = "bNyU";
1226var Freeze$1 = !!React.Suspense ? Freeze : function (_ref) {
1227 var children = _ref.children;
1228 return children;
1229};
1230
1231var Keeper = /*#__PURE__*/function (_PureComponent) {
1232 _inherits(Keeper, _PureComponent);
1233
1234 var _super = _createSuper(Keeper);
1235
1236 function Keeper(props) {
1237 var _this;
1238
1239 _classCallCheck(this, Keeper);
1240
1241 for (var _len = arguments.length, rest = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
1242 rest[_key - 1] = arguments[_key];
1243 }
1244
1245 _this = _super.call.apply(_super, [this, props].concat(rest));
1246
1247 _defineProperty(_assertThisInitialized(_this), "eventBus", new _EventBus());
1248
1249 _defineProperty(_assertThisInitialized(_this), "listeners", new Map());
1250
1251 _defineProperty(_assertThisInitialized(_this), "wrapper", null);
1252
1253 _defineProperty(_assertThisInitialized(_this), "cache", undefined);
1254
1255 _defineProperty(_assertThisInitialized(_this), "attach", function (ref) {
1256 var _listeners$set;
1257
1258 var listeners = _this.listeners;
1259
1260 if (!ref) {
1261 return function () {
1262 return null;
1263 };
1264 }
1265
1266 if (ref.isKeepAlive) {
1267 _nextTick(function () {
1268 var _this$props = _this.props,
1269 id = _this$props.id,
1270 store = _this$props.store;
1271 var cache = store.get(id);
1272 cache.aliveNodesId = new Set([].concat(_toConsumableArray(cache.aliveNodesId), [ref.id]));
1273 });
1274 }
1275
1276 listeners.set(ref, (_listeners$set = {}, _defineProperty(_listeners$set, LIFECYCLE_ACTIVATE, function () {
1277 return _run(ref, LIFECYCLE_ACTIVATE);
1278 }), _defineProperty(_listeners$set, LIFECYCLE_UNACTIVATE, function () {
1279 return _run(ref, LIFECYCLE_UNACTIVATE);
1280 }), _listeners$set)); // 返回 listenerRemover 用以在对应组件卸载时解除监听
1281
1282 return function () {
1283 listeners["delete"](ref);
1284 };
1285 });
1286
1287 _defineProperty(_assertThisInitialized(_this), "contextValue", {
1288 id: _this.props.id,
1289 attach: _this.attach
1290 });
1291
1292 _defineProperty(_assertThisInitialized(_this), "drop", function () {
1293 var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
1294 _ref2$delay = _ref2.delay,
1295 delay = _ref2$delay === void 0 ? 1200 : _ref2$delay;
1296
1297 return new Promise(function (resolve) {
1298 var timeout;
1299 var _this$props2 = _this.props,
1300 scope = _this$props2.scope,
1301 id = _this$props2.id;
1302
1303 var drop = function drop() {
1304 clearTimeout(timeout);
1305
1306 _this.eventBus.off(LIFECYCLE_UNACTIVATE, drop); // 用在多层 KeepAlive 同时触发 drop 时,避免触发深层 KeepAlive 节点的缓存生命周期
1307
1308
1309 _this.cache.willDrop = true;
1310 scope.nodes["delete"](id);
1311 scope.helpers = _objectSpread2({}, scope.helpers);
1312 scope.smartForceUpdate(function () {
1313 return resolve(true);
1314 });
1315 };
1316
1317 var canDrop = _get(_this.cache, 'cached') || _get(_this.cache, 'willDrop');
1318
1319 if (!canDrop) {
1320 _this.eventBus.on(LIFECYCLE_UNACTIVATE, drop);
1321
1322 timeout = setTimeout(function () {
1323 _this.eventBus.off(LIFECYCLE_UNACTIVATE, drop);
1324
1325 resolve(false);
1326 }, delay);
1327 return;
1328 }
1329
1330 drop();
1331 });
1332 });
1333
1334 _defineProperty(_assertThisInitialized(_this), "refresh", function () {
1335 return new Promise(function (resolve) {
1336 var canRefresh = !_get(_this.cache, 'cached');
1337
1338 if (!canRefresh) {
1339 resolve(false);
1340 }
1341
1342 _this.setState({
1343 key: Math.random()
1344 }, function () {
1345 return resolve(true);
1346 });
1347 });
1348 });
1349
1350 _this.state = {
1351 children: props.children,
1352 bridgeProps: props.bridgeProps,
1353 key: Math.random(),
1354 freeze: false
1355 };
1356 return _this;
1357 }
1358
1359 _createClass(Keeper, [{
1360 key: "componentDidMount",
1361 value: function componentDidMount() {
1362 var _this2 = this,
1363 _this$cache;
1364
1365 var _this$props3 = this.props,
1366 store = _this$props3.store,
1367 id = _this$props3.id;
1368 var listeners = this.listeners;
1369 var node = this.wrapper; // 已存在检测,防止意外现象
1370
1371 if (store.has(id)) {
1372 return;
1373 }
1374
1375 var nodes;
1376
1377 try {
1378 nodes = _toConsumableArray(node.children);
1379 } catch (e) {
1380 nodes = [node.children];
1381 }
1382
1383 this.cache = (_this$cache = {
1384 listeners: listeners,
1385 aliveNodesId: [],
1386 inited: false,
1387 cached: false,
1388 wrapper: node,
1389 nodes: nodes
1390 }, _defineProperty(_this$cache, LIFECYCLE_ACTIVATE, function () {
1391 return _this2[LIFECYCLE_ACTIVATE]();
1392 }), _defineProperty(_this$cache, LIFECYCLE_UNACTIVATE, function () {
1393 return _this2[LIFECYCLE_UNACTIVATE]();
1394 }), _this$cache);
1395 store.set(id, this.cache);
1396 }
1397 }, {
1398 key: "componentWillUnmount",
1399 value: function componentWillUnmount() {
1400 var _this$props4 = this.props,
1401 store = _this$props4.store,
1402 keepers = _this$props4.keepers,
1403 id = _this$props4.id; // 卸载前尝试归位 DOM 节点
1404
1405 try {
1406 var cache = store.get(id);
1407 cache.nodes.forEach(function (node) {
1408 cache.wrapper.appendChild(node);
1409 });
1410 } catch (error) {// console.error(error) // do nothing
1411 }
1412
1413 store["delete"](id);
1414 keepers["delete"](id);
1415 }
1416 }, {
1417 key: LIFECYCLE_ACTIVATE,
1418 value: function value() {
1419 this.setState({
1420 freeze: false
1421 });
1422 this.eventBus.emit(LIFECYCLE_ACTIVATE);
1423 this.listeners.forEach(function (listener) {
1424 return _run(listener, [LIFECYCLE_ACTIVATE]);
1425 });
1426 }
1427 }, {
1428 key: LIFECYCLE_UNACTIVATE,
1429 value: function value() {
1430 this.eventBus.emit(LIFECYCLE_UNACTIVATE);
1431
1432 var listeners = _toConsumableArray(this.listeners);
1433
1434 listeners.reverse().forEach(function (_ref3) {
1435 var _ref4 = _slicedToArray(_ref3, 2),
1436 listener = _ref4[1];
1437
1438 return _run(listener, [LIFECYCLE_UNACTIVATE]);
1439 });
1440 this.setState({
1441 freeze: true
1442 });
1443 } // // 原先打算更新过程中先重置 dom 节点状态,更新后恢复 dom 节点
1444 // // 但考虑到性能消耗可能过大,且可能因 dom 操作时机引发其他 react 渲染问题,故不使用
1445 // // 对应 KeepAlive 处 update 也注释起来不使用
1446 // // 组件更新后,更新 DOM 节点列表状态
1447 // componentDidUpdate() {
1448 // const { store, id } = this.props
1449 // const node = this.wrapper
1450 // if (get(node, 'children.length') > 0) {
1451 // store[id].nodes = [...node.children]
1452 // }
1453 // console.log(store[id].nodes)
1454 // }
1455 // 生命周期绑定
1456
1457 }, {
1458 key: "render",
1459 value: function render() {
1460 var _this3 = this;
1461
1462 var _this$props5 = this.props,
1463 id = _this$props5.id,
1464 props = _objectWithoutProperties(_this$props5, _excluded$2);
1465
1466 var _this$state = this.state,
1467 children = _this$state.children,
1468 bridgeProps = _this$state.bridgeProps,
1469 key = _this$state.key,
1470 freeze = _this$state.freeze;
1471 return /*#__PURE__*/React__default.createElement(Freeze$1, {
1472 freeze: freeze,
1473 _nk: "".concat(_filehash$6, "11")
1474 }, /*#__PURE__*/React__default.createElement("div", {
1475 ref: function ref(node) {
1476 _this3.wrapper = node;
1477 },
1478 _nk: "".concat(_filehash$6, "21")
1479 }, /*#__PURE__*/React__default.createElement("div", {
1480 key: "keeper-container",
1481 className: "ka-content"
1482 }, /*#__PURE__*/React__default.createElement(Bridge, {
1483 id: id,
1484 bridgeProps: bridgeProps,
1485 _nk: "".concat(_filehash$6, "31")
1486 }, /*#__PURE__*/React__default.createElement(AliveNodeProvider, {
1487 value: this.contextValue,
1488 _nk: "".concat(_filehash$6, "41")
1489 }, React__default.Children.map(children, function (child, idx) {
1490 return /*#__PURE__*/React__default.cloneElement(child, {
1491 key: "".concat(child.key || '', ":").concat(key, ":").concat(idx)
1492 });
1493 }))))));
1494 }
1495 }]);
1496
1497 return Keeper;
1498}(React.PureComponent);
1499
1500var _excluded$3 = ["children"];
1501var _filehash$7 = "UVSV";
1502var HANDLE_TYPE_DROP = 'drop';
1503var HANDLE_TYPE_REFRESH = 'refresh';
1504
1505var AliveScope = /*#__PURE__*/function (_Component) {
1506 _inherits(AliveScope, _Component);
1507
1508 var _super = _createSuper(AliveScope);
1509
1510 function AliveScope() {
1511 var _this;
1512
1513 _classCallCheck(this, AliveScope);
1514
1515 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
1516 args[_key] = arguments[_key];
1517 }
1518
1519 _this = _super.call.apply(_super, [this].concat(args));
1520
1521 _defineProperty(_assertThisInitialized(_this), "store", new Map());
1522
1523 _defineProperty(_assertThisInitialized(_this), "nodes", new Map());
1524
1525 _defineProperty(_assertThisInitialized(_this), "keepers", new Map());
1526
1527 _defineProperty(_assertThisInitialized(_this), "debouncedForceUpdate", _debounce(function (cb) {
1528 return _this.forceUpdate(cb);
1529 }));
1530
1531 _defineProperty(_assertThisInitialized(_this), "updateCallbackList", []);
1532
1533 _defineProperty(_assertThisInitialized(_this), "smartForceUpdate", function (cb) {
1534 _this.updateCallbackList.push(cb);
1535
1536 _this.debouncedForceUpdate(function () {
1537 _this.updateCallbackList.forEach(function (cb) {
1538 return _run(cb);
1539 });
1540
1541 _this.updateCallbackList = [];
1542 });
1543 });
1544
1545 _defineProperty(_assertThisInitialized(_this), "update", function (id, params) {
1546 return new Promise(function (resolve) {
1547 var keeper = _this.keepers.get(id);
1548
1549 var isNew = !keeper;
1550 var now = Date.now();
1551 var node = _this.nodes.get(id) || null;
1552
1553 _this.nodes.set(id, _objectSpread2(_objectSpread2({
1554 id: id,
1555 createTime: now,
1556 updateTime: now
1557 }, node), params));
1558
1559 if (isNew) {
1560 _this.helpers = _objectSpread2({}, _this.helpers);
1561
1562 _this.forceUpdate(resolve);
1563 } else {
1564 var children = params.children,
1565 bridgeProps = params.bridgeProps;
1566 keeper.setState({
1567 children: children,
1568 bridgeProps: bridgeProps
1569 }, resolve);
1570 }
1571 });
1572 });
1573
1574 _defineProperty(_assertThisInitialized(_this), "keep", function (id, params) {
1575 return new Promise(function (resolve) {
1576 _this.update(id, _objectSpread2({
1577 id: id
1578 }, params)).then(function () {
1579 resolve(_this.store.get(id));
1580 });
1581 });
1582 });
1583
1584 _defineProperty(_assertThisInitialized(_this), "getCachingNodesByName", function (name) {
1585 return _this.getCachingNodes().filter(function (node) {
1586 return isRegExp(name) ? name.test(node.name) : node.name === name;
1587 });
1588 });
1589
1590 _defineProperty(_assertThisInitialized(_this), "getScopeIds", function (ids) {
1591 // 递归采集 scope alive nodes id
1592 var getCachingNodesId = function getCachingNodesId(id) {
1593 var aliveNodesId = _get(_this.getCache(id), 'aliveNodesId', []);
1594
1595 if (aliveNodesId.size > 0) {
1596 return [id, _toConsumableArray(aliveNodesId).map(getCachingNodesId)];
1597 }
1598
1599 return [id].concat(_toConsumableArray(aliveNodesId));
1600 };
1601
1602 return _flatten(ids.map(function (id) {
1603 return getCachingNodesId(id);
1604 }));
1605 });
1606
1607 _defineProperty(_assertThisInitialized(_this), "dropById", function (id) {
1608 var _this2;
1609
1610 for (var _len2 = arguments.length, rest = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
1611 rest[_key2 - 1] = arguments[_key2];
1612 }
1613
1614 return (_this2 = _this).handleNodes.apply(_this2, [[id], HANDLE_TYPE_DROP].concat(rest));
1615 });
1616
1617 _defineProperty(_assertThisInitialized(_this), "dropScopeByIds", function (ids) {
1618 var _this3;
1619
1620 for (var _len3 = arguments.length, rest = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
1621 rest[_key3 - 1] = arguments[_key3];
1622 }
1623
1624 return (_this3 = _this).handleNodes.apply(_this3, [_this.getScopeIds(ids), HANDLE_TYPE_DROP].concat(rest));
1625 });
1626
1627 _defineProperty(_assertThisInitialized(_this), "drop", function (name) {
1628 var _this4;
1629
1630 for (var _len4 = arguments.length, rest = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
1631 rest[_key4 - 1] = arguments[_key4];
1632 }
1633
1634 return (_this4 = _this).handleNodes.apply(_this4, [_this.getCachingNodesByName(name).map(function (node) {
1635 return node.id;
1636 }), HANDLE_TYPE_DROP].concat(rest));
1637 });
1638
1639 _defineProperty(_assertThisInitialized(_this), "dropScope", function (name) {
1640 var _this5;
1641
1642 for (var _len5 = arguments.length, rest = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) {
1643 rest[_key5 - 1] = arguments[_key5];
1644 }
1645
1646 return (_this5 = _this).dropScopeByIds.apply(_this5, [_this.getCachingNodesByName(name).map(function (_ref) {
1647 var id = _ref.id;
1648 return id;
1649 })].concat(rest));
1650 });
1651
1652 _defineProperty(_assertThisInitialized(_this), "refreshById", function (id) {
1653 var _this6;
1654
1655 for (var _len6 = arguments.length, rest = new Array(_len6 > 1 ? _len6 - 1 : 0), _key6 = 1; _key6 < _len6; _key6++) {
1656 rest[_key6 - 1] = arguments[_key6];
1657 }
1658
1659 return (_this6 = _this).handleNodes.apply(_this6, [[id], HANDLE_TYPE_REFRESH].concat(rest));
1660 });
1661
1662 _defineProperty(_assertThisInitialized(_this), "refreshScopeByIds", function (ids) {
1663 var _this7;
1664
1665 for (var _len7 = arguments.length, rest = new Array(_len7 > 1 ? _len7 - 1 : 0), _key7 = 1; _key7 < _len7; _key7++) {
1666 rest[_key7 - 1] = arguments[_key7];
1667 }
1668
1669 return (_this7 = _this).handleNodes.apply(_this7, [_this.getScopeIds(ids), HANDLE_TYPE_REFRESH].concat(rest));
1670 });
1671
1672 _defineProperty(_assertThisInitialized(_this), "refresh", function (name) {
1673 var _this8;
1674
1675 for (var _len8 = arguments.length, rest = new Array(_len8 > 1 ? _len8 - 1 : 0), _key8 = 1; _key8 < _len8; _key8++) {
1676 rest[_key8 - 1] = arguments[_key8];
1677 }
1678
1679 return (_this8 = _this).handleNodes.apply(_this8, [_this.getCachingNodesByName(name).map(function (node) {
1680 return node.id;
1681 }), HANDLE_TYPE_REFRESH].concat(rest));
1682 });
1683
1684 _defineProperty(_assertThisInitialized(_this), "refreshScope", function (name) {
1685 var _this9;
1686
1687 for (var _len9 = arguments.length, rest = new Array(_len9 > 1 ? _len9 - 1 : 0), _key9 = 1; _key9 < _len9; _key9++) {
1688 rest[_key9 - 1] = arguments[_key9];
1689 }
1690
1691 return (_this9 = _this).refreshScopeByIds.apply(_this9, [_this.getCachingNodesByName(name).map(function (_ref2) {
1692 var id = _ref2.id;
1693 return id;
1694 })].concat(rest));
1695 });
1696
1697 _defineProperty(_assertThisInitialized(_this), "handleNodes", function (nodesId) {
1698 var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : HANDLE_TYPE_DROP;
1699
1700 for (var _len10 = arguments.length, rest = new Array(_len10 > 2 ? _len10 - 2 : 0), _key10 = 2; _key10 < _len10; _key10++) {
1701 rest[_key10 - 2] = arguments[_key10];
1702 }
1703
1704 return new Promise(function (resolve) {
1705 var handleKeepers = [];
1706 nodesId.forEach(function (id) {
1707 var cache = _this.store.get(id);
1708
1709 if (!cache) {
1710 return;
1711 }
1712
1713 var keeper = _this.keepers.get(id);
1714
1715 handleKeepers.push(keeper);
1716 });
1717
1718 if (handleKeepers.length === 0) {
1719 resolve(false);
1720 return;
1721 }
1722
1723 Promise.all(handleKeepers.map(function (keeper) {
1724 return _run.apply(void 0, [keeper, type].concat(rest));
1725 })).then(function (responses) {
1726 return resolve(responses.every(Boolean));
1727 });
1728 });
1729 });
1730
1731 _defineProperty(_assertThisInitialized(_this), "clear", function () {
1732 var _this10;
1733
1734 for (var _len11 = arguments.length, rest = new Array(_len11), _key11 = 0; _key11 < _len11; _key11++) {
1735 rest[_key11] = arguments[_key11];
1736 }
1737
1738 return (_this10 = _this).handleNodes.apply(_this10, [_this.getCachingNodes().map(function (_ref3) {
1739 var id = _ref3.id;
1740 return id;
1741 }), HANDLE_TYPE_DROP].concat(rest));
1742 });
1743
1744 _defineProperty(_assertThisInitialized(_this), "getCache", function (id) {
1745 return _this.store.get(id);
1746 });
1747
1748 _defineProperty(_assertThisInitialized(_this), "getNode", function (id) {
1749 return _this.nodes.get(id);
1750 });
1751
1752 _defineProperty(_assertThisInitialized(_this), "getCachingNodes", function () {
1753 return _toConsumableArray(_this.nodes.values());
1754 });
1755
1756 _defineProperty(_assertThisInitialized(_this), "helpers", {
1757 keep: _this.keep,
1758 update: _this.update,
1759 drop: _this.drop,
1760 dropScope: _this.dropScope,
1761 dropById: _this.dropById,
1762 dropScopeByIds: _this.dropScopeByIds,
1763 refresh: _this.refresh,
1764 refreshScope: _this.refreshScope,
1765 refreshById: _this.refreshById,
1766 refreshScopeByIds: _this.refreshScopeByIds,
1767 getScopeIds: _this.getScopeIds,
1768 clear: _this.clear,
1769 getCache: _this.getCache,
1770 getNode: _this.getNode,
1771 getCachingNodes: _this.getCachingNodes
1772 });
1773
1774 return _this;
1775 }
1776
1777 _createClass(AliveScope, [{
1778 key: "render",
1779 value: function render() {
1780 var _this11 = this;
1781
1782 var _this$props$children = this.props.children,
1783 children = _this$props$children === void 0 ? null : _this$props$children;
1784 return /*#__PURE__*/React__default.createElement(AliveScopeProvider$1, {
1785 value: this.helpers,
1786 _nk: "".concat(_filehash$7, "11")
1787 }, children, /*#__PURE__*/React__default.createElement("div", {
1788 style: {
1789 display: 'none'
1790 },
1791 _nk: "".concat(_filehash$7, "21")
1792 }, _toConsumableArray(this.nodes.values()).map(function (_ref4) {
1793 var children = _ref4.children,
1794 props = _objectWithoutProperties(_ref4, _excluded$3);
1795
1796 return /*#__PURE__*/React__default.createElement(Keeper, _extends({
1797 key: props.id
1798 }, props, {
1799 scope: _this11,
1800 store: _this11.store,
1801 keepers: _this11.keepers,
1802 ref: function ref(keeper) {
1803 _this11.keepers.set(props.id, keeper);
1804 },
1805 _nk: "iAr".concat(_filehash$7, "31")
1806 }), children);
1807 })));
1808 }
1809 }]);
1810
1811 return AliveScope;
1812}(React.Component);
1813
1814function renderDefaultScope() {
1815 if (!_get(_globalThis, 'document')) {
1816 return;
1817 }
1818
1819 var container = _run(_globalThis, 'document.createElement', 'div');
1820
1821 reactDom.render( /*#__PURE__*/React__default.createElement(AliveScope, {
1822 _nk: "".concat(_filehash$7, "41")
1823 }), container);
1824}
1825
1826renderDefaultScope();
1827
1828var _excluded$4 = ["id"],
1829 _excluded2 = ["id"],
1830 _excluded3 = ["forwardedRef"],
1831 _excluded4 = ["forwardedRef"];
1832var _filehash$8 = "X7Aa";
1833
1834function controllerCherryPick(controller) {
1835 var drop = controller.drop,
1836 dropScope = controller.dropScope,
1837 refresh = controller.refresh,
1838 refreshScope = controller.refreshScope,
1839 clear = controller.clear,
1840 getCachingNodes = controller.getCachingNodes;
1841 return {
1842 drop: drop,
1843 dropScope: dropScope,
1844 refresh: refresh,
1845 refreshScope: refreshScope,
1846 clear: clear,
1847 getCachingNodes: getCachingNodes
1848 };
1849}
1850
1851var expandKeepAlive = function expandKeepAlive(KeepAlive) {
1852 var renderContent = function renderContent(_ref) {
1853 var idPrefix = _ref.idPrefix,
1854 helpers = _ref.helpers,
1855 props = _ref.props;
1856
1857 var isOutsideAliveScope = _isUndefined(helpers);
1858
1859 if (isOutsideAliveScope) {
1860 console.error('You should not use <KeepAlive /> outside a <AliveScope>');
1861 }
1862
1863 return isOutsideAliveScope ? _get(props, 'children', null) : /*#__PURE__*/React__default.createElement(NodeKey, {
1864 prefix: idPrefix,
1865 key: props._nk,
1866 _nk: "".concat(_filehash$8, "11")
1867 }, function (id) {
1868 return /*#__PURE__*/React__default.createElement(Acceptor, {
1869 key: id,
1870 id: id,
1871 _nk: "".concat(_filehash$8, "21")
1872 }, function (bridgeProps) {
1873 return /*#__PURE__*/React__default.createElement(KeepAlive, _extends({
1874 key: id
1875 }, props, bridgeProps, {
1876 id: id,
1877 _helpers: helpers,
1878 _nk: "".concat(_filehash$8, "31")
1879 }));
1880 });
1881 });
1882 };
1883
1884 var HookExpand = function HookExpand(_ref2) {
1885 var idPrefix = _ref2.id,
1886 props = _objectWithoutProperties(_ref2, _excluded$4);
1887
1888 return renderContent({
1889 idPrefix: idPrefix,
1890 helpers: useScopeContext(),
1891 props: props
1892 });
1893 };
1894
1895 var WithExpand = function WithExpand(_ref3) {
1896 var idPrefix = _ref3.id,
1897 props = _objectWithoutProperties(_ref3, _excluded2);
1898
1899 return /*#__PURE__*/React__default.createElement(AliveScopeConsumer$1, {
1900 _nk: "".concat(_filehash$8, "41")
1901 }, function (helpers) {
1902 return renderContent({
1903 idPrefix: idPrefix,
1904 helpers: helpers,
1905 props: props
1906 });
1907 });
1908 };
1909
1910 return _isFunction(React.useContext) ? HookExpand : WithExpand;
1911};
1912
1913var withAliveScope = function withAliveScope(WrappedComponent) {
1914 var renderContent = function renderContent(_ref4) {
1915 var helpers = _ref4.helpers,
1916 props = _ref4.props,
1917 forwardedRef = _ref4.forwardedRef;
1918 return /*#__PURE__*/React__default.createElement(WrappedComponent, _extends({}, props, helpers, {
1919 ref: forwardedRef,
1920 _nk: "".concat(_filehash$8, "51")
1921 }));
1922 };
1923
1924 var HookScope = function HookScope(_ref5) {
1925 var forwardedRef = _ref5.forwardedRef,
1926 props = _objectWithoutProperties(_ref5, _excluded3);
1927
1928 return renderContent({
1929 helpers: controllerCherryPick(useScopeContext() || {}),
1930 props: props,
1931 forwardedRef: forwardedRef
1932 });
1933 };
1934
1935 var WithScope = function WithScope(_ref6) {
1936 var forwardedRef = _ref6.forwardedRef,
1937 props = _objectWithoutProperties(_ref6, _excluded4);
1938
1939 return /*#__PURE__*/React__default.createElement(AliveScopeConsumer$1, {
1940 _nk: "".concat(_filehash$8, "42")
1941 }, function () {
1942 var controller = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1943 return renderContent({
1944 helpers: controllerCherryPick(controller),
1945 props: props,
1946 forwardedRef: forwardedRef
1947 });
1948 });
1949 };
1950
1951 var HOCWithAliveScope = _isFunction(React.useContext) ? HookScope : WithScope;
1952
1953 if (_isFunction(React.forwardRef)) {
1954 var ForwardedRefHOC = /*#__PURE__*/React.forwardRef(function (props, ref) {
1955 return /*#__PURE__*/React__default.createElement(HOCWithAliveScope, _extends({}, props, {
1956 forwardedRef: ref,
1957 _nk: "".concat(_filehash$8, "61")
1958 }));
1959 });
1960 return hoistStatics(ForwardedRefHOC, WrappedComponent);
1961 } else {
1962 return hoistStatics(HOCWithAliveScope, WrappedComponent);
1963 }
1964};
1965
1966var useAliveController = function useAliveController() {
1967 if (!_isFunction(React.useContext)) {
1968 return {};
1969 }
1970
1971 var ctxValue = useScopeContext();
1972
1973 if (!ctxValue) {
1974 return {};
1975 }
1976
1977 return controllerCherryPick(ctxValue);
1978};
1979
1980function isScrollableNode() {
1981 var node = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1982
1983 if (!_isExist(node)) {
1984 return false;
1985 }
1986
1987 return node.scrollWidth > node.clientWidth || node.scrollHeight > node.clientHeight;
1988}
1989
1990function getScrollableNodes(from) {
1991 if (!_isFunction(_get(_globalThis, 'document.querySelectorAll'))) {
1992 return [];
1993 }
1994
1995 return [].concat(_toConsumableArray(_value(_run(from, 'querySelectorAll', '*'), [])), [from]).filter(isScrollableNode);
1996}
1997
1998function saveScrollPosition(from) {
1999 var nodes = _toConsumableArray(new Set(_toConsumableArray(_flatten(from.map(getScrollableNodes)))));
2000
2001 var saver = nodes.map(function (node) {
2002 return [node, {
2003 x: node.scrollLeft,
2004 y: node.scrollTop
2005 }];
2006 });
2007 return function revert() {
2008 saver.forEach(function (_ref) {
2009 var _ref2 = _slicedToArray(_ref, 2),
2010 node = _ref2[0],
2011 _ref2$ = _ref2[1],
2012 x = _ref2$.x,
2013 y = _ref2$.y;
2014
2015 node.scrollLeft = x;
2016 node.scrollTop = y;
2017 });
2018 };
2019}
2020
2021var _excluded$5 = ["_helpers", "id", "children"],
2022 _excluded2$1 = ["_helpers", "id", "name"];
2023
2024var body = _get(_globalThis, 'document.body');
2025
2026var screenScrollingElement = _get(_globalThis, 'document.scrollingElement', _get(_globalThis, 'document.documentElement', {}));
2027
2028var getErrorTips = function getErrorTips(name) {
2029 return "<KeepAlive ".concat(name ? "name=\"".concat(name, "\" ") : '', "/> Too many transient updates, may have encountered an infinite loop of updates, forced to pause the update\nThere are serious performance issues with the update results you are currently seeing\nMay encounter an implied bug, please don't use KeepAlive and contact the author to solve");
2030};
2031
2032var parseWhenResult = function parseWhenResult(res) {
2033 if (_isArray(res)) {
2034 return res;
2035 }
2036
2037 return [res];
2038};
2039
2040var KeepAlive = /*#__PURE__*/function (_Component) {
2041 _inherits(KeepAlive, _Component);
2042
2043 var _super = _createSuper(KeepAlive);
2044
2045 // 本段为 KeepAlive 更新隐患检测,通过检测 KeepAlive 瞬时更新次数来判断是否进入死循环,并在 update 中强制阻止更新
2046 // 用作 Keeper 识别 KeepAlive
2047 // 用作 Keeper 识别 KeepAlive
2048 function KeepAlive(props) {
2049 var _this;
2050
2051 _classCallCheck(this, KeepAlive);
2052
2053 _this = _super.call(this, props);
2054
2055 _defineProperty(_assertThisInitialized(_this), "updateTimes", 0);
2056
2057 _defineProperty(_assertThisInitialized(_this), "errorTips", _debounce(function () {
2058 var name = _this.props.name;
2059 console.error(getErrorTips(name));
2060 }, 100));
2061
2062 _defineProperty(_assertThisInitialized(_this), "releaseUpdateTimes", _debounce(function () {
2063 _this.updateTimes = 0;
2064 }, 16));
2065
2066 _defineProperty(_assertThisInitialized(_this), "needForceStopUpdate", function () {
2067 var needForceStopUpdate = _this.updateTimes > 64;
2068
2069 if (needForceStopUpdate) {
2070 _this.errorTips();
2071 }
2072
2073 _this.updateTimes++;
2074
2075 _this.releaseUpdateTimes();
2076
2077 return needForceStopUpdate;
2078 });
2079
2080 _defineProperty(_assertThisInitialized(_this), "id", null);
2081
2082 _defineProperty(_assertThisInitialized(_this), "isKeepAlive", true);
2083
2084 _defineProperty(_assertThisInitialized(_this), "cached", false);
2085
2086 _defineProperty(_assertThisInitialized(_this), "inject", function () {
2087 var didActivate = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
2088 var _this$props = _this.props,
2089 id = _this$props.id,
2090 saveScrollPosition = _this$props.saveScrollPosition,
2091 _helpers = _this$props._helpers;
2092
2093 var cache = _helpers.getCache(id); // DOM 操作有风险,try catch 护体
2094
2095
2096 try {
2097 // // 原计划不增加额外的节点,直接将 Keeper 中所有内容节点一一迁移
2098 // // 后发现缺乏统一 react 认可的外层包裹,可能会造成 react dom 操作的错误
2099 // // 且将导致 KeepAlive 进行 update 时需先恢复各 dom 节点的组件归属,成本过高
2100 // // 故此处增加统一的 div 外层,Keeper 中与 KeepAlive 中各一个且外层不做移除处理
2101 // this.parentNode = this.placeholder.parentNode
2102 // cache.nodes.forEach(node => {
2103 // this.parentNode.insertBefore(node, this.placeholder)
2104 // })
2105 // this.parentNode.removeChild(this.placeholder)
2106 // 将 AliveScopeProvider 中的渲染内容通过 dom 操作置回当前 KeepAlive
2107 cache.nodes.forEach(function (node) {
2108 _this.placeholder.appendChild(node);
2109 });
2110
2111 if (didActivate && saveScrollPosition) {
2112 // 恢复该节点下各可滚动元素的滚动位置
2113 _run(cache.revertScrollPos);
2114 }
2115 } catch (error) {// console.error(error)
2116 }
2117 });
2118
2119 _defineProperty(_assertThisInitialized(_this), "eject", function () {
2120 var willUnactivate = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
2121 var _this$props2 = _this.props,
2122 id = _this$props2.id,
2123 _helpers = _this$props2._helpers;
2124
2125 var cache = _helpers.getCache(id);
2126
2127 var nodesNeedToSaveScrollPosition = _flatten(_flatten([_this.props.saveScrollPosition]).map(function (flag) {
2128 if (flag === true) {
2129 return cache.nodes;
2130 }
2131
2132 if (flag === 'screen') {
2133 return [screenScrollingElement, body];
2134 }
2135
2136 return _toConsumableArray(_value(_run(_globalThis, 'document.querySelectorAll', flag), []));
2137 })).filter(Boolean); // DOM 操作有风险,try catch 护体
2138
2139
2140 try {
2141 if (willUnactivate && nodesNeedToSaveScrollPosition.length > 0) {
2142 // 保存该节点下各可滚动元素的滚动位置
2143 cache.revertScrollPos = saveScrollPosition(nodesNeedToSaveScrollPosition);
2144 } // // 原计划不增加额外的节点,直接将 Keeper 中所有内容节点一一迁移
2145 // // 后发现缺乏统一 react 认可的外层包裹,可能会造成 react dom 操作的错误
2146 // // 且将导致 KeepAlive 进行 update 时需先恢复各 dom 节点的组件归属,成本过高
2147 // // 故此处增加统一的 div 外层,Keeper 中与 KeepAlive 中各一个且外层不做移除处理
2148 // this.parentNode.insertBefore(this.placeholder, cache.nodes[0])
2149 // cache.nodes.forEach(node => {
2150 // if (willUnactivate) {
2151 // this.parentNode.removeChild(node)
2152 // } else {
2153 // cache.wrapper.appendChild(node)
2154 // }
2155 // })
2156 // this.parentNode.insertBefore(this.placeholder, cache.nodes[0])
2157 // 将 KeepAlive 中的节点恢复为原先的占位节点,保证卸载操作正常进行
2158
2159
2160 cache.nodes.forEach(function (node) {
2161 if (willUnactivate) {
2162 _this.placeholder.removeChild(node);
2163 } else {
2164 cache.wrapper.appendChild(node);
2165 }
2166 });
2167 } catch (error) {// console.error(error)
2168 }
2169 });
2170
2171 _defineProperty(_assertThisInitialized(_this), "init", function () {
2172 var _this$props3 = _this.props,
2173 _helpers = _this$props3._helpers,
2174 id = _this$props3.id,
2175 children = _this$props3.children,
2176 rest = _objectWithoutProperties(_this$props3, _excluded$5); // 将 children 渲染至 AliveScopeProvider 中
2177
2178
2179 _helpers.keep(id, _objectSpread2({
2180 children: children,
2181 getInstance: function getInstance() {
2182 return _assertThisInitialized(_this);
2183 }
2184 }, rest)).then(function (cache) {
2185 // fix #22
2186 if (!cache) {
2187 return;
2188 }
2189
2190 _this.inject(); // 触发 didActivate 生命周期
2191
2192
2193 if (cache.inited) {
2194 _run(_assertThisInitialized(_this), LIFECYCLE_ACTIVATE);
2195 } else {
2196 cache.inited = true;
2197 }
2198
2199 _this.cached = false;
2200 });
2201 });
2202
2203 _defineProperty(_assertThisInitialized(_this), "update", function () {
2204 var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
2205 _helpers = _ref._helpers,
2206 id = _ref.id,
2207 name = _ref.name,
2208 rest = _objectWithoutProperties(_ref, _excluded2$1);
2209
2210 if (!_helpers || _this.cached || _this.needForceStopUpdate(name)) {
2211 return;
2212 } // // 原先打算更新过程中先重置 dom 节点状态,更新后恢复 dom 节点
2213 // // 但考虑到性能消耗可能过大,且可能因 dom 操作时机引发其他 react 渲染问题,故不使用
2214 // // 对应 Keeper 处 componentDidUpdate 也注释起来不使用
2215 // this.eject(false)
2216
2217
2218 _helpers.update(id, _objectSpread2({
2219 name: name,
2220 getInstance: function getInstance() {
2221 return _assertThisInitialized(_this);
2222 }
2223 }, rest)); // this.inject(false)
2224
2225 });
2226
2227 _this.id = props.id;
2228
2229 _this.init() // 继承响应父级 KeepAlive 的生命周期
2230 ;
2231
2232 [LIFECYCLE_ACTIVATE, LIFECYCLE_UNACTIVATE].forEach(function (lifecycleName) {
2233 _this[lifecycleName] = function () {
2234 var _this$props4 = _this.props,
2235 id = _this$props4.id,
2236 _helpers = _this$props4._helpers;
2237
2238 var cache = _helpers.getCache(id);
2239
2240 var node = _helpers.getNode(id);
2241
2242 if (node && lifecycleName === LIFECYCLE_ACTIVATE) {
2243 node.updateTime = Date.now();
2244 }
2245
2246 var cached = lifecycleName === LIFECYCLE_UNACTIVATE; // 若组件即将卸载则不再触发缓存生命周期
2247
2248 if (!cache || cache.willDrop) {
2249 // 若组件在父 KeepAlive 缓存期间被卸载,后续恢复后需重新触发 init
2250 if (_this.cached && !cached) {
2251 _this.init();
2252 }
2253
2254 return;
2255 }
2256
2257 _run(cache, lifecycleName);
2258
2259 cache.cached = cached;
2260 _this.cached = cached;
2261 };
2262 });
2263 return _this;
2264 } // DOM 操作将实际内容插入占位元素
2265
2266
2267 _createClass(KeepAlive, [{
2268 key: "shouldComponentUpdate",
2269 value: // 利用 shouldComponentUpdate 提前触发组件更新
2270 function shouldComponentUpdate(nextProps) {
2271 this.update(nextProps);
2272 return false;
2273 } // 组件卸载时重置 dom 状态,保证 react dom 操作正常进行,并触发 unactivate 生命周期
2274
2275 }, {
2276 key: "componentWillUnmount",
2277 value: function componentWillUnmount() {
2278 var _this$props5 = this.props,
2279 id = _this$props5.id,
2280 _helpers = _this$props5._helpers,
2281 _this$props5$when = _this$props5.when,
2282 calcWhen = _this$props5$when === void 0 ? true : _this$props5$when;
2283
2284 var cache = _helpers.getCache(id);
2285
2286 var _parseWhenResult = parseWhenResult(_run(calcWhen)),
2287 _parseWhenResult2 = _slicedToArray(_parseWhenResult, 2),
2288 when = _parseWhenResult2[0],
2289 isScope = _parseWhenResult2[1];
2290
2291 if (!cache) {
2292 return;
2293 }
2294
2295 this.eject();
2296 delete cache.getInstance;
2297
2298 if (!when) {
2299 if (isScope) {
2300 var needToDrop = [cache].concat(_toConsumableArray(_helpers.getScopeIds([id]).map(function (id) {
2301 return _helpers.getCache(id);
2302 })));
2303 needToDrop.forEach(function (cache) {
2304 cache.willDrop = true;
2305 });
2306
2307 _nextTick(function () {
2308 return _helpers.dropScopeByIds([id]);
2309 });
2310 } else {
2311 cache.willDrop = true;
2312
2313 _nextTick(function () {
2314 return _helpers.dropById(id);
2315 });
2316 }
2317 } // 触发 willUnactivate 生命周期
2318
2319
2320 _run(this, LIFECYCLE_UNACTIVATE);
2321 }
2322 }, {
2323 key: "render",
2324 value: function render() {
2325 var _this2 = this;
2326
2327 return /*#__PURE__*/React__default.createElement("div", {
2328 key: "keep-alive-placeholder",
2329 className: "ka-wrapper",
2330 ref: function ref(node) {
2331 _this2.placeholder = node;
2332 }
2333 });
2334 }
2335 }]);
2336
2337 return KeepAlive;
2338}(React.Component); // 兼容 SSR 服务端渲染
2339
2340
2341_defineProperty(KeepAlive, "defaultProps", {
2342 saveScrollPosition: true
2343});
2344
2345function SSRKeepAlive(_ref2) {
2346 var children = _ref2.children;
2347 return /*#__PURE__*/React__default.createElement("div", {
2348 key: "keep-alive-placeholder",
2349 className: "ka-wrapper"
2350 }, /*#__PURE__*/React__default.createElement("div", {
2351 key: "keeper-container",
2352 className: "ka-content"
2353 }, children));
2354}
2355
2356var KeepAlive$1 = _isFunction(_get(_globalThis, 'document.getElementById')) ? expandKeepAlive(withActivation(KeepAlive)) : SSRKeepAlive;
2357
2358exports.AliveScope = AliveScope;
2359exports.KeepAlive = KeepAlive$1;
2360exports.NodeKey = NodeKey;
2361exports.autoFixContext = autoFixContext;
2362exports.createContext = createContext;
2363exports.default = KeepAlive$1;
2364exports.fixContext = fixContext;
2365exports.useActivate = useActivate;
2366exports.useAliveController = useAliveController;
2367exports.useUnactivate = useUnactivate;
2368exports.withActivation = withActivation;
2369exports.withAliveScope = withAliveScope;
2370//# sourceMappingURL=index.js.map