# Magnet

Wrapper that pulls its content toward a nearby mouse, or pushes it away, then springs back. Inner layers can travel further for depth.

- Category: MarkasUI
- Status: stable
- Registry: https://markas.jenderalcorp.com/r/magnet.json
- CLI: `npx markasui@latest add magnet`

## When to use

One or a few targets that invite a click: a hero or pricing call to action, social icons in a footer, the main action in a navbar.

- Wrap a single focused element; do not wrap whole forms or long lists
- Keep strength between 0.2 and 0.5 and radius under about 100 so targets stay easy to hit
- Use repel only on decorative or playful elements, never on a button people need
- Give icon-only links an aria-label

## Code

### Blade

Save at `resources/views/components/markas/magnet.blade.php`. Dependencies: alpinejs.

```blade
@props([
    'strength' => 0.35,
    'radius' => 80,
    'mode' => 'attract',
])

@php
    $base = 'w-fit transition-[translate,scale] duration-500 ease-[cubic-bezier(0.34,1.56,0.64,1)] has-[:focus-visible]:scale-105 data-[state=active]:duration-150 data-[state=active]:ease-out motion-reduce:transition-none [&_[data-depth]]:inline-block [&_[data-depth]]:transition-[translate] [&_[data-depth]]:duration-500 [&_[data-depth]]:ease-[cubic-bezier(0.34,1.56,0.64,1)] data-[state=active]:[&_[data-depth]]:duration-150 motion-reduce:[&_[data-depth]]:transition-none';
@endphp

{{-- Pulls the element toward (or pushes it away from) a mouse within radius px of its edges, then lets it spring back. Children with data-depth="0.5" travel that much further. Listens only while on screen. --}}
<div
    wire:ignore.self
    x-data="{
        stop: null,
        init() {
            if (matchMedia('(prefers-reduced-motion: reduce)').matches) return;
            const o = { strength: @js((float) $strength), radius: @js((float) $radius), mode: @js($mode) };
            const root = this.$el;
            let x = 0;
            let y = 0;
            const set = (nx, ny) => {
                x = nx;
                y = ny;
                if (x || y) root.dataset.state = 'active';
                else delete root.dataset.state;
                root.style.translate = x || y ? `${x}px ${y}px` : '';
                for (const layer of root.querySelectorAll('[data-depth]')) {
                    const depth = Number(layer.dataset.depth) || 0;
                    layer.style.translate = x || y ? `${x * depth}px ${y * depth}px` : '';
                }
            };
            const move = (e) => {
                if (e.pointerType === 'touch') return;
                const r = root.getBoundingClientRect();
                const dx = e.clientX - (r.left + r.width / 2 - x);
                const dy = e.clientY - (r.top + r.height / 2 - y);
                const gap = Math.hypot(Math.max(Math.abs(dx) - r.width / 2, 0), Math.max(Math.abs(dy) - r.height / 2, 0));
                const near = Math.max(1 - gap / o.radius, 0);
                if (o.mode === 'repel') {
                    const push = (near * o.radius * o.strength) / (Math.hypot(dx, dy) || 1);
                    return set(-dx * push, -dy * push);
                }
                set(dx * near * o.strength, dy * near * o.strength);
            };
            const reset = () => set(0, 0);
            const html = document.documentElement;
            const listen = (on) => {
                if (on) {
                    document.addEventListener('pointermove', move);
                    html.addEventListener('pointerleave', reset);
                    return;
                }
                document.removeEventListener('pointermove', move);
                html.removeEventListener('pointerleave', reset);
                reset();
            };
            const observer = typeof IntersectionObserver === 'undefined' ? null : new IntersectionObserver(([entry]) => listen(!! entry?.isIntersecting));
            if (observer) observer.observe(root);
            else listen(true);
            this.stop = () => {
                observer?.disconnect();
                listen(false);
            };
        },
        destroy() {
            this.stop?.();
        },
    }"
    {{ $attributes->class([$base]) }}
>
    {{ $slot }}
</div>
```

