-
Notifications
You must be signed in to change notification settings - Fork 152
Expand file tree
/
Copy pathKeepAlive.js
More file actions
299 lines (263 loc) · 8.37 KB
/
KeepAlive.js
File metadata and controls
299 lines (263 loc) · 8.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
import React, { Component } from 'react'
import {
value,
get,
run,
globalThis as root,
nextTick,
isFunction,
isArray,
debounce,
flatten,
} from 'szfe-tools'
import { expandKeepAlive } from './withAliveScope'
import {
LIFECYCLE_ACTIVATE,
LIFECYCLE_UNACTIVATE,
withActivation,
} from './lifecycles'
import saveScrollPosition from '../helpers/saveScrollPosition'
const body = get(root, 'document.body')
const screenScrollingElement = get(
root,
'document.scrollingElement',
get(root, 'document.documentElement', {})
)
const parseWhenResult = (res) => {
if (isArray(res)) {
return res
}
return [res]
}
class KeepAlive extends Component {
static defaultProps = {
saveScrollPosition: true,
}
id = null // 用作 Keeper 识别 KeepAlive
isKeepAlive = true // 用作 Keeper 识别 KeepAlive
cached = false
constructor(props) {
super(props)
this.id = props.id
this.init()
// 继承响应父级 KeepAlive 的生命周期
;[LIFECYCLE_ACTIVATE, LIFECYCLE_UNACTIVATE].forEach((lifecycleName) => {
this[lifecycleName] = () => {
const { id, _helpers } = this.props
const cache = _helpers.getCache(id)
const node = _helpers.getNode(id)
if (node && lifecycleName === LIFECYCLE_ACTIVATE) {
node.updateTime = Date.now()
}
const cached = lifecycleName === LIFECYCLE_UNACTIVATE
// 若组件即将卸载则不再触发缓存生命周期
if (!cache || cache.willDrop) {
// 若组件在父 KeepAlive 缓存期间被卸载,后续恢复后需重新触发 init
if (this.cached && !cached) {
this.init()
}
return
}
run(cache, lifecycleName)
cache.cached = cached
this.cached = cached
}
})
}
// DOM 操作将实际内容插入占位元素
inject = (didActivate = true) => {
const { id, saveScrollPosition, _helpers } = this.props
const cache = _helpers.getCache(id)
// DOM 操作有风险,try catch 护体
try {
// // 原计划不增加额外的节点,直接将 Keeper 中所有内容节点一一迁移
// // 后发现缺乏统一 react 认可的外层包裹,可能会造成 react dom 操作的错误
// // 且将导致 KeepAlive 进行 update 时需先恢复各 dom 节点的组件归属,成本过高
// // 故此处增加统一的 div 外层,Keeper 中与 KeepAlive 中各一个且外层不做移除处理
// this.parentNode = this.placeholder.parentNode
// cache.nodes.forEach(node => {
// this.parentNode.insertBefore(node, this.placeholder)
// })
// this.parentNode.removeChild(this.placeholder)
// 将 AliveScopeProvider 中的渲染内容通过 dom 操作置回当前 KeepAlive
cache.nodes.forEach((node) => {
this.placeholder.appendChild(node)
})
if (didActivate && saveScrollPosition) {
// 恢复该节点下各可滚动元素的滚动位置
run(cache.revertScrollPos)
}
} catch (error) {
// console.error(error)
}
}
// DOM 操作将实际内容移出占位元素
eject = (willUnactivate = true) => {
const { id, _helpers, saveScrollPositionIgnoreNodeIds } = this.props
const cache = _helpers.getCache(id)
const nodesNeedToSaveScrollPosition = flatten(
flatten([this.props.saveScrollPosition]).map((flag) => {
if (flag === true) {
return cache.nodes
}
if (flag === 'screen') {
return [screenScrollingElement, body]
}
return [...value(run(root, 'document.querySelectorAll', flag), [])]
})
).filter(Boolean)
// DOM 操作有风险,try catch 护体
try {
if (willUnactivate && nodesNeedToSaveScrollPosition.length > 0) {
// 保存该节点下各可滚动元素的滚动位置
cache.revertScrollPos = saveScrollPosition(
nodesNeedToSaveScrollPosition,
{
ignoreNodeIds: saveScrollPositionIgnoreNodeIds,
}
)
}
// // 原计划不增加额外的节点,直接将 Keeper 中所有内容节点一一迁移
// // 后发现缺乏统一 react 认可的外层包裹,可能会造成 react dom 操作的错误
// // 且将导致 KeepAlive 进行 update 时需先恢复各 dom 节点的组件归属,成本过高
// // 故此处增加统一的 div 外层,Keeper 中与 KeepAlive 中各一个且外层不做移除处理
// this.parentNode.insertBefore(this.placeholder, cache.nodes[0])
// cache.nodes.forEach(node => {
// if (willUnactivate) {
// this.parentNode.removeChild(node)
// } else {
// cache.wrapper.appendChild(node)
// }
// })
// this.parentNode.insertBefore(this.placeholder, cache.nodes[0])
// 将 KeepAlive 中的节点恢复为原先的占位节点,保证卸载操作正常进行
cache.nodes.forEach((node) => {
if (willUnactivate) {
this.placeholder.removeChild(node)
} else {
cache.wrapper.appendChild(node)
}
})
} catch (error) {
// console.error(error)
}
}
refresh = () => {
const { _helpers, id } = this.props
return _helpers.refreshById(id)
}
drop = (config) => {
const { _helpers, id } = this.props
return _helpers.dropById(id, config)
}
init = () => {
const { _helpers, id, children, ...rest } = this.props
// 将 children 渲染至 AliveScopeProvider 中
_helpers
.keep(id, {
children,
getInstance: () => this,
...rest,
})
.then((cache) => {
// fix #22
if (!cache) {
return
}
this.inject()
// 触发 didActivate 生命周期
if (cache.inited) {
run(this, LIFECYCLE_ACTIVATE)
} else {
cache.inited = true
}
this.cached = false
})
}
update = ({ _helpers, id, name, ...rest } = {}) => {
if (!_helpers || this.cached) {
return
}
// // 原先打算更新过程中先重置 dom 节点状态,更新后恢复 dom 节点
// // 但考虑到性能消耗可能过大,且可能因 dom 操作时机引发其他 react 渲染问题,故不使用
// // 对应 Keeper 处 componentDidUpdate 也注释起来不使用
// this.eject(false)
_helpers.update(id, {
name,
getInstance: () => this,
...rest,
})
// this.inject(false)
}
// 利用 shouldComponentUpdate 提前触发组件更新
shouldComponentUpdate(nextProps) {
this.update(nextProps)
return false
}
// 组件卸载时重置 dom 状态,保证 react dom 操作正常进行,并触发 unactivate 生命周期
componentWillUnmount() {
const { id, _helpers, when: calcWhen = true } = this.props
const cache = _helpers.getCache(id)
const [when, isScope] = parseWhenResult(run(calcWhen))
if (!cache) {
return
}
this.eject()
delete cache.getInstance
if (!when) {
if (isScope) {
const needToDrop = [
cache,
..._helpers.getScopeIds([id]).map((id) => _helpers.getCache(id)),
].filter(Boolean)
needToDrop.forEach((cache) => {
cache.willDrop = true
})
nextTick(() => _helpers.dropScopeByIds([id]))
} else {
cache.willDrop = true
nextTick(() => _helpers.dropById(id))
}
}
// 触发 willUnactivate 生命周期
run(this, LIFECYCLE_UNACTIVATE)
}
render() {
const { wrapperProps = {} } = this.props || {}
return (
<div
{...wrapperProps}
key='keep-alive-placeholder'
nodeKeyIgnore
className={`ka-wrapper ${wrapperProps.className || ''}`}
ref={(node) => {
this.placeholder = node
}}
/>
)
}
}
// 兼容 SSR 服务端渲染
function SSRKeepAlive({ children }) {
const { wrapperProps = {}, contentProps = {} } = this.props || {}
return (
<div
{...wrapperProps}
key='keep-alive-placeholder'
nodeKeyIgnore
className={`ka-wrapper ${wrapperProps.className || ''}`}
>
<div
{...contentProps}
key='keeper-container'
nodeKeyIgnore
className={`ka-content ${contentProps.className || ''}`}
>
{children}
</div>
</div>
)
}
export default isFunction(get(root, 'document.getElementById'))
? expandKeepAlive(withActivation(KeepAlive))
: SSRKeepAlive