astro 3.5.7 → 3.6.1

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.
package/client.d.ts CHANGED
@@ -109,6 +109,7 @@ declare module 'astro:transitions' {
109
109
  type TransitionModule = typeof import('./dist/transitions/index.js');
110
110
  export const slide: TransitionModule['slide'];
111
111
  export const fade: TransitionModule['fade'];
112
+ export const createAnimationScope: TransitionModule['createAnimationScope'];
112
113
 
113
114
  type ViewTransitionsModule = typeof import('./components/ViewTransitions.astro');
114
115
  export const ViewTransitions: ViewTransitionsModule['default'];
@@ -116,10 +117,30 @@ declare module 'astro:transitions' {
116
117
 
117
118
  declare module 'astro:transitions/client' {
118
119
  type TransitionRouterModule = typeof import('./dist/transitions/router.js');
119
- export const supportsViewTransitions: TransitionRouterModule['supportsViewTransitions'];
120
- export const transitionEnabledOnThisPage: TransitionRouterModule['transitionEnabledOnThisPage'];
121
120
  export const navigate: TransitionRouterModule['navigate'];
122
- export type Options = import('./dist/transitions/router.js').Options;
121
+
122
+ type TransitionUtilModule = typeof import('./dist/transitions/util.js');
123
+ export const supportsViewTransitions: TransitionUtilModule['supportsViewTransitions'];
124
+ export const getFallback: TransitionUtilModule['getFallback'];
125
+ export const transitionEnabledOnThisPage: TransitionUtilModule['transitionEnabledOnThisPage'];
126
+
127
+ export type Fallback = import('./dist/transitions/types.ts').Fallback;
128
+ export type Direction = import('./dist/transitions/types.ts').Direction;
129
+ export type NavigationTypeString = import('./dist/transitions/types.ts').NavigationTypeString;
130
+ export type Options = import('./dist/transitions/types.ts').Options;
131
+
132
+ type EventModule = typeof import('./dist/transitions/events.js');
133
+ export const TRANSITION_BEFORE_PREPARATION: EventModule['TRANSITION_BEFORE_PREPARATION'];
134
+ export const TRANSITION_AFTER_PREPARATION: EventModule['TRANSITION_AFTER_PREPARATION'];
135
+ export const TRANSITION_BEFORE_SWAP: EventModule['TRANSITION_BEFORE_SWAP'];
136
+ export const TRANSITION_AFTER_SWAP: EventModule['TRANSITION_AFTER_SWAP'];
137
+ export const TRANSITION_PAGE_LOAD: EventModule['TRANSITION_PAGE_LOAD'];
138
+ export type TransitionBeforePreparationEvent =
139
+ import('./dist/transitions/events.ts').TransitionBeforePreparationEvent;
140
+ export type TransitionBeforeSwapEvent =
141
+ import('./dist/transitions/events.ts').TransitionBeforeSwapEvent;
142
+ export const isTransitionBeforePreparationEvent: EventModule['isTransitionBeforePreparationEvent'];
143
+ export const isTransitionBeforeSwapEvent: EventModule['isTransitionBeforeSwapEvent'];
123
144
  }
124
145
 
125
146
  declare module 'astro:prefetch' {
@@ -33,7 +33,7 @@ const { fallback = 'animate', handleForms } = Astro.props;
33
33
  // @ts-ignore
34
34
  import { init } from 'astro/prefetch';
35
35
 
36
- export type Fallback = 'none' | 'animate' | 'swap';
36
+ type Fallback = 'none' | 'animate' | 'swap';
37
37
 
38
38
  function getFallback(): Fallback {
39
39
  const el = document.querySelector('[name="astro-view-transitions-fallback"]');
@@ -85,6 +85,7 @@ const { fallback = 'animate', handleForms } = Astro.props;
85
85
  ev.preventDefault();
86
86
  navigate(href, {
87
87
  history: link.dataset.astroHistory === 'replace' ? 'replace' : 'auto',
88
+ sourceElement: link,
88
89
  });
89
90
  });
90
91
 
@@ -102,7 +103,7 @@ const { fallback = 'animate', handleForms } = Astro.props;
102
103
  let action = submitter?.getAttribute('formaction') ?? form.action ?? location.pathname;
103
104
  const method = submitter?.getAttribute('formmethod') ?? form.method;
104
105
 
105
- const options: Options = {};
106
+ const options: Options = { sourceElement: submitter ?? form };
106
107
  if (method === 'get') {
107
108
  const params = new URLSearchParams(formData as any);
108
109
  const url = new URL(action);
@@ -1,4 +1,4 @@
1
- const ASTRO_VERSION = "3.5.7";
1
+ const ASTRO_VERSION = "3.6.1";
2
2
  const SUPPORTED_MARKDOWN_FILE_EXTENSIONS = [
3
3
  ".markdown",
4
4
  ".mdown",
@@ -20,7 +20,7 @@ async function dev(inlineConfig) {
20
20
  base: restart.container.settings.config.base
21
21
  })
22
22
  );
23
- const currentVersion = "3.5.7";
23
+ const currentVersion = "3.6.1";
24
24
  if (currentVersion.includes("-")) {
25
25
  logger.warn(null, msg.prerelease({ currentVersion }));
26
26
  }
@@ -50,7 +50,7 @@ function serverStart({
50
50
  base,
51
51
  isRestart = false
52
52
  }) {
53
- const version = "3.5.7";
53
+ const version = "3.6.1";
54
54
  const localPrefix = `${dim("\u2503")} Local `;
55
55
  const networkPrefix = `${dim("\u2503")} Network `;
56
56
  const emptyPrefix = " ".repeat(11);
@@ -235,7 +235,7 @@ function printHelp({
235
235
  message.push(
236
236
  linebreak(),
237
237
  ` ${bgGreen(black(` ${commandName} `))} ${green(
238
- `v${"3.5.7"}`
238
+ `v${"3.6.1"}`
239
239
  )} ${headline}`
240
240
  );
241
241
  }
@@ -2,7 +2,7 @@ import type { Plugin as VitePlugin } from 'vite';
2
2
  import type { AstroSettings } from '../../@types/astro.js';
3
3
  import type { BuildInternals } from '../build/internal.js';
4
4
  import type { StaticBuildOptions } from '../build/types.js';
5
- export declare const MIDDLEWARE_MODULE_ID = "@astro-middleware";
5
+ export declare const MIDDLEWARE_MODULE_ID = "\0astro-internal:middleware";
6
6
  export declare function vitePluginMiddleware({ settings }: {
7
7
  settings: AstroSettings;
8
8
  }): VitePlugin;
@@ -2,7 +2,7 @@ import { normalizePath } from "vite";
2
2
  import { getOutputDirectory } from "../../prerender/utils.js";
3
3
  import { addRollupInput } from "../build/add-rollup-input.js";
4
4
  import { MIDDLEWARE_PATH_SEGMENT_NAME } from "../constants.js";
5
- const MIDDLEWARE_MODULE_ID = "@astro-middleware";
5
+ const MIDDLEWARE_MODULE_ID = "\0astro-internal:middleware";
6
6
  const EMPTY_MIDDLEWARE = "\0empty-middleware";
7
7
  function vitePluginMiddleware({ settings }) {
8
8
  let isCommandBuild = false;
@@ -15,6 +15,10 @@ export interface PrefetchOptions {
15
15
  * - `'fetch'`: use `fetch()`, has higher loading priority.
16
16
  */
17
17
  with?: 'link' | 'fetch';
18
+ /**
19
+ * Should prefetch even on data saver mode or slow connection. (default `false`)
20
+ */
21
+ ignoreSlowConnection?: boolean;
18
22
  }
19
23
  /**
20
24
  * Prefetch a URL so it's cached when the user navigates to it.
@@ -24,7 +24,7 @@ function initTapStrategy() {
24
24
  event,
25
25
  (e) => {
26
26
  if (elMatchesStrategy(e.target, "tap")) {
27
- prefetch(e.target.href, { with: "fetch" });
27
+ prefetch(e.target.href, { with: "fetch", ignoreSlowConnection: true });
28
28
  }
29
29
  },
30
30
  { passive: true }
@@ -112,7 +112,8 @@ function createViewportIntersectionObserver() {
112
112
  });
113
113
  }
114
114
  function prefetch(url, opts) {
115
- if (!canPrefetchUrl(url))
115
+ const ignoreSlowConnection = opts?.ignoreSlowConnection ?? false;
116
+ if (!canPrefetchUrl(url, ignoreSlowConnection))
116
117
  return;
117
118
  prefetchedUrls.add(url);
118
119
  const priority = opts?.with ?? "link";
@@ -129,14 +130,11 @@ function prefetch(url, opts) {
129
130
  });
130
131
  }
131
132
  }
132
- function canPrefetchUrl(url) {
133
+ function canPrefetchUrl(url, ignoreSlowConnection) {
133
134
  if (!navigator.onLine)
134
135
  return false;
135
- if ("connection" in navigator) {
136
- const conn = navigator.connection;
137
- if (conn.saveData || /(2|3)g/.test(conn.effectiveType))
138
- return false;
139
- }
136
+ if (!ignoreSlowConnection && isSlowConnection())
137
+ return false;
140
138
  try {
141
139
  const urlObj = new URL(url, location.href);
142
140
  return location.origin === urlObj.origin && location.pathname !== urlObj.pathname && !prefetchedUrls.has(url);
@@ -151,6 +149,9 @@ function elMatchesStrategy(el, strategy) {
151
149
  if (attrValue === "false") {
152
150
  return false;
153
151
  }
152
+ if (strategy === "tap" && (attrValue != null || prefetchAll) && isSlowConnection()) {
153
+ return true;
154
+ }
154
155
  if (attrValue == null && prefetchAll || attrValue === "") {
155
156
  return strategy === defaultStrategy;
156
157
  }
@@ -159,6 +160,13 @@ function elMatchesStrategy(el, strategy) {
159
160
  }
160
161
  return false;
161
162
  }
163
+ function isSlowConnection() {
164
+ if ("connection" in navigator) {
165
+ const conn = navigator.connection;
166
+ return conn.saveData || /(2|3)g/.test(conn.effectiveType);
167
+ }
168
+ return false;
169
+ }
162
170
  function onPageLoad(cb) {
163
171
  cb();
164
172
  let firstLoad = false;
@@ -1,3 +1,7 @@
1
- import type { SSRResult, TransitionAnimationValue } from '../../@types/astro.js';
1
+ import type { SSRResult, TransitionAnimationPair, TransitionAnimationValue } from '../../@types/astro.js';
2
2
  export declare function createTransitionScope(result: SSRResult, hash: string): string;
3
3
  export declare function renderTransition(result: SSRResult, hash: string, animationName: TransitionAnimationValue | undefined, transitionName: string): string;
4
+ export declare function createAnimationScope(transitionName: string, animations: Record<string, TransitionAnimationPair>): {
5
+ scope: string;
6
+ styles: string;
7
+ };
@@ -24,6 +24,13 @@ const getAnimations = (name) => {
24
24
  if (typeof name === "object")
25
25
  return name;
26
26
  };
27
+ const addPairs = (animations, stylesheet) => {
28
+ for (const [direction, images] of Object.entries(animations)) {
29
+ for (const [image, rules] of Object.entries(images)) {
30
+ stylesheet.addAnimationPair(direction, image, rules);
31
+ }
32
+ }
33
+ };
27
34
  function renderTransition(result, hash, animationName, transitionName) {
28
35
  if (!animationName)
29
36
  animationName = "fade";
@@ -32,11 +39,7 @@ function renderTransition(result, hash, animationName, transitionName) {
32
39
  const sheet = new ViewTransitionStyleSheet(scope, name);
33
40
  const animations = getAnimations(animationName);
34
41
  if (animations) {
35
- for (const [direction, images] of Object.entries(animations)) {
36
- for (const [image, rules] of Object.entries(images)) {
37
- sheet.addAnimationPair(direction, image, rules);
38
- }
39
- }
42
+ addPairs(animations, sheet);
40
43
  } else if (animationName === "none") {
41
44
  sheet.addFallback("old", "animation: none; mix-blend-mode: normal;");
42
45
  sheet.addModern("old", "animation: none; opacity: 0; mix-blend-mode: normal;");
@@ -45,6 +48,13 @@ function renderTransition(result, hash, animationName, transitionName) {
45
48
  result._metadata.extraHead.push(markHTMLString(`<style>${sheet.toString()}</style>`));
46
49
  return scope;
47
50
  }
51
+ function createAnimationScope(transitionName, animations) {
52
+ const hash = Math.random().toString(36).slice(2, 8);
53
+ const scope = `astro-${hash}`;
54
+ const sheet = new ViewTransitionStyleSheet(scope, transitionName);
55
+ addPairs(animations, sheet);
56
+ return { scope, styles: sheet.toString().replaceAll('"', "") };
57
+ }
48
58
  class ViewTransitionStyleSheet {
49
59
  constructor(scope, name) {
50
60
  this.scope = scope;
@@ -87,7 +97,7 @@ class ViewTransitionStyleSheet {
87
97
  addAnimationPair(direction, image, rules) {
88
98
  const { scope, name } = this;
89
99
  const animation = stringifyAnimation(rules);
90
- const prefix = direction === "backwards" ? `[data-astro-transition=back]` : "";
100
+ const prefix = direction === "backwards" ? `[data-astro-transition=back]` : direction === "forwards" ? "" : `[data-astro-transition=${direction}]`;
91
101
  this.addRule("modern", `${prefix}::view-transition-${image}(${name}) { ${animation} }`);
92
102
  this.addRule(
93
103
  "fallback",
@@ -152,6 +162,7 @@ function toTimeValue(num) {
152
162
  return typeof num === "number" ? num + "ms" : num;
153
163
  }
154
164
  export {
165
+ createAnimationScope,
155
166
  createTransitionScope,
156
167
  renderTransition
157
168
  };
@@ -0,0 +1,36 @@
1
+ /// <reference types="@types/dom-view-transitions" />
2
+ import type { Direction, NavigationTypeString } from './types.js';
3
+ export declare const TRANSITION_BEFORE_PREPARATION = "astro:before-preparation";
4
+ export declare const TRANSITION_AFTER_PREPARATION = "astro:after-preparation";
5
+ export declare const TRANSITION_BEFORE_SWAP = "astro:before-swap";
6
+ export declare const TRANSITION_AFTER_SWAP = "astro:after-swap";
7
+ export declare const TRANSITION_PAGE_LOAD = "astro:page-load";
8
+ type Events = typeof TRANSITION_AFTER_PREPARATION | typeof TRANSITION_AFTER_SWAP | typeof TRANSITION_PAGE_LOAD;
9
+ export declare const triggerEvent: (name: Events) => boolean;
10
+ export declare const onPageLoad: () => boolean;
11
+ declare class BeforeEvent extends Event {
12
+ readonly from: URL;
13
+ to: URL;
14
+ direction: Direction | string;
15
+ readonly navigationType: NavigationTypeString;
16
+ readonly sourceElement: Element | undefined;
17
+ readonly info: any;
18
+ newDocument: Document;
19
+ constructor(type: string, eventInitDict: EventInit | undefined, from: URL, to: URL, direction: Direction | string, navigationType: NavigationTypeString, sourceElement: Element | undefined, info: any, newDocument: Document);
20
+ }
21
+ export declare const isTransitionBeforePreparationEvent: (value: any) => value is TransitionBeforePreparationEvent;
22
+ export declare class TransitionBeforePreparationEvent extends BeforeEvent {
23
+ formData: FormData | undefined;
24
+ loader: () => Promise<void>;
25
+ constructor(from: URL, to: URL, direction: Direction | string, navigationType: NavigationTypeString, sourceElement: Element | undefined, info: any, newDocument: Document, formData: FormData | undefined, loader: (event: TransitionBeforePreparationEvent) => Promise<void>);
26
+ }
27
+ export declare const isTransitionBeforeSwapEvent: (value: any) => value is TransitionBeforeSwapEvent;
28
+ export declare class TransitionBeforeSwapEvent extends BeforeEvent {
29
+ readonly direction: Direction | string;
30
+ readonly viewTransition: ViewTransition;
31
+ swap: () => void;
32
+ constructor(afterPreparation: BeforeEvent, viewTransition: ViewTransition, swap: (event: TransitionBeforeSwapEvent) => void);
33
+ }
34
+ export declare function doPreparation(from: URL, to: URL, direction: Direction | string, navigationType: NavigationTypeString, sourceElement: Element | undefined, info: any, formData: FormData | undefined, defaultLoader: (event: TransitionBeforePreparationEvent) => Promise<void>): Promise<TransitionBeforePreparationEvent>;
35
+ export declare function doSwap(afterPreparation: BeforeEvent, viewTransition: ViewTransition, defaultSwap: (event: TransitionBeforeSwapEvent) => void): Promise<TransitionBeforeSwapEvent>;
36
+ export {};
@@ -0,0 +1,131 @@
1
+ import { updateScrollPosition } from "./router.js";
2
+ const TRANSITION_BEFORE_PREPARATION = "astro:before-preparation";
3
+ const TRANSITION_AFTER_PREPARATION = "astro:after-preparation";
4
+ const TRANSITION_BEFORE_SWAP = "astro:before-swap";
5
+ const TRANSITION_AFTER_SWAP = "astro:after-swap";
6
+ const TRANSITION_PAGE_LOAD = "astro:page-load";
7
+ const triggerEvent = (name) => document.dispatchEvent(new Event(name));
8
+ const onPageLoad = () => triggerEvent(TRANSITION_PAGE_LOAD);
9
+ class BeforeEvent extends Event {
10
+ from;
11
+ to;
12
+ direction;
13
+ navigationType;
14
+ sourceElement;
15
+ info;
16
+ newDocument;
17
+ constructor(type, eventInitDict, from, to, direction, navigationType, sourceElement, info, newDocument) {
18
+ super(type, eventInitDict);
19
+ this.from = from;
20
+ this.to = to;
21
+ this.direction = direction;
22
+ this.navigationType = navigationType;
23
+ this.sourceElement = sourceElement;
24
+ this.info = info;
25
+ this.newDocument = newDocument;
26
+ Object.defineProperties(this, {
27
+ from: { enumerable: true },
28
+ to: { enumerable: true, writable: true },
29
+ direction: { enumerable: true, writable: true },
30
+ navigationType: { enumerable: true },
31
+ sourceElement: { enumerable: true },
32
+ info: { enumerable: true },
33
+ newDocument: { enumerable: true, writable: true }
34
+ });
35
+ }
36
+ }
37
+ const isTransitionBeforePreparationEvent = (value) => value.type === TRANSITION_BEFORE_PREPARATION;
38
+ class TransitionBeforePreparationEvent extends BeforeEvent {
39
+ formData;
40
+ loader;
41
+ constructor(from, to, direction, navigationType, sourceElement, info, newDocument, formData, loader) {
42
+ super(
43
+ TRANSITION_BEFORE_PREPARATION,
44
+ { cancelable: true },
45
+ from,
46
+ to,
47
+ direction,
48
+ navigationType,
49
+ sourceElement,
50
+ info,
51
+ newDocument
52
+ );
53
+ this.formData = formData;
54
+ this.loader = loader.bind(this, this);
55
+ Object.defineProperties(this, {
56
+ formData: { enumerable: true },
57
+ loader: { enumerable: true, writable: true }
58
+ });
59
+ }
60
+ }
61
+ const isTransitionBeforeSwapEvent = (value) => value.type === TRANSITION_BEFORE_SWAP;
62
+ class TransitionBeforeSwapEvent extends BeforeEvent {
63
+ direction;
64
+ viewTransition;
65
+ swap;
66
+ constructor(afterPreparation, viewTransition, swap) {
67
+ super(
68
+ TRANSITION_BEFORE_SWAP,
69
+ void 0,
70
+ afterPreparation.from,
71
+ afterPreparation.to,
72
+ afterPreparation.direction,
73
+ afterPreparation.navigationType,
74
+ afterPreparation.sourceElement,
75
+ afterPreparation.info,
76
+ afterPreparation.newDocument
77
+ );
78
+ this.direction = afterPreparation.direction;
79
+ this.viewTransition = viewTransition;
80
+ this.swap = swap.bind(this, this);
81
+ Object.defineProperties(this, {
82
+ direction: { enumerable: true },
83
+ viewTransition: { enumerable: true },
84
+ swap: { enumerable: true, writable: true }
85
+ });
86
+ }
87
+ }
88
+ async function doPreparation(from, to, direction, navigationType, sourceElement, info, formData, defaultLoader) {
89
+ const event = new TransitionBeforePreparationEvent(
90
+ from,
91
+ to,
92
+ direction,
93
+ navigationType,
94
+ sourceElement,
95
+ info,
96
+ window.document,
97
+ formData,
98
+ defaultLoader
99
+ );
100
+ if (document.dispatchEvent(event)) {
101
+ await event.loader();
102
+ if (!event.defaultPrevented) {
103
+ triggerEvent(TRANSITION_AFTER_PREPARATION);
104
+ if (event.navigationType !== "traverse") {
105
+ updateScrollPosition({ scrollX, scrollY });
106
+ }
107
+ }
108
+ }
109
+ return event;
110
+ }
111
+ async function doSwap(afterPreparation, viewTransition, defaultSwap) {
112
+ const event = new TransitionBeforeSwapEvent(afterPreparation, viewTransition, defaultSwap);
113
+ document.dispatchEvent(event);
114
+ event.swap();
115
+ return event;
116
+ }
117
+ export {
118
+ TRANSITION_AFTER_PREPARATION,
119
+ TRANSITION_AFTER_SWAP,
120
+ TRANSITION_BEFORE_PREPARATION,
121
+ TRANSITION_BEFORE_SWAP,
122
+ TRANSITION_PAGE_LOAD,
123
+ TransitionBeforePreparationEvent,
124
+ TransitionBeforeSwapEvent,
125
+ doPreparation,
126
+ doSwap,
127
+ isTransitionBeforePreparationEvent,
128
+ isTransitionBeforeSwapEvent,
129
+ onPageLoad,
130
+ triggerEvent
131
+ };
@@ -1,4 +1,5 @@
1
1
  import type { TransitionDirectionalAnimations } from '../@types/astro.js';
2
+ export { createAnimationScope } from '../runtime/server/transition.js';
2
3
  export declare function slide({ duration, }?: {
3
4
  duration?: string | number;
4
5
  }): TransitionDirectionalAnimations;
@@ -1,3 +1,4 @@
1
+ import { createAnimationScope } from "../runtime/server/transition.js";
1
2
  const EASE_IN_OUT_QUART = "cubic-bezier(0.76, 0, 0.24, 1)";
2
3
  function slide({
3
4
  duration
@@ -63,6 +64,7 @@ function fade({
63
64
  };
64
65
  }
65
66
  export {
67
+ createAnimationScope,
66
68
  fade,
67
69
  slide
68
70
  };
@@ -1,9 +1,8 @@
1
- export type Fallback = 'none' | 'animate' | 'swap';
2
- export type Direction = 'forward' | 'back';
3
- export type Options = {
4
- history?: 'auto' | 'push' | 'replace';
5
- formData?: FormData;
6
- };
1
+ import type { Options } from './types.js';
2
+ export declare const updateScrollPosition: (positions: {
3
+ scrollX: number;
4
+ scrollY: number;
5
+ }) => void;
7
6
  export declare const supportsViewTransitions: boolean;
8
7
  export declare const transitionEnabledOnThisPage: () => boolean;
9
- export declare function navigate(href: string, options?: Options): void;
8
+ export declare function navigate(href: string, options?: Options): Promise<void>;
@@ -1,8 +1,23 @@
1
- const updateScrollPosition = (positions) => history.state && history.replaceState({ ...history.state, ...positions }, "");
1
+ import {
2
+ TRANSITION_AFTER_SWAP,
3
+ TransitionBeforeSwapEvent,
4
+ doPreparation,
5
+ doSwap
6
+ } from "./events.js";
7
+ const updateScrollPosition = (positions) => {
8
+ if (history.state) {
9
+ history.scrollRestoration = "manual";
10
+ history.replaceState({ ...history.state, ...positions }, "");
11
+ }
12
+ };
2
13
  const inBrowser = import.meta.env.SSR === false;
3
14
  const supportsViewTransitions = inBrowser && !!document.startViewTransition;
4
15
  const transitionEnabledOnThisPage = () => inBrowser && !!document.querySelector('[name="astro-view-transitions-enabled"]');
5
- const samePage = (otherLocation) => location.pathname === otherLocation.pathname && location.search === otherLocation.search;
16
+ const samePage = (thisLocation, otherLocation) => thisLocation.origin === otherLocation.origin && thisLocation.pathname === otherLocation.pathname && thisLocation.search === otherLocation.search;
17
+ let originalLocation;
18
+ let viewTransition;
19
+ let skipTransition = false;
20
+ let viewTransitionFinished;
6
21
  const triggerEvent = (name) => document.dispatchEvent(new Event(name));
7
22
  const onPageLoad = () => triggerEvent("astro:page-load");
8
23
  const announce = () => {
@@ -23,6 +38,8 @@ const announce = () => {
23
38
  );
24
39
  };
25
40
  const PERSIST_ATTR = "data-astro-transition-persist";
41
+ const DIRECTION_ATTR = "data-astro-transition";
42
+ const OLD_NEW_ATTR = "data-astro-transition-fallback";
26
43
  const VITE_ID = "data-vite-dev-id";
27
44
  let parser;
28
45
  let currentHistoryIndex = 0;
@@ -31,7 +48,8 @@ if (inBrowser) {
31
48
  currentHistoryIndex = history.state.index;
32
49
  scrollTo({ left: history.state.scrollX, top: history.state.scrollY });
33
50
  } else if (transitionEnabledOnThisPage()) {
34
- history.replaceState({ index: currentHistoryIndex, scrollX, scrollY, intraPage: false }, "");
51
+ history.replaceState({ index: currentHistoryIndex, scrollX, scrollY }, "");
52
+ history.scrollRestoration = "manual";
35
53
  }
36
54
  }
37
55
  const throttle = (cb, delay) => {
@@ -98,41 +116,50 @@ function runScripts() {
98
116
  }
99
117
  return wait;
100
118
  }
101
- function isInfinite(animation) {
102
- const effect = animation.effect;
103
- if (!effect || !(effect instanceof KeyframeEffect) || !effect.target)
104
- return false;
105
- const style = window.getComputedStyle(effect.target, effect.pseudoElement);
106
- return style.animationIterationCount === "infinite";
107
- }
108
- const moveToLocation = (toLocation, replace, intraPage) => {
109
- const fresh = !samePage(toLocation);
119
+ const moveToLocation = (to, from, options, historyState) => {
120
+ const intraPage = samePage(from, to);
110
121
  let scrolledToTop = false;
111
- if (toLocation.href !== location.href) {
112
- if (replace) {
113
- history.replaceState({ ...history.state }, "", toLocation.href);
122
+ if (to.href !== location.href && !historyState) {
123
+ if (options.history === "replace") {
124
+ const current = history.state;
125
+ history.replaceState(
126
+ {
127
+ ...options.state,
128
+ index: current.index,
129
+ scrollX: current.scrollX,
130
+ scrollY: current.scrollY
131
+ },
132
+ "",
133
+ to.href
134
+ );
114
135
  } else {
115
- history.replaceState({ ...history.state, intraPage }, "");
116
136
  history.pushState(
117
- { index: ++currentHistoryIndex, scrollX: 0, scrollY: 0 },
137
+ { ...options.state, index: ++currentHistoryIndex, scrollX: 0, scrollY: 0 },
118
138
  "",
119
- toLocation.href
139
+ to.href
120
140
  );
121
141
  }
122
- if (fresh) {
123
- scrollTo({ left: 0, top: 0, behavior: "instant" });
124
- scrolledToTop = true;
125
- }
126
142
  }
127
- if (toLocation.hash) {
128
- location.href = toLocation.href;
143
+ originalLocation = to;
144
+ if (!intraPage) {
145
+ scrollTo({ left: 0, top: 0, behavior: "instant" });
146
+ scrolledToTop = true;
147
+ }
148
+ if (historyState) {
149
+ scrollTo(historyState.scrollX, historyState.scrollY);
129
150
  } else {
130
- if (!scrolledToTop) {
131
- scrollTo({ left: 0, top: 0, behavior: "instant" });
151
+ if (to.hash) {
152
+ history.scrollRestoration = "auto";
153
+ location.href = to.href;
154
+ } else {
155
+ if (!scrolledToTop) {
156
+ scrollTo({ left: 0, top: 0, behavior: "instant" });
157
+ }
132
158
  }
159
+ history.scrollRestoration = "manual";
133
160
  }
134
161
  };
135
- function stylePreloadLinks(newDocument) {
162
+ function preloadStyleLinks(newDocument) {
136
163
  const links = [];
137
164
  for (const el of newDocument.querySelectorAll("head link[rel=stylesheet]")) {
138
165
  if (!document.querySelector(
@@ -154,16 +181,16 @@ function stylePreloadLinks(newDocument) {
154
181
  }
155
182
  return links;
156
183
  }
157
- async function updateDOM(newDocument, toLocation, options, popState, fallback) {
158
- const persistedHeadElement = (el) => {
184
+ async function updateDOM(preparationEvent, options, historyState, fallback) {
185
+ const persistedHeadElement = (el, newDoc) => {
159
186
  const id = el.getAttribute(PERSIST_ATTR);
160
- const newEl = id && newDocument.head.querySelector(`[${PERSIST_ATTR}="${id}"]`);
187
+ const newEl = id && newDoc.head.querySelector(`[${PERSIST_ATTR}="${id}"]`);
161
188
  if (newEl) {
162
189
  return newEl;
163
190
  }
164
191
  if (el.matches("link[rel=stylesheet]")) {
165
192
  const href = el.getAttribute("href");
166
- return newDocument.head.querySelector(`link[rel=stylesheet][href="${href}"]`);
193
+ return newDoc.head.querySelector(`link[rel=stylesheet][href="${href}"]`);
167
194
  }
168
195
  return null;
169
196
  };
@@ -189,16 +216,16 @@ async function updateDOM(newDocument, toLocation, options, popState, fallback) {
189
216
  }
190
217
  }
191
218
  };
192
- const swap = () => {
219
+ const defaultSwap = (beforeSwapEvent) => {
193
220
  const html = document.documentElement;
194
- const astro = [...html.attributes].filter(
221
+ const astroAttributes = [...html.attributes].filter(
195
222
  ({ name }) => (html.removeAttribute(name), name.startsWith("data-astro-"))
196
223
  );
197
- [...newDocument.documentElement.attributes, ...astro].forEach(
224
+ [...beforeSwapEvent.newDocument.documentElement.attributes, ...astroAttributes].forEach(
198
225
  ({ name, value }) => html.setAttribute(name, value)
199
226
  );
200
227
  for (const s1 of document.scripts) {
201
- for (const s2 of newDocument.scripts) {
228
+ for (const s2 of beforeSwapEvent.newDocument.scripts) {
202
229
  if (
203
230
  // Inline
204
231
  !s1.src && s1.textContent === s2.textContent || // External
@@ -210,17 +237,17 @@ async function updateDOM(newDocument, toLocation, options, popState, fallback) {
210
237
  }
211
238
  }
212
239
  for (const el of Array.from(document.head.children)) {
213
- const newEl = persistedHeadElement(el);
240
+ const newEl = persistedHeadElement(el, beforeSwapEvent.newDocument);
214
241
  if (newEl) {
215
242
  newEl.remove();
216
243
  } else {
217
244
  el.remove();
218
245
  }
219
246
  }
220
- document.head.append(...newDocument.head.children);
247
+ document.head.append(...beforeSwapEvent.newDocument.head.children);
221
248
  const oldBody = document.body;
222
249
  const savedFocus = saveFocus();
223
- document.body.replaceWith(newDocument.body);
250
+ document.body.replaceWith(beforeSwapEvent.newDocument.body);
224
251
  for (const el of oldBody.querySelectorAll(`[${PERSIST_ATTR}]`)) {
225
252
  const id = el.getAttribute(PERSIST_ATTR);
226
253
  const newEl = document.querySelector(`[${PERSIST_ATTR}="${id}"]`);
@@ -229,73 +256,131 @@ async function updateDOM(newDocument, toLocation, options, popState, fallback) {
229
256
  }
230
257
  }
231
258
  restoreFocus(savedFocus);
232
- if (popState) {
233
- scrollTo(popState.scrollX, popState.scrollY);
234
- } else {
235
- moveToLocation(toLocation, options.history === "replace", false);
236
- }
237
- triggerEvent("astro:after-swap");
238
259
  };
239
- const links = stylePreloadLinks(newDocument);
240
- links.length && await Promise.all(links);
241
- if (fallback === "animate") {
260
+ async function animate(phase) {
261
+ function isInfinite(animation) {
262
+ const effect = animation.effect;
263
+ if (!effect || !(effect instanceof KeyframeEffect) || !effect.target)
264
+ return false;
265
+ const style = window.getComputedStyle(effect.target, effect.pseudoElement);
266
+ return style.animationIterationCount === "infinite";
267
+ }
242
268
  const currentAnimations = document.getAnimations();
243
- document.documentElement.dataset.astroTransitionFallback = "old";
244
- const newAnimations = document.getAnimations().filter((a) => !currentAnimations.includes(a) && !isInfinite(a));
245
- const finished = Promise.all(newAnimations.map((a) => a.finished));
246
- await finished;
247
- swap();
248
- document.documentElement.dataset.astroTransitionFallback = "new";
269
+ document.documentElement.setAttribute(OLD_NEW_ATTR, phase);
270
+ const nextAnimations = document.getAnimations();
271
+ const newAnimations = nextAnimations.filter(
272
+ (a) => !currentAnimations.includes(a) && !isInfinite(a)
273
+ );
274
+ return Promise.all(newAnimations.map((a) => a.finished));
275
+ }
276
+ if (!skipTransition) {
277
+ document.documentElement.setAttribute(DIRECTION_ATTR, preparationEvent.direction);
278
+ if (fallback === "animate") {
279
+ await animate("old");
280
+ }
249
281
  } else {
250
- swap();
282
+ throw new DOMException("Transition was skipped");
251
283
  }
252
- }
253
- async function transition(direction, toLocation, options, popState) {
254
- let finished;
255
- const href = toLocation.href;
256
- const init = {};
257
- if (options.formData) {
258
- init.method = "POST";
259
- init.body = options.formData;
284
+ const swapEvent = await doSwap(preparationEvent, viewTransition, defaultSwap);
285
+ moveToLocation(swapEvent.to, swapEvent.from, options, historyState);
286
+ triggerEvent(TRANSITION_AFTER_SWAP);
287
+ if (fallback === "animate" && !skipTransition) {
288
+ animate("new").then(() => viewTransitionFinished());
260
289
  }
261
- const response = await fetchHTML(href, init);
262
- if (response === null) {
263
- location.href = href;
290
+ }
291
+ async function transition(direction, from, to, options, historyState) {
292
+ const navigationType = historyState ? "traverse" : options.history === "replace" ? "replace" : "push";
293
+ if (samePage(from, to) && !options.formData) {
294
+ if (navigationType !== "traverse") {
295
+ updateScrollPosition({ scrollX, scrollY });
296
+ }
297
+ moveToLocation(to, from, options, historyState);
264
298
  return;
265
299
  }
266
- if (response.redirected) {
267
- toLocation = new URL(response.redirected);
268
- }
269
- parser ??= new DOMParser();
270
- const newDocument = parser.parseFromString(response.html, response.mediaType);
271
- newDocument.querySelectorAll("noscript").forEach((el) => el.remove());
272
- if (!newDocument.querySelector('[name="astro-view-transitions-enabled"]') && !options.formData) {
273
- location.href = href;
300
+ const prepEvent = await doPreparation(
301
+ from,
302
+ to,
303
+ direction,
304
+ navigationType,
305
+ options.sourceElement,
306
+ options.info,
307
+ options.formData,
308
+ defaultLoader
309
+ );
310
+ if (prepEvent.defaultPrevented) {
311
+ location.href = to.href;
274
312
  return;
275
313
  }
276
- if (import.meta.env.DEV)
277
- await prepareForClientOnlyComponents(newDocument, toLocation);
278
- if (!popState) {
279
- history.replaceState({ ...history.state, scrollX, scrollY }, "");
314
+ function pageMustReload(preparationEvent) {
315
+ return preparationEvent.to.hash === "" || !samePage(preparationEvent.from, preparationEvent.to) || preparationEvent.sourceElement instanceof HTMLFormElement;
316
+ }
317
+ async function defaultLoader(preparationEvent) {
318
+ if (pageMustReload(preparationEvent)) {
319
+ const href = preparationEvent.to.href;
320
+ const init = {};
321
+ if (preparationEvent.formData) {
322
+ init.method = "POST";
323
+ init.body = preparationEvent.formData;
324
+ }
325
+ const response = await fetchHTML(href, init);
326
+ if (response === null) {
327
+ preparationEvent.preventDefault();
328
+ return;
329
+ }
330
+ if (response.redirected) {
331
+ preparationEvent.to = new URL(response.redirected);
332
+ }
333
+ parser ??= new DOMParser();
334
+ preparationEvent.newDocument = parser.parseFromString(response.html, response.mediaType);
335
+ preparationEvent.newDocument.querySelectorAll("noscript").forEach((el) => el.remove());
336
+ if (!preparationEvent.newDocument.querySelector('[name="astro-view-transitions-enabled"]') && !preparationEvent.formData) {
337
+ preparationEvent.preventDefault();
338
+ return;
339
+ }
340
+ const links = preloadStyleLinks(preparationEvent.newDocument);
341
+ links.length && await Promise.all(links);
342
+ if (import.meta.env.DEV)
343
+ await prepareForClientOnlyComponents(preparationEvent.newDocument, preparationEvent.to);
344
+ } else {
345
+ preparationEvent.newDocument = document;
346
+ return;
347
+ }
280
348
  }
281
- document.documentElement.dataset.astroTransition = direction;
349
+ skipTransition = false;
282
350
  if (supportsViewTransitions) {
283
- finished = document.startViewTransition(
284
- () => updateDOM(newDocument, toLocation, options, popState)
285
- ).finished;
351
+ viewTransition = document.startViewTransition(
352
+ async () => await updateDOM(prepEvent, options, historyState)
353
+ );
286
354
  } else {
287
- finished = updateDOM(newDocument, toLocation, options, popState, getFallback());
355
+ const updateDone = (async () => {
356
+ await new Promise((r) => setTimeout(r));
357
+ await updateDOM(prepEvent, options, historyState, getFallback());
358
+ })();
359
+ viewTransition = {
360
+ updateCallbackDone: updateDone,
361
+ // this is about correct
362
+ ready: updateDone,
363
+ // good enough
364
+ finished: new Promise((r) => viewTransitionFinished = r),
365
+ // see end of updateDOM
366
+ skipTransition: () => {
367
+ skipTransition = true;
368
+ }
369
+ };
288
370
  }
289
- try {
290
- await finished;
291
- } finally {
371
+ viewTransition.ready.then(async () => {
292
372
  await runScripts();
293
373
  onPageLoad();
294
374
  announce();
295
- }
375
+ });
376
+ viewTransition.finished.then(() => {
377
+ document.documentElement.removeAttribute(DIRECTION_ATTR);
378
+ document.documentElement.removeAttribute(OLD_NEW_ATTR);
379
+ });
380
+ await viewTransition.ready;
296
381
  }
297
382
  let navigateOnServerWarned = false;
298
- function navigate(href, options) {
383
+ async function navigate(href, options) {
299
384
  if (inBrowser === false) {
300
385
  if (!navigateOnServerWarned) {
301
386
  const warning = new Error(
@@ -311,45 +396,28 @@ function navigate(href, options) {
311
396
  location.href = href;
312
397
  return;
313
398
  }
314
- const toLocation = new URL(href, location.href);
315
- if (location.origin === toLocation.origin && samePage(toLocation) && !options?.formData) {
316
- moveToLocation(toLocation, options?.history === "replace", true);
317
- } else {
318
- transition("forward", toLocation, options ?? {});
319
- }
399
+ await transition("forward", originalLocation, new URL(href, location.href), options ?? {});
320
400
  }
321
401
  function onPopState(ev) {
322
402
  if (!transitionEnabledOnThisPage() && ev.state) {
323
- if (history.scrollRestoration) {
324
- history.scrollRestoration = "manual";
325
- }
326
403
  location.reload();
327
404
  return;
328
405
  }
329
406
  if (ev.state === null) {
330
- if (history.scrollRestoration) {
331
- history.scrollRestoration = "auto";
332
- }
333
407
  return;
334
408
  }
335
- if (history.scrollRestoration) {
336
- history.scrollRestoration = "manual";
337
- }
338
409
  const state = history.state;
339
- if (state.intraPage) {
340
- scrollTo(state.scrollX, state.scrollY);
341
- } else {
342
- const nextIndex = state.index;
343
- const direction = nextIndex > currentHistoryIndex ? "forward" : "back";
344
- currentHistoryIndex = nextIndex;
345
- transition(direction, new URL(location.href), {}, state);
346
- }
410
+ const nextIndex = state.index;
411
+ const direction = nextIndex > currentHistoryIndex ? "forward" : "back";
412
+ currentHistoryIndex = nextIndex;
413
+ transition(direction, originalLocation, new URL(location.href), {}, state);
347
414
  }
348
415
  const onScroll = () => {
349
416
  updateScrollPosition({ scrollX, scrollY });
350
417
  };
351
418
  if (inBrowser) {
352
419
  if (supportsViewTransitions || getFallback() !== "none") {
420
+ originalLocation = new URL(location.href);
353
421
  addEventListener("popstate", onPopState);
354
422
  addEventListener("load", onPageLoad);
355
423
  if ("onscrollend" in window)
@@ -404,5 +472,6 @@ async function prepareForClientOnlyComponents(newDocument, toLocation) {
404
472
  export {
405
473
  navigate,
406
474
  supportsViewTransitions,
407
- transitionEnabledOnThisPage
475
+ transitionEnabledOnThisPage,
476
+ updateScrollPosition
408
477
  };
@@ -0,0 +1,10 @@
1
+ export type Fallback = 'none' | 'animate' | 'swap';
2
+ export type Direction = 'forward' | 'back';
3
+ export type NavigationTypeString = 'push' | 'replace' | 'traverse';
4
+ export type Options = {
5
+ history?: 'auto' | 'push' | 'replace';
6
+ info?: any;
7
+ state?: any;
8
+ formData?: FormData;
9
+ sourceElement?: Element;
10
+ };
File without changes
@@ -23,7 +23,14 @@ function astroTransitions({ settings }) {
23
23
  }
24
24
  if (id === resolvedVirtualClientModuleId) {
25
25
  return `
26
- export * from "astro/transitions/router";
26
+ export { navigate, supportsViewTransitions, transitionEnabledOnThisPage } from "astro/transitions/router";
27
+ export * from "astro/transitions/types";
28
+ export {
29
+ TRANSITION_BEFORE_PREPARATION, isTransitionBeforePreparationEvent, TransitionBeforePreparationEvent,
30
+ TRANSITION_AFTER_PREPARATION,
31
+ TRANSITION_BEFORE_SWAP, isTransitionBeforeSwapEvent, TransitionBeforeSwapEvent,
32
+ TRANSITION_AFTER_SWAP, TRANSITION_PAGE_LOAD
33
+ } from "astro/transitions/events";
27
34
  `;
28
35
  }
29
36
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "astro",
3
- "version": "3.5.7",
3
+ "version": "3.6.1",
4
4
  "description": "Astro is a modern site builder with web best practices, performance, and DX front-of-mind.",
5
5
  "type": "module",
6
6
  "author": "withastro",
@@ -78,7 +78,9 @@
78
78
  "default": "./dist/core/middleware/namespace.js"
79
79
  },
80
80
  "./transitions": "./dist/transitions/index.js",
81
+ "./transitions/events": "./dist/transitions/events.js",
81
82
  "./transitions/router": "./dist/transitions/router.js",
83
+ "./transitions/types": "./dist/transitions/types.js",
82
84
  "./prefetch": "./dist/prefetch/index.js",
83
85
  "./i18n": "./dist/i18n/index.js"
84
86
  },
@@ -165,8 +167,8 @@
165
167
  "yargs-parser": "^21.1.1",
166
168
  "zod": "^3.22.4",
167
169
  "@astrojs/internal-helpers": "0.2.1",
168
- "@astrojs/markdown-remark": "3.5.0",
169
- "@astrojs/telemetry": "3.0.4"
170
+ "@astrojs/telemetry": "3.0.4",
171
+ "@astrojs/markdown-remark": "3.5.0"
170
172
  },
171
173
  "optionalDependencies": {
172
174
  "sharp": "^0.32.5"