```blade
<x-markas.magnet>
    <x-markas.button size="lg">
        Get started <span data-depth="0.5">&rarr;</span>
    </x-markas.button>
</x-markas.magnet>
```

Needs Alpine.js.

### React

Save at `src/components/markas/Magnet.tsx`. No extra dependencies.

```tsx
"use client";

import { useEffect, useRef, type ComponentProps } from "react";

const base =
  "w-fit transition-[translate,scale] duration-500 ease-[cubic-bezier(0.34,1.56,0.64,1)] has-[:focus-visible]:scale-105 data-[state=active]:duration-150 data-[state=active]:ease-out motion-reduce:transition-none [&_[data-depth]]:inline-block [&_[data-depth]]:transition-[translate] [&_[data-depth]]:duration-500 [&_[data-depth]]:ease-[cubic-bezier(0.34,1.56,0.64,1)] data-[state=active]:[&_[data-depth]]:duration-150 motion-reduce:[&_[data-depth]]:transition-none";

export type MagnetMode = "attract" | "repel";
type Options = { strength: number; radius: number; mode: MagnetMode };

const cx = (...c: (string | false | null | undefined)[]) =>
  c.filter(Boolean).join(" ");
const still = () =>
  window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;

/**
 * Pull the element toward (or push it away from) a mouse within `radius` px of its edges, then let
 * it spring back. Children with data-depth="0.5" travel that much further. Listens only while on screen.
 */
export function startMagnet(root: HTMLElement, o: Options) {
  let x = 0;
  let y = 0;
  const set = (nx: number, ny: number) => {
    x = nx;
    y = ny;
    if (x || y) root.dataset.state = "active";
    else delete root.dataset.state;
    root.style.translate = x || y ? `${x}px ${y}px` : "";
    for (const layer of root.querySelectorAll<HTMLElement>("[data-depth]")) {
      const depth = Number(layer.dataset.depth) || 0;
      layer.style.translate = x || y ? `${x * depth}px ${y * depth}px` : "";
    }
  };
  const move = (e: PointerEvent) => {
    if (e.pointerType === "touch") return;
    const r = root.getBoundingClientRect();
    const dx = e.clientX - (r.left + r.width / 2 - x);
    const dy = e.clientY - (r.top + r.height / 2 - y);
    const gap = Math.hypot(
      Math.max(Math.abs(dx) - r.width / 2, 0),
      Math.max(Math.abs(dy) - r.height / 2, 0),
    );
    const near = Math.max(1 - gap / o.radius, 0);
    if (o.mode === "repel") {
      const push = (near * o.radius * o.strength) / (Math.hypot(dx, dy) || 1);
      return set(-dx * push, -dy * push);
    }
    set(dx * near * o.strength, dy * near * o.strength);
  };
  const reset = () => set(0, 0);
  const html = document.documentElement;
  const listen = (on: boolean) => {
    if (on) {
      document.addEventListener("pointermove", move);
      html.addEventListener("pointerleave", reset);
      return;
    }
    document.removeEventListener("pointermove", move);
    html.removeEventListener("pointerleave", reset);
    reset();
  };
  const observer =
    typeof IntersectionObserver === "undefined"
      ? undefined
      : new IntersectionObserver(([entry]) => listen(!!entry?.isIntersecting));
  if (observer) observer.observe(root);
  else listen(true);
  return () => {
    observer?.disconnect();
    listen(false);
  };
}

export type MagnetProps = ComponentProps<"div"> & {
  /** Share of the pointer distance the element follows, 0 to 1. For repel, how far it is pushed. */
  strength?: number;
  /** Distance in px beyond the element edges where the pull starts. */
  radius?: number;
  /** Move toward the pointer or away from it. */
  mode?: MagnetMode;
};

export function Magnet({
  strength = 0.35,
  radius = 80,
  mode = "attract",
  className,
  children,
  ...props
}: MagnetProps) {
  const ref = useRef<HTMLDivElement>(null);
  useEffect(() => {
    if (!ref.current || still()) return;
    return startMagnet(ref.current, { strength, radius, mode });
  }, [strength, radius, mode]);
  return (
    <div ref={ref} {...props} className={cx(base, className)}>
      {children}
    </div>
  );
}
```

