# Download Link

> A download link that shows the file's type and weight beside its words, read from the file itself. On hover the arrow sinks into its tray; a click sends it through and back from the top.

Links · link, download, file, file size, wordpress · HTML, CSS, vanilla JS · no dependencies · updated 2026-10-27
Demo: https://kodza.dev/components/download-link/
Source on GitHub: https://github.com/kodza-dev/kodza/tree/main/components/download-link

## Files

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

- [`kodza-download-link.css`](https://kodza.dev/registry/download-link/kodza-download-link.css) · 6.2 KB
- [`kodza-download-link.js`](https://kodza.dev/registry/download-link/kodza-download-link.js) · 11.8 KB
- [`kodza-download-link.html`](https://kodza.dev/registry/download-link/kodza-download-link.html) · 0.7 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-download-link.css https://kodza.dev/registry/download-link/kodza-download-link.css
curl -fsSL --create-dirs -o kodza/kodza-download-link.js https://kodza.dev/registry/download-link/kodza-download-link.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-download-link]`
- Variables (set them on the root element itself: it declares its own defaults):
  - `--kz-download-link-gap: 0.32em`
  - `--kz-download-link-icon: 0.82em`
  - `--kz-download-link-meta: color-mix(in srgb, currentColor 64%, transparent)`
  - `--kz-download-link-duration: 0.25s`
  - `--kz-download-link-ease: cubic-bezier(0.22, 1, 0.36, 1)`
- Attributes:
  - `data-kodza-download-link`
  - `data-target`
- Lifecycle: `kodza:init` / `kodza:destroy` on `document`, with `{ detail: { root } }` to target a container.

## Dark mode

Nothing to set: it takes its colours from the text around it, or looks the same on a light and a dark page.

Its images have dark versions next to them (`kz-reel.mp4` → `kz-reel.mp4`). To swap them on a dark page: `<picture><source media="(prefers-color-scheme: dark)" srcset="…-dark-….webp"><img …></picture>`.

## Use it

### Plain HTML page

- CSS: `kodza/kodza-download-link.css` next to the page (the Files commands as they are), linked in `<head>`: `<link rel="stylesheet" href="kodza/kodza-download-link.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-download-link.js`, loaded with `<script src="kodza/kodza-download-link.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. 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">`.
- 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-download-link.css' -e 'd' -e '}' -e '/^KODZA-JS$/{r kodza/kodza-download-link.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">`.
- Images: the artifact blocks every other host, `kodza.dev` included, without an error. Embed each one as a `data:` URI, with a command if you can run one (`curl -s <url> | base64`; the 1400 px files weigh 10 to 30 KB), never by typing base64 out. If you can't run commands, keep the `<img>` with its `width` and `height`, and tell the user the picture stays blank inside the artifact.
- 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 is inline (it flows like a word): pasted alone, many themes leave it at the edge of the page (block themes, and classic ones like Twenty Twenty-One or Blocksy), so put the Custom HTML block inside a **Group** block to line it up with the text.
- 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-download-link', $uri . 'kodza-download-link.css', [], filemtime($dir . 'kodza-download-link.css'));
    wp_enqueue_script('kodza-download-link', $uri . 'kodza-download-link.js', [], filemtime($dir . 'kodza-download-link.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>`).

#### With Elementor

- HTML: an **HTML** widget (Elementor shows it to administrators only). It keeps the code exactly as pasted, straight quotes included.
- 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-download-link.css` and `assets/kodza-download-link.js` (the Files commands with `-o assets/…`).
- In the section: `{{ 'kodza-download-link.css' | asset_url | stylesheet_tag }}` and `<script src="{{ 'kodza-download-link.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/`): `DownloadLink.tsx` (below), the CSS block under Code saved as `download-link.css` and the JS block as `download-link.js`, both as they are. The HTML block is already inside the component: skip it.
- Use it: `import { DownloadLink } from '@/components/kodza/DownloadLink';` then `<DownloadLink />`. Props: `vars` (the `--kz-…` variables listed under API, e.g. `vars={{ '--kz-download-link-gap': … }}`), `className`, `style` and the other props of its `<a>` (`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 './download-link.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 — Download Link, for React. From https://kodza.dev/components/download-link/
// 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: download-link.css and download-link.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.
// 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 './download-link.css';

export type DownloadLinkProps = Omit<ComponentPropsWithoutRef<'a'>, "children" | "vars"> & {
  /** Settings, as CSS variables on the root */
  vars?: {
    /** default: 0.32em */
    "--kz-download-link-gap"?: string | number;
    /** default: 0.82em */
    "--kz-download-link-icon"?: string | number;
    /** default: color-mix(in srgb, currentColor 64%, transparent) */
    "--kz-download-link-meta"?: string | number;
    /** default: 0.25s */
    "--kz-download-link-duration"?: string | number;
    /** default: cubic-bezier(0.22, 1, 0.36, 1) */
    "--kz-download-link-ease"?: string | number;
  };
  className?: string;
};

export function DownloadLink({ vars, className, style, ...rest }: DownloadLinkProps) {
  const ref = useRef<ComponentRef<'a'>>(null);
  const classes = ["kodza-download-link", 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('./download-link.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 (
    <a href="https://kodza.dev/media/kz-reel.mp4" download="" data-kodza-download-link="" key={key} {...rest} className={classes} style={{ ...vars, ...style } as CSSProperties} ref={ref}>
      <span className="kodza-download-link__icon" aria-hidden="true">
        <svg viewBox="0 0 16 16" focusable="false">
          <path className="kodza-download-link__tray" d="M2.75 10.5v1.75c0 .69.56 1.25 1.25 1.25h8c.69 0 1.25-.56 1.25-1.25V10.5" />
          <g className="kodza-download-link__arrow">
            <path d="M8 2.5v7.25" />
            <path d="M4.75 6.5 8 9.75l3.25-3.25" />
          </g>
        </svg>
      </span>
      {' '}
      <span className="kodza-download-link__label">Download the reel</span>
      {' '}
      <span className="kodza-download-link__meta">
        <span className="kodza-download-link__type">MP4</span>
        {' '}
        <span className="kodza-download-link__size">4.3 MB</span>
      </span>
    </a>
  );
}
```

## Code

```html
<a class="kodza-download-link" href="https://kodza.dev/media/kz-reel.mp4" download data-kodza-download-link>
  <span class="kodza-download-link__icon" aria-hidden="true"><svg viewBox="0 0 16 16" focusable="false"><path class="kodza-download-link__tray" d="M2.75 10.5v1.75c0 .69.56 1.25 1.25 1.25h8c.69 0 1.25-.56 1.25-1.25V10.5" /><g class="kodza-download-link__arrow"><path d="M8 2.5v7.25" /><path d="M4.75 6.5 8 9.75l3.25-3.25" /></g></svg></span>
  <span class="kodza-download-link__label">Download the reel</span>
  <span class="kodza-download-link__meta"><span class="kodza-download-link__type">MP4</span> <span class="kodza-download-link__size">4.3 MB</span></span>
</a>
```

```css
/* Kodza License: free to use, client work included. Not to resell or redistribute, ported or not: https://kodza.dev/docs/#print-license */
/* Kodza — Download Link
   A link that says what it gets: the file's type and weight in mono beside the words
   ("MP4 · 4.3 MB"). On hover the arrow sinks into its tray; on a click it goes through and comes
   back from the top. Written in the link, type and weight read without the script; with it, the
   weight is read on the file itself, so it stays right when the file is replaced.
   Tuned with the --kz-download-link-* variables (for the File blocks of a WordPress article, on
   .wp-block-file .kodza-download-link). */
.kodza-download-link {
  --kz-download-link-gap: 0.32em;
  --kz-download-link-icon: 0.82em;
  --kz-download-link-meta: color-mix(in srgb, currentColor 64%, transparent);
  --kz-download-link-duration: 0.25s;
  --kz-download-link-ease: cubic-bezier(0.22, 1, 0.36, 1);

  display: inline-flex;
  align-items: baseline;
  gap: var(--kz-download-link-gap);
  color: inherit;
  text-decoration: none;
  -webkit-tap-highlight-color: transparent;
}

.kodza-download-link:focus-visible {
  outline: 2px solid currentColor;
  outline-offset: 4px;
  border-radius: 3px;
}

/* The arrow's mask: what goes through the bottom comes back from the top */
.kodza-download-link__icon {
  display: inline-block;
  flex: none;
  align-self: center;
  width: var(--kz-download-link-icon);
  height: var(--kz-download-link-icon);
  overflow: hidden;
}

.kodza-download-link__icon svg {
  display: block;
  width: 100%;
  height: 100%;
  fill: none;
  stroke: currentColor;
  stroke-width: 1.7;
  stroke-linecap: round;
  stroke-linejoin: round;
}

.kodza-download-link__arrow {
  transition: translate var(--kz-download-link-duration) var(--kz-download-link-ease);
}

.kodza-download-link:hover .kodza-download-link__arrow,
.kodza-download-link:focus-visible .kodza-download-link__arrow {
  translate: 0 2px;
}

/* Type and weight, in mono, a dot between them */
.kodza-download-link__meta {
  display: inline-flex;
  flex: none;
  align-items: baseline;
  margin-inline-start: 0.15em;
  color: var(--kz-download-link-meta);
  font: 500 max(12px, 0.44em)/1.5 "Geist Mono", ui-monospace, "SF Mono", Menlo, monospace;
  letter-spacing: 0;
  text-transform: none;
  white-space: nowrap;
}

.kodza-download-link__type,
.kodza-download-link__size {
  position: relative;
  display: inline-block;
  box-sizing: border-box;
}

.kodza-download-link__size {
  padding-inline-start: 1.1em;
  background: radial-gradient(circle, currentColor 0 1.5px, transparent 2px) no-repeat calc(0.55em - 2px) 50% / 4px 4px;
}

.kodza-download-link__size:dir(rtl) {
  background-position: calc(100% - 0.55em + 2px) 50%;
}

.kodza-download-link__type:empty,
.kodza-download-link__size:empty,
.kodza-download-link__meta:not(:has(> :not(:empty))) {
  display: none;
}

.kodza-download-link__type:empty + .kodza-download-link__size {
  padding-inline-start: 0;
  background: none;
}

/* A weight that changes rolls: the old one up and out, the new one in from below */
.kodza-download-link__size.is-rolling {
  clip-path: inset(0);
}

.kodza-download-link__now {
  display: inline-block;
}

.kodza-download-link__was {
  position: absolute;
}

/* The empty root that dresses the File blocks of its article holds nothing to see */
.kodza-download-link:not(a) {
  display: none;
}

@media (prefers-reduced-motion: reduce) {
  .kodza-download-link__arrow {
    transition-duration: 0.01ms !important;
  }
}

/* kodza-guard bfcc9eec0bb6 — 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, where the component sets it only in some states: at the lowest weight, so its own rules below put it back */

:where(.kodza-download-link):not(#_) {
  border-radius: revert;
  outline: revert;
  outline-offset: revert;
}

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

.kodza-download-link:not(#_) {
  border: revert;
  padding: revert;
  transition: revert;
  list-style: revert;
  box-sizing: revert;
  position: revert;
  background-color: revert;
  background-image: revert;
  box-shadow: revert;
  appearance: revert;
  max-height: revert;
  font-family: revert;
  font-size: revert;
  font-weight: revert;
  font-style: revert;
  line-height: revert;
  letter-spacing: revert;
  text-transform: revert;
  text-underline-offset: revert;
  text-align: revert;
  text-indent: revert;
  text-shadow: revert;
  vertical-align: revert;
}

.kodza-download-link__icon:not(#_),
.kodza-download-link__tray:not(#_),
.kodza-download-link__arrow:not(#_),
.kodza-download-link__label:not(#_),
.kodza-download-link__meta:not(#_) {
  box-sizing: revert;
}

.kodza-download-link__icon svg:where(:not([class*="kodza-"])):not(#_) {
  border: revert;
  margin: revert;
  padding: revert;
  border-radius: revert;
  outline: revert;
  text-decoration: revert;
  transition: revert;
  list-style: revert;
  box-sizing: revert;
  float: revert;
  position: revert;
  background-color: revert;
  background-image: revert;
  box-shadow: revert;
  outline-offset: revert;
  appearance: revert;
  max-width: revert;
  max-height: revert;
  color: revert;
  font-family: revert;
  font-size: revert;
  font-weight: revert;
  font-style: revert;
  line-height: revert;
  letter-spacing: revert;
  text-transform: revert;
  text-underline-offset: revert;
  text-align: revert;
  text-indent: revert;
  text-shadow: revert;
  vertical-align: revert;
}

/* The component's own rules, one step stronger: real buttons and fields, what it sets on tags themes style (links, lists, headings, images…), and the root width (a theme may narrow it, never widen it) */

.kodza-download-link:not(#_) {
  display: inline-flex;
  color: inherit;
  text-decoration: none;
}

.kodza-download-link:focus-visible:not(#_) {
  outline: 2px solid currentColor;
  outline-offset: 4px;
  border-radius: 3px;
}

.kodza-download-link__icon svg:not(#_) {
  display: block;
}

.kodza-download-link:not(a):not(#_) {
  display: none;
}
```

```js
// Kodza License: free to use, client work included. Not to resell or redistribute, ported or not: https://kodza.dev/docs/#print-license
// Kodza — Download Link
// Reads the file's weight on the file itself (one HEAD request, same site only, once per file for
// the whole page) and rolls it in if the link said otherwise. A click sends the arrow through its
// tray and back from the top. An empty root (<div data-kodza-download-link></div>, a Custom HTML
// block in WordPress) dresses the File blocks of the article around or beside it (data-target).
(() => {
  const SELECTOR = '[data-kodza-download-link]';
  const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
  const UNITS = ['byte', 'kilobyte', 'megabyte', 'gigabyte'];
  const EASE = 'cubic-bezier(0.22, 1, 0.36, 1)';
  const sizes = new Map();

  // The icon, written once and copied for each File block
  const ICON = '<span class="kodza-download-link__icon" aria-hidden="true"><svg viewBox="0 0 16 16" focusable="false"><path class="kodza-download-link__tray" d="M2.75 10.5v1.75c0 .69.56 1.25 1.25 1.25h8c.69 0 1.25-.56 1.25-1.25V10.5" /><g class="kodza-download-link__arrow"><path d="M8 2.5v7.25" /><path d="M4.75 6.5 8 9.75l3.25-3.25" /></g></svg></span>';
  const META = '<span class="kodza-download-link__meta"><span class="kodza-download-link__type"></span> <span class="kodza-download-link__size"></span></span>';

  // "PDF" from the file's extension, or from its media type when the address has none
  const typeOf = (url, mime = '') => {
    const ext = url.pathname.match(/\.([a-z0-9]{2,5})$/i)?.[1];
    if (ext) return ext.toUpperCase();
    const sub = mime.split(';')[0].split('/')[1] || '';
    return sub.length <= 5 ? sub.toUpperCase() : '';
  };

  // "4.3 MB" in English, "4,3 Mo" on a French page
  const sizeOf = (bytes, lang) => {
    let n = bytes;
    let i = 0;
    while (n >= 1000 && i < UNITS.length - 1) { n /= 1000; i += 1; }
    const options = { style: 'unit', unit: UNITS[i], unitDisplay: 'short', maximumFractionDigits: i && n < 10 ? 1 : 0 };
    try { return new Intl.NumberFormat(lang, options).format(n); } catch { return new Intl.NumberFormat('en', options).format(n); }
  };

  // One HEAD request per file. Not the site's page answering for a missing file, not a compressed length
  const weigh = (url) => {
    if (!sizes.has(url.href)) {
      sizes.set(url.href, fetch(url.href, { method: 'HEAD', cache: 'no-cache' }).then((res) => {
        const mime = res.headers.get('content-type') || '';
        const bytes = Number(res.headers.get('content-length'));
        const packed = !/^(identity)?$/i.test(res.headers.get('content-encoding') || '');
        const page = /^text\/html/i.test(mime) && !/\.html?$/i.test(url.pathname);
        return res.ok && bytes > 0 && !packed && !page ? { bytes, mime } : null;
      }).catch(() => null));
    }
    return sizes.get(url.href);
  };

  // The old text goes up out of its mask while the new one comes up from below, the width
  // following from one to the other
  const roll = (el, text, signal) => {
    const before = el.textContent;
    if (before === text) return;
    if (reduceMotion || !el.parentElement?.offsetParent) { el.textContent = text; return; }
    const from = before ? el.offsetWidth : 0;
    const was = document.createElement('span');
    was.className = 'kodza-download-link__was';
    was.setAttribute('aria-hidden', 'true');
    was.textContent = before;
    const now = document.createElement('span');
    now.className = 'kodza-download-link__now';
    now.textContent = text;
    el.replaceChildren(now);
    const to = el.offsetWidth;
    const pad = getComputedStyle(el).paddingInlineStart;
    if (before) el.prepend(was);
    el.classList.add('is-rolling');
    const timing = { duration: 460, easing: EASE };
    const moves = [
      now.animate([{ transform: 'translateY(100%)' }, { transform: 'none' }], timing),
      el.animate(before
        ? [{ width: `${from}px` }, { width: `${to}px` }]
        : [{ width: '0px', paddingInlineStart: '0px' }, { width: `${to}px`, paddingInlineStart: pad }], timing),
    ];
    if (before) moves.push(was.animate([{ transform: 'none' }, { transform: 'translateY(-100%)' }], timing));
    signal.addEventListener('abort', () => moves.forEach((move) => move.cancel()), { once: true });
    moves[0].finished.then(() => {
      el.classList.remove('is-rolling');
      el.textContent = text;
    }, () => {});
  };

  // One link: its type from the address, its weight from the file, its arrow on a click
  const dress = (link, signal, watcher) => {
    const type = link.querySelector('.kodza-download-link__type');
    const size = link.querySelector('.kodza-download-link__size');
    const arrow = link.querySelector('.kodza-download-link__arrow');
    const tray = link.querySelector('.kodza-download-link__tray');
    let url;
    try { url = new URL(link.href, location.href); } catch { return; }
    if (type && !type.textContent.trim()) type.textContent = typeOf(url);

    let moves = [];
    link.addEventListener('click', () => {
      if (reduceMotion || !arrow) return;
      moves.forEach((move) => move.cancel());
      // Down and faster into the tray, out through its floor, then back in from the top
      moves = [
        arrow.animate([
          { transform: 'none', easing: 'cubic-bezier(0.55, 0, 1, 0.45)' },
          { transform: 'translateY(15px)', offset: 0.4 },
          { transform: 'translateY(-15px)', offset: 0.4, easing: EASE },
          { transform: 'none' },
        ], { duration: 720 }),
        tray?.animate([
          { transform: 'none', easing: 'cubic-bezier(0.65, 0, 0.35, 1)' },
          { transform: 'translateY(1.25px)', offset: 0.38, easing: EASE },
          { transform: 'none' },
        ], { duration: 720 }),
      ].filter(Boolean);
    }, { signal });

    // Same site only (the browser would not say, nor save under another site's name), never the page itself
    const local = /^https?:$/.test(url.protocol) && url.origin === location.origin && url.pathname !== location.pathname;
    if (!size || !local) return;
    const lang = link.closest('[lang]')?.lang || 'en';
    watcher.add(link, () => weigh(url).then((file) => {
      if (!file || signal.aborted) return;
      if (type && !type.textContent.trim()) type.textContent = typeOf(url, file.mime);
      roll(size, sizeOf(file.bytes, lang), signal);
    }));
  };

  // The weight is asked for when the link comes near the screen, not for every file of the page at once
  const watch = (signal) => {
    const calls = new Map();
    const observer = new IntersectionObserver((entries) => entries.forEach(({ isIntersecting, target }) => {
      if (!isIntersecting) return;
      observer.unobserve(target);
      calls.get(target)?.();
    }), { rootMargin: '200px' });
    signal.addEventListener('abort', () => observer.disconnect(), { once: true });
    return { add: (link, call) => { calls.set(link, call); observer.observe(link); } };
  };

  // One instance, with its own state: two copies on a page never interfere. Everything it
  // starts is tied to `signal` (listeners get { signal }, observers and timers stop on its
  // 'abort' event), so kodza:destroy stops it all.
  function mount(root, signal) {
    const watcher = watch(signal);
    if (root.matches('a[href]')) { dress(root, signal, watcher); return; }

    // An empty root: the File blocks of its article, their file name made the link, the button hidden
    const selector = root.dataset.target || 'article, main, .entry-content';
    let scope = root.parentElement?.closest(selector);
    for (let up = root.parentElement; !scope && up; up = up.parentElement) scope = up.querySelector(selector);
    if (!scope) return;
    scope.querySelectorAll('.wp-block-file').forEach((block) => {
      if (block.parentElement.closest('[class*="kodza-"]')) return;
      const button = block.querySelector('a.wp-block-file__button');
      const link = block.querySelector('a[href]:not(.wp-block-file__button)') || button;
      if (!link || link.classList.contains('kodza-download-link')) return;
      const saved = { html: link.innerHTML, className: link.getAttribute('class'), download: link.getAttribute('download'), hidden: button?.hidden };
      const label = document.createElement('span');
      label.className = 'kodza-download-link__label';
      label.append(...link.childNodes);
      link.replaceChildren(label);
      // The spaces keep the words apart for a screen reader; the flex layout ignores them
      link.insertAdjacentHTML('afterbegin', `${ICON} `);
      link.insertAdjacentHTML('beforeend', ` ${META}`);
      link.classList.add('kodza-download-link');
      if (button?.hasAttribute('download') && !link.hasAttribute('download')) link.setAttribute('download', button.getAttribute('download'));
      if (button && button !== link) button.hidden = true;
      dress(link, signal, watcher);
      signal.addEventListener('abort', () => {
        link.innerHTML = saved.html;
        if (saved.className === null) link.removeAttribute('class');
        else link.setAttribute('class', saved.className);
        if (saved.download === null) link.removeAttribute('download');
        if (button && button !== link) button.hidden = saved.hidden;
      }, { 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.
  const KODZA = Symbol.for('kodza');
  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) => {
    if (root.classList.contains('is-ready')) return; // already running, maybe from another copy of this script
    const controller = new AbortController();
    const saved = { html: written(root), attrs: attrsOf(root), stop: () => destroy(root) };
    instances.set(root, { controller, saved });
    root[KODZA] = saved;
    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);
    // 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[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).
