# Zajno Text Interaction

Zajno Text Interaction is a word cut into an invisible grid. Under the cursor the cells shift along with the movement, and the letters briefly break into pixel fragments.

- Live demo: https://dmivanov.ru/experiments/zajno
- Original CodePen: https://codepen.io/divulture/pen/wBvvmQb

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

3. Mount the effect from a module script:

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

     const effect = mount(document.getElementById("zajno"), { ...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 |
| --- | --- | --- | --- |
| `text` | Text | `"zajno"` | text, up to 10 chars |
| `size` | Size | `400` | 100–560 px |
| `cell` | Cell | `32` | 16–64 px |
| `radius` | Radius | `64` | 24–200 px |
| `strength` | Strength | `2` | 0.5–5 x |
| `textColor` | Text color | `"#000000"` | hex color |
| `background` | Background | `"#ffffff"` | 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));
}
```

## zajno.js

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

export const meta = {
  slug: "zajno",
  description: "Zajno Text Interaction is a word cut into an invisible grid. Under the cursor the cells shift along with the movement, and the letters briefly break into pixel fragments.",
  title: "Zajno Text Interaction",
  codepen: "https://codepen.io/divulture/pen/wBvvmQb",
  replay: false,
  fonts: [{ family: "MuseoModerno", href: "https://fonts.googleapis.com/css2?family=MuseoModerno&display=swap" }],
  controls: [
    { key: "text", label: "Text", type: "text", maxlength: 10 },
    { key: "size", label: "Size", type: "range", min: 100, max: 560, step: 10, unit: "px" },
    { key: "cell", label: "Cell", type: "range", min: 16, max: 64, step: 4, unit: "px" },
    { key: "radius", label: "Radius", type: "range", min: 24, max: 200, step: 4, unit: "px" },
    { key: "strength", label: "Strength", type: "range", min: 0.5, max: 5, step: 0.5, unit: "x" },
    { key: "textColor", label: "Text color", type: "color" },
    { key: "background", label: "Background", type: "color" }
  ],
  defaults: {
    text: "zajno",
    size: 400,
    cell: 32,
    radius: 64,
    strength: 2,
    textColor: "#000000",
    background: "#ffffff"
  }
};

const CSS = `
.fx-zajno { position: absolute; inset: 0; overflow: hidden; background: var(--fx-bg); cursor: pointer; touch-action: none; }
.fx-zajno__cell { position: absolute; background-repeat: no-repeat; transition: background-position .2s ease-out; }
`;

const MAX_SHIFT = 20;

export function mount(stage, initialSettings, { mode = "live", preview = false } = {}) {
  injectStyle("fx-zajno-style", CSS);
  let settings = { ...meta.defaults, ...initialSettings };
  const root = document.createElement("div");
  root.className = "fx-zajno";
  stage.append(root);
  let cells = [];
  let cellSize = 32;
  let previous = null;

  // The word is drawn once to a canvas; every cell shows its own slice of it.
  function picture(width, height, unit) {
    const dpr = Math.min(window.devicePixelRatio || 1, 2);
    const canvas = document.createElement("canvas");
    canvas.width = width * dpr;
    canvas.height = height * dpr;
    const ctx = canvas.getContext("2d");
    ctx.scale(dpr, dpr);
    let size = settings.size * unit;
    ctx.font = `${size}px MuseoModerno`;
    ctx.letterSpacing = `${-size * .1}px`;
    const metrics = ctx.measureText(settings.text);
    size *= fitScale(stage, metrics.width, metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent, { grow: preview, fill: .8 });
    ctx.font = `${size}px MuseoModerno`;
    ctx.fillStyle = settings.textColor;
    ctx.textBaseline = "middle";
    ctx.letterSpacing = `${-size * .1}px`;
    ctx.textAlign = "center";
    ctx.fillText(settings.text, width / 2, height / 2);
    return canvas.toDataURL();
  }

  function render() {
    const unit = stageUnit(stage);
    const width = root.clientWidth;
    const height = root.clientHeight;
    root.style.setProperty("--fx-bg", settings.background);
    const url = `url("${picture(width, height, unit)}")`;
    root.replaceChildren();
    cells = [];
    if (mode !== "live") {
      const still = document.createElement("div");
      still.className = "fx-zajno__cell";
      Object.assign(still.style, { inset: "0", backgroundImage: url, backgroundSize: `${width}px ${height}px` });
      root.append(still);
      return;
    }
    cellSize = Math.max(8, Math.round(settings.cell * unit));
    const cols = Math.ceil(width / cellSize);
    const rows = Math.ceil(height / cellSize);
    const fragment = document.createDocumentFragment();
    for (let row = 0; row < rows; row++) {
      for (let col = 0; col < cols; col++) {
        const cell = document.createElement("div");
        cell.className = "fx-zajno__cell";
        const baseX = -col * cellSize;
        const baseY = -row * cellSize;
        Object.assign(cell.style, {
          width: `${cellSize}px`,
          height: `${cellSize}px`,
          left: `${col * cellSize}px`,
          top: `${row * cellSize}px`,
          backgroundImage: url,
          backgroundSize: `${width}px ${height}px`,
          backgroundPosition: `${baseX}px ${baseY}px`
        });
        fragment.append(cell);
        cells.push({ cell, baseX, baseY, cx: col * cellSize + cellSize / 2, cy: row * cellSize + cellSize / 2 });
      }
    }
    root.append(fragment);
  }

  // Cells near the pointer slide their slice in the direction of movement.
  function onMove(event) {
    const point = localPoint(stage, event);
    const dx = previous ? point.x - previous.x : 0;
    const dy = previous ? point.y - previous.y : 0;
    previous = point;
    const shiftX = Math.max(-MAX_SHIFT, Math.min(MAX_SHIFT, dx * settings.strength));
    const shiftY = Math.max(-MAX_SHIFT, Math.min(MAX_SHIFT, dy * settings.strength));
    const reach = settings.radius * stageUnit(stage);
    cells.forEach((item) => {
      if (Math.hypot(point.x - item.cx, point.y - item.cy) >= reach) return;
      item.cell.style.backgroundPosition = `${item.baseX + shiftX}px ${item.baseY + shiftY}px`;
      setTimeout(() => { item.cell.style.backgroundPosition = `${item.baseX}px ${item.baseY}px`; }, 100);
    });
  }
  function onLeave() {
    previous = null;
    cells.forEach((item) => { item.cell.style.backgroundPosition = `${item.baseX}px ${item.baseY}px`; });
  }

  if (mode === "live") {
    stage.addEventListener("pointermove", onMove);
    stage.addEventListener("pointerleave", onLeave);
  }
  const stopWatching = watchSize(stage, 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();
    }
  };
}
```
