# Morphing Text

Morphing Text is two lines of large type that squeeze and stretch after the cursor like a soft sculpture.

- Live demo: https://dmivanov.ru/experiments/morphing-text
- Original CodePen: https://codepen.io/divulture/pen/gbOrmQz

## 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 `morphing-text.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="morphing-text" style="position: relative; width: 100%; height: 480px;"></div>
   ```

3. Mount the effect from a module script:

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

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

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 |
| --- | --- | --- | --- |
| `line1` | Top line | `"SCULPTING"` | text, up to 12 chars |
| `line2` | Bottom line | `"HARMONY"` | text, up to 12 chars |
| `minScale` | Squeeze | `0.5` | 0.1–1 x |
| `maxScale` | Stretch | `1.4` | 1–2 x |
| `textColor` | Text color | `"#e6edf2"` | 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));
}
```

## morphing-text.js

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

export const meta = {
  slug: "morphing-text",
  description: "Morphing Text is two lines of large type that squeeze and stretch after the cursor like a soft sculpture.",
  title: "Morphing Text",
  codepen: "https://codepen.io/divulture/pen/gbOrmQz",
  replay: false,
  fonts: [{ family: "Notable", href: "https://fonts.googleapis.com/css2?family=Notable&display=swap" }],
  controls: [
    { key: "line1", label: "Top line", type: "text", maxlength: 12, uppercase: true },
    { key: "line2", label: "Bottom line", type: "text", maxlength: 12, uppercase: true },
    { key: "minScale", label: "Squeeze", type: "range", min: 0.1, max: 1, step: 0.05, unit: "x" },
    { key: "maxScale", label: "Stretch", type: "range", min: 1, max: 2, step: 0.05, unit: "x" },
    { key: "textColor", label: "Text color", type: "color" },
    { key: "background", label: "Background", type: "color" }
  ],
  defaults: {
    line1: "SCULPTING",
    line2: "HARMONY",
    minScale: 0.5,
    maxScale: 1.4,
    textColor: "#e6edf2",
    background: "#171717"
  }
};

const CSS = `
.fx-morphing { position: absolute; inset: 0; display: grid; place-items: center; overflow: hidden; background: var(--fx-bg); color: var(--fx-fg); touch-action: none; user-select: none; }
.fx-morphing__text { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%) scale(var(--fx-fit, 1)); font-family: "Notable", sans-serif; line-height: .8; text-align: center; text-transform: uppercase; white-space: nowrap; }
.fx-morphing__line { display: block; }
.fx-morphing__letter { display: inline-block; transition: transform .4s ease-out; }
.fx-morphing__line:first-child .fx-morphing__letter { transform-origin: center top; }
.fx-morphing__line:last-child .fx-morphing__letter { transform-origin: center bottom; }
`;

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

  function line(value) {
    const element = document.createElement("span");
    element.className = "fx-morphing__line";
    element.append(...Array.from(String(value || " "), (character) => {
      const letter = document.createElement("span");
      letter.className = "fx-morphing__letter";
      letter.textContent = character === " " ? " " : character;
      return letter;
    }));
    return element;
  }

  // The two lines are laid out at a fixed size and scaled into the safe area.
  function render() {
    root.style.setProperty("--fx-bg", settings.background);
    root.style.setProperty("--fx-fg", settings.textColor);
    text.replaceChildren(line(settings.line1), line(settings.line2));
    text.style.fontSize = "200px";
    fitElement(stage, text, { grow: true });
  }

  function onMove(event) {
    const point = localPoint(stage, event);
    const lower = point.y > root.clientHeight / 2;
    const maxDistance = root.clientWidth / 2;
    const stageLeft = stage.getBoundingClientRect().left;
    const { minScale, maxScale } = settings;
    text.querySelectorAll(".fx-morphing__line").forEach((lineElement, lineIndex) => {
      lineElement.querySelectorAll(".fx-morphing__letter").forEach((letter) => {
        const rect = letter.getBoundingClientRect();
        const factor = Math.max(0, 1 - Math.abs(rect.left - stageLeft + rect.width / 2 - point.x) / maxDistance);
        const scale = lineIndex === 0
          ? (lower ? maxScale : minScale + factor * (maxScale - minScale))
          : (lower ? minScale : maxScale - factor * (maxScale - minScale));
        letter.style.transform = `scaleY(${scale})`;
      });
    });
  }
  function onLeave() {
    text.querySelectorAll(".fx-morphing__letter").forEach((letter) => { letter.style.transform = ""; });
  }

  if (mode === "live") {
    stage.addEventListener("pointermove", onMove);
    stage.addEventListener("pointerleave", onLeave);
  }
  const stopWatching = watchSize(stage, render);
  render();
  loadFonts(meta.fonts).then(render);

  return {
    update(next) {
      settings = { ...settings, ...next };
      render();
    },
    replay() {},
    destroy() {
      stage.removeEventListener("pointermove", onMove);
      stage.removeEventListener("pointerleave", onLeave);
      stopWatching();
      root.remove();
    }
  };
}
```
