# Overlap Transition

Overlap Transition is a navigation effect where the old page sinks back and dims while the new one rises from below over it, tilted and smaller, and then straightens up to full size.

- Live demo: https://dmivanov.ru/experiments/overlap-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 `overlap-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="overlap-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 "./overlap-transition.js";

     const effect = mount(document.getElementById("overlap-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 | `"Contact"` | text, up to 16 chars |
| `second` | Second page | `"About"` | text, up to 16 chars |
| `duration` | Duration | `1000` | 400–3000 ms |
| `rotation` | Rotation | `5` | 0–20 ° |
| `scale` | Scale | `85` | 50–100 % |
| `dim` | Dim | `50` | 0–100 % |
| `firstColor` | First page color | `"#F2EEE8"` | hex color |
| `secondColor` | Second page color | `"#FF4552"` | 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));
}
```

## overlap-transition.js

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

// Overlap Transition: the old page sinks back (shrinks a little and dims into
// the background) while the new one rises from below over it, tilted and
// smaller, straightens up and then grows to full size; its title slides up
// last. Timings follow a GSAP timeline, played here with the Web Animations
// API. All times are shares of `duration`, the length of the rise.

export const meta = {
  slug: "overlap-transition",
  description: "Overlap Transition is a navigation effect where the old page sinks back and dims while the new one rises from below over it, tilted and smaller, and then straightens up to full size.",
  title: "Overlap Transition",
  codepen: "",
  replay: true,
  fonts: [{ family: "Inter", weight: "600", href: "https://fonts.googleapis.com/css2?family=Inter:wght@500;600&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: 400, max: 3000, step: 50, unit: "ms" },
    { key: "rotation", label: "Rotation", type: "range", min: 0, max: 20, step: 1, unit: "°" },
    { key: "scale", label: "Scale", type: "range", min: 50, max: 100, step: 1, unit: "%" },
    { key: "dim", label: "Dim", type: "range", min: 0, max: 100, step: 5, unit: "%" },
    { key: "firstColor", label: "First page color", type: "color" },
    { key: "secondColor", label: "Second page color", type: "color" },
    { key: "background", label: "Background", type: "color" }
  ],
  defaults: {
    first: "Contact",
    second: "About",
    duration: 1000,
    rotation: 5,
    scale: 85,
    dim: 50,
    firstColor: "#F2EEE8",
    secondColor: "#FF4552",
    background: "#171717"
  }
};

// CSS equivalents of the GSAP eases in the original timeline.
export const EASE = {
  sink: "cubic-bezier(.25, .46, .45, .94)", // power2.out
  rise: "cubic-bezier(.65, 0, .35, 1)", // power3.inOut
  grow: "cubic-bezier(.4, 0, .2, .95)",
  title: "cubic-bezier(.23, 1, .32, 1)" // power4.out
};

// The old page shrinks to this size while it dims.
const SINK_SCALE = 0.95;

// Start and length of every step as a share of `duration`.
export const TIMELINE = {
  sink: { delay: 0, duration: 0.7 },
  dim: { delay: 0, duration: 0.5 },
  rise: { delay: 0, duration: 1 },
  grow: { delay: 0.6, duration: 0.8 },
  title: { delay: 0.75, duration: 0.6, stagger: 0.08 }
};

const CSS = `
.fx-ot { position: absolute; inset: 0; overflow: hidden; background: var(--fx-bg); font-family: "Inter", sans-serif; }
.fx-ot[data-mode="still"] { pointer-events: none; }
.fx-ot__slot { position: absolute; inset: 0; visibility: hidden; transform-origin: 50% 50%; }
.fx-ot__slot[data-visible="true"] { visibility: visible; }
.fx-ot__page { position: absolute; inset: 0; display: flex; flex-direction: column; padding: var(--fx-pad); overflow: hidden; background: var(--fx-page); color: var(--fx-fg); transform-origin: 50% 50%; }
.fx-ot__dim { position: absolute; inset: 0; background: var(--fx-bg); opacity: 0; pointer-events: none; }
.fx-ot__header { display: flex; align-items: baseline; justify-content: space-between; gap: var(--fx-gap); font-size: var(--fx-small); font-weight: 600; }
.fx-ot__brand { display: inline-flex; align-items: center; gap: .4em; }
.fx-ot__brand::before { content: ""; width: .7em; height: .7em; border-radius: 50%; background: currentColor; }
.fx-ot__nav { display: flex; gap: var(--fx-gap); }
.fx-ot__link { padding: 0; border: 0; background: none; color: inherit; font: inherit; cursor: pointer; opacity: .5; }
.fx-ot__link[aria-current="page"] { opacity: 1; cursor: default; }
.fx-ot__link:focus-visible { outline: 2px solid currentColor; outline-offset: 4px; }
.fx-ot__footer { display: flex; justify-content: flex-end; margin-top: auto; }
.fx-ot__title { margin: var(--fx-gap) 0 0; font-size: var(--fx-title); font-weight: 600; line-height: 1; letter-spacing: -.045em; overflow-wrap: anywhere; }
.fx-ot__line { display: block; overflow: hidden; padding-bottom: .05em; }
.fx-ot__line > span { display: block; }
.fx-ot__meta { font-size: var(--fx-small); font-weight: 500; text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }
`;

// Dark text on light pages, light text on dark ones.
function textColor(hex) {
  const value = parseInt(String(hex).slice(1), 16);
  if (Number.isNaN(value)) return "#121212";
  const [r, g, b] = [value >> 16, (value >> 8) & 255, value & 255];
  return 0.299 * r + 0.587 * g + 0.114 * b > 150 ? "#121212" : "#F4F1EA";
}

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

  let current = 0;
  let animations = [];
  let timer = 0;

  // Each page sits in a slot: the slot carries the rise and tilt, the page
  // inside it the scale, the dim layer darkens the page while it sinks.
  const slots = [0, 1].map(() => {
    const slot = document.createElement("div");
    slot.className = "fx-ot__slot";
    const page = document.createElement("section");
    page.className = "fx-ot__page";
    const dim = document.createElement("div");
    dim.className = "fx-ot__dim";
    slot.append(page, dim);
    root.append(slot);
    return { slot, page, dim, lines: [] };
  });

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

  function renderPage(item, index) {
    const header = document.createElement("div");
    header.className = "fx-ot__header";
    const brand = document.createElement("span");
    brand.className = "fx-ot__brand";
    brand.textContent = "Dm.Ivanov";
    const nav = document.createElement("nav");
    nav.className = "fx-ot__nav";
    titles().forEach((title, target) => {
      const link = document.createElement("button");
      link.type = "button";
      link.className = "fx-ot__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-ot__footer";
    const title = document.createElement("h2");
    title.className = "fx-ot__title";
    // One masked line per word, so a long title rises line by line.
    item.lines = String(titles()[index]).trim().split(/\s+/).filter(Boolean).map((word) => {
      const line = document.createElement("span");
      line.className = "fx-ot__line";
      const inner = document.createElement("span");
      inner.textContent = word;
      line.append(inner);
      title.append(line);
      return inner;
    });
    const counter = document.createElement("span");
    counter.className = "fx-ot__meta";
    counter.textContent = `0${index + 1} / 02`;
    footer.append(counter);

    const color = index === 0 ? settings.firstColor : settings.secondColor;
    item.page.style.setProperty("--fx-page", color);
    item.page.style.setProperty("--fx-fg", textColor(color));
    item.page.replaceChildren(header, title, footer);
  }

  // Sizes only: safe to run mid-transition, the animated nodes stay in place.
  function layout() {
    const unit = stageUnit(stage);
    root.style.setProperty("--fx-bg", settings.background);
    root.style.setProperty("--fx-pad", `${36 * unit}px`);
    root.style.setProperty("--fx-gap", `${24 * unit}px`);
    root.style.setProperty("--fx-small", `${Math.max(10, 16 * unit)}px`);
    root.style.setProperty("--fx-title", `${150 * unit}px`);
  }

  function render() {
    layout();
    slots.forEach(renderPage);
  }

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

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

  function timing(step, extra = 0) {
    const { delay, duration } = TIMELINE[step];
    return {
      delay: (delay + extra) * settings.duration,
      duration: duration * settings.duration,
      easing: EASE[step],
      fill: "both"
    };
  }

  function transition(from, to) {
    const old = slots[from];
    const next = slots[to];
    old.slot.style.zIndex = "1";
    next.slot.style.zIndex = "2";
    old.slot.dataset.visible = "true";
    next.slot.dataset.visible = "true";
    const scale = settings.scale / 100;
    const list = [
      old.page.animate([{ transform: "scale(1)" }, { transform: `scale(${SINK_SCALE})` }], timing("sink")),
      old.dim.animate([{ opacity: 0 }, { opacity: settings.dim / 100 }], timing("dim")),
      next.slot.animate([
        { transform: `translateY(100%) rotate(${settings.rotation}deg)` },
        { transform: "translateY(0) rotate(0deg)" }
      ], timing("rise")),
      next.page.animate([{ transform: `scale(${scale})` }, { transform: "scale(1)" }], timing("grow"))
    ];
    next.lines.forEach((line, i) => {
      list.push(line.animate([
        { transform: "translateY(100%)", opacity: 0 },
        { transform: "translateY(0)", opacity: 1 }
      ], timing("title", i * TIMELINE.title.stagger)));
    });
    return list;
  }

  function go(target) {
    if (target === current && !animations.length) return;
    const from = current;
    clear();
    animations = transition(from, target);
    current = target;
    Promise.all(animations.map((animation) => animation.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 the middle of the rise, while the new page is still tilted.
  function still() {
    clear();
    animations = transition(0, 1);
    animations.forEach((animation) => {
      animation.pause();
      animation.currentTime = settings.duration * 0.55;
    });
  }

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

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