```tsx
import { Magnet } from "@/components/markas/Magnet";

<Magnet strength={0.5} radius={32}>
  <a
    href="/contact"
    aria-label="Email"
    className="grid size-10 place-items-center rounded-full border border-line"
  >
    ...
  </a>
</Magnet>;
```

### Vue

Save at `src/components/markas/Magnet.vue`. No extra dependencies.

```vue
<script setup lang="ts">
import { onBeforeUnmount, onMounted, useTemplateRef, watch } from "vue";

const props = withDefaults(
  defineProps<{
    /** Share of the pointer distance the element follows, 0 to 1. For repel, how far it is pushed. */
    strength?: number;
    /** Distance in px beyond the element edges where the pull starts. */
    radius?: number;
    /** Move toward the pointer or away from it. */
    mode?: "attract" | "repel";
  }>(),
  { strength: 0.35, radius: 80, mode: "attract" },
);

const base =
  "w-fit transition-[translate,scale] duration-500 ease-[cubic-bezier(0.34,1.56,0.64,1)] has-[:focus-visible]:scale-105 data-[state=active]:duration-150 data-[state=active]:ease-out motion-reduce:transition-none [&_[data-depth]]:inline-block [&_[data-depth]]:transition-[translate] [&_[data-depth]]:duration-500 [&_[data-depth]]:ease-[cubic-bezier(0.34,1.56,0.64,1)] data-[state=active]:[&_[data-depth]]:duration-150 motion-reduce:[&_[data-depth]]:transition-none";

type MagnetMode = "attract" | "repel";
type Options = { strength: number; radius: number; mode: MagnetMode };

const still = () =>
  window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;

/**
 * Pull the element toward (or push it away from) a mouse within `radius` px of its edges, then let
 * it spring back. Children with data-depth="0.5" travel that much further. Listens only while on screen.
 */
function startMagnet(root: HTMLElement, o: Options) {
  let x = 0;
  let y = 0;
  const set = (nx: number, ny: number) => {
    x = nx;
    y = ny;
    if (x || y) root.dataset.state = "active";
    else delete root.dataset.state;
    root.style.translate = x || y ? `${x}px ${y}px` : "";
    for (const layer of root.querySelectorAll<HTMLElement>("[data-depth]")) {
      const depth = Number(layer.dataset.depth) || 0;
      layer.style.translate = x || y ? `${x * depth}px ${y * depth}px` : "";
    }
  };
  const move = (e: PointerEvent) => {
    if (e.pointerType === "touch") return;
    const r = root.getBoundingClientRect();
    const dx = e.clientX - (r.left + r.width / 2 - x);
    const dy = e.clientY - (r.top + r.height / 2 - y);
    const gap = Math.hypot(
      Math.max(Math.abs(dx) - r.width / 2, 0),
      Math.max(Math.abs(dy) - r.height / 2, 0),
    );
    const near = Math.max(1 - gap / o.radius, 0);
    if (o.mode === "repel") {
      const push = (near * o.radius * o.strength) / (Math.hypot(dx, dy) || 1);
      return set(-dx * push, -dy * push);
    }
    set(dx * near * o.strength, dy * near * o.strength);
  };
  const reset = () => set(0, 0);
  const html = document.documentElement;
  const listen = (on: boolean) => {
    if (on) {
      document.addEventListener("pointermove", move);
      html.addEventListener("pointerleave", reset);
      return;
    }
    document.removeEventListener("pointermove", move);
    html.removeEventListener("pointerleave", reset);
    reset();
  };
  const observer =
    typeof IntersectionObserver === "undefined"
      ? undefined
      : new IntersectionObserver(([entry]) => listen(!!entry?.isIntersecting));
  if (observer) observer.observe(root);
  else listen(true);
  return () => {
    observer?.disconnect();
    listen(false);
  };
}

const rootEl = useTemplateRef<HTMLDivElement>("rootRef");
let stop = () => {};
function start() {
  stop();
  stop = () => {};
  if (rootEl.value && !still()) stop = startMagnet(rootEl.value, { ...props });
}
onMounted(start);
watch(() => [props.strength, props.radius, props.mode], start, {
  flush: "post",
});
onBeforeUnmount(() => stop());
</script>

<template>
  <div ref="rootRef" :class="base">
    <slot />
  </div>
</template>
```

