-
-
Notifications
You must be signed in to change notification settings - Fork 106
/
Copy pathcomponentSlots.ts
271 lines (249 loc) · 7.84 KB
/
componentSlots.ts
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
import { type IfAny, isArray, isFunction } from '@vue/shared'
import {
type EffectScope,
effectScope,
isReactive,
shallowReactive,
} from '@vue/reactivity'
import {
type ComponentInternalInstance,
currentInstance,
setCurrentInstance,
} from './component'
import { type Block, type Fragment, fragmentKey } from './apiRender'
import { firstEffect, renderEffect } from './renderEffect'
import { createComment, createTextNode, insert, remove } from './dom/element'
import type { NormalizedRawProps } from './componentProps'
import type { Data } from '@vue/runtime-shared'
import { mergeProps } from './dom/prop'
// TODO: SSR
export type Slot<T extends any = any> = (
...args: IfAny<T, any[], [T] | (T extends undefined ? [] : never)>
) => Block
export type StaticSlots = Record<string, Slot>
export type DynamicSlot = { name: string; fn: Slot }
export type DynamicSlotFn = () => DynamicSlot | DynamicSlot[] | undefined
export type NormalizedRawSlots = Array<StaticSlots | DynamicSlotFn>
export type RawSlots = NormalizedRawSlots | StaticSlots | null
export const isDynamicSlotFn = isFunction as (
val: StaticSlots | DynamicSlotFn,
) => val is DynamicSlotFn
export function initSlots(
instance: ComponentInternalInstance,
rawSlots: RawSlots | null = null,
): void {
if (!rawSlots) return
if (!isArray(rawSlots)) rawSlots = [rawSlots]
if (!rawSlots.some(slot => isDynamicSlotFn(slot))) {
instance.slots = {}
// with ctx
const slots = rawSlots[0] as StaticSlots
for (const name in slots) {
addSlot(name, slots[name])
}
return
}
instance.slots = shallowReactive({})
const renderedSlotKeys: Set<string>[] = []
/**
* Maintain a queue for each slot name, so that we can
* render the next slot when the highest level slot was removed
*/
const slotsQueue: Record<string, [level: number, slot: Slot][]> = {}
rawSlots.forEach((slots, index) => {
const isDynamicSlot = isDynamicSlotFn(slots)
if (isDynamicSlot) {
firstEffect(instance, () => {
const renderedKeys = (renderedSlotKeys[index] ||= new Set())
let dynamicSlot = slots()
// cleanup slots and re-calc to avoid diffing slots between renders
// cleanup will return a slotNames array contains the slot names that need to be restored
const restoreSlotNames = cleanupSlot(index)
if (isArray(dynamicSlot)) {
for (const slot of dynamicSlot) {
registerSlot(slot.name, slot.fn, index, renderedKeys)
}
} else if (dynamicSlot) {
registerSlot(dynamicSlot.name, dynamicSlot.fn, index, renderedKeys)
}
// restore after re-calc slots
if (restoreSlotNames.length) {
for (const key of restoreSlotNames) {
const [restoreLevel, restoreFn] = slotsQueue[key][0]
renderedSlotKeys[restoreLevel] &&
renderedSlotKeys[restoreLevel].add(key)
addSlot(key, restoreFn)
}
}
// delete stale slots
for (const name of renderedKeys) {
if (
!(isArray(dynamicSlot)
? dynamicSlot.some(s => s.name === name)
: dynamicSlot && dynamicSlot.name === name)
) {
renderedKeys.delete(name)
delete instance.slots[name]
}
}
})
} else {
for (const name in slots) {
registerSlot(name, slots[name], index)
}
}
})
function cleanupSlot(level: number) {
const restoreSlotNames: string[] = []
// remove slots from all queues
Object.keys(slotsQueue).forEach(slotName => {
const index = slotsQueue[slotName].findIndex(([l]) => l === level)
if (index > -1) {
slotsQueue[slotName] = slotsQueue[slotName].filter(([l]) => l !== level)
if (!slotsQueue[slotName].length) {
delete slotsQueue[slotName]
return
}
// restore next slot if the removed slots was the highest level slot
if (index === 0) {
renderedSlotKeys[level] && renderedSlotKeys[level].delete(slotName)
restoreSlotNames.push(slotName)
}
}
})
return restoreSlotNames
}
function registerSlot(
name: string,
slot: Slot,
level: number,
renderedKeys?: Set<string>,
) {
slotsQueue[name] ||= []
slotsQueue[name].push([level, slot])
slotsQueue[name].sort((a, b) => b[0] - a[0])
// hide old slot if the registered slot is the highest level
if (slotsQueue[name][1]) {
const hidenLevel = slotsQueue[name][1][0]
renderedSlotKeys[hidenLevel] && renderedSlotKeys[hidenLevel].delete(name)
}
if (slotsQueue[name][0][0] === level) {
renderedKeys && renderedKeys.add(name)
}
// render the highest level slot
addSlot(name, slotsQueue[name][0][1])
}
function addSlot(name: string, fn: Slot) {
instance.slots[name] = withCtx(fn)
}
function withCtx(fn: Slot): Slot {
return (...args: any[]) => {
const reset = setCurrentInstance(instance.parent!)
try {
return fn(...(args as any))
} finally {
reset()
}
}
}
}
export function createSlot(
name: string | (() => string),
binds?: NormalizedRawProps,
fallback?: () => Block,
): Block {
let block: Block | undefined
let branch: Slot | undefined
let oldBranch: Slot | undefined
let parent: ParentNode | undefined | null
let scope: EffectScope | undefined
const isDynamicName = isFunction(name)
const instance = currentInstance!
const { slots } = instance
// When not using dynamic slots, simplify the process to improve performance
if (!isDynamicName && !isReactive(slots)) {
if ((branch = withProps(slots[name]) || fallback)) {
return branch(binds)
} else {
return []
}
}
const getSlot = isDynamicName ? () => slots[name()] : () => slots[name]
const anchor = __DEV__ ? createComment('slot') : createTextNode()
const fragment: Fragment = {
nodes: [],
anchor,
[fragmentKey]: true,
}
// TODO lifecycle hooks
renderEffect(() => {
if ((branch = withProps(getSlot()) || fallback) !== oldBranch) {
parent ||= anchor.parentNode
if (block) {
scope!.stop()
remove(block, parent!)
}
if ((oldBranch = branch)) {
scope = effectScope()
fragment.nodes = block = scope.run(() => branch!(binds))!
parent && insert(block, parent, anchor)
} else {
scope = block = undefined
fragment.nodes = []
}
}
})
return fragment
function withProps<T extends (p: any) => any>(fn?: T) {
if (fn)
return (binds?: NormalizedRawProps): ReturnType<T> =>
fn(binds && normalizeSlotProps(binds))
}
}
function normalizeSlotProps(rawPropsList: NormalizedRawProps) {
const { length } = rawPropsList
const mergings = length > 1 ? shallowReactive<Data[]>([]) : undefined
const result = shallowReactive<Data>({})
for (let i = 0; i < length; i++) {
const rawProps = rawPropsList[i]
if (isFunction(rawProps)) {
// dynamic props
renderEffect(() => {
const props = rawProps()
if (mergings) {
mergings[i] = props
} else {
setDynamicProps(props)
}
})
} else {
// static props
const props = mergings
? (mergings[i] = shallowReactive<Data>({}))
: result
for (const key in rawProps) {
const valueSource = rawProps[key]
renderEffect(() => {
props[key] = valueSource()
})
}
}
}
if (mergings) {
renderEffect(() => {
setDynamicProps(mergeProps(...mergings))
})
}
return result
function setDynamicProps(props: Data) {
const otherExistingKeys = new Set(Object.keys(result))
for (const key in props) {
result[key] = props[key]
otherExistingKeys.delete(key)
}
// delete other stale props
for (const key of otherExistingKeys) {
delete result[key]
}
}
}