[ci] format

This commit is contained in:
matthewp 2023-07-19 19:21:13 +00:00 committed by astrobot-houston
parent 6a12fcecb0
commit 7a6ca236e8
12 changed files with 198 additions and 148 deletions

View file

@ -7,8 +7,9 @@ export interface Props {
const { fallback = 'animate' } = Astro.props as Props; const { fallback = 'animate' } = Astro.props as Props;
--- ---
<meta name="astro-view-transitions-enabled" content="true">
<meta name="astro-view-transitions-fallback" content={fallback}> <meta name="astro-view-transitions-enabled" content="true" />
<meta name="astro-view-transitions-fallback" content={fallback} />
<script> <script>
type Fallback = 'none' | 'animate' | 'swap'; type Fallback = 'none' | 'animate' | 'swap';
type Direction = 'forward' | 'back'; type Direction = 'forward' | 'back';
@ -22,10 +23,11 @@ const { fallback = 'animate' } = Astro.props as Props;
} }
const supportsViewTransitions = !!document.startViewTransition; const supportsViewTransitions = !!document.startViewTransition;
const transitionEnabledOnThisPage = () => !!document.querySelector('[name="astro-view-transitions-enabled"]'); const transitionEnabledOnThisPage = () =>
!!document.querySelector('[name="astro-view-transitions-enabled"]');
async function getHTML(href: string) { async function getHTML(href: string) {
const res = await fetch(href) const res = await fetch(href);
const html = await res.text(); const html = await res.text();
return { ok: res.ok, html }; return { ok: res.ok, html };
} }
@ -47,7 +49,7 @@ const { fallback = 'animate' } = Astro.props as Props;
if (fallback === 'animate') { if (fallback === 'animate') {
let isAnimating = false; let isAnimating = false;
addEventListener('animationstart', () => isAnimating = true, { once: true }); addEventListener('animationstart', () => (isAnimating = true), { once: true });
// Trigger the animations // Trigger the animations
document.documentElement.dataset.astroTransitionFallback = 'old'; document.documentElement.dataset.astroTransitionFallback = 'old';
@ -105,7 +107,8 @@ const { fallback = 'animate' } = Astro.props as Props;
// This check verifies that the click is happening on an anchor // This check verifies that the click is happening on an anchor
// that is going to another page within the same origin. Basically it determines // that is going to another page within the same origin. Basically it determines
// same-origin navigation, but omits special key combos for new tabs, etc. // same-origin navigation, but omits special key combos for new tabs, etc.
if (link && if (
link &&
link instanceof HTMLAnchorElement && link instanceof HTMLAnchorElement &&
link.href && link.href &&
(!link.target || link.target === '_self') && (!link.target || link.target === '_self') &&
@ -126,21 +129,29 @@ const { fallback = 'animate' } = Astro.props as Props;
}); });
window.addEventListener('popstate', () => { window.addEventListener('popstate', () => {
if (!transitionEnabledOnThisPage()) return; if (!transitionEnabledOnThisPage()) return;
const nextIndex = history.state?.index ?? (currentHistoryIndex + 1); const nextIndex = history.state?.index ?? currentHistoryIndex + 1;
const direction: Direction = nextIndex > currentHistoryIndex ? 'forward' : 'back'; const direction: Direction = nextIndex > currentHistoryIndex ? 'forward' : 'back';
navigate(direction, location.href); navigate(direction, location.href);
currentHistoryIndex = nextIndex; currentHistoryIndex = nextIndex;
}); });
['mouseenter', 'touchstart', 'focus'].forEach(evName => { ['mouseenter', 'touchstart', 'focus'].forEach((evName) => {
document.addEventListener(evName, ev => { document.addEventListener(
evName,
(ev) => {
if (ev.target instanceof HTMLAnchorElement) { if (ev.target instanceof HTMLAnchorElement) {
let el = ev.target; let el = ev.target;
if(el.origin === location.origin && el.pathname !== location.pathname && transitionEnabledOnThisPage()) { if (
el.origin === location.origin &&
el.pathname !== location.pathname &&
transitionEnabledOnThisPage()
) {
maybePrefetch(el.pathname); maybePrefetch(el.pathname);
} }
} }
}, { passive: true, capture: true }); },
{ passive: true, capture: true }
);
}); });
} }
</script> </script>