```vue
<template>
  <Magnet
    mode="repel"
    :strength="0.6"
    :radius="70"
    class="rounded-lg border-2 border-dashed px-4 py-2"
  >
    Rp 50.000 off
  </Magnet>
</template>
```

### Svelte

Save at `src/lib/components/markas/Magnet.svelte`. No extra dependencies.

```svelte
<script lang="ts">
  import type { Snippet } from "svelte";
  import type { HTMLAttributes } from "svelte/elements";

  const base =
    "w-fit transition-[translate,scale] duration-500 ease-[cubic-bezier(0.34,1.56,0.64,1)] has-[:focus-visible]:scale-105 data-[state=active]:duration-150 data-[state=active]:ease-out motion-reduce:transition-none [&_[data-depth]]:inline-block [&_[data-depth]]:transition-[translate] [&_[data-depth]]:duration-500 [&_[data-depth]]:ease-[cubic-bezier(0.34,1.56,0.64,1)] data-[state=active]:[&_[data-depth]]:duration-150 motion-reduce:[&_[data-depth]]:transition-none";

  type MagnetMode = "attract" | "repel";
  type Options = { strength: number; radius: number; mode: MagnetMode };

  const still = () =>
    window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;

  /**
   * Pull the element toward (or push it away from) a mouse within `radius` px of its edges, then
   * let it spring back. Children with data-depth="0.5" travel that much further. Listens only
   * while on screen.
   */
  function startMagnet(root: HTMLElement, o: Options) {
    let x = 0;
    let y = 0;
    const set = (nx: number, ny: number) => {
      x = nx;
      y = ny;
      if (x || y) root.dataset.state = "active";
      else delete root.dataset.state;
      root.style.translate = x || y ? `${x}px ${y}px` : "";
      for (const layer of root.querySelectorAll<HTMLElement>("[data-depth]")) {
        const depth = Number(layer.dataset.depth) || 0;
        layer.style.translate = x || y ? `${x * depth}px ${y * depth}px` : "";
      }
    };
    const move = (e: PointerEvent) => {
      if (e.pointerType === "touch") return;
      const r = root.getBoundingClientRect();
      const dx = e.clientX - (r.left + r.width / 2 - x);
      const dy = e.clientY - (r.top + r.height / 2 - y);
      const gap = Math.hypot(
        Math.max(Math.abs(dx) - r.width / 2, 0),
        Math.max(Math.abs(dy) - r.height / 2, 0),
      );
      const near = Math.max(1 - gap / o.radius, 0);
      if (o.mode === "repel") {
        const push = (near * o.radius * o.strength) / (Math.hypot(dx, dy) || 1);
        return set(-dx * push, -dy * push);
      }
      set(dx * near * o.strength, dy * near * o.strength);
    };
    const reset = () => set(0, 0);
    const html = document.documentElement;
    const listen = (on: boolean) => {
      if (on) {
        document.addEventListener("pointermove", move);
        html.addEventListener("pointerleave", reset);
        return;
      }
      document.removeEventListener("pointermove", move);
      html.removeEventListener("pointerleave", reset);
      reset();
    };
    const observer =
      typeof IntersectionObserver === "undefined"
        ? undefined
        : new IntersectionObserver(([entry]) =>
            listen(!!entry?.isIntersecting),
          );
    if (observer) observer.observe(root);
    else listen(true);
    return () => {
      observer?.disconnect();
      listen(false);
    };
  }

  type Props = HTMLAttributes<HTMLDivElement> & {
    /** Share of the pointer distance the element follows, 0 to 1. For repel, how far it is pushed. */
    strength?: number;
    /** Distance in px beyond the element edges where the pull starts. */
    radius?: number;
    /** Move toward the pointer or away from it. */
    mode?: MagnetMode;
    children?: Snippet;
  };

  let {
    strength = 0.35,
    radius = 80,
    mode = "attract",
    class: className,
    children,
    ...rest
  }: Props = $props();

  let root = $state<HTMLDivElement>();

  $effect(() => {
    const options = { strength, radius, mode };
    if (!root || still()) return;
    return startMagnet(root, options);
  });
</script>

<div bind:this={root} {...rest} class={[base, className]}>
  {@render children?.()}
</div>
```

