-
-
Notifications
You must be signed in to change notification settings - Fork 43
/
renderer.ts
402 lines (347 loc) · 12.4 KB
/
renderer.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
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
import type { KeyedToken, KeyedTokensInfo, MagicMoveRenderOptions } from './types'
const CLASS_PREFIX = 'shiki-magic-move'
const CLASS_LEAVE_FROM = `${CLASS_PREFIX}-leave-from`
const CLASS_LEAVE_TO = `${CLASS_PREFIX}-leave-to`
const CLASS_LEAVE_ACTIVE = `${CLASS_PREFIX}-leave-active`
const CLASS_ENTER_FROM = `${CLASS_PREFIX}-enter-from`
const CLASS_ENTER_TO = `${CLASS_PREFIX}-enter-to`
const CLASS_ENTER_ACTIVE = `${CLASS_PREFIX}-enter-active`
const CLASS_MOVE = `${CLASS_PREFIX}-move`
const CLASS_CONTAINER_RESIZE = `${CLASS_PREFIX}-container-resize`
const CLASS_CONTAINER_RESTYLE = `${CLASS_PREFIX}-container-restyle`
interface PromiseWithResolve<T = void> extends Promise<T> {
resolve: (value: T) => void
}
export const defaultOptions: Required<MagicMoveRenderOptions> = {
globalScale: 1,
duration: 500,
delayMove: 0.3,
delayLeave: 0.1,
delayEnter: 0.7,
delayContainer: 0.4,
stagger: 0,
easing: 'ease',
animateContainer: true,
containerStyle: true,
}
export class MagicMoveRenderer {
private mapDom = new Map<string, HTMLElement>()
private container: HTMLElement
private anchor: HTMLElement
private previousPromises: PromiseWithResolve[] = []
public options: Required<MagicMoveRenderOptions>
private isFirstRender = true
constructor(
target: HTMLElement | string,
options: MagicMoveRenderOptions = {},
) {
this.options = {
...defaultOptions,
...options,
}
if (typeof target === 'string')
this.container = document.querySelector(target) as HTMLElement
else
this.container = target
// Create anchor
this.anchor = document.createElement('span')
this.anchor.style.position = 'absolute'
this.anchor.style.top = '0'
this.anchor.style.left = '0'
this.anchor.style.height = '1px'
this.anchor.style.width = '1px'
this.container.prepend(this.anchor)
}
private applyElementContent(el: HTMLElement, token: KeyedToken) {
if (token.content !== '\n') {
el.textContent = token.content
el.classList.add(`${CLASS_PREFIX}-item`)
}
}
private applyElementStyle(el: HTMLElement, token: KeyedToken) {
if (token.htmlStyle) {
if (typeof token.htmlStyle === 'string') {
el.setAttribute('style', token.htmlStyle)
}
else {
for (const [key, value] of Object.entries(token.htmlStyle)) {
el.style.setProperty(key, value)
}
}
}
if (token.htmlClass)
el.className = [`${CLASS_PREFIX}-item`, token.htmlClass].join(' ')
if (token.color)
el.style.color = token.color
if (token.bgColor)
el.style.backgroundColor = token.bgColor
}
private applyElement(el: HTMLElement, token: KeyedToken) {
this.applyElementContent(el, token)
this.applyElementStyle(el, token)
}
private applyNodeStyle(node: HTMLElement, step: KeyedTokensInfo) {
if (step.bg)
node.style.backgroundColor = step.bg
if (step.fg)
node.style.color = step.fg
if (step.rootStyle) {
const items = step.rootStyle.split(';')
for (const item of items) {
const [key, value] = item.split(':')
if (key && value)
node.style.setProperty(key.trim(), value.trim())
}
}
}
private applyContainerStyle(step: KeyedTokensInfo) {
if (!this.options.containerStyle)
return
this.applyNodeStyle(this.container, step)
}
private registerTransitionEnd(el: HTMLElement, cb: () => void) {
return () => {
let resolved = false
let resolve = () => { }
const promise = Promise.race([
// wait for the finish of all animation and transitions on this element then invoke the callback
Promise.allSettled(el.getAnimations().map(animation => animation.finished)).then(() => cb()),
// race it with another promise so it's still resolvable separately
new Promise<void>((_resolve) => {
resolve = () => {
if (resolved)
return
resolved = true
cb()
_resolve()
}
}),
]) as PromiseWithResolve
promise.resolve = resolve
return promise
}
}
setCssVariables() {
// Update CSS variables
this.container.style.setProperty('--smm-duration', `${this.options.duration}ms`)
this.container.style.setProperty('--smm-delay-move', `${this.options.delayMove}`)
this.container.style.setProperty('--smm-delay-leave', `${this.options.delayLeave}`)
this.container.style.setProperty('--smm-delay-enter', `${this.options.delayEnter}`)
this.container.style.setProperty('--smm-delay-container', `${this.options.delayContainer}`)
this.container.style.setProperty('--smm-easing', this.options.easing)
this.container.style.setProperty('--smm-stagger', '0')
}
/**
* Replace tokens without animation
*/
replace(step: KeyedTokensInfo): void {
const newDomMap = new Map<string, HTMLElement>()
const newChildren = step.tokens.map((token) => {
if (this.mapDom.has(token.key)) {
const el = this.mapDom.get(token.key)!
this.applyElement(el, token)
newDomMap.set(token.key, el)
this.mapDom.delete(token.key)
return el
}
else {
const el = document.createElement(token.content === '\n' ? 'br' : 'span')
this.applyElement(el, token)
newDomMap.set(token.key, el)
return el
}
})
this.container.replaceChildren(
this.anchor,
...newChildren,
)
this.applyContainerStyle(step)
this.mapDom = newDomMap
}
// Note: This function is intentionally not async to keep the operations sync
/**
* Render tokens with animation
*/
render(step: KeyedTokensInfo): Promise<void> {
this.setCssVariables()
const newDomMap = new Map<string, HTMLElement>()
const move: HTMLElement[] = []
const enter: HTMLElement[] = []
const leave: HTMLElement[] = []
const promises: (() => PromiseWithResolve)[] = []
this.previousPromises.forEach(p => p.resolve())
this.previousPromises = []
// Callbacks to run after forced reflow
const postReflow: (() => void)[] = []
const {
globalScale: scale,
} = this.options
// Record the current position of the elements (before rerendering)
const position = new Map<HTMLElement, { x: number, y: number }>()
let anchorRect = this.anchor.getBoundingClientRect()
const containerRect = this.container.getBoundingClientRect()
for (const el of this.mapDom.values()) {
const rect = el.getBoundingClientRect()
position.set(el, { x: rect.x - anchorRect.x, y: rect.y - anchorRect.y })
}
const newChildren = step.tokens.map((token) => {
if (this.mapDom.has(token.key)) {
const el = this.mapDom.get(token.key)!
this.applyElementContent(el, token)
postReflow.push(() => {
// Update color and style after reflow
this.applyElementStyle(el, token)
})
move.push(el)
newDomMap.set(token.key, el)
this.mapDom.delete(token.key)
return el
}
else {
const el = document.createElement(token.content === '\n' ? 'br' : 'span')
this.applyElement(el, token)
enter.push(el)
newDomMap.set(token.key, el)
return el
}
})
for (const [_, el] of this.mapDom) {
if (el.tagName === 'BR')
continue
leave.push(el)
}
for (const el of leave)
el.style.position = 'absolute'
// Update DOM
this.container.replaceChildren(
this.anchor,
...newChildren,
...leave,
)
this.mapDom = newDomMap
// Lock leave elements to their position with absolute positioning
leave.forEach((el, idx) => {
el.style.position = 'absolute'
const pos = position.get(el)!
el.style.top = `${pos.y / scale}px`
el.style.left = `${pos.x / scale}px`
if (this.options.stagger)
el.style.setProperty('--smm-stagger', `${idx * this.options.stagger}ms`)
else
el.style.removeProperty('--smm-stagger')
el.classList.add(CLASS_LEAVE_FROM)
el.classList.add(CLASS_LEAVE_ACTIVE)
postReflow.unshift(() => {
el.classList.remove(CLASS_LEAVE_FROM)
el.classList.add(CLASS_LEAVE_TO)
})
promises.push(
this.registerTransitionEnd(el, () => {
el.classList.remove(CLASS_LEAVE_FROM)
el.classList.remove(CLASS_LEAVE_ACTIVE)
el.classList.remove(CLASS_ENTER_TO)
el.remove()
}),
)
})
// Apply enter animation
if (!this.isFirstRender) {
enter.forEach((el, idx) => {
el.classList.add(CLASS_ENTER_FROM)
el.classList.add(CLASS_ENTER_ACTIVE)
if (this.options.stagger)
el.style.setProperty('--smm-stagger', `${idx * this.options.stagger}ms`)
else
el.style.removeProperty('--smm-stagger')
postReflow.push(() => {
el.classList.remove(CLASS_ENTER_FROM)
el.classList.add(CLASS_ENTER_TO)
})
promises.push(
this.registerTransitionEnd(el, () => {
el.classList.remove(CLASS_ENTER_FROM)
el.classList.remove(CLASS_ENTER_ACTIVE)
el.classList.remove(CLASS_ENTER_TO)
}),
)
})
}
// We recalculate the anchor position because the container might be moved
anchorRect = this.anchor.getBoundingClientRect()
// Set the position of the move elements to the old position
// Set the transition duration to 0ms to make it immediate
move.forEach((el, idx) => {
const newRect = el.getBoundingClientRect()
const newPos = { x: newRect.x - anchorRect.x, y: newRect.y - anchorRect.y }
const oldPos = position.get(el)!
el.style.transitionDuration = el.style.transitionDelay = '0ms'
const dx = (oldPos.x - newPos.x) / scale
const dy = (oldPos.y - newPos.y) / scale
el.style.transform = `translate(${dx}px, ${dy}px)`
if (this.options.stagger)
el.style.setProperty('--smm-stagger', `${idx * this.options.stagger}ms`)
else
el.style.removeProperty('--smm-stagger')
postReflow.unshift(() => {
// Remove transform overrides, so it will start animating back to the new position
el.classList.add(CLASS_MOVE)
el.style.transform = el.style.transitionDuration = el.style.transitionDelay = ''
})
promises.push(
this.registerTransitionEnd(el, () => {
el.classList.remove(CLASS_MOVE)
}),
)
})
// Animate the container size
if (this.options.animateContainer && !this.isFirstRender) {
const newRect = this.container.getBoundingClientRect()
if (newRect.width !== containerRect.width || newRect.height !== containerRect.height) {
this.container.style.transitionDuration = this.container.style.transitionDelay = '0ms'
this.container.style.height = `${containerRect.height / scale}px`
this.container.style.width = `${containerRect.width / scale}px`
postReflow.unshift(() => {
this.container.classList.add(CLASS_CONTAINER_RESIZE)
this.container.style.transitionDuration = this.container.style.transitionDelay = ''
this.container.style.height = `${newRect.height / scale}px`
this.container.style.width = `${newRect.width / scale}px`
})
promises.push(
this.registerTransitionEnd(this.container, () => {
this.container.classList.remove(CLASS_CONTAINER_RESIZE)
this.container.style.height = this.container.style.width = ''
}),
)
}
}
if (this.options.containerStyle) {
if (this.isFirstRender) {
this.applyContainerStyle(step)
}
else {
postReflow.push(() => {
this.container.classList.add(CLASS_CONTAINER_RESTYLE)
this.applyContainerStyle(step)
})
promises.push(
this.registerTransitionEnd(this.container, () => {
this.container.classList.remove(CLASS_CONTAINER_RESTYLE)
}),
)
}
}
// Trigger reflow to apply the transform
forceReflow()
postReflow.forEach(cb => cb())
// we need to call the functions that return the promises after the reflow
// to to allow getAnimations to have the correct transitions
const actualPromises = promises.map(promise => promise())
this.isFirstRender = false
this.previousPromises = actualPromises
return Promise.all(actualPromises).then()
}
}
// synchronously force layout to put elements into a certain state
function forceReflow() {
return document.body.offsetHeight
}