-
Notifications
You must be signed in to change notification settings - Fork 219
Expand file tree
/
Copy pathindex.jsx
More file actions
620 lines (552 loc) · 19.9 KB
/
index.jsx
File metadata and controls
620 lines (552 loc) · 19.9 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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
import React, { useEffect, useRef, createContext, useContext, useLayoutEffect, useState } from 'react'
import { createPortal } from 'react-dom'
import PropTypes from 'prop-types'
// React 19.2+ 提供 Activity API;若存在则使用,用于更精确的激活/失活检测
const ActivityComponent = React?.Activity ?? null
const KeepAliveContext = createContext(false)
export const useKeepAliveContext = () => useContext(KeepAliveContext)
/**
* Hook triggered when the component is activated
* @param {Function} callback
*/
export const useActivate = (callback) => {
const active = useKeepAliveContext()
const mountedRef = useRef(false)
useEffect(() => {
if (active) {
callback()
}
mountedRef.current = true
}, [active])
}
/**
* Hook triggered when the component is deactivated (hidden)
* @param {Function} callback
*/
export const useUnactivate = (callback) => {
const active = useKeepAliveContext()
const mountedRef = useRef(false)
useEffect(() => {
if (mountedRef.current && !active) {
callback()
}
mountedRef.current = true
}, [active])
}
const ensureHiddenContainer = () => {
if (typeof document === 'undefined') return null
let el = document.getElementById('__keepalive_hidden_root')
if (!el) {
el = document.createElement('div')
el.id = '__keepalive_hidden_root'
// Use fixed position and move out of viewport instead of display:none to keep internal state active if needed
el.style.cssText =
'position: fixed; left: -9999px; top: -9999px; width: 0; height: 0; overflow: hidden; pointer-events: none; opacity: 0; z-index: -1;'
document.body.appendChild(el)
}
return el
}
// Global LRU Cache Manager
const createKeepAliveManager = () => {
let limit = 10 // Default limit
let keys = [] // LRU keys (most recent at end)
const instances = new Map() // id -> { setShouldRender, persistOnUnmount }
const activeMap = new Map() // id -> boolean
const timeouts = new Map() // id -> timeoutId
// global options for deactivate strategy
let deactivateDelay = 3000 // ms to wait before hiding an inactive instance
let keepInactiveCount = 1 // how many most-recent inactive instances to keep rendered
const safeInvoke = (fn, label) => {
try {
fn()
} catch (err) {
// 仅在开发环境输出,避免生产环境噪音;同时满足 Sonar 对异常处理的要求
if (process.env.NODE_ENV === 'development') {
console.warn(`[KeepAlive] ${label} failed`, err)
}
}
}
return {
setLimit: (n) => {
limit = n
},
// set global options: { deactivateDelay, keepInactiveCount, limit }
setOptions: (opts = {}) => {
if (typeof opts.deactivateDelay === 'number') deactivateDelay = opts.deactivateDelay
if (typeof opts.keepInactiveCount === 'number') {
keepInactiveCount = Math.max(0, Math.floor(opts.keepInactiveCount))
}
if (typeof opts.limit === 'number') limit = Math.max(0, Math.floor(opts.limit))
},
register: (id, opts) => {
// opts: { setShouldRender, persistOnUnmount }
instances.set(id, {
setShouldRender: opts.setShouldRender,
persistOnUnmount: !!opts.persistOnUnmount
})
},
unregister: (id) => {
if (timeouts.has(id)) {
clearTimeout(timeouts.get(id))
timeouts.delete(id)
}
instances.delete(id)
activeMap.delete(id)
keys = keys.filter((k) => k !== id)
},
activate: (id) => {
// Move to end (most recently used)
keys = keys.filter((k) => k !== id)
keys.push(id)
activeMap.set(id, true)
// cancel any pending hide timer for this id
if (timeouts.has(id)) {
clearTimeout(timeouts.get(id))
timeouts.delete(id)
}
// Check limit and evict least-recent non-persistent entries
while (keys.length > limit) {
const idToDrop = keys.shift()
const instance = instances.get(idToDrop)
if (instance && !instance.persistOnUnmount) {
safeInvoke(() => instance.setShouldRender(false), `setShouldRender(false) for ${idToDrop}`)
}
}
// Ensure current is rendered
const current = instances.get(id)
if (current) {
safeInvoke(() => current.setShouldRender(true), `setShouldRender(true) for ${id}`)
}
},
// advanced deactivate behavior: schedule hide with delay and preserve N most-recent inactive
deactivate: (id) => {
// mark inactive
activeMap.set(id, false)
const instance = instances.get(id)
if (!instance) return
// move id to front (least recently used) so it becomes a candidate for eviction
keys = keys.filter((k) => k !== id)
keys.unshift(id)
// If instance is persistent, do nothing
if (instance.persistOnUnmount) return
// cancel existing timer
if (timeouts.has(id)) {
clearTimeout(timeouts.get(id))
timeouts.delete(id)
}
const t = setTimeout(() => {
// if reactivated meanwhile, skip
if (activeMap.get(id)) {
timeouts.delete(id)
return
}
// compute inactive rendered ids (non-persistent) in LRU order
const inactiveRendered = keys.filter((k) => {
const inst = instances.get(k)
return inst && !activeMap.get(k) && !inst.persistOnUnmount
})
// preserve the last `keepInactiveCount` of them (most recently used)
const preserved = inactiveRendered.slice(-keepInactiveCount)
if (!preserved.includes(id)) {
const inst = instances.get(id)
if (inst) {
safeInvoke(() => inst.setShouldRender(false), `setShouldRender(false) for ${id}`)
}
}
timeouts.delete(id)
}, deactivateDelay)
timeouts.set(id, t)
},
// Force drop (unmount) an id regardless of persist flag
forceDrop: (id) => {
const instance = instances.get(id)
if (instance) {
safeInvoke(() => instance.setShouldRender(false), `forceDrop setShouldRender(false) for ${id}`)
}
if (timeouts.has(id)) {
clearTimeout(timeouts.get(id))
timeouts.delete(id)
}
instances.delete(id)
activeMap.delete(id)
keys = keys.filter((k) => k !== id)
}
}
}
// 优化:支持 HMR (热更新)
// 在开发环境下,将 manager 挂载到 window 上,防止模块重载导致 manager 状态丢失
let manager
if (typeof window !== 'undefined') {
if (!window.__keepAliveManager) {
window.__keepAliveManager = createKeepAliveManager()
}
manager = window.__keepAliveManager
} else {
manager = createKeepAliveManager()
}
export const keepAliveManager = manager
const KeepAlive = ({ id, active = false, children, persistOnUnmount = false, cacheLimit }) => {
const placeholderRef = useRef(null)
const containerRef = useRef(null)
const [shouldRender, setShouldRender] = useState(true)
const scrollPos = useRef(new Map())
// Activity 模式下需要一个受控的可见性开关(用于延迟隐藏,给副作用留出执行时间)
const [isActivityVisible, setIsActivityVisible] = useState(active)
// Update global limit if provided
useEffect(() => {
if (cacheLimit) {
keepAliveManager.setLimit(cacheLimit)
}
}, [cacheLimit])
// Register to manager (pass persistOnUnmount so manager knows whether to keep rendered)
useEffect(() => {
if (id) {
// 优化:如果使用 ActivityComponent,我们强制认为它是持久化的,
// 防止 Manager 在超时后销毁组件,从而避免状态丢失(如视频重播)。
// Activity 模式下,隐藏的开销很小,适合保留状态。
const effectivePersist = ActivityComponent ? true : persistOnUnmount
keepAliveManager.register(id, {
setShouldRender,
persistOnUnmount: effectivePersist
})
}
return () => {
if (id) {
keepAliveManager.unregister(id)
}
}
}, [id, persistOnUnmount])
// Notify manager on active; Activity 模式下同步 deactivate(非 Activity 维持原有行为,不触发 deactivate)
useEffect(() => {
if (!id) return
if (active) {
keepAliveManager.activate(id)
return
}
if (ActivityComponent) {
keepAliveManager.deactivate(id)
}
}, [active, id])
useEffect(() => {
if (!ActivityComponent) return
let showTimer = null
if (active) {
// schedule state update asynchronously to avoid cascading render warnings
showTimer = setTimeout(() => setIsActivityVisible(true), 0)
return () => clearTimeout(showTimer)
}
const timer = setTimeout(() => {
setIsActivityVisible(false)
}, 16)
return () => {
clearTimeout(timer)
if (showTimer) clearTimeout(showTimer)
}
}, [active])
// Initialize container once (move DOM mutations into effect to satisfy hooks rules)
const [containerNode, setContainerNode] = useState(null)
useEffect(() => {
if (typeof document === 'undefined') return
if (containerRef.current) {
setContainerNode(containerRef.current)
return
}
// 优化:支持 HMR (热更新) —— 在开发环境下尝试复用已存在的 DOM 节点
let existing = null
try {
if (process.env.NODE_ENV === 'development' && id) {
const hidden = document.getElementById('__keepalive_hidden_root')
if (hidden) {
existing = hidden.querySelector(`[data-keepalive-id="${id}"]`)
}
}
} catch (err) {
existing = null
}
if (existing) {
containerRef.current = existing
} else {
const div = document.createElement('div')
div.dataset.keepaliveId = id || ''
// Ensure the container takes full space
div.style.height = '100%'
div.style.width = '100%'
containerRef.current = div
}
setContainerNode(containerRef.current)
if (process.env.NODE_ENV === 'development') {
try {
console.debug('[KeepAlive] setContainerNode', id, containerRef.current)
} catch (e) {}
}
// no cleanup here; mount/unmount handled elsewhere
}, [id])
// Scroll restoration logic
useEffect(() => {
const target = ActivityComponent ? placeholderRef.current : containerRef.current
if (!target) return
const onScroll = (e) => {
if (!active) return
scrollPos.current.set(e.target, {
left: e.target.scrollLeft,
top: e.target.scrollTop
})
}
// Capture scroll events to record positions
target.addEventListener('scroll', onScroll, {
capture: true,
passive: true
})
return () => {
target.removeEventListener('scroll', onScroll, { capture: true })
}
}, [active])
// Mount/Unmount logic
useEffect(() => {
const container = containerRef.current
// const hidden = ensureHiddenContainer() // 移除这里原本的 ensureHiddenContainer 逻辑,不要在挂载时立即移动
// 初始化样式
if (container) {
container.style.display = active ? 'block' : 'none'
}
return () => {
// Cleanup on unmount
if (!persistOnUnmount) {
container?.parentNode?.removeChild(container)
} else {
// 只有在组件真正卸载且需要持久化时,才移动到隐藏容器
const hidden = ensureHiddenContainer()
if (container && hidden) {
hidden.appendChild(container)
}
}
}
}, [persistOnUnmount])
// Toggle visibility logic
useLayoutEffect(() => {
const container = containerRef.current
const placeholder = placeholderRef.current
if (!container || !placeholder) return
// If React Activity API is available, avoid moving DOM to prevent forced reflows.
// Render children inline into the placeholder and point container refs to placeholder.
if (ActivityComponent) {
try {
containerRef.current = placeholder
setContainerNode(placeholder)
} catch (e) {}
return
}
// 如果 container 还在隐藏容器里(比如从缓存恢复),把它移到当前占位符下
if (container.parentNode !== placeholder) {
// 在移动 DOM 之前,发送自定义事件通知子组件,然后同步移动到占位符下。
// 之前使用短延迟的异步移动会导致渲染滞后和大量定时器/帧回调,移到同步移动以提升响应性。
const event = new CustomEvent('keepalive-dom-move', {
detail: { from: container.parentNode, to: placeholder }
})
let dispatchError = null
try {
container.dispatchEvent(event)
} catch (e) {
dispatchError = String(e && e.message)
}
if (process.env.NODE_ENV === 'development') {
try {
console.debug('[KeepAlive] appending container to placeholder', id, {
from: container.parentNode,
to: placeholder,
dispatchError
})
} catch (e) {}
}
let appended = false
try {
if (container.parentNode !== placeholder) {
container.dataset.keepaliveAttached = String(Date.now())
placeholder.appendChild(container)
appended = true
// Watchdog: if children not mounted soon after append, record and mark on body
try {
setTimeout(() => {
try {
if (container.childElementCount === 0) {
if (typeof window !== 'undefined') {
window.__keepalive_debug_details = window.__keepalive_debug_details || []
window.__keepalive_debug_details.push({
id,
note: 'no-children-after-append',
childElementCount: container.childElementCount,
time: Date.now()
})
try {
document.body.dataset.keepaliveIssue = 'no-children'
} catch (e) {}
}
}
} catch (e) {}
}, 50)
} catch (e) {}
}
} catch (e) {
// swallow; we'll record below
}
// 记录附加信息,包含父节点信息与子元素计数,便于生产环境排查
try {
if (typeof window !== 'undefined') {
window.__keepalive_debug_details = window.__keepalive_debug_details || []
window.__keepalive_debug_details.push({
id,
parentTag: container.parentNode ? container.parentNode.tagName : null,
parentClass: container.parentNode ? container.parentNode.className : null,
childElementCount: container.childElementCount,
appended,
dispatchError,
time: Date.now()
})
}
} catch (e) {}
// If we just appended and this instance is active, clear any stray inline "display: none" styles
if (appended && active && shouldRender) {
try {
// run in next frame to let other sync updates finish
requestAnimationFrame(() => {
try {
const cleared = []
// Limit to direct descendants first for safety
const nodes = Array.from(container.querySelectorAll('*'))
nodes.forEach((el) => {
try {
if (el && el.style && el.style.display === 'none') {
el.style.removeProperty('display')
cleared.push(el.tagName)
}
} catch (e) {}
})
// Ensure the root keepalive node is visible (force with !important)
try {
const root = container.querySelector(`[data-keepalive-id="${id}"]`)
if (root && root.style) {
root.style.setProperty('display', 'block', 'important')
}
} catch (e) {}
if (typeof window !== 'undefined') {
window.__keepalive_debug_details = window.__keepalive_debug_details || []
window.__keepalive_debug_details.push({
id,
note: 'cleared-inline-display-none',
clearedCount: cleared.length,
clearedTagsSample: cleared.slice(0, 5),
time: Date.now()
})
}
} catch (e) {}
})
} catch (e) {}
}
// Ensure root visible when active (force with !important) — covers cases where append didn't run
if (active && shouldRender) {
try {
const root = container.querySelector(`[data-keepalive-id="${id}"]`)
if (root && root.style) {
root.style.setProperty('display', 'block', 'important')
// also remove any stray inline display:none on descendants
try {
const nodes = Array.from(container.querySelectorAll('*'))
nodes.forEach((el) => {
try {
if (el && el.style && el.style.display === 'none') {
el.style.removeProperty('display')
}
} catch (e) {}
})
} catch (e) {}
if (typeof window !== 'undefined') {
window.__keepalive_debug_details = window.__keepalive_debug_details || []
window.__keepalive_debug_details.push({
id,
note: 'force-visible-root',
time: Date.now()
})
}
}
} catch (e) {}
}
// Restore scroll positions
scrollPos.current.forEach((pos, node) => {
if (node.isConnected) {
node.scrollLeft = pos.left
node.scrollTop = pos.top
}
})
} else {
// 失活时:仅隐藏,不移动 DOM
container.style.display = 'none'
}
}, [active, shouldRender])
// Record lightweight runtime debug info in an effect (avoid doing impure work during render)
useEffect(() => {
if (typeof window === 'undefined') return
if (!shouldRender) return
try {
window.__keepalive_debug = window.__keepalive_debug || []
window.__keepalive_debug.push({
id,
active,
shouldRender,
containerNode: !!containerNode,
childrenType: typeof children,
time: Date.now()
})
} catch (e) {}
}, [shouldRender, active, containerNode, id, children])
// Activity mode: render children inline and avoid DOM moving to reduce reflows
useEffect(() => {
if (!ActivityComponent) return
if (!active || !shouldRender) return
try {
requestAnimationFrame(() => {
try {
const p = placeholderRef.current
if (!p) return
const nodes = Array.from(p.querySelectorAll('*'))
nodes.forEach((el) => {
try {
if (el && el.style && el.style.display === 'none') {
el.style.removeProperty('display')
}
} catch (e) {}
})
if (typeof window !== 'undefined') {
window.__keepalive_debug_details = window.__keepalive_debug_details || []
window.__keepalive_debug_details.push({ id, note: 'activity-mode-cleaned-display', time: Date.now() })
}
} catch (e) {}
})
} catch (e) {}
}, [ActivityComponent, active, isActivityVisible, shouldRender])
if (!shouldRender) return null
if (ActivityComponent) {
return (
<KeepAliveContext.Provider value={active}>
<ActivityComponent mode={isActivityVisible ? 'visible' : 'hidden'}>
<div ref={placeholderRef} style={{ width: '100%', height: '100%' }}>
{children}
</div>
</ActivityComponent>
</KeepAliveContext.Provider>
)
}
return (
<KeepAliveContext.Provider value={active}>
<div ref={placeholderRef} style={{ width: '100%', height: '100%' }} />
{containerNode && createPortal(children, containerNode)}
</KeepAliveContext.Provider>
)
}
KeepAlive.propTypes = {
id: PropTypes.string,
active: PropTypes.bool,
children: PropTypes.node,
persistOnUnmount: PropTypes.bool,
cacheLimit: PropTypes.number
}
export default KeepAlive