```svelte
<script lang="ts">
  import Button from "$lib/components/markas/Button.svelte";
  import Magnet from "$lib/components/markas/Magnet.svelte";
</script>

<Magnet>
  <Button size="lg">Get started <span data-depth="0.5">&rarr;</span></Button>
</Magnet>
```

### Astro

Save at `src/components/markas/Magnet.astro`. No extra dependencies.

```astro
---
import type { HTMLAttributes } from "astro/types";

const base =
  "w-fit transition-[translate,scale] duration-500 ease-[cubic-bezier(0.34,1.56,0.64,1)] has-[:focus-visible]:scale-105 data-[state=active]:duration-150 data-[state=active]:ease-out motion-reduce:transition-none [&_[data-depth]]:inline-block [&_[data-depth]]:transition-[translate] [&_[data-depth]]:duration-500 [&_[data-depth]]:ease-[cubic-bezier(0.34,1.56,0.64,1)] data-[state=active]:[&_[data-depth]]:duration-150 motion-reduce:[&_[data-depth]]:transition-none";

type Props = HTMLAttributes<"div"> & {
  /** Share of the pointer distance the element follows, 0 to 1. For repel, how far it is pushed. */
  strength?: number;
  /** Distance in px beyond the element edges where the pull starts. */
  radius?: number;
  /** Move toward the pointer or away from it. */
  mode?: "attract" | "repel";
};

const {
  strength = 0.35,
  radius = 80,
  mode = "attract",
  class: className,
  ...rest
} = Astro.props;
---

<markas-magnet
  class="contents"
  data-strength={Number(strength)}
  data-radius={Number(radius)}
  data-mode={mode}
>
  <div {...rest} class:list={[base, className]}><slot /></div>
</markas-magnet>

<script>
  // Per instance: each wrapper listens to the pointer only while its content is on screen.
  class Magnet extends HTMLElement {
    #stop = () => {};

    connectedCallback() {
      const root = this.firstElementChild as HTMLElement | null;
      if (!root) return;
      if (window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)
        return;
      const strength = Number(this.dataset.strength);
      const radius = Number(this.dataset.radius);
      const repel = this.dataset.mode === "repel";
      let x = 0;
      let y = 0;
      const set = (nx: number, ny: number) => {
        x = nx;
        y = ny;
        if (x || y) root.dataset.state = "active";
        else delete root.dataset.state;
        root.style.translate = x || y ? `${x}px ${y}px` : "";
        for (const layer of root.querySelectorAll<HTMLElement>(
          "[data-depth]",
        )) {
          const depth = Number(layer.dataset.depth) || 0;
          layer.style.translate = x || y ? `${x * depth}px ${y * depth}px` : "";
        }
      };
      const move = (e: PointerEvent) => {
        if (e.pointerType === "touch") return;
        const r = root.getBoundingClientRect();
        const dx = e.clientX - (r.left + r.width / 2 - x);
        const dy = e.clientY - (r.top + r.height / 2 - y);
        const gap = Math.hypot(
          Math.max(Math.abs(dx) - r.width / 2, 0),
          Math.max(Math.abs(dy) - r.height / 2, 0),
        );
        const near = Math.max(1 - gap / radius, 0);
        if (repel) {
          const push = (near * radius * strength) / (Math.hypot(dx, dy) || 1);
          return set(-dx * push, -dy * push);
        }
        set(dx * near * strength, dy * near * strength);
      };
      const reset = () => set(0, 0);
      const html = document.documentElement;
      const listen = (on: boolean) => {
        if (on) {
          document.addEventListener("pointermove", move);
          html.addEventListener("pointerleave", reset);
          return;
        }
        document.removeEventListener("pointermove", move);
        html.removeEventListener("pointerleave", reset);
        reset();
      };
      const observer =
        typeof IntersectionObserver === "undefined"
          ? undefined
          : new IntersectionObserver(([entry]) =>
              listen(!!entry?.isIntersecting),
            );
      if (observer) observer.observe(root);
      else listen(true);
      this.#stop = () => {
        observer?.disconnect();
        listen(false);
      };
    }

    disconnectedCallback() {
      this.#stop();
    }
  }

  if (!customElements.get("markas-magnet"))
    customElements.define("markas-magnet", Magnet);
</script>
```

