-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
transition.ts
219 lines (191 loc) · 6.33 KB
/
transition.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
import type {
SSRResult,
TransitionAnimation,
TransitionAnimationPair,
TransitionAnimationValue,
TransitionDirectionalAnimations,
} from '../../@types/astro.js';
import { fade, slide } from '../../transitions/index.js';
import { markHTMLString } from './escape.js';
import cssesc from 'cssesc';
const transitionNameMap = new WeakMap<SSRResult, number>();
function incrementTransitionNumber(result: SSRResult) {
let num = 1;
if (transitionNameMap.has(result)) {
num = transitionNameMap.get(result)! + 1;
}
transitionNameMap.set(result, num);
return num;
}
export function createTransitionScope(result: SSRResult, hash: string) {
const num = incrementTransitionNumber(result);
return `astro-${hash}-${num}`;
}
type Entries<T extends Record<string, any>> = Iterable<[keyof T, T[keyof T]]>;
const getAnimations = (name: TransitionAnimationValue) => {
if (name === 'fade') return fade();
if (name === 'slide') return slide();
if (typeof name === 'object') return name;
};
const addPairs = (
animations: TransitionDirectionalAnimations | Record<string, TransitionAnimationPair>,
stylesheet: ViewTransitionStyleSheet
) => {
for (const [direction, images] of Object.entries(animations) as Entries<typeof animations>) {
for (const [image, rules] of Object.entries(images) as Entries<
(typeof animations)[typeof direction]
>) {
stylesheet.addAnimationPair(direction, image, rules);
}
}
};
export function renderTransition(
result: SSRResult,
hash: string,
animationName: TransitionAnimationValue | undefined,
transitionName: string
) {
// Default to `fade` (similar to `initial`, but snappier)
if (!animationName) animationName = 'fade';
const scope = createTransitionScope(result, hash);
const name = transitionName ? cssesc(transitionName, { isIdentifier: true }) : scope;
const sheet = new ViewTransitionStyleSheet(scope, name);
const animations = getAnimations(animationName);
if (animations) {
addPairs(animations, sheet);
} else if (animationName === 'none') {
sheet.addFallback('old', 'animation: none; mix-blend-mode: normal;');
sheet.addModern('old', 'animation: none; opacity: 0; mix-blend-mode: normal;');
sheet.addAnimationRaw('new', 'animation: none; mix-blend-mode: normal;');
}
result._metadata.extraHead.push(markHTMLString(`<style>${sheet.toString()}</style>`));
return scope;
}
export function createAnimationScope(
transitionName: string,
animations: Record<string, TransitionAnimationPair>
) {
const hash = Math.random().toString(36).slice(2, 8);
const scope = `astro-${hash}`;
const sheet = new ViewTransitionStyleSheet(scope, transitionName);
addPairs(animations, sheet);
return { scope, styles: sheet.toString().replaceAll('"', '') };
}
class ViewTransitionStyleSheet {
private modern: string[] = [];
private fallback: string[] = [];
constructor(
private scope: string,
private name: string
) {}
toString() {
const { scope, name } = this;
const [modern, fallback] = [this.modern, this.fallback].map((rules) => rules.join(''));
return [
`[data-astro-transition-scope="${scope}"] { view-transition-name: ${name}; }`,
this.layer(modern),
fallback,
].join('');
}
private layer(cssText: string) {
return cssText ? `@layer astro { ${cssText} }` : '';
}
private addRule(target: 'modern' | 'fallback', cssText: string) {
this[target].push(cssText);
}
addAnimationRaw(image: 'old' | 'new' | 'group', animation: string) {
this.addModern(image, animation);
this.addFallback(image, animation);
}
addModern(image: 'old' | 'new' | 'group', animation: string) {
const { name } = this;
this.addRule('modern', `::view-transition-${image}(${name}) { ${animation} }`);
}
addFallback(image: 'old' | 'new' | 'group', animation: string) {
const { scope } = this;
this.addRule(
'fallback',
// Two selectors here, the second in case there is an animation on the root.
`[data-astro-transition-fallback="${image}"] [data-astro-transition-scope="${scope}"],
[data-astro-transition-fallback="${image}"][data-astro-transition-scope="${scope}"] { ${animation} }`
);
}
addAnimationPair(
direction: 'forwards' | 'backwards' | string,
image: 'old' | 'new',
rules: TransitionAnimation | TransitionAnimation[]
) {
const { scope, name } = this;
const animation = stringifyAnimation(rules);
const prefix =
direction === 'backwards'
? `[data-astro-transition=back]`
: direction === 'forwards'
? ''
: `[data-astro-transition=${direction}]`;
this.addRule('modern', `${prefix}::view-transition-${image}(${name}) { ${animation} }`);
this.addRule(
'fallback',
`${prefix}[data-astro-transition-fallback="${image}"] [data-astro-transition-scope="${scope}"],
${prefix}[data-astro-transition-fallback="${image}"][data-astro-transition-scope="${scope}"] { ${animation} }`
);
}
}
type AnimationBuilder = {
toString(): string;
[key: string]: string[] | ((k: string) => string);
};
function addAnimationProperty(builder: AnimationBuilder, prop: string, value: string | number) {
let arr = builder[prop];
if (Array.isArray(arr)) {
arr.push(value.toString());
} else {
builder[prop] = [value.toString()];
}
}
function animationBuilder(): AnimationBuilder {
return {
toString() {
let out = '';
for (let k in this) {
let value = this[k];
if (Array.isArray(value)) {
out += `\n\t${k}: ${value.join(', ')};`;
}
}
return out;
},
};
}
function stringifyAnimation(anim: TransitionAnimation | TransitionAnimation[]): string {
if (Array.isArray(anim)) {
return stringifyAnimations(anim);
} else {
return stringifyAnimations([anim]);
}
}
function stringifyAnimations(anims: TransitionAnimation[]): string {
const builder = animationBuilder();
for (const anim of anims) {
if (anim.duration) {
addAnimationProperty(builder, 'animation-duration', toTimeValue(anim.duration));
}
if (anim.easing) {
addAnimationProperty(builder, 'animation-timing-function', anim.easing);
}
if (anim.direction) {
addAnimationProperty(builder, 'animation-direction', anim.direction);
}
if (anim.delay) {
addAnimationProperty(builder, 'animation-delay', anim.delay);
}
if (anim.fillMode) {
addAnimationProperty(builder, 'animation-fill-mode', anim.fillMode);
}
addAnimationProperty(builder, 'animation-name', anim.name);
}
return builder.toString();
}
function toTimeValue(num: number | string) {
return typeof num === 'number' ? num + 'ms' : num;
}