View file

@ -8,25 +8,37 @@
} }
@keyframes astroFadeIn { @keyframes astroFadeIn {
from { opacity: 0; } from {
opacity: 0;
}
} }
@keyframes astroFadeOut { @keyframes astroFadeOut {
to { opacity: 0; } to {
opacity: 0;
}
} }
@keyframes astroSlideFromRight { @keyframes astroSlideFromRight {
from { transform: translateX(100%); } from {
transform: translateX(100%);
}
} }
@keyframes astroSlideFromLeft { @keyframes astroSlideFromLeft {
from { transform: translateX(-100%); } from {
transform: translateX(-100%);
}
} }
@keyframes astroSlideToRight { @keyframes astroSlideToRight {
to { transform: translateX(100%); } to {
transform: translateX(100%);
}
} }
@keyframes astroSlideToLeft { @keyframes astroSlideToLeft {
to { transform: translateX(-100%); } to {
transform: translateX(-100%);
}
} }

View file

@ -16,7 +16,7 @@ test.afterAll(async () => {
test.describe('View Transitions', () => { test.describe('View Transitions', () => {
test('Moving from page 1 to page 2', async ({ page, astro }) => { test('Moving from page 1 to page 2', async ({ page, astro }) => {
const loads = []; const loads = [];
page.addListener('load', p => { page.addListener('load', (p) => {
loads.push(p.title()); loads.push(p.title());
}); });
@ -35,7 +35,7 @@ test.describe('View Transitions', () => {
test('Back button is captured', async ({ page, astro }) => { test('Back button is captured', async ({ page, astro }) => {
const loads = []; const loads = [];
page.addListener('load', p => { page.addListener('load', (p) => {
loads.push(p.title()); loads.push(p.title());
}); });
@ -59,7 +59,7 @@ test.describe('View Transitions', () => {
test('Clicking on a link with nested content', async ({ page, astro }) => { test('Clicking on a link with nested content', async ({ page, astro }) => {
const loads = []; const loads = [];
page.addListener('load', p => { page.addListener('load', (p) => {
loads.push(p.title()); loads.push(p.title());
}); });
@ -76,9 +76,12 @@ test.describe('View Transitions', () => {
expect(loads.length, 'There should only be 1 page load').toEqual(1); expect(loads.length, 'There should only be 1 page load').toEqual(1);
}); });
test('Moving from a page without ViewTransitions triggers a full page navigation', async ({ page, astro }) => { test('Moving from a page without ViewTransitions triggers a full page navigation', async ({
page,
astro,
}) => {
const loads = []; const loads = [];
page.addListener('load', p => { page.addListener('load', (p) => {
loads.push(p.title()); loads.push(p.title());
}); });
@ -96,6 +99,9 @@ test.describe('View Transitions', () => {
p = page.locator('#two'); p = page.locator('#two');
await expect(p, 'should have content').toHaveText('Page 2'); await expect(p, 'should have content').toHaveText('Page 2');
expect(loads.length, 'There should be 2 page loads. The original, then going from 3 to 2').toEqual(2); expect(
loads.length,
'There should be 2 page loads. The original, then going from 3 to 2'
).toEqual(2);
}); });
}); });

View file

@ -233,7 +233,10 @@ export const AstroConfigSchema = z.object({
experimental: z experimental: z
.object({ .object({
assets: z.boolean().optional().default(ASTRO_CONFIG_DEFAULTS.experimental.assets), assets: z.boolean().optional().default(ASTRO_CONFIG_DEFAULTS.experimental.assets),
viewTransitions: z.boolean().optional().default(ASTRO_CONFIG_DEFAULTS.experimental.viewTransitions), viewTransitions: z
.boolean()
.optional()
.default(ASTRO_CONFIG_DEFAULTS.experimental.viewTransitions),
}) })
.passthrough() .passthrough()
.refine( .refine(

View file

@ -11,6 +11,7 @@ import {
astroContentImportPlugin, astroContentImportPlugin,
astroContentVirtualModPlugin, astroContentVirtualModPlugin,
} from '../content/index.js'; } from '../content/index.js';
import astroTransitions from '../transitions/vite-plugin-transitions.js';
import astroPostprocessVitePlugin from '../vite-plugin-astro-postprocess/index.js'; import astroPostprocessVitePlugin from '../vite-plugin-astro-postprocess/index.js';
import { vitePluginAstroServer } from '../vite-plugin-astro-server/index.js'; import { vitePluginAstroServer } from '../vite-plugin-astro-server/index.js';
import astroVitePlugin from '../vite-plugin-astro/index.js'; import astroVitePlugin from '../vite-plugin-astro/index.js';
@ -27,7 +28,6 @@ import astroScannerPlugin from '../vite-plugin-scanner/index.js';
import astroScriptsPlugin from '../vite-plugin-scripts/index.js'; import astroScriptsPlugin from '../vite-plugin-scripts/index.js';
import astroScriptsPageSSRPlugin from '../vite-plugin-scripts/page-ssr.js'; import astroScriptsPageSSRPlugin from '../vite-plugin-scripts/page-ssr.js';
import { vitePluginSSRManifest } from '../vite-plugin-ssr-manifest/index.js'; import { vitePluginSSRManifest } from '../vite-plugin-ssr-manifest/index.js';
import astroTransitions from '../transitions/vite-plugin-transitions.js';
import { joinPaths } from './path.js'; import { joinPaths } from './path.js';
interface CreateViteOptions { interface CreateViteOptions {

View file

@ -7,7 +7,11 @@ function validateArgs(args: unknown[]): args is Parameters<AstroComponentFactory
if (!args[0] || typeof args[0] !== 'object') return false; if (!args[0] || typeof args[0] !== 'object') return false;
return true; return true;
} }
function baseCreateComponent(cb: AstroComponentFactory, moduleId?: string, propagation?: PropagationHint): AstroComponentFactory { function baseCreateComponent(
cb: AstroComponentFactory,
moduleId?: string,
propagation?: PropagationHint
): AstroComponentFactory {
const name = moduleId?.split('/').pop()?.replace('.astro', '') ?? ''; const name = moduleId?.split('/').pop()?.replace('.astro', '') ?? '';
const fn = (...args: Parameters<AstroComponentFactory>) => { const fn = (...args: Parameters<AstroComponentFactory>) => {
if (!validateArgs(args)) { if (!validateArgs(args)) {
@ -40,7 +44,7 @@ function createComponentWithOptions(opts: CreateComponentOptions) {
export function createComponent( export function createComponent(
arg1: AstroComponentFactory | CreateComponentOptions, arg1: AstroComponentFactory | CreateComponentOptions,
moduleId?: string, moduleId?: string,
propagation?: PropagationHint, propagation?: PropagationHint
) { ) {
if (typeof arg1 === 'function') { if (typeof arg1 === 'function') {
return baseCreateComponent(arg1, moduleId, propagation); return baseCreateComponent(arg1, moduleId, propagation);

View file

@ -33,13 +33,13 @@ export {
stringifyChunk, stringifyChunk,
voidElementNames, voidElementNames,
} from './render/index.js'; } from './render/index.js';
export { renderTransition } from './transition.js';
export type { export type {
AstroComponentFactory, AstroComponentFactory,
AstroComponentInstance, AstroComponentInstance,
ComponentSlots, ComponentSlots,
RenderInstruction, RenderInstruction,
} from './render/index.js'; } from './render/index.js';
export { renderTransition } from './transition.js';
import { markHTMLString } from './escape.js'; import { markHTMLString } from './escape.js';
import { addAttribute, Renderer } from './render/index.js'; import { addAttribute, Renderer } from './render/index.js';

View file

@ -1,11 +1,11 @@
import type { import type {
SSRResult, SSRResult,
TransitionAnimation, TransitionAnimation,
TransitionDirectionalAnimations,
TransitionAnimationValue, TransitionAnimationValue,
TransitionDirectionalAnimations,
} from '../../@types/astro'; } from '../../@types/astro';
import { fade, slide } from '../../transitions/index.js';
import { markHTMLString } from './escape.js'; import { markHTMLString } from './escape.js';
import { slide, fade } from '../../transitions/index.js';
const transitionNameMap = new WeakMap<SSRResult, number>(); const transitionNameMap = new WeakMap<SSRResult, number>();
function incrementTransitionNumber(result: SSRResult) { function incrementTransitionNumber(result: SSRResult) {
@ -21,7 +21,12 @@ function createTransitionScope(result: SSRResult, hash: string) {
const num = incrementTransitionNumber(result); const num = incrementTransitionNumber(result);
return `astro-${hash}-${num}`; return `astro-${hash}-${num}`;
} }
export function renderTransition(result: SSRResult, hash: string, animationName: TransitionAnimationValue | undefined, transitionName: string) { export function renderTransition(
result: SSRResult,
hash: string,
animationName: TransitionAnimationValue | undefined,
transitionName: string
) {
let animations: TransitionDirectionalAnimations | null = null; let animations: TransitionDirectionalAnimations | null = null;
switch (animationName) { switch (animationName) {
case 'fade': { case 'fade': {
@ -49,8 +54,10 @@ export function renderTransition(result: SSRResult, hash: string, animationName:
const styles = markHTMLString(`<style>[data-astro-transition-scope="${scope}"] { const styles = markHTMLString(`<style>[data-astro-transition-scope="${scope}"] {
view-transition-name: ${transitionName}; view-transition-name: ${transitionName};
} }
${!animations ? `` : ${
// Regular animations !animations
? ``
: // Regular animations
` `
::view-transition-old(${transitionName}) { ::view-transition-old(${transitionName}) {
${stringifyAnimation(animations.forwards.old)} ${stringifyAnimation(animations.forwards.old)}
@ -79,8 +86,9 @@ export function renderTransition(result: SSRResult, hash: string, animationName:
[data-astro-transition=back][data-astro-transition-fallback=new] [data-astro-transition-scope="${scope}"] { [data-astro-transition=back][data-astro-transition-fallback=new] [data-astro-transition-scope="${scope}"] {
${stringifyAnimation(animations.backwards.new)} ${stringifyAnimation(animations.backwards.new)}
} }
`.trim()} `.trim()
</style>`) }
</style>`);
result._metadata.extraHead.push(styles); result._metadata.extraHead.push(styles);
@ -90,7 +98,7 @@ export function renderTransition(result: SSRResult, hash: string, animationName:
type AnimationBuilder = { type AnimationBuilder = {
toString(): string; toString(): string;
[key: string]: string[] | ((k: string) => string); [key: string]: string[] | ((k: string) => string);
} };
function addAnimationProperty(builder: AnimationBuilder, prop: string, value: string | number) { function addAnimationProperty(builder: AnimationBuilder, prop: string, value: string | number) {
let arr = builder[prop]; let arr = builder[prop];
@ -108,11 +116,11 @@ function animationBuilder(): AnimationBuilder {
for (let k in this) { for (let k in this) {
let value = this[k]; let value = this[k];
if (Array.isArray(value)) { if (Array.isArray(value)) {
out += `\n\t${k}: ${value.join(', ')};` out += `\n\t${k}: ${value.join(', ')};`;
} }
} }
return out; return out;
} },
}; };
} }

View file

@ -1,45 +1,51 @@
import type { TransitionDirectionalAnimations, TransitionAnimationPair } from '../@types/astro'; import type { TransitionDirectionalAnimations } from '../@types/astro';
export function slide({ export function slide({
duration duration,
}: { }: {
duration?: string | number; duration?: string | number;
} = {}): TransitionDirectionalAnimations { } = {}): TransitionDirectionalAnimations {
return { return {
forwards: { forwards: {
old: [{ old: [
{
name: 'astroFadeOut', name: 'astroFadeOut',
duration: duration ?? '90ms', duration: duration ?? '90ms',
easing: 'cubic-bezier(0.4, 0, 1, 1)', easing: 'cubic-bezier(0.4, 0, 1, 1)',
fillMode: 'both' fillMode: 'both',
}, { },
{
name: 'astroSlideToLeft', name: 'astroSlideToLeft',
duration: duration ?? '300ms', duration: duration ?? '300ms',
easing: 'cubic-bezier(0.4, 0, 0.2, 1)', easing: 'cubic-bezier(0.4, 0, 0.2, 1)',
fillMode: 'both' fillMode: 'both',
}], },
new: [{ ],
new: [
{
name: 'astroFadeIn', name: 'astroFadeIn',
duration: duration ?? '210ms', duration: duration ?? '210ms',
easing: 'cubic-bezier(0, 0, 0.2, 1)', easing: 'cubic-bezier(0, 0, 0.2, 1)',
delay: '90ms', delay: '90ms',
fillMode: 'both' fillMode: 'both',
}, { },
{
name: 'astroSlideFromRight', name: 'astroSlideFromRight',
duration: duration ?? '300ms', duration: duration ?? '300ms',
easing: 'cubic-bezier(0.4, 0, 0.2, 1)', easing: 'cubic-bezier(0.4, 0, 0.2, 1)',
fillMode: 'both' fillMode: 'both',
}] },
],
}, },
backwards: { backwards: {
old: [{ name: 'astroFadeOut' }, { name: 'astroSlideToRight' }], old: [{ name: 'astroFadeOut' }, { name: 'astroSlideToRight' }],
new: [{ name: 'astroFadeIn' }, { name: 'astroSlideFromLeft' }] new: [{ name: 'astroFadeIn' }, { name: 'astroSlideFromLeft' }],
} },
}; };
} }
export function fade({ export function fade({
duration duration,
}: { }: {
duration?: string | number; duration?: string | number;
} = {}): TransitionDirectionalAnimations { } = {}): TransitionDirectionalAnimations {
@ -55,7 +61,7 @@ export function fade({
duration: duration ?? '0.3s', duration: duration ?? '0.3s',
easing: 'linear', easing: 'linear',
fillMode: 'backwards', fillMode: 'backwards',
} },
} satisfies TransitionAnimationPair; } satisfies TransitionAnimationPair;
return { return {

View file

@ -1,12 +1,12 @@
import type { AstroConfig } from '../@types/astro';
import * as vite from 'vite'; import * as vite from 'vite';
import type { AstroConfig } from '../@types/astro';
import { AstroError } from '../core/errors/index.js'; import { AstroError } from '../core/errors/index.js';
const virtualModuleId = 'astro:transitions'; const virtualModuleId = 'astro:transitions';
const resolvedVirtualModuleId = '\0' + virtualModuleId; const resolvedVirtualModuleId = '\0' + virtualModuleId;
// The virtual module for the astro:transitions namespace // The virtual module for the astro:transitions namespace
export default function astroTransitions({ config }: { config: AstroConfig; }): vite.Plugin { export default function astroTransitions({ config }: { config: AstroConfig }): vite.Plugin {
return { return {
name: 'astro:transitions', name: 'astro:transitions',
async resolveId(id) { async resolveId(id) {
@ -25,7 +25,7 @@ export default defineConfig({
experimental: { experimental: {
viewTransitions: true viewTransitions: true
} }
})` })`,
}); });
} }

View file

@ -12,7 +12,7 @@ describe('astro/src/core/compile', () => {
await cachedCompilation({ await cachedCompilation({
astroConfig: { astroConfig: {
root: pathToFileURL('/'), root: pathToFileURL('/'),
experimental: {} experimental: {},
}, },
viteConfig: await resolveConfig({ configFile: false }, 'serve'), viteConfig: await resolveConfig({ configFile: false }, 'serve'),
filename: '/src/pages/index.astro', filename: '/src/pages/index.astro',