```astro
---
import Button from "@/components/markas/Button.astro";
import Magnet from "@/components/markas/Magnet.astro";
---

<Magnet>
  <Button size="lg">Get started <span data-depth="0.5">&rarr;</span></Button>
</Magnet>
```

A small bundled script runs each magnet through the `markas-magnet` element.

### Angular

Save at `src/app/markas/magnet.component.ts`. No extra dependencies.

```ts
import {
  afterRenderEffect,
  ChangeDetectionStrategy,
  Component,
  computed,
  type ElementRef,
  input,
  numberAttribute,
  viewChild,
} from "@angular/core";

const base =
  "w-fit transition-[translate,scale] duration-500 ease-[cubic-bezier(0.34,1.56,0.64,1)] has-[:focus-visible]:scale-105 data-[state=active]:duration-150 data-[state=active]:ease-out motion-reduce:transition-none [&_[data-depth]]:inline-block [&_[data-depth]]:transition-[translate] [&_[data-depth]]:duration-500 [&_[data-depth]]:ease-[cubic-bezier(0.34,1.56,0.64,1)] data-[state=active]:[&_[data-depth]]:duration-150 motion-reduce:[&_[data-depth]]:transition-none";

export type MagnetMode = "attract" | "repel";
type Options = { strength: number; radius: number; mode: MagnetMode };

const still = () =>
  window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;

/**
 * Pull the element toward (or push it away from) a mouse within `radius` px of its edges, then let
 * it spring back. Children with data-depth="0.5" travel that much further. Listens only while on screen.
 */
function startMagnet(root: HTMLElement, o: Options) {
  let x = 0;
  let y = 0;
  const set = (nx: number, ny: number) => {
    x = nx;
    y = ny;
    if (x || y) root.dataset.state = "active";
    else delete root.dataset.state;
    root.style.translate = x || y ? `${x}px ${y}px` : "";
    for (const layer of root.querySelectorAll<HTMLElement>("[data-depth]")) {
      const depth = Number(layer.dataset.depth) || 0;
      layer.style.translate = x || y ? `${x * depth}px ${y * depth}px` : "";
    }
  };
  const move = (e: PointerEvent) => {
    if (e.pointerType === "touch") return;
    const r = root.getBoundingClientRect();
    const dx = e.clientX - (r.left + r.width / 2 - x);
    const dy = e.clientY - (r.top + r.height / 2 - y);
    const gap = Math.hypot(
      Math.max(Math.abs(dx) - r.width / 2, 0),
      Math.max(Math.abs(dy) - r.height / 2, 0),
    );
    const near = Math.max(1 - gap / o.radius, 0);
    if (o.mode === "repel") {
      const push = (near * o.radius * o.strength) / (Math.hypot(dx, dy) || 1);
      return set(-dx * push, -dy * push);
    }
    set(dx * near * o.strength, dy * near * o.strength);
  };
  const reset = () => set(0, 0);
  const html = document.documentElement;
  const listen = (on: boolean) => {
    if (on) {
      document.addEventListener("pointermove", move);
      html.addEventListener("pointerleave", reset);
      return;
    }
    document.removeEventListener("pointermove", move);
    html.removeEventListener("pointerleave", reset);
    reset();
  };
  const observer =
    typeof IntersectionObserver === "undefined"
      ? undefined
      : new IntersectionObserver(([entry]) => listen(!!entry?.isIntersecting));
  if (observer) observer.observe(root);
  else listen(true);
  return () => {
    observer?.disconnect();
    listen(false);
  };
}

/**
 * Wraps one element, usually a button or link. The host stays out of layout; the user's class
 * lands on the moving wrapper.
 */
@Component({
  selector: "markas-magnet",
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { class: "contents" },
  template: `<div #rootEl [class]="classes()"><ng-content /></div>`,
})
export class Magnet {
  /** Share of the pointer distance the element follows, 0 to 1. For repel, how far it is pushed. */
  readonly strength = input(0.35, { transform: numberAttribute });
  /** Distance in px beyond the element edges where the pull starts. */
  readonly radius = input(80, { transform: numberAttribute });
  /** Move toward the pointer or away from it. */
  readonly mode = input<MagnetMode>("attract");
  readonly userClass = input("", { alias: "class" });

