@tschk/moonshine-astro 0.4.4 → 0.4.80

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,496 @@
1
+ /** Independent host-free Astro View Transitions animations, navigation, and DOM swap helpers. */
2
+
3
+ export interface TransitionAnimation {
4
+ name: string;
5
+ delay?: number | string;
6
+ duration?: number | string;
7
+ easing?: string;
8
+ fillMode?: string;
9
+ direction?: string;
10
+ }
11
+
12
+ export interface TransitionAnimationPair {
13
+ old: TransitionAnimation | TransitionAnimation[];
14
+ new: TransitionAnimation | TransitionAnimation[];
15
+ }
16
+
17
+ export interface TransitionDirectionalAnimations {
18
+ forwards: TransitionAnimationPair;
19
+ backwards: TransitionAnimationPair;
20
+ }
21
+
22
+ export interface AnimationOptions {
23
+ duration?: string | number;
24
+ }
25
+
26
+ export type Direction = "forward" | "back";
27
+
28
+ export interface NavigationOptions {
29
+ history?: "auto" | "push" | "replace";
30
+ formData?: FormData;
31
+ info?: unknown;
32
+ state?: unknown;
33
+ sourceElement?: Element;
34
+ }
35
+
36
+ export const TRANSITION_BEFORE_PREPARATION = "astro:before-preparation";
37
+ export const TRANSITION_AFTER_PREPARATION = "astro:after-preparation";
38
+ export const TRANSITION_BEFORE_SWAP = "astro:before-swap";
39
+ export const TRANSITION_AFTER_SWAP = "astro:after-swap";
40
+ export const TRANSITION_PAGE_LOAD = "astro:page-load";
41
+
42
+ const EASE_IN_OUT_CUBIC = "cubic-bezier(0.76, 0, 0.24, 1)";
43
+
44
+ function formatCssTime(
45
+ value: number | string | undefined,
46
+ fallback: string,
47
+ ): string {
48
+ if (value === undefined) return fallback;
49
+ return typeof value === "number" ? `${value}ms` : value;
50
+ }
51
+
52
+ export function fade(
53
+ opts: AnimationOptions = {},
54
+ ): TransitionDirectionalAnimations {
55
+ const { duration } = opts;
56
+ const oldAnim: TransitionAnimation = {
57
+ name: "astroFadeOut",
58
+ duration: duration ?? "90ms",
59
+ easing: EASE_IN_OUT_CUBIC,
60
+ fillMode: "both",
61
+ };
62
+ const newAnim: TransitionAnimation = {
63
+ name: "astroFadeIn",
64
+ duration: duration ?? "210ms",
65
+ easing: EASE_IN_OUT_CUBIC,
66
+ delay: duration ? undefined : "30ms",
67
+ fillMode: "both",
68
+ };
69
+ return {
70
+ forwards: { old: oldAnim, new: newAnim },
71
+ backwards: { old: oldAnim, new: newAnim },
72
+ };
73
+ }
74
+
75
+ export function slide(
76
+ opts: AnimationOptions = {},
77
+ ): TransitionDirectionalAnimations {
78
+ const { duration } = opts;
79
+ return {
80
+ forwards: {
81
+ old: [
82
+ {
83
+ name: "astroFadeOut",
84
+ duration: duration ?? "90ms",
85
+ easing: EASE_IN_OUT_CUBIC,
86
+ fillMode: "both",
87
+ },
88
+ {
89
+ name: "astroSlideToLeft",
90
+ duration: duration ?? "220ms",
91
+ easing: EASE_IN_OUT_CUBIC,
92
+ fillMode: "both",
93
+ },
94
+ ],
95
+ new: [
96
+ {
97
+ name: "astroFadeIn",
98
+ duration: duration ?? "210ms",
99
+ easing: EASE_IN_OUT_CUBIC,
100
+ delay: duration ? undefined : "30ms",
101
+ fillMode: "both",
102
+ },
103
+ {
104
+ name: "astroSlideFromRight",
105
+ duration: duration ?? "220ms",
106
+ easing: EASE_IN_OUT_CUBIC,
107
+ fillMode: "both",
108
+ },
109
+ ],
110
+ },
111
+ backwards: {
112
+ old: [{ name: "astroFadeOut" }, { name: "astroSlideToRight" }],
113
+ new: [{ name: "astroFadeIn" }, { name: "astroSlideFromLeft" }],
114
+ },
115
+ };
116
+ }
117
+
118
+ export function none(): TransitionDirectionalAnimations {
119
+ const pair: TransitionAnimationPair = {
120
+ old: {
121
+ name: "none",
122
+ duration: 0,
123
+ easing: "linear",
124
+ fillMode: "both",
125
+ },
126
+ new: {
127
+ name: "none",
128
+ duration: 0,
129
+ easing: "linear",
130
+ fillMode: "both",
131
+ },
132
+ };
133
+ return {
134
+ forwards: pair,
135
+ backwards: pair,
136
+ };
137
+ }
138
+
139
+ function serializeAnimations(
140
+ anim: TransitionAnimation | TransitionAnimation[],
141
+ ): string {
142
+ const list = Array.isArray(anim) ? anim : [anim];
143
+ return list
144
+ .map((item) => {
145
+ const duration = formatCssTime(item.duration, "180ms");
146
+ const easing = item.easing ?? EASE_IN_OUT_CUBIC;
147
+ const delay =
148
+ item.delay !== undefined ? ` ${formatCssTime(item.delay, "0ms")}` : "";
149
+ const direction = item.direction ? ` ${item.direction}` : "";
150
+ const fillMode = item.fillMode ? ` ${item.fillMode}` : " both";
151
+ return `${duration} ${easing}${delay}${direction}${fillMode} ${item.name}`;
152
+ })
153
+ .join(", ");
154
+ }
155
+
156
+ let scopeCounter = 0;
157
+
158
+ export function createAnimationScope(
159
+ name: string,
160
+ animations: TransitionDirectionalAnimations,
161
+ scopeId?: string,
162
+ ): {
163
+ scope: string;
164
+ styles: string;
165
+ attributes: {
166
+ "data-astro-transition-scope": string;
167
+ };
168
+ } {
169
+ const safeName = name.replace(/[^a-zA-Z0-9_-]/g, "-") || "element";
170
+ const scope = scopeId ?? `astro-${safeName}-${++scopeCounter}`;
171
+ const fwdOld = serializeAnimations(animations.forwards.old);
172
+ const fwdNew = serializeAnimations(animations.forwards.new);
173
+ const bwdOld = serializeAnimations(animations.backwards.old);
174
+ const bwdNew = serializeAnimations(animations.backwards.new);
175
+ const styles =
176
+ `[data-astro-transition-scope="${scope}"] { view-transition-name: ${scope}; }` +
177
+ `@layer astro { ` +
178
+ `::view-transition-old(${scope}) { animation: ${fwdOld}; } ` +
179
+ `::view-transition-new(${scope}) { animation: ${fwdNew}; } ` +
180
+ `[data-astro-transition=back] ::view-transition-old(${scope}) { animation: ${bwdOld}; } ` +
181
+ `[data-astro-transition=back] ::view-transition-new(${scope}) { animation: ${bwdNew}; } ` +
182
+ `}`;
183
+ return {
184
+ scope,
185
+ styles,
186
+ attributes: {
187
+ "data-astro-transition-scope": scope,
188
+ },
189
+ };
190
+ }
191
+
192
+ export function transition(opts: {
193
+ name?: string;
194
+ animate?:
195
+ "initial" | "none" | "fade" | "slide" | TransitionDirectionalAnimations;
196
+ }): Record<string, string> {
197
+ const name = opts.name ?? "element";
198
+ const anim =
199
+ opts.animate === "none"
200
+ ? none()
201
+ : opts.animate === "slide"
202
+ ? slide()
203
+ : typeof opts.animate === "object" && opts.animate !== null
204
+ ? opts.animate
205
+ : fade();
206
+ const { scope } = createAnimationScope(name, anim);
207
+ return {
208
+ "data-astro-transition-scope": scope,
209
+ };
210
+ }
211
+
212
+ export const supportsViewTransitions: boolean =
213
+ typeof document !== "undefined" && "startViewTransition" in document;
214
+
215
+ export function isTransitionEnabled(): boolean {
216
+ if (typeof document === "undefined") return false;
217
+ return Boolean(
218
+ document.querySelector('meta[name="astro-view-transitions-enabled"]'),
219
+ );
220
+ }
221
+
222
+ export const swapFunctions = {
223
+ deselectScripts(newDocument: Document): void {
224
+ const existingKeys = new Set<string>();
225
+ if (typeof document !== "undefined") {
226
+ for (const s of Array.from(document.scripts)) {
227
+ if (s.dataset.astroExec === "" && s.src) {
228
+ existingKeys.add(s.src);
229
+ }
230
+ }
231
+ }
232
+ for (const s of Array.from(newDocument.scripts)) {
233
+ if (s.src && existingKeys.has(s.src)) {
234
+ s.dataset.astroExec = "";
235
+ }
236
+ }
237
+ },
238
+
239
+ swapRootAttributes(newDocument: Document): void {
240
+ if (typeof document === "undefined") return;
241
+ const currentRoot = document.documentElement;
242
+ const incomingRoot = newDocument.documentElement;
243
+ const direction = currentRoot.getAttribute("data-astro-transition");
244
+ for (const attr of Array.from(currentRoot.attributes)) {
245
+ currentRoot.removeAttribute(attr.name);
246
+ }
247
+ for (const attr of Array.from(incomingRoot.attributes)) {
248
+ currentRoot.setAttribute(attr.name, attr.value);
249
+ }
250
+ if (direction) {
251
+ currentRoot.setAttribute("data-astro-transition", direction);
252
+ }
253
+ },
254
+
255
+ swapHeadElements(newDocument: Document): void {
256
+ if (typeof document === "undefined") return;
257
+ document.title = newDocument.title;
258
+ },
259
+
260
+ saveFocus(): () => void {
261
+ if (typeof document === "undefined") return () => {};
262
+ const activeElement = document.activeElement as HTMLElement | null;
263
+ return () => {
264
+ if (
265
+ activeElement &&
266
+ typeof activeElement.focus === "function" &&
267
+ document.contains(activeElement)
268
+ ) {
269
+ activeElement.focus();
270
+ }
271
+ };
272
+ },
273
+
274
+ swapBodyElement(newBody: Element, oldBody: Element): void {
275
+ oldBody.replaceWith(newBody);
276
+ },
277
+
278
+ swap(newDocument: Document): void {
279
+ if (typeof document === "undefined") return;
280
+ swapFunctions.deselectScripts(newDocument);
281
+ swapFunctions.swapRootAttributes(newDocument);
282
+ swapFunctions.swapHeadElements(newDocument);
283
+ const restoreFocus = swapFunctions.saveFocus();
284
+ swapFunctions.swapBodyElement(newDocument.body, document.body);
285
+ restoreFocus();
286
+ },
287
+ };
288
+
289
+ export async function navigate(
290
+ href: string,
291
+ options: NavigationOptions = {},
292
+ ): Promise<void> {
293
+ if (typeof window === "undefined" || typeof document === "undefined") {
294
+ return;
295
+ }
296
+
297
+ const base = window.location?.href ?? "http://localhost/";
298
+ const to = new URL(href, base);
299
+ const from = new URL(base);
300
+ const direction: Direction = "forward";
301
+ const historyMode =
302
+ options.history === "replace"
303
+ ? "replace"
304
+ : options.history === "push"
305
+ ? "push"
306
+ : to.href === from.href
307
+ ? "replace"
308
+ : "push";
309
+
310
+ const beforePrep = new CustomEvent(TRANSITION_BEFORE_PREPARATION, {
311
+ cancelable: true,
312
+ detail: {
313
+ from,
314
+ to,
315
+ direction,
316
+ navigationType: historyMode,
317
+ sourceElement: options.sourceElement,
318
+ info: options.info,
319
+ formData: options.formData,
320
+ },
321
+ });
322
+ if (!document.dispatchEvent(beforePrep)) {
323
+ return;
324
+ }
325
+
326
+ document.dispatchEvent(new Event(TRANSITION_AFTER_PREPARATION));
327
+
328
+ const performSwap = () => {
329
+ const beforeSwap = new CustomEvent(TRANSITION_BEFORE_SWAP, {
330
+ cancelable: false,
331
+ detail: {
332
+ from,
333
+ to,
334
+ direction,
335
+ navigationType: historyMode,
336
+ sourceElement: options.sourceElement,
337
+ info: options.info,
338
+ },
339
+ });
340
+ document.dispatchEvent(beforeSwap);
341
+
342
+ if (typeof window.history !== "undefined") {
343
+ if (
344
+ historyMode === "replace" &&
345
+ typeof window.history.replaceState === "function"
346
+ ) {
347
+ window.history.replaceState(
348
+ options.state ?? {},
349
+ "",
350
+ to.pathname + to.search + to.hash,
351
+ );
352
+ } else if (typeof window.history.pushState === "function") {
353
+ window.history.pushState(
354
+ options.state ?? {},
355
+ "",
356
+ to.pathname + to.search + to.hash,
357
+ );
358
+ }
359
+ }
360
+
361
+ document.dispatchEvent(new Event(TRANSITION_AFTER_SWAP));
362
+ };
363
+
364
+ const docWithVT = document as Document & {
365
+ startViewTransition?: (cb: () => void | Promise<void>) => {
366
+ finished: Promise<void>;
367
+ };
368
+ };
369
+
370
+ if (typeof docWithVT.startViewTransition === "function") {
371
+ const vt = docWithVT.startViewTransition(performSwap);
372
+ await vt.finished;
373
+ } else {
374
+ performSwap();
375
+ }
376
+
377
+ document.dispatchEvent(new Event(TRANSITION_PAGE_LOAD));
378
+ }
379
+
380
+ import { h, type SSRChild } from "./ssr";
381
+
382
+ export type Fallback = "none" | "animate" | "swap";
383
+
384
+ export interface ClientRouterProps {
385
+ fallback?: Fallback;
386
+ handleForms?: boolean;
387
+ }
388
+
389
+ export function ClientRouter(props: ClientRouterProps = {}): SSRChild {
390
+ const fallback: Fallback = props.fallback ?? "animate";
391
+ const children: SSRChild[] = [
392
+ h("meta", { name: "astro-view-transitions-enabled", content: "true" }),
393
+ h("meta", { name: "astro-view-transitions-fallback", content: fallback }),
394
+ ];
395
+ if (props.handleForms !== undefined) {
396
+ children.push(
397
+ h("meta", {
398
+ name: "astro-view-transitions-forms",
399
+ content: String(Boolean(props.handleForms)),
400
+ }),
401
+ );
402
+ }
403
+ return children;
404
+ }
405
+
406
+ /** Legacy alias for `<ClientRouter />` from `astro:transitions`. */
407
+ export const ViewTransitions: typeof ClientRouter = ClientRouter;
408
+
409
+ export type PrefetchStrategy = "tap" | "hover" | "viewport" | "load";
410
+
411
+ export interface PrefetchOptions {
412
+ with?: "fetch" | "link";
413
+ ignoreSlowConnection?: boolean;
414
+ eagerness?: "immediate" | "eager" | "moderate" | "conservative";
415
+ }
416
+
417
+ export interface PrefetchInitOptions {
418
+ defaultStrategy?: PrefetchStrategy;
419
+ prefetchAll?: boolean;
420
+ }
421
+
422
+ const PREFETCHED_URLS = /* @__PURE__ */ new Set<string>();
423
+ let activePrefetchConfig: PrefetchInitOptions = {
424
+ defaultStrategy: "hover",
425
+ prefetchAll: false,
426
+ };
427
+
428
+ /** Programmatically prefetch a URL (`astro:prefetch`). */
429
+ export function prefetch(url: string, options: PrefetchOptions = {}): void {
430
+ if (!url) return;
431
+ const rawBase =
432
+ typeof window !== "undefined" && typeof window.location?.href === "string"
433
+ ? window.location.href
434
+ : "";
435
+ const base = /^https?:\/\//i.test(rawBase) ? rawBase : "http://localhost/";
436
+ let resolvedUrl: string;
437
+ try {
438
+ resolvedUrl = new URL(url, base).href;
439
+ } catch {
440
+ resolvedUrl = url;
441
+ }
442
+ if (PREFETCHED_URLS.has(resolvedUrl)) return;
443
+ PREFETCHED_URLS.add(resolvedUrl);
444
+
445
+ const mode = options.with ?? "link";
446
+ if (
447
+ mode === "link" &&
448
+ typeof document !== "undefined" &&
449
+ document.head &&
450
+ typeof document.head.appendChild === "function" &&
451
+ typeof document.createElement === "function"
452
+ ) {
453
+ const link = document.createElement("link");
454
+ link.rel = "prefetch";
455
+ link.href = url;
456
+ document.head.appendChild(link);
457
+ } else if (mode === "fetch" && typeof fetch === "function") {
458
+ void Promise.resolve(
459
+ fetch(resolvedUrl, { priority: "low" } as RequestInit),
460
+ ).catch(() => {});
461
+ }
462
+ }
463
+
464
+ /** Initialize automatic link prefetching (`astro:prefetch`). */
465
+ export function init(options: PrefetchInitOptions = {}): void {
466
+ activePrefetchConfig = {
467
+ defaultStrategy: options.defaultStrategy ?? "hover",
468
+ prefetchAll: options.prefetchAll ?? false,
469
+ };
470
+ if (
471
+ typeof document !== "undefined" &&
472
+ typeof document.querySelectorAll === "function"
473
+ ) {
474
+ const selector = activePrefetchConfig.prefetchAll
475
+ ? "a[href]"
476
+ : "a[href][data-astro-prefetch]";
477
+ for (const anchor of Array.from(
478
+ document.querySelectorAll<HTMLAnchorElement>(selector),
479
+ )) {
480
+ const strategy =
481
+ (anchor.getAttribute("data-astro-prefetch") as
482
+ PrefetchStrategy | "" | null) || activePrefetchConfig.defaultStrategy;
483
+ if (strategy === "load" && anchor.href) {
484
+ prefetch(anchor.href);
485
+ }
486
+ }
487
+ }
488
+ }
489
+
490
+ export function getPrefetchedUrls(): string[] {
491
+ return Array.from(PREFETCHED_URLS);
492
+ }
493
+
494
+ export function clearPrefetchedUrls(): void {
495
+ PREFETCHED_URLS.clear();
496
+ }