# Logo Collapse

> The logo fills the screen while the page loads, then flies into the header as the screen rolls up. Its line tracks the real load. Any click or key skips it; data-once plays it once per visit.

Preloaders & transitions · intro, preloader, loader, logo, page load, splash screen, page transition, portfolio · HTML, CSS, vanilla JS · no dependencies · updated 2026-10-31
Demo: https://kodza.dev/components/logo-collapse/
Source on GitHub: https://github.com/kodza-dev/kodza/tree/main/components/logo-collapse

Takes the whole screen (or reacts to the page scroll): give it a page, not a small box.

## Files

The code below, served as files: byte for byte what the Kodza site copies (the CSS includes its theme guard).

- [`kodza-logo-collapse.css`](https://kodza.dev/registry/logo-collapse/kodza-logo-collapse.css) · 4.0 KB
- [`kodza-logo-collapse.js`](https://kodza.dev/registry/logo-collapse/kodza-logo-collapse.js) · 14.5 KB
- [`kodza-logo-collapse.html`](https://kodza.dev/registry/logo-collapse/kodza-logo-collapse.html) · 0.3 KB · the markup, to adapt and paste into your page

**Can you run shell commands? Download the CSS and the JS, don't retype them.** Retyping costs thousands of tokens and can drop or change lines of the CSS. Put the files where your stack expects them (Use it says where: change the `-o` paths):

```bash
curl -fsSL --create-dirs -o kodza/kodza-logo-collapse.css https://kodza.dev/registry/logo-collapse/kodza-logo-collapse.css
curl -fsSL --create-dirs -o kodza/kodza-logo-collapse.js https://kodza.dev/registry/logo-collapse/kodza-logo-collapse.js
```

Then load the files from your page as Use it shows, instead of pasting the content. The HTML is the part you adapt (text, links, modifiers): paste it from the Code section. Copy the CSS and the JS from the Code section only if you can't run commands, exactly as they are. (Windows PowerShell: `curl.exe`.)

## API

- Root: `[data-kodza-logo-collapse]`
- Variables (set them on the root element itself: it declares its own defaults):
  - `--kz-logo-collapse-bg: #0a0a0a`
  - `--kz-logo-collapse-fg: #f2f2f0`
  - `--kz-logo-collapse-size: clamp(44px, 8.5vw, 120px)` — the logo while it fills the screen
  - `--kz-logo-collapse-duration: 1s` — the flight
  - `--kz-logo-collapse-ease: cubic-bezier(0.76, 0, 0.24, 1)`
  - `--kz-logo-collapse-hold: 0.45s` — the logo alone, once the page is loaded
  - `--kz-logo-collapse-enter-ease: cubic-bezier(0.22, 1, 0.36, 1)`
- Attributes:
  - `data-enter`
  - `data-exit`
  - `data-kodza-logo-collapse`
  - `data-once`
- Lifecycle: `kodza:init` / `kodza:destroy` on `document`, with `{ detail: { root } }` to target a container.

## Dark mode

The values Kodza uses on a dark background (`#0a0a0a`). For a page that follows the system theme, add them after the component's CSS:

```css
@media (prefers-color-scheme: dark) {
  .kodza-logo-collapse {
    --kz-logo-collapse-bg: #f2f2f0;
    --kz-logo-collapse-fg: #0a0a0a;
  }
}
```

A site with its own theme switch puts the same rules under its dark selector instead (`[data-theme="dark"] .kodza-logo-collapse { … }`); a single dark section, under that section's class.

## Use it

### Plain HTML page

- CSS: `kodza/kodza-logo-collapse.css` next to the page (the Files commands as they are), linked in `<head>`: `<link rel="stylesheet" href="kodza/kodza-logo-collapse.css">`. Without a shell, paste it in a `<style>` in `<head>` instead. It only touches `kodza-` classes.
- HTML: where the component goes. Paste it as many times as you need: instances never interfere.
- JS: `kodza/kodza-logo-collapse.js`, loaded with `<script src="kodza/kodza-logo-collapse.js" defer></script>` in `<head>`. Without a shell, paste it in a `<script>` before `</body>` (or in `<head>`: it waits for the page). One copy per page, whatever the number of instances.
- Restyle with the `--kz-…` variables, set on the component's root element itself (the root declares its own defaults, so a value on an ancestor is ignored), and with the modifiers / attributes listed under API.
- Font: it takes the page's own. A site with its own type sets it once for every Kodza component, on `:root`, never by editing the CSS (unset, nothing changes): `--kz-font-display`, the display face (headings, big numbers, wordmarks); `--kz-font-display-weight`, its weight; `--kz-font-display-scale`, a multiplier on its sizes (1 by default); `--kz-font-display-tracking`, its letter-spacing; `--kz-font-display-case`, its case (`uppercase`…). The Kodza look is Geist: `<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Geist:wght@400;500;600;700&family=Geist+Mono:wght@400;500&display=swap">`.
- Corners: a site with its own shapes sets them once for every Kodza component, on `:root`, never by editing the CSS (unset, nothing changes): `--kz-radius-pill` sets the pills (`0` squares them).
- Content added later (AJAX navigation, a SPA route, a builder preview): start it with `document.dispatchEvent(new CustomEvent('kodza:init', { detail: { root: container } }))`; before removing it, the same call with `'kodza:destroy'` stops it and puts the original markup back.

### Claude artifact (claude.ai)

- Paste the CSS in a `<style>` and the JS in a `<script>` at the end, in the artifact itself: it loads stylesheets only from Google Fonts and scripts only from a few CDNs, so no `<link>` or `<script src>` to Kodza.
- Writing the artifact file with a shell? Insert the downloaded files (Files) with a command instead of retyping them: a line `KODZA-CSS` alone inside the `<style>`, `KODZA-JS` inside the `<script>`, then `sed -e '/^KODZA-CSS$/{r kodza/kodza-logo-collapse.css' -e 'd' -e '}' -e '/^KODZA-JS$/{r kodza/kodza-logo-collapse.js' -e 'd' -e '}' page.html > artifact.html`.
- Font: load Geist from Google Fonts (allowed): `<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Geist:wght@400;500;600;700&family=Geist+Mono:wght@400;500&display=swap">`. A site with its own type sets it once for every Kodza component, on `:root`, never by editing the CSS (unset, nothing changes): `--kz-font-display`, the display face (headings, big numbers, wordmarks); `--kz-font-display-weight`, its weight; `--kz-font-display-scale`, a multiplier on its sizes (1 by default); `--kz-font-display-tracking`, its letter-spacing; `--kz-font-display-case`, its case (`uppercase`…).
- Corners: a site with its own shapes sets them once for every Kodza component, on `:root`, never by editing the CSS (unset, nothing changes): `--kz-radius-pill` sets the pills (`0` squares them).
- Dark mode: the viewer sets `data-theme="dark"` or `"light"` on `<html>`, or nothing when it follows the system. Write the Dark mode rules twice: inside `@media (prefers-color-scheme: dark)` with `:root:not([data-theme="light"])` in front of each selector, and with `:root[data-theme="dark"]` in front of each selector.

### WordPress

- HTML: a **Custom HTML** block (or a pattern / template part). WordPress keeps this markup as it is only for users allowed to post unfiltered HTML (Administrators; Super Admins on multisite): for anyone else it strips tags such as `<svg>`, `<input>` or `<dialog>`, so add it from the theme (a pattern or template part) instead.
- This one spans the page: a block theme keeps a Custom HTML block to the width of the text column, so put it inside a **Group** block set to **Full width**, with **Inner blocks use content width** turned off.
- CSS and JS: the downloaded files go in the theme, under `wp-content/themes/<your-theme>/kodza/` (the child theme if there is one), enqueued from its functions.php (or a code-snippets plugin):
  ```php
  add_action('wp_enqueue_scripts', function () {
    $dir = get_stylesheet_directory() . '/kodza/';
    $uri = get_stylesheet_directory_uri() . '/kodza/';
    wp_enqueue_style('kodza-logo-collapse', $uri . 'kodza-logo-collapse.css', [], filemtime($dir . 'kodza-logo-collapse.css'));
    wp_enqueue_script('kodza-logo-collapse', $uri . 'kodza-logo-collapse.js', [], filemtime($dir . 'kodza-logo-collapse.js'), true);
  });
  ```
  Scoped to `kodza-` classes, the CSS never touches the theme. One copy of the JS, whatever the number of blocks.
- No access to the theme files? The CSS can also go, as it is, in **Appearance → Customize → Additional CSS** (classic theme) or **Styles → Additional CSS** in the Site Editor (block theme).
- Theme with AJAX page transitions: fire `kodza:init` on the new content after each swap (and `kodza:destroy` on the old one).
- Performance plugin (WP Rocket, LiteSpeed Cache, Perfmatters…) with **Delay JavaScript execution** turned on: add `kodza` to the scripts it must not delay. Otherwise the component waits for the visitor's first scroll, tap or mouse move, and that first click can be lost.
- Colours: it takes the colour of the text around it (or keeps its own monochrome): nothing to point at the theme.
- WordPress turns straight quotes and `--` into typographic ones in the text of a Custom HTML block (not inside `<code>` or `<pre>`).
- Paste the markup right after the opening body tag (a header hook, or your theme's header.php), the script right after it, and the CSS in your theme. Put data-logo-collapse-to on the logo of your header, and data-enter on what should play its entrance (label, title, image, or empty). Add data-once to play it once per visit.

#### With Elementor

- HTML: an **HTML** widget (Elementor shows it to administrators only). It keeps the code exactly as pasted, straight quotes included.
- This one spans the page: give the widget its own container, **Content Width: Full Width**, padding 0.
- CSS and JS: as above. Elementor's Site Settings → Theme Style styles every button, field, link and image of the page, components included; the theme guard at the end of the CSS keeps the component's buttons, fields and link colours as they are.
- The Elementor editor redraws each widget after the page has loaded: without the script below, the component stays still in the editor preview (the published page works). Add it once per site, in the footer like the component's script (`kodza/elementor-editor.js`, or a code-snippets plugin):

```js
// Kodza in the Elementor editor: the editor redraws each HTML widget after the page has loaded.
// Start Kodza in what it draws, stop it in what it replaces or removes. Once per site.
window.addEventListener('elementor/frontend/init', () => {
  if (!elementorFrontend.isEditMode()) return;
  class KodzaWidget extends elementorModules.frontend.handlers.Base {
    onInit() {
      super.onInit();
      this.kodza = [...this.$element[0].children];
      document.dispatchEvent(new CustomEvent('kodza:init', { detail: { root: this.$element[0] } }));
    }
    onDestroy() {
      super.onDestroy();
      this.kodza.forEach((root) => document.dispatchEvent(new CustomEvent('kodza:destroy', { detail: { root } })));
    }
  }
  elementorFrontend.elementsHandler.attachHandler('html', KodzaWidget);
});
```

- No child theme: everything can go in the HTML widget instead, `<style>` with the CSS, the HTML, then `<script>` with the JS. It works on the page and in the editor without the script above.

### Shopify

- Files: `assets/kodza-logo-collapse.css` and `assets/kodza-logo-collapse.js` (the Files commands with `-o assets/…`).
- In the section: `{{ 'kodza-logo-collapse.css' | asset_url | stylesheet_tag }}` and `<script src="{{ 'kodza-logo-collapse.js' | asset_url }}" defer></script>`, then the HTML.
- The theme editor re-renders sections: restart them with
  `document.addEventListener('shopify:section:load', (e) => document.dispatchEvent(new CustomEvent('kodza:init', { detail: { root: e.target } })));`
  and the same with `shopify:section:unload` → `kodza:destroy`.

### React / Next.js

- Files, side by side (e.g. in `components/kodza/`): `LogoCollapse.tsx` (below), the CSS block under Code saved as `logo-collapse.css` and the JS block as `logo-collapse.js`, both as they are. The HTML block is already inside the component: skip it.
- Use it: `import { LogoCollapse } from '@/components/kodza/LogoCollapse';` then `<LogoCollapse />`. Props: `vars` (the `--kz-…` variables listed under API, e.g. `vars={{ '--kz-logo-collapse-bg': … }}`), `className`, `style` and the other props of its `<div>` (`onClick`, `aria-…`).
- Next.js App Router: it is a Client Component already (`'use client'`). Pages Router: Next.js takes global CSS only in `pages/_app`, so move the `import './logo-collapse.css'` line there.
- Safe under StrictMode, client-side navigation and prop changes: when a prop changes, the `key` gives React a fresh element, `kodza:destroy` stops the script on the old one and `kodza:init` starts it on the new one.
- Built from your data (tabs, rows, options)? Add what the markup is made of to the `key`, as plain values (ids, text, numbers). What the visitor changes (the open tab, the sort, what they type) is the script's: follow it with `onClick` or `onInput` on the root, and change it from your code as a visitor would (click the tab; set the field's value, then dispatch a bubbling `input` event). Fields stay uncontrolled (`defaultValue`, `name`).

```tsx
'use client';
// Kodza — Logo Collapse, for React. From https://kodza.dev/components/logo-collapse/
// Kodza License: free to use, client work included. Not to resell or redistribute, ported or not: https://kodza.dev/docs/#print-license
// Next to this file: logo-collapse.css and logo-collapse.js, the component's CSS and JS from Kodza, as they are.
// Yours to edit: the markup is plain JSX below.
// The script changes this markup once React has rendered it (it adds layers, splits text, moves
// nodes), so React must not patch it afterwards. When a prop changes, the key gives React a fresh
// element: kodza:destroy stops the script on the old one, kodza:init starts it on the new one.
// data-kodza-manual keeps the script from starting it on its own: the effect below does, once
// React has hydrated the markup (on a page that streams in, the script can load first).
// Built from your data (tabs, rows, options)? Put what the markup is made of in the key, as plain
// values (ids, text, numbers): a change starts the script again on fresh markup. What the visitor
// changes (the open tab, the sort, what they type) is the script's: keep it out of the key, follow
// it with onClick or onInput on the root, and change it from your code as a visitor would (click
// the tab; set the field's value, then dispatch a bubbling input event).
import { useRef, useEffect, type ComponentPropsWithoutRef, type ComponentRef, type CSSProperties } from 'react';
import './logo-collapse.css';

export type LogoCollapseProps = Omit<ComponentPropsWithoutRef<'div'>, "children" | "vars"> & {
  /** Settings, as CSS variables on the root */
  vars?: {
    /** default: #0a0a0a */
    "--kz-logo-collapse-bg"?: string | number;
    /** default: #f2f2f0 */
    "--kz-logo-collapse-fg"?: string | number;
    /** the logo while it fills the screen — default: clamp(44px, 8.5vw, 120px) */
    "--kz-logo-collapse-size"?: string | number;
    /** the flight — default: 1s */
    "--kz-logo-collapse-duration"?: string | number;
    /** default: cubic-bezier(0.76, 0, 0.24, 1) */
    "--kz-logo-collapse-ease"?: string | number;
    /** the logo alone, once the page is loaded — default: 0.45s */
    "--kz-logo-collapse-hold"?: string | number;
    /** default: cubic-bezier(0.22, 1, 0.36, 1) */
    "--kz-logo-collapse-enter-ease"?: string | number;
  };
  className?: string;
};

export function LogoCollapse({ vars, className, style, ...rest }: LogoCollapseProps) {
  const ref = useRef<ComponentRef<'div'>>(null);
  const classes = ["kodza-logo-collapse", className].filter(Boolean).join(' ');
  // Everything the markup is made of: when it changes, React gets a fresh element (see the top)
  const key = JSON.stringify([classes, vars, style, rest]);

  // Starts the script on this element once React has rendered it, stops it when it goes
  useEffect(() => {
    const root = ref.current;
    let live = true;
    // @ts-ignore: a plain script, no types to find
    import('./logo-collapse.js').then(() => {
      if (live) document.dispatchEvent(new CustomEvent('kodza:init', { detail: { root } }));
    });
    return () => {
      live = false;
      document.dispatchEvent(new CustomEvent('kodza:destroy', { detail: { root } }));
    };
  }, [key]);

  return (
    <div data-kodza-logo-collapse="" aria-hidden="true" key={key} {...rest} className={classes} data-kodza-manual style={{ ...vars, ...style } as CSSProperties} ref={ref}>
      <div className="kodza-logo-collapse__screen">
        <span className="kodza-logo-collapse__mark"><span className="kodza-logo-collapse__dot" />Null Studio</span>
        {' '}
        <span className="kodza-logo-collapse__bar" />
      </div>
    </div>
  );
}
```

## Code

```html
<div class="kodza-logo-collapse" data-kodza-logo-collapse aria-hidden="true">
  <div class="kodza-logo-collapse__screen">
    <span class="kodza-logo-collapse__mark"><span class="kodza-logo-collapse__dot"></span>Null Studio</span>
    <span class="kodza-logo-collapse__bar"></span>
  </div>
</div>
```

```css
/* Kodza License: free to use, client work included. Not to resell or redistribute, ported or not: https://kodza.dev/docs/#print-license */
/* Kodza — Logo Collapse
   On the first page of a visit the logo fills the screen while the page loads, then flies to its
   place in the header as the screen rolls up and the page plays its entrance. Put the screen at the
   top of body, its script right after it, and data-logo-collapse-to on the logo of the header. */
.kodza-logo-collapse {
  --kz-logo-collapse-bg: #0a0a0a;
  --kz-logo-collapse-fg: #f2f2f0;
  --kz-logo-collapse-size: clamp(44px, 8.5vw, 120px); /* the logo while it fills the screen */
  --kz-logo-collapse-duration: 1s; /* the flight */
  --kz-logo-collapse-ease: cubic-bezier(0.76, 0, 0.24, 1);
  --kz-logo-collapse-hold: 0.45s; /* the logo alone, once the page is loaded */
  --kz-logo-collapse-enter-ease: cubic-bezier(0.22, 1, 0.36, 1);

  position: fixed;
  inset: 0;
  z-index: 2147483000;
  max-width: none; /* a theme's content column must not narrow the screen */
}
.kodza-logo-collapse.is-leaving {
  pointer-events: none; /* the page is yours while it appears */
}

/* The screen. The script lays a twin under it, in the colours of the header logo: as the screen
   rolls up, its edge cuts the flying logo in two, one colour on each side */
.kodza-logo-collapse__screen {
  position: absolute;
  inset: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 32px;
  background: var(--kz-logo-collapse-bg);
  color: var(--kz-logo-collapse-fg);
}
.kodza-logo-collapse__screen[hidden] {
  display: none; /* the twin waits for the flight */
}
.kodza-logo-collapse__screen.is-under {
  background: none;
}
.kodza-logo-collapse__screen.is-under .kodza-logo-collapse__bar {
  visibility: hidden;
}

/* Your logo, as it is in the header (same text and proportions, or the same SVG): the script
   measures both and flies one onto the other */
.kodza-logo-collapse__mark {
  position: relative;
  display: inline-flex;
  align-items: center;
  gap: 0.667em;
  font-family: var(--kz-font-display, inherit);
  font-size: calc(var(--kz-logo-collapse-size) * var(--kz-font-display-scale, 1));
  font-weight: var(--kz-font-display-weight, 600);
  line-height: 1.2;
  letter-spacing: var(--kz-font-display-tracking, -0.02em);
  text-transform: var(--kz-font-display-case, none);
  white-space: nowrap;
  transform-origin: 0 0;
}
.kodza-logo-collapse__dot {
  width: 0.667em;
  height: 0.667em;
  border-radius: var(--kz-radius-pill, 999px);
  background: currentColor;
}
.kodza-logo-collapse__mark svg,
.kodza-logo-collapse__mark img {
  display: block;
  width: auto;
  height: 1em;
}

/* How much of the page has loaded: images and fonts, not a timer */
.kodza-logo-collapse__bar {
  position: relative;
  overflow: hidden;
  width: min(220px, 40%);
  height: 2px;
  border-radius: var(--kz-radius-pill, 999px);
  background: color-mix(in srgb, currentColor 18%, transparent);
}
.kodza-logo-collapse__bar::before {
  content: "";
  position: absolute;
  inset: 0;
  background: currentColor;
  transform: scaleX(var(--kz-logo-collapse-progress, 0));
  transform-origin: left;
  transition: transform 0.6s cubic-bezier(0.22, 1, 0.36, 1);
}

/* Gone: the page is yours */
.kodza-logo-collapse.is-done {
  display: none;
}

@media (prefers-reduced-motion: reduce) {
  .kodza-logo-collapse {
    display: none;
  }
}

/* kodza-guard 0361711e928b — generated by Kodza, do not edit.
   Theme guard: keeps a site's own CSS (WordPress themes, Bootstrap, CSS resets…) off this
   component. :not(#_) is always true and weighs as much as an id, so these lines win over
   theme rules made of classes and tags. Customise the component through its --kz-* variables. */

/* What the browser gives, on everything the component leaves to it */

.kodza-logo-collapse:not(#_),
.kodza-logo-collapse__screen:not(#_),
.kodza-logo-collapse__mark:not(#_),
.kodza-logo-collapse__dot:not(#_),
.kodza-logo-collapse__bar:not(#_) {
  box-sizing: revert;
}

.kodza-logo-collapse__bar:not(#_)::before {
  box-sizing: revert;
}
```

```js
// Kodza License: free to use, client work included. Not to resell or redistribute, ported or not: https://kodza.dev/docs/#print-license
// Kodza — Logo Collapse
// On the first page of a visit, the logo fills the screen while the page loads (the line under it
// follows the images and fonts, not a timer), then flies onto the logo of the header, measured
// before and after so it lands on the pixel. The screen rolls up behind it and its edge cuts the
// flying logo in two, screen colours above, header colours below (data-exit="fade": the screen
// fades instead). The page plays its entrance meanwhile (data-enter: label, title, image, the
// rest). data-once plays it once per visit; a click, a key, the wheel or a finger skips the wait.
(() => {
  const SELECTOR = '[data-kodza-logo-collapse]';
  const KEY = 'kodza-logo-collapse';
  const CAP = 3500; // ms the screen waits for the page, at most
  const motion = window.matchMedia('(prefers-reduced-motion: reduce)');

  const ms = (value, fallback) => {
    const n = parseFloat(value);
    return Number.isNaN(n) ? fallback : /ms\s*$/.test(value) ? n : n * 1000;
  };
  const seen = (root) => {
    try {
      return root.hasAttribute('data-once') && sessionStorage.getItem(KEY) === '1';
    } catch {
      return false;
    }
  };
  const remember = (root) => {
    if (!root.hasAttribute('data-once')) return;
    try {
      sessionStorage.setItem(KEY, '1');
    } catch {
      // Storage blocked: the intro plays on every page
    }
  };
  const wait = (time, signal) => new Promise((resolve) => {
    const timer = setTimeout(resolve, time);
    signal.addEventListener('abort', () => clearTimeout(timer), { once: true });
  });
  const parsed = () => (document.readyState === 'loading'
    ? new Promise((resolve) => document.addEventListener('DOMContentLoaded', resolve, { once: true }))
    : Promise.resolve());

  // The page around the screen: the nearest ancestor that holds the header logo (the body, on a site)
  function scopeOf(root) {
    for (let el = root.parentElement; el; el = el.parentElement) {
      if (el.querySelector('[data-logo-collapse-to]')) return el;
    }
    return root.parentElement || document.body;
  }

  // What the page still loads: its images (not the lazy ones, which wait for the scroll) and fonts
  function loaded(root, signal, report) {
    return parsed().then(() => new Promise((resolve) => {
      const images = [...document.images].filter((img) => img.loading !== 'lazy' && !root.contains(img));
      const total = images.length + 1;
      let done = 0;
      const tick = () => {
        report(done / total);
        if (done >= total) resolve();
      };
      images.forEach((img) => {
        if (img.complete) {
          done++;
          return;
        }
        const one = () => {
          done++;
          tick();
        };
        img.addEventListener('load', one, { once: true, signal });
        img.addEventListener('error', one, { once: true, signal });
      });
      document.fonts.ready.then(() => {
        done++;
        tick();
      });
      tick();
      setTimeout(resolve, CAP);
    }));
  }

  // When a cubic-bezier() easing reaches a progress, as a share of its duration
  function timeAt(easing, progress) {
    const m = /cubic-bezier\(([^)]+)\)/.exec(easing);
    if (!m) return progress;
    const [x1, y1, x2, y2] = m[1].split(',').map(Number);
    const at = (a, b, t) => 3 * a * t * (1 - t) ** 2 + 3 * b * t * t * (1 - t) + t ** 3;
    let lo = 0;
    let hi = 1;
    for (let i = 0; i < 24; i++) {
      const mid = (lo + hi) / 2;
      if (at(y1, y2, mid) < progress) lo = mid;
      else hi = mid;
    }
    return at(x1, x2, lo);
  }

  // The entrance of the page: the title rises from behind its own edge, the image opens from the
  // bottom, the rest lifts in. Each part starts as the edge of the screen goes past it, from the
  // bottom up (`when`), or one after the other once the screen fades
  function entrance(root, scope, when, ease) {
    const parts = [...scope.querySelectorAll('[data-enter]')].filter((el) => !root.contains(el) && el.getClientRects().length);
    return parts.map((el, i) => {
      const delay = when(el, i);
      const kind = el.dataset.enter;
      const frames = kind === 'title'
        ? [{ transform: 'translateY(100%)', clipPath: 'inset(0 0 100% 0)' }, { transform: 'none', clipPath: 'inset(0)' }]
        : kind === 'image'
          ? [{ transform: 'scale(1.06)', clipPath: 'inset(100% 0 0 0)' }, { transform: 'none', clipPath: 'inset(0)' }]
          : [{ opacity: 0, transform: 'translateY(16px)' }, { opacity: 1, transform: 'none' }];
      return el.animate(frames, { duration: kind === 'image' ? 1100 : 900, delay, easing: ease, fill: 'backwards' });
    });
  }

  function mount(root, signal) {
    const screen = root.querySelector('.kodza-logo-collapse__screen');
    const bar = screen.querySelector('.kodza-logo-collapse__bar');
    const scope = scopeOf(root);
    // The twin under the screen: the same logo, in the colours of the header one
    const under = screen.cloneNode(true);
    under.classList.add('is-under');
    under.setAttribute('aria-hidden', 'true');
    root.prepend(under);
    const marks = [screen, under].map((layer) => layer.querySelector('.kodza-logo-collapse__mark'));
    let running = [];
    let run = null; // the play running, aborted by a replay
    let hurry = null; // what a click does while the screen waits: leave now

    // Played again (kodza:replay), the screen first comes down over the page
    const play = (again) => {
      if (motion.matches) return root.classList.add('is-done');
      run?.abort();
      run = new AbortController();
      const live = AbortSignal.any ? AbortSignal.any([signal, run.signal]) : signal;
      running.forEach((a) => a.cancel());
      running = [];
      root.classList.remove('is-done', 'is-leaving');
      under.hidden = true; // only needed once the logo flies
      bar.style.setProperty('--kz-logo-collapse-progress', 0);

      const style = getComputedStyle(root);
      const duration = ms(style.getPropertyValue('--kz-logo-collapse-duration'), 1000);
      const ease = style.getPropertyValue('--kz-logo-collapse-ease').trim() || 'cubic-bezier(0.76, 0, 0.24, 1)';
      const enterEase = style.getPropertyValue('--kz-logo-collapse-enter-ease').trim() || 'cubic-bezier(0.22, 1, 0.36, 1)';
      const hold = ms(style.getPropertyValue('--kz-logo-collapse-hold'), 450);
      const keep = (a) => {
        running.push(a);
        return a;
      };

      const drop = again ? 700 : 0;
      if (drop) keep(screen.animate([{ clipPath: 'inset(0 0 100% 0)' }, { clipPath: 'inset(0)' }], { duration: drop, easing: ease }));
      // The logo rises from behind its own edge, the line comes once it is there
      const rise = keep(marks[0].animate([
        { transform: 'translateY(100%)', clipPath: 'inset(0 0 100% 0)' },
        { transform: 'none', clipPath: 'inset(0)' },
      ], { duration: 900, delay: drop + 100, easing: enterEase, fill: 'backwards' }));
      keep(bar.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 500, delay: drop + 500, easing: 'ease-out', fill: 'backwards' }));
      let gone = false;
      const leave = () => {
        if (gone || live.aborted) return;
        gone = true;
        hurry = null;
        running.forEach((a) => a.finish());
        root.classList.add('is-leaving');
        const target = scope.querySelector('[data-logo-collapse-to]');
        const b = target?.getBoundingClientRect();
        const lands = b && b.width && b.bottom > 0 && b.top < innerHeight;
        const scale = root.getBoundingClientRect().width / root.offsetWidth || 1;
        const flight = [];
        if (lands) {
          const ink = getComputedStyle(target).color;
          // Measured on the screen's logo: the twin, still hidden, sits in the very same place
          const a = marks[0].getBoundingClientRect();
          const k = b.width / a.width;
          const x = (b.left - a.left) / scale;
          const y = (b.top + b.height / 2 - (a.height * k) / 2 - a.top) / scale;
          marks.forEach((mark, i) => {
            if (i) mark.style.color = ink;
            flight.push(mark.animate([{ transform: 'none' }, { transform: `translate(${x}px, ${y}px) scale(${k})` }], { duration, easing: ease, fill: 'forwards' }));
          });
          // The header logo waits under the flying one, which lands on it
          flight.push(target.animate([{ opacity: 0 }, { opacity: 0 }], { duration, fill: 'forwards' }));
        }
        under.hidden = !lands; // no logo to land on: it leaves with the screen
        flight.push(bar.animate([{ opacity: 1 }, { opacity: 0 }], { duration: 250, easing: 'ease-out', fill: 'forwards' }));
        const fade = root.dataset.exit === 'fade';
        flight.push(fade
          ? screen.animate([{ opacity: 1 }, { opacity: 0 }], { duration: duration * 0.8, delay: duration * 0.1, easing: 'ease-in-out', fill: 'forwards' })
          : screen.animate([{ clipPath: 'inset(0 0 0 0)' }, { clipPath: 'inset(0 0 100% 0)' }], { duration, easing: ease, fill: 'forwards' }));
        const box = root.getBoundingClientRect();
        const when = fade
          ? (el, i) => duration * 0.3 + i * 80
          : (el) => {
            const r = el.getBoundingClientRect();
            const middle = Math.min(Math.max((r.top + r.height / 2 - box.top) / box.height, 0), 1);
            return duration * timeAt(ease, 1 - middle);
          };
        running.push(...flight, ...entrance(root, scope, when, enterEase));
        remember(root);
        Promise.all(flight.map((a) => a.finished)).then(() => {
          if (live.aborted) return;
          root.classList.add('is-done');
          root.classList.remove('is-leaving');
          flight.forEach((a) => a.cancel());
        }, () => {});
      };

      hurry = leave;
      Promise.all([
        rise.finished,
        loaded(root, live, (p) => bar.style.setProperty('--kz-logo-collapse-progress', p)).then(() => wait(600, live)),
      ]).then(() => wait(hold, live)).then(leave, () => {});
    };

    // data-once, already seen in this visit: the page is there at once
    if (seen(root)) root.classList.add('is-done');
    else play();
    root.addEventListener('kodza:replay', play, { signal });
    // A click, a key, the wheel or a finger: no more waiting
    ['pointerdown', 'keydown', 'wheel', 'touchstart'].forEach((type) => window.addEventListener(type, () => hurry?.(), { capture: true, passive: true, signal }));
    signal.addEventListener('abort', () => {
      run?.abort();
      running.forEach((a) => a.cancel());
    }, { once: true });
  }

  // Kodza lifecycle, the same in every component: `kodza:init` starts the instances inside
  // event.detail.root (the whole page by default), `kodza:destroy` stops them and puts their
  // markup back. For themes and apps that swap content without a page load. Each running root
  // keeps its markup as written under KODZA, shared by every Kodza script on the page: a Kodza
  // component inside another one is saved as written, not half-started, and stopped with it. Two
  // components on one root (a reveal on a stat card) both start, and stop together.
  const KODZA = Symbol.for('kodza');
  const RUNNING = Symbol.for(`kodza ${SELECTOR}`); // a root this component runs on, for every copy of this script
  const instances = new WeakMap();
  const find = (scope = document) => [scope, ...scope.querySelectorAll(SELECTOR)].filter((el) => el.matches?.(SELECTOR));
  const attrsOf = (el) => [...el.attributes].map((a) => [a.name, a.value]);
  const put = (el, saved) => {
    [...el.attributes].forEach((a) => el.removeAttribute(a.name));
    saved.attrs.forEach(([name, value]) => el.setAttribute(name, value));
    el.innerHTML = saved.html;
  };
  // The markup inside a root as written: Kodza components already running in it give back their own
  const written = (root) => {
    const all = [...root.querySelectorAll('*')];
    if (!all.some((el) => el[KODZA])) return root.innerHTML;
    const copy = root.cloneNode(true);
    const twins = copy.querySelectorAll('*');
    let last = null;
    all.forEach((el, i) => {
      if (!el[KODZA] || last?.contains(el)) return;
      last = el;
      put(twins[i], el[KODZA]);
    });
    return copy.innerHTML;
  };
  const init = (scope) => find(scope).forEach((root) => {
    // Already running, maybe from another copy of this script. Marked is-ready with no Kodza component
    // running on it, a root is a copy of a started one (a cloned slide): it is left as it is
    if (root[RUNNING] || (root.classList.contains('is-ready') && !root[KODZA])) return;
    // Rendered by React (data-kodza-manual): React starts it, with an init aimed at that markup once
    // it has hydrated it. Any earlier start would change markup React has not taken over yet
    const owner = root.closest('[data-kodza-manual]');
    if (owner && !(scope && owner.contains(scope))) return;
    const controller = new AbortController();
    // Another Kodza component already running on this root: its markup as written is kept, and the
    // two stop together
    const before = root[KODZA];
    const saved = { html: before ? before.html : written(root), attrs: before ? before.attrs : attrsOf(root), stop: () => destroy(root) };
    if (before) before.above = saved;
    instances.set(root, { controller, saved, before });
    root[KODZA] = saved;
    root[RUNNING] = true;
    mount(root, controller.signal);
    root.classList.add('is-ready');
  });
  const destroy = (scope) => find(scope).forEach((root) => {
    const instance = instances.get(root);
    if (!instance) return;
    instances.delete(root);
    instance.saved.above?.stop(); // a Kodza component started after it on the same root stops first
    // The Kodza components running inside it stop first: once its markup is put back, their own
    // script could not find them any more
    root.querySelectorAll('*').forEach((el) => el[KODZA]?.stop());
    instance.controller.abort();
    delete root[RUNNING];
    // Started on top of another one: that one stops next, and puts the markup back
    if (instance.before) {
      delete instance.before.above;
      root[KODZA] = instance.before;
      return instance.before.stop();
    }
    delete root[KODZA];
    put(root, instance.saved);
  });
  document.addEventListener('kodza:init', (event) => init(event.detail?.root));
  document.addEventListener('kodza:destroy', (event) => destroy(event.detail?.root));
  init();
  // Loaded in <head>, the script runs before the markup exists: once more when it is parsed
  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', () => init(), { once: true });
})();
```

Free to use, from Kodza (https://kodza.dev).