  protected readonly classes = computed(() =>
    [base, this.userClass()].filter(Boolean).join(" "),
  );
  private readonly root = viewChild.required<ElementRef<HTMLElement>>("rootEl");

  constructor() {
    afterRenderEffect((onCleanup) => {
      const options = {
        strength: this.strength(),
        radius: this.radius(),
        mode: this.mode(),
      };
      if (still()) return;
      onCleanup(startMagnet(this.root().nativeElement, options));
    });
  }
}
```

```ts
import { Component } from "@angular/core";
import { Button } from "./markas/button.component";
import { Magnet } from "./markas/magnet.component";

@Component({
  selector: "app-cta",
  imports: [Button, Magnet],
  template: `
    <markas-magnet [strength]="0.5" [radius]="32">
      <button markas-button size="lg">
        Get started <span data-depth="0.5">&rarr;</span>
      </button>
    </markas-magnet>
  `,
})
export class Cta {}
```

## Props

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `strength` | `number` | 0.35 | Share of the pointer distance the content follows, from 0 to 1. For repel it sets how far the content is pushed, as a share of radius. |
| `radius` | `number` | 80 | Distance in px beyond the content edges where the pull starts. It grows smoothly as the pointer comes closer. |
| `mode` | `"attract" \| "repel"` | "attract" | Move toward the pointer, or dodge away from it. |
| `children / slot` | `ReactNode / slot` | - | The content, usually one button, link, or icon. Inner elements with data-depth="0.5" travel that much further, such as the arrow in a button. |

## Accessibility

- The pull is visual only; the button or link inside keeps its role, name, and position in the tab order.
- Keyboard focus inside lifts the content slightly so the focus is easy to follow.
- Touch input is ignored, and with reduced motion the content stays still.

## Notes

- Within `radius` px of its edges the content follows the mouse by `strength` (0 to 1) and springs back with a slight overshoot when the mouse moves away.
- `mode="repel"` dodges the pointer instead. Keep it for playful, decorative elements.
- Inner elements with `data-depth="0.5"` travel 50% further, which makes an arrow or icon inside a button feel layered.
- The wrapper is `w-fit`; attributes and `class` go to it. It listens only while on screen, ignores touch, and stays still with reduced motion.
