# Page Transition

Page Transition is a navigation effect where the old page drifts up, shrinks and fades while the new one slides in from below over it.

- Live demo: https://dmivanov.ru/experiments/page-transition

## How to embed

Instructions for an AI agent or developer adding this effect to a website.

1. Save the two code blocks below as `shared.js` and `page-transition.js` in the same folder of the project's scripts. They are plain ES modules with no build step and no dependencies.
2. Add a container with an explicit size where the effect should appear. The effect fills it completely:

   ```html
   <div id="page-transition" style="position: relative; width: 100%; height: 480px;"></div>
   ```

3. Mount the effect from a module script:

   ```html
   <script type="module">
     import { mount, meta } from "./page-transition.js";

     const effect = mount(document.getElementById("page-transition"), { ...meta.defaults });
     // effect.update({ ... }) changes parameters at runtime.
     // effect.replay() restarts one-shot animations.
     // effect.destroy() removes the effect and its listeners.
   </script>
   ```

This animation plays once when it is mounted. Call `effect.replay()` to play it again, for example from a button or when the section scrolls into view.

The module injects its own CSS and loads its Google Font. Pixel values are authored for a 1000px-wide container and scale with the container width. In React, Vue or Svelte, call `mount` when the component mounts and `destroy` when it unmounts. Pass `{ mode: "still" }` as the third argument of `mount` to render a single static frame, for example for a preview card.

## Parameters

| Key | Control | Default | Values |
| --- | --- | --- | --- |
| `first` | First page | `"About"` | text, up to 16 chars |
| `second` | Second page | `"Works"` | text, up to 16 chars |
| `duration` | Duration | `1500` | 300–3000 ms |
| `offset` | Offset | `10` | 0–40 % |
| `scale` | Scale | `95` | 70–100 % |
| `firstColor` | First page color | `"#FF4552"` | hex color |
| `secondColor` | Second page color | `"#EFE8D8"` | hex color |
| `textColor` | Text color | `"#111210"` | hex color |
| `background` | Background | `"#171717"` | hex color |

## shared.js

```js
// Shared helpers for experiment modules.
//
// Every experiment exports `meta` (title, controls, defaults) and
// `mount(stage, settings, { mode })`. The stage is any positioned element; the
// effect fills it and scales its pixel values to the stage width, so the same
// code runs in the full demo, in small card previews, and on a client's site.
// `mode` is "live" (interactive / animated) or "still" (one static frame).

export const REFERENCE_WIDTH = 1000;

const fontRequests = new Map();

// Loads a Google Fonts stylesheet once and resolves when the family is ready.
export function loadFont(href, family, weight = "400") {
  if (!href || typeof document === "undefined") return Promise.resolve();
  const key = `${family}:${weight}`;
  if (fontRequests.has(key)) return fontRequests.get(key);
  // The @font-face rules exist only after the stylesheet loads, so wait for
  // it before asking the browser to fetch the font itself.
  let link = document.querySelector(`link[href="${href}"]`);
  const stylesheet = link && link.sheet ? Promise.resolve() : new Promise((resolve) => {
    if (!link) {
      link = document.createElement("link");
      link.rel = "stylesheet";
      link.href = href;
      document.head.append(link);
    }
    link.addEventListener("load", resolve, { once: true });
    link.addEventListener("error", resolve, { once: true });
  });
  const request = stylesheet
    .then(() => (document.fonts ? document.fonts.load(`${weight} 32px "${family}"`) : null))
    .catch(() => {})
    .then(() => undefined);
  fontRequests.set(key, request);
  return request;
}

export function loadFonts(fonts = []) {
  return Promise.all(fonts.map((font) => loadFont(font.href, font.family, font.weight)));
}

// Adds a stylesheet for an effect once per document.
export function injectStyle(id, css) {
  if (typeof document === "undefined" || document.getElementById(id)) return;
  const style = document.createElement("style");
  style.id = id;
  style.textContent = css;
  document.head.append(style);
}

// Pixel values in settings are authored for a 1000px-wide stage.
export function stageUnit(stage) {
  return (stage.clientWidth || REFERENCE_WIDTH) / REFERENCE_WIDTH;
}

// Every effect keeps the same margin inside its stage: 8% of the stage width.
export const SAFE_AREA = 0.08;

export function safeArea(stage) {
  const pad = Math.round(stage.clientWidth * SAFE_AREA);
  return {
    pad,
    width: Math.max(1, stage.clientWidth - pad * 2),
    height: Math.max(1, stage.clientHeight - pad * 2)
  };
}

// Scale that fits a box of the given size into the safe area. Previews pass
// `grow` so every card fills its safe area the same way; the full demo only
// shrinks content that would otherwise overflow. `fill` lets a preview whose
// type reads heavy take less of the area than the others.
export function fitScale(stage, width, height, { grow = false, fill = 1 } = {}) {
  if (!width || !height) return 1;
  const area = safeArea(stage);
  const scale = Math.min(area.width / width, area.height / height);
  return grow ? scale * fill : Math.min(1, scale);
}

// Fits an element by its layout size (transforms do not affect offset sizes)
// and writes the result to its `--fx-fit` custom property.
export function fitElement(stage, element, options) {
  const scale = fitScale(stage, element.offsetWidth, element.offsetHeight, options);
  element.style.setProperty("--fx-fit", scale.toFixed(4));
  return scale;
}

export function watchSize(stage, callback) {
  if (typeof ResizeObserver === "undefined") return () => {};
  let width = stage.clientWidth;
  let height = stage.clientHeight;
  const observer = new ResizeObserver(() => {
    if (stage.clientWidth === width && stage.clientHeight === height) return;
    width = stage.clientWidth;
    height = stage.clientHeight;
    callback();
  });
  observer.observe(stage);
  return () => observer.disconnect();
}

export function localPoint(stage, event) {
  const rect = stage.getBoundingClientRect();
  return { x: event.clientX - rect.left, y: event.clientY - rect.top };
}

let uid = 0;
export function uniqueId(prefix) {
  uid += 1;
  return `${prefix}-${uid}`;
}

// Splits text into words and letters without touching the original string.
export function splitWords(text) {
  return String(text).trim().split(/\s+/).filter(Boolean);
}

export function isHexColor(value) {
  return /^#[0-9a-f]{6}$/i.test(String(value));
}
```

## page-transition.js

```js
import { injectStyle, loadFonts, stageUnit, watchSize } from "./shared.js";

// Page Transition: the old page drifts up, shrinks and fades while the new one
// slides in from below over it. The scene plays it between two mock pages with
// the Web Animations API. On a real multi-page site the same motion is a
// cross-document View Transition in plain CSS: see `pageTransitionCSS` below.

export const meta = {
  slug: "page-transition",
  description: "Page Transition is a navigation effect where the old page drifts up, shrinks and fades while the new one slides in from below over it.",
  title: "Page Transition",
  codepen: "",
  replay: true,
  fonts: [{ family: "Inter", weight: "700", href: "https://fonts.googleapis.com/css2?family=Inter:wght@500;700&display=swap" }],
  controls: [
    { key: "first", label: "First page", type: "text", maxlength: 16 },
    { key: "second", label: "Second page", type: "text", maxlength: 16 },
    { key: "duration", label: "Duration", type: "range", min: 300, max: 3000, step: 50, unit: "ms" },
    { key: "offset", label: "Offset", type: "range", min: 0, max: 40, step: 1, unit: "%" },
    { key: "scale", label: "Scale", type: "range", min: 70, max: 100, step: 1, unit: "%" },
    { key: "firstColor", label: "First page color", type: "color" },
    { key: "secondColor", label: "Second page color", type: "color" },
    { key: "textColor", label: "Text color", type: "color" },
    { key: "background", label: "Background", type: "color" }
  ],
  defaults: {
    first: "About",
    second: "Works",
    duration: 1500,
    offset: 10,
    scale: 95,
    firstColor: "#FF4552",
    secondColor: "#EFE8D8",
    textColor: "#111210",
    background: "#171717"
  }
};

// Strong ease-in-out: slow start, fast middle, long settle.
export const EASING = "cubic-bezier(.76, 0, .24, 1)";

// The same motion for a real website, as a cross-document View Transition
// (Chromium, Safari 18.2+; other browsers simply navigate). Add the returned
// CSS to the stylesheet shared by every page. In a single-page app, keep the
// ::view-transition rules and wrap the route change in
// document.startViewTransition(() => renderNextPage()).
// If pages have their own fade-in, switch it off while the transition runs:
// html:active-view-transition .page { animation: none; }
export function pageTransitionCSS(settings = meta.defaults) {
  const { duration, offset, scale, background } = { ...meta.defaults, ...settings };
  return `@media (prefers-reduced-motion: no-preference) {
  @view-transition { navigation: auto; }
}
@keyframes page-leave { to { opacity: 0; transform: translateY(-${offset}%) scale(${scale / 100}); } }
@keyframes page-arrive { from { transform: translateY(${offset}%); } }
::view-transition-old(root),
::view-transition-new(root) { mix-blend-mode: normal; animation-duration: ${duration}ms; animation-timing-function: ${EASING}; animation-fill-mode: both; }
::view-transition-old(root) { animation-name: page-leave; }
::view-transition-new(root) { animation-name: page-arrive; }
/* seen around the shrinking old page */
::view-transition { background: ${background}; }`;
}

const CSS = `
.fx-pt { position: absolute; inset: 0; overflow: hidden; background: var(--fx-bg); font-family: "Inter", sans-serif; }
.fx-pt[data-mode="still"] { pointer-events: none; }
.fx-pt__page { position: absolute; inset: 0; display: flex; flex-direction: column; justify-content: space-between; padding: var(--fx-pad); background: var(--fx-page); color: var(--fx-fg); visibility: hidden; transform-origin: 50% 50%; }
.fx-pt__page[data-visible="true"] { visibility: visible; }
.fx-pt__header { display: flex; align-items: baseline; justify-content: space-between; gap: var(--fx-gap); font-size: var(--fx-small); font-weight: 700; letter-spacing: -.02em; }
.fx-pt__nav { display: flex; gap: var(--fx-gap); }
.fx-pt__link { padding: 0; border: 0; background: none; color: inherit; font: inherit; letter-spacing: inherit; cursor: pointer; opacity: .45; }
.fx-pt__link[aria-current="page"] { opacity: 1; cursor: default; }
.fx-pt__link:focus-visible { outline: 2px solid currentColor; outline-offset: 4px; }
.fx-pt__footer { display: flex; align-items: flex-end; justify-content: space-between; gap: var(--fx-gap); }
.fx-pt__title { margin: 0; font-size: var(--fx-title); font-weight: 700; line-height: .9; letter-spacing: -.05em; overflow-wrap: anywhere; }
.fx-pt__index { font-size: var(--fx-small); font-weight: 500; font-variant-numeric: tabular-nums; }
`;

export function mount(stage, initialSettings, { mode = "live" } = {}) {
  injectStyle("fx-pt-style", CSS);
  let settings = { ...meta.defaults, ...initialSettings };
  const root = document.createElement("div");
  root.className = "fx-pt";
  root.dataset.mode = mode;
  stage.append(root);

  let current = 0;
  let animations = [];
  let timer = 0;
  const pages = [0, 1].map((index) => {
    const page = document.createElement("section");
    page.className = "fx-pt__page";
    root.append(page);
    return page;
  });

  const titles = () => [settings.first, settings.second];

  function renderPage(page, index) {
    const header = document.createElement("div");
    header.className = "fx-pt__header";
    const brand = document.createElement("span");
    brand.textContent = "Dm.Ivanov";
    const nav = document.createElement("nav");
    nav.className = "fx-pt__nav";
    titles().forEach((title, target) => {
      const link = document.createElement("button");
      link.type = "button";
      link.className = "fx-pt__link";
      link.textContent = title;
      if (target === index) link.setAttribute("aria-current", "page");
      else link.addEventListener("click", () => go(target));
      if (mode !== "live") link.tabIndex = -1;
      nav.append(link);
    });
    header.append(brand, nav);

    const footer = document.createElement("div");
    footer.className = "fx-pt__footer";
    const title = document.createElement("h2");
    title.className = "fx-pt__title";
    title.textContent = titles()[index];
    const counter = document.createElement("span");
    counter.className = "fx-pt__index";
    counter.textContent = `0${index + 1} / 02`;
    footer.append(title, counter);

    page.style.setProperty("--fx-page", index === 0 ? settings.firstColor : settings.secondColor);
    page.replaceChildren(header, footer);
  }

  function render() {
    const unit = stageUnit(stage);
    root.style.setProperty("--fx-bg", settings.background);
    root.style.setProperty("--fx-fg", settings.textColor);
    root.style.setProperty("--fx-pad", `${40 * unit}px`);
    root.style.setProperty("--fx-gap", `${24 * unit}px`);
    root.style.setProperty("--fx-small", `${Math.max(11, 18 * unit)}px`);
    root.style.setProperty("--fx-title", `${200 * unit}px`);
    pages.forEach(renderPage);
  }

  function clear() {
    clearTimeout(timer);
    animations.forEach((animation) => animation.cancel());
    animations = [];
  }

  function show(index) {
    pages.forEach((page, i) => {
      page.dataset.visible = String(i === index);
      page.style.zIndex = i === index ? "2" : "1";
    });
    current = index;
  }

  // Old page: up, smaller, transparent. New page: from below, on top, opaque.
  function transition(from, to) {
    const timing = { duration: settings.duration, easing: EASING, fill: "both" };
    pages[from].style.zIndex = "1";
    pages[to].style.zIndex = "2";
    pages[from].dataset.visible = "true";
    pages[to].dataset.visible = "true";
    return [
      pages[from].animate([
        { transform: "none", opacity: 1 },
        { transform: `translateY(-${settings.offset}%) scale(${settings.scale / 100})`, opacity: 0 }
      ], timing),
      pages[to].animate([
        { transform: `translateY(${settings.offset}%)` },
        { transform: "none" }
      ], timing)
    ];
  }

  function go(target) {
    if (target === current && !animations.length) return;
    const from = current;
    clear();
    animations = transition(from, target);
    current = target;
    animations[1].finished.then(() => {
      if (current !== target) return;
      clear();
      show(target);
    }).catch(() => {});
  }

  // Starts on the first page and moves to the second after a short pause.
  function play() {
    clear();
    show(0);
    timer = setTimeout(() => go(1), 500);
  }

  // One frame from early in the transition, while both pages are in view.
  function still() {
    clear();
    animations = transition(0, 1);
    animations.forEach((animation) => {
      animation.pause();
      animation.currentTime = settings.duration * 0.35;
    });
  }

  const start = () => (mode === "live" ? play() : still());
  const stopWatching = watchSize(stage, render);
  render();
  start();
  loadFonts(meta.fonts).then(render);

  return {
    update(next) {
      settings = { ...settings, ...next };
      render();
      start();
    },
    replay: start,
    destroy() {
      clear();
      stopWatching();
      root.remove();
    }
  };
}
```
