# Elastic Line

SVG line that bends toward, away from, or with the pointer when it comes close, then springs back. Works as a divider or a heading underline.

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

## When to use

A divider between sections, a separator between stats or footer links, or an underline under a heading that should feel tactile when the pointer passes.

- Use pull for calm dividers, push for hero areas, and pluck for small playful underlines
- Set reach to the space you can spare around the line; the component takes twice that
- Mark underlines and ornaments as decorative
- Put a vertical line inside a flex row so it can stretch

## Code

### Blade

Save at `resources/views/components/markas/elastic-line.blade.php`. Dependencies: alpinejs.

```blade
@props([
    'variant' => 'pull',
    'orientation' => 'horizontal',
    'reach' => 24,
    'color' => 'line',
    'strokeWidth' => 1.5,
    'playOnView' => false,
    'decorative' => false,
])

@php
    $base = 'relative block';
    $orientations = [
        'horizontal' => 'h-[calc(var(--reach)*2)]',
        'vertical' => 'w-[calc(var(--reach)*2)] self-stretch',
    ];
    $colors = [
        'line' => 'text-line',
        'muted' => 'text-muted',
        'ink' => 'text-ink',
        'primary' => 'text-primary',
        'success' => 'text-success',
        'warning' => 'text-warning',
        'danger' => 'text-danger',
    ];
    $svgClass = 'pointer-events-none absolute inset-0 size-full overflow-visible';
    $pathClass = 'fill-none stroke-current [vector-effect:non-scaling-stroke]';
    $vertical = $orientation === 'vertical';
    $options = [
        'vertical' => $vertical,
        'variant' => in_array($variant, ['pull', 'push', 'pluck'], true) ? $variant : 'pull',
        'playOnView' => (bool) $playOnView,
    ];
    $a11y = $decorative ? ['aria-hidden' => 'true'] : ['role' => 'separator', 'aria-orientation' => $vertical ? 'vertical' : 'horizontal'];
@endphp

{{-- Bends toward (pull), away from (push), or with the pointer until it slips (pluck), then springs back. rAF only runs while active. --}}
<div
    x-data="{
        stop: null,
        curve(vertical, along = 50, bend = 0) {
            return vertical ? `M50 0Q${50 + 2 * bend} ${along} 50 100` : `M0 50Q${along} ${50 + 2 * bend} 100 50`;
        },
        init() {
            const { vertical, variant, playOnView } = @js($options);
            const springs = { pull: { k: 0.12, d: 0.82 }, push: { k: 0.1, d: 0.8 }, pluck: { k: 0.3, d: 0.6 }, release: { k: 0.18, d: 0.93 } };
            const root = this.$root;
            const path = this.$refs.path;
            const still = () => window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
            let pointer = null;
            let along = 50;
            let bend = 0;
            let speed = 0;
            let grabbed = false;
            let frame = 0;
            const reach = () => {
                const rect = root.getBoundingClientRect();
                return (vertical ? rect.width : rect.height) / 2 || 1;
            };
            const step = () => {
                const half = reach();
                let target = 0;
                let spring = springs.release;
                if (pointer) {
                    along = Math.min(Math.max(pointer.along, 10), 90);
                    const perp = pointer.perp;
                    if (variant === 'pull') target = perp;
                    if (variant === 'push') target = -Math.sign(perp || 1) * (half - Math.abs(perp)) * 0.6;
                    if (variant === 'pluck') {
                        if (Math.abs(perp) > half * 0.8) grabbed = false;
                        if (grabbed) target = perp;
                    }
                    if (variant !== 'pluck') spring = springs[variant];
                    else if (grabbed) spring = springs.pluck;
                }
                speed = (speed + (target - bend) * spring.k) * spring.d;
                bend += speed;
                const settled = ! pointer && Math.abs(bend) < 0.05 && Math.abs(speed) < 0.05;
                if (settled) bend = speed = 0;
                path.setAttribute('d', this.curve(vertical, along, (bend / half) * 50));
                frame = settled ? 0 : requestAnimationFrame(step);
            };
            const wake = () => {
                frame ||= requestAnimationFrame(step);
            };
            const move = (event) => {
                if (still()) return;
                const rect = root.getBoundingClientRect();
                const x = event.clientX - rect.left;
                const y = event.clientY - rect.top;
                const next = vertical ? { along: (y / rect.height) * 100, perp: x - rect.width / 2 } : { along: (x / rect.width) * 100, perp: y - rect.height / 2 };
                {{-- Pluck grabs when the pointer touches or crosses the line, even between two frames. --}}
                const crossed = pointer && Math.sign(pointer.perp) !== Math.sign(next.perp);
                if (Math.abs(next.perp) < 6 || crossed) grabbed = true;
                pointer = next;
                wake();
            };
            const leave = () => {
                pointer = null;
                grabbed = false;
                wake();
            };
            root.addEventListener('pointermove', move);
            root.addEventListener('pointerleave', leave);
            {{-- Twang once when the line first scrolls into view. --}}
            let observer = null;
            if (playOnView && ! still() && typeof IntersectionObserver === 'function') {
                observer = new IntersectionObserver(([entry]) => {
                    if (! entry?.isIntersecting) return;
                    observer.disconnect();
                    speed = reach() * 0.5;
                    wake();
                });
                observer.observe(root);
            }
            this.stop = () => {
                root.removeEventListener('pointermove', move);
                root.removeEventListener('pointerleave', leave);
                observer?.disconnect();
                cancelAnimationFrame(frame);
            };
        },
        destroy() {
            this.stop?.();
        },
    }"
    {{ $attributes->merge([...$a11y, 'style' => '--reach: '.(float) $reach.'px'])->class([$base, $orientations[$orientation] ?? $orientations['horizontal'], $colors[$color] ?? $colors['line']]) }}
>
    <svg aria-hidden="true" viewBox="0 0 100 100" preserveAspectRatio="none" class="{{ $svgClass }}">
        <path
            x-ref="path"
            d="{{ $vertical ? 'M50 0Q50 50 50 100' : 'M0 50Q50 50 100 50' }}"
            stroke-width="{{ (float) $strokeWidth }}"
            stroke-linecap="round"
            class="{{ $pathClass }}"
        />
    </svg>
</div>
```

```blade
<h2 class="text-3xl font-semibold">Our services</h2>
<x-markas.elastic-line variant="pluck" color="primary" :stroke-width="3" :reach="16" play-on-view decorative class="w-40" />

<x-markas.elastic-line variant="push" :reach="32" />
```

Needs Alpine.js.

### React

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

```tsx
"use client";

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

export type ElasticLineVariant = "pull" | "push" | "pluck";
export type ElasticLineOrientation = "horizontal" | "vertical";

const base = "relative block";
const orientations: Record<ElasticLineOrientation, string> = {
  horizontal: "h-[calc(var(--reach)*2)]",
  vertical: "w-[calc(var(--reach)*2)] self-stretch",
};
const colors = {
  line: "text-line",
  muted: "text-muted",
  ink: "text-ink",
  primary: "text-primary",
  success: "text-success",
  warning: "text-warning",
  danger: "text-danger",
};
const svgClass =
  "pointer-events-none absolute inset-0 size-full overflow-visible";
const pathClass = "fill-none stroke-current [vector-effect:non-scaling-stroke]";

/** Spring per variant: k pulls toward the target, d keeps that share of the speed each frame. */
const SPRINGS = {
  pull: { k: 0.12, d: 0.82 },
  push: { k: 0.1, d: 0.8 },
  pluck: { k: 0.3, d: 0.6 },
  release: { k: 0.18, d: 0.93 },
};
const REST = 0.05;

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

/** Quadratic curve in a 0 to 100 box. The control sits at twice the bend so the line peaks at the bend. */
export const curve = (vertical: boolean, along = 50, bend = 0) =>
  vertical
    ? `M50 0Q${50 + 2 * bend} ${along} 50 100`
    : `M0 50Q${along} ${50 + 2 * bend} 100 50`;

/**
 * Bend the line toward (pull), away from (push), or with the pointer until it slips (pluck), then spring
 * back. requestAnimationFrame only runs while the pointer is near or the line still moves.
 */
function createLine(
  root: HTMLElement,
  path: SVGPathElement,
  vertical: boolean,
  variant: ElasticLineVariant,
  playOnView: boolean,
) {
  let pointer: { along: number; perp: number } | null = null;
  let along = 50;
  let bend = 0;
  let speed = 0;
  let grabbed = false;
  let frame = 0;
  const reach = () => {
    const rect = root.getBoundingClientRect();
    return (vertical ? rect.width : rect.height) / 2 || 1;
  };

  const step = () => {
    const half = reach();
    let target = 0;
    let spring = SPRINGS.release;
    if (pointer) {
      along = Math.min(Math.max(pointer.along, 10), 90);
      const perp = pointer.perp;
      if (variant === "pull") target = perp;
      if (variant === "push")
        target = -Math.sign(perp || 1) * (half - Math.abs(perp)) * 0.6;
      if (variant === "pluck") {
        if (Math.abs(perp) > half * 0.8) grabbed = false;
        if (grabbed) target = perp;
      }
      if (variant !== "pluck") spring = SPRINGS[variant];
      else if (grabbed) spring = SPRINGS.pluck;
    }
    speed = (speed + (target - bend) * spring.k) * spring.d;
    bend += speed;
    const settled = !pointer && Math.abs(bend) < REST && Math.abs(speed) < REST;
    if (settled) bend = speed = 0;
    path.setAttribute("d", curve(vertical, along, (bend / half) * 50));
    frame = settled ? 0 : requestAnimationFrame(step);
  };
  const wake = () => {
    frame ||= requestAnimationFrame(step);
  };

  const move = (event: PointerEvent) => {
    if (still()) return;
    const rect = root.getBoundingClientRect();
    const x = event.clientX - rect.left;
    const y = event.clientY - rect.top;
    const next = vertical
      ? { along: (y / rect.height) * 100, perp: x - rect.width / 2 }
      : { along: (x / rect.width) * 100, perp: y - rect.height / 2 };
    // Pluck grabs when the pointer touches or crosses the line, even between two frames.
    const crossed = pointer && Math.sign(pointer.perp) !== Math.sign(next.perp);
    if (Math.abs(next.perp) < 6 || crossed) grabbed = true;
    pointer = next;
    wake();
  };
  const leave = () => {
    pointer = null;
    grabbed = false;
    wake();
  };
  root.addEventListener("pointermove", move);
  root.addEventListener("pointerleave", leave);

  // Twang once when the line first scrolls into view.
  let observer: IntersectionObserver | null = null;
  if (playOnView && !still() && typeof IntersectionObserver === "function") {
    observer = new IntersectionObserver(([entry]) => {
      if (!entry?.isIntersecting) return;
      observer?.disconnect();
      speed = reach() * 0.5;
      wake();
    });
    observer.observe(root);
  }

  return () => {
    root.removeEventListener("pointermove", move);
    root.removeEventListener("pointerleave", leave);
    observer?.disconnect();
    cancelAnimationFrame(frame);
  };
}

export type ElasticLineProps = ComponentProps<"div"> & {
  /** How the line answers the pointer. */
  variant?: ElasticLineVariant;
  /** Direction of the line. */
  orientation?: ElasticLineOrientation;
  /** Px on each side of the line where the pointer bends it, and the most it can bend. */
  reach?: number;
  /** Line color token. */
  color?: keyof typeof colors;
  /** Line width in px. */
  strokeWidth?: number;
  /** Twangs once when the line first scrolls into view. */
  playOnView?: boolean;
  /** Hides the line from assistive tech instead of announcing a separator. */
  decorative?: boolean;
};

export function ElasticLine({
  variant = "pull",
  orientation = "horizontal",
  reach = 24,
  color = "line",
  strokeWidth = 1.5,
  playOnView = false,
  decorative = false,
  className,
  style,
  ...props
}: ElasticLineProps) {
  const rootRef = useRef<HTMLDivElement>(null);
  const pathRef = useRef<SVGPathElement>(null);
  const vertical = orientation === "vertical";
  useEffect(
    () =>
      createLine(
        rootRef.current!,
        pathRef.current!,
        vertical,
        variant,
        playOnView,
      ),
    [vertical, variant, playOnView],
  );
  return (
    <div
      role={decorative ? undefined : "separator"}
      aria-orientation={decorative ? undefined : orientation}
      aria-hidden={decorative ? "true" : undefined}
      {...props}
      ref={rootRef}
      className={cx(base, orientations[orientation], colors[color], className)}
      style={
        { "--reach": `${reach}px`, ...style } as ComponentProps<"div">["style"]
      }
    >
      <svg
        aria-hidden="true"
        viewBox="0 0 100 100"
        preserveAspectRatio="none"
        className={svgClass}
      >
        <path
          ref={pathRef}
          d={curve(vertical)}
          strokeWidth={strokeWidth}
          strokeLinecap="round"
          className={pathClass}
        />
      </svg>
    </div>
  );
}
```

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

<h2 className="text-3xl font-semibold">Our services</h2>
<ElasticLine
  variant="pluck"
  color="primary"
  strokeWidth={3}
  reach={16}
  playOnView
  decorative
  className="w-40"
/>

<ElasticLine variant="push" reach={32} />
```

### Vue

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

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

export type ElasticLineVariant = "pull" | "push" | "pluck";
export type ElasticLineOrientation = "horizontal" | "vertical";

const colors = {
  line: "text-line",
  muted: "text-muted",
  ink: "text-ink",
  primary: "text-primary",
  success: "text-success",
  warning: "text-warning",
  danger: "text-danger",
};

const props = withDefaults(
  defineProps<{
    /** How the line answers the pointer. */
    variant?: ElasticLineVariant;
    /** Direction of the line. */
    orientation?: ElasticLineOrientation;
    /** Px on each side of the line where the pointer bends it, and the most it can bend. */
    reach?: number;
    /** Line color token. */
    color?: keyof typeof colors;
    /** Line width in px. */
    strokeWidth?: number;
    /** Twangs once when the line first scrolls into view. */
    playOnView?: boolean;
    /** Hides the line from assistive tech instead of announcing a separator. */
    decorative?: boolean;
  }>(),
  {
    variant: "pull",
    orientation: "horizontal",
    reach: 24,
    color: "line",
    strokeWidth: 1.5,
    playOnView: false,
    decorative: false,
  },
);

const base = "relative block";
const orientations: Record<ElasticLineOrientation, string> = {
  horizontal: "h-[calc(var(--reach)*2)]",
  vertical: "w-[calc(var(--reach)*2)] self-stretch",
};
const svgClass =
  "pointer-events-none absolute inset-0 size-full overflow-visible";
const pathClass = "fill-none stroke-current [vector-effect:non-scaling-stroke]";

/** Spring per variant: k pulls toward the target, d keeps that share of the speed each frame. */
const SPRINGS = {
  pull: { k: 0.12, d: 0.82 },
  push: { k: 0.1, d: 0.8 },
  pluck: { k: 0.3, d: 0.6 },
  release: { k: 0.18, d: 0.93 },
};
const REST = 0.05;

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

/** Quadratic curve in a 0 to 100 box. The control sits at twice the bend so the line peaks at the bend. */
const curve = (vertical: boolean, along = 50, bend = 0) =>
  vertical
    ? `M50 0Q${50 + 2 * bend} ${along} 50 100`
    : `M0 50Q${along} ${50 + 2 * bend} 100 50`;

/**
 * Bend the line toward (pull), away from (push), or with the pointer until it slips (pluck), then spring
 * back. requestAnimationFrame only runs while the pointer is near or the line still moves.
 */
function createLine(root: HTMLElement, path: SVGPathElement) {
  const vertical = props.orientation === "vertical";
  const variant = props.variant;
  let pointer: { along: number; perp: number } | null = null;
  let along = 50;
  let bend = 0;
  let speed = 0;
  let grabbed = false;
  let frame = 0;
  const reach = () => {
    const rect = root.getBoundingClientRect();
    return (vertical ? rect.width : rect.height) / 2 || 1;
  };

  const step = () => {
    const half = reach();
    let target = 0;
    let spring = SPRINGS.release;
    if (pointer) {
      along = Math.min(Math.max(pointer.along, 10), 90);
      const perp = pointer.perp;
      if (variant === "pull") target = perp;
      if (variant === "push")
        target = -Math.sign(perp || 1) * (half - Math.abs(perp)) * 0.6;
      if (variant === "pluck") {
        if (Math.abs(perp) > half * 0.8) grabbed = false;
        if (grabbed) target = perp;
      }
      if (variant !== "pluck") spring = SPRINGS[variant];
      else if (grabbed) spring = SPRINGS.pluck;
    }
    speed = (speed + (target - bend) * spring.k) * spring.d;
    bend += speed;
    const settled = !pointer && Math.abs(bend) < REST && Math.abs(speed) < REST;
    if (settled) bend = speed = 0;
    path.setAttribute("d", curve(vertical, along, (bend / half) * 50));
    frame = settled ? 0 : requestAnimationFrame(step);
  };
  const wake = () => {
    frame ||= requestAnimationFrame(step);
  };

  const move = (event: PointerEvent) => {
    if (still()) return;
    const rect = root.getBoundingClientRect();
    const x = event.clientX - rect.left;
    const y = event.clientY - rect.top;
    const next = vertical
      ? { along: (y / rect.height) * 100, perp: x - rect.width / 2 }
      : { along: (x / rect.width) * 100, perp: y - rect.height / 2 };
    // Pluck grabs when the pointer touches or crosses the line, even between two frames.
    const crossed = pointer && Math.sign(pointer.perp) !== Math.sign(next.perp);
    if (Math.abs(next.perp) < 6 || crossed) grabbed = true;
    pointer = next;
    wake();
  };
  const leave = () => {
    pointer = null;
    grabbed = false;
    wake();
  };
  root.addEventListener("pointermove", move);
  root.addEventListener("pointerleave", leave);

  // Twang once when the line first scrolls into view.
  let observer: IntersectionObserver | null = null;
  if (
    props.playOnView &&
    !still() &&
    typeof IntersectionObserver === "function"
  ) {
    observer = new IntersectionObserver(([entry]) => {
      if (!entry?.isIntersecting) return;
      observer?.disconnect();
      speed = reach() * 0.5;
      wake();
    });
    observer.observe(root);
  }

  return () => {
    root.removeEventListener("pointermove", move);
    root.removeEventListener("pointerleave", leave);
    observer?.disconnect();
    cancelAnimationFrame(frame);
  };
}

const rootEl = useTemplateRef<HTMLDivElement>("rootRef");
const pathEl = useTemplateRef<SVGPathElement>("pathRef");
let stop = () => {};
const start = () => {
  stop();
  stop = createLine(rootEl.value!, pathEl.value!);
};
onMounted(start);
watch(() => [props.orientation, props.variant, props.playOnView], start);
onBeforeUnmount(() => stop());
</script>

<template>
  <div
    ref="rootRef"
    :role="props.decorative ? undefined : 'separator'"
    :aria-orientation="props.decorative ? undefined : props.orientation"
    :aria-hidden="props.decorative ? 'true' : undefined"
    :class="[base, orientations[props.orientation], colors[props.color]]"
    :style="{ '--reach': `${props.reach}px` }"
  >
    <svg
      aria-hidden="true"
      viewBox="0 0 100 100"
      preserveAspectRatio="none"
      :class="svgClass"
    >
      <path
        ref="pathRef"
        :d="curve(props.orientation === 'vertical')"
        :stroke-width="props.strokeWidth"
        stroke-linecap="round"
        :class="pathClass"
      />
    </svg>
  </div>
</template>
```

```vue
<template>
  <h2 class="text-3xl font-semibold">Our services</h2>
  <ElasticLine
    variant="pluck"
    color="primary"
    :stroke-width="3"
    :reach="16"
    play-on-view
    decorative
    class="w-40"
  />

  <ElasticLine variant="push" :reach="32" />
</template>
```

### Svelte

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

```svelte
<script lang="ts" module>
  export type ElasticLineVariant = "pull" | "push" | "pluck";
  export type ElasticLineOrientation = "horizontal" | "vertical";

  /** Spring per variant: k pulls toward the target, d keeps that share of the speed each frame. */
  const SPRINGS = {
    pull: { k: 0.12, d: 0.82 },
    push: { k: 0.1, d: 0.8 },
    pluck: { k: 0.3, d: 0.6 },
    release: { k: 0.18, d: 0.93 },
  };
  const REST = 0.05;

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

  /** Quadratic curve in a 0 to 100 box. The control sits at twice the bend so the line peaks at the bend. */
  export const curve = (vertical: boolean, along = 50, bend = 0) =>
    vertical
      ? `M50 0Q${50 + 2 * bend} ${along} 50 100`
      : `M0 50Q${along} ${50 + 2 * bend} 100 50`;

  /**
   * Bend the line toward (pull), away from (push), or with the pointer until it slips (pluck), then spring
   * back. requestAnimationFrame only runs while the pointer is near or the line still moves.
   */
  function createLine(
    root: HTMLElement,
    path: SVGPathElement,
    vertical: boolean,
    variant: ElasticLineVariant,
    playOnView: boolean,
  ) {
    let pointer: { along: number; perp: number } | null = null;
    let along = 50;
    let bend = 0;
    let speed = 0;
    let grabbed = false;
    let frame = 0;
    const reach = () => {
      const rect = root.getBoundingClientRect();
      return (vertical ? rect.width : rect.height) / 2 || 1;
    };

    const step = () => {
      const half = reach();
      let target = 0;
      let spring = SPRINGS.release;
      if (pointer) {
        along = Math.min(Math.max(pointer.along, 10), 90);
        const perp = pointer.perp;
        if (variant === "pull") target = perp;
        if (variant === "push")
          target = -Math.sign(perp || 1) * (half - Math.abs(perp)) * 0.6;
        if (variant === "pluck") {
          if (Math.abs(perp) > half * 0.8) grabbed = false;
          if (grabbed) target = perp;
        }
        if (variant !== "pluck") spring = SPRINGS[variant];
        else if (grabbed) spring = SPRINGS.pluck;
      }
      speed = (speed + (target - bend) * spring.k) * spring.d;
      bend += speed;
      const settled =
        !pointer && Math.abs(bend) < REST && Math.abs(speed) < REST;
      if (settled) bend = speed = 0;
      path.setAttribute("d", curve(vertical, along, (bend / half) * 50));
      frame = settled ? 0 : requestAnimationFrame(step);
    };
    const wake = () => {
      frame ||= requestAnimationFrame(step);
    };

    const move = (event: PointerEvent) => {
      if (still()) return;
      const rect = root.getBoundingClientRect();
      const x = event.clientX - rect.left;
      const y = event.clientY - rect.top;
      const next = vertical
        ? { along: (y / rect.height) * 100, perp: x - rect.width / 2 }
        : { along: (x / rect.width) * 100, perp: y - rect.height / 2 };
      // Pluck grabs when the pointer touches or crosses the line, even between two frames.
      const crossed =
        pointer && Math.sign(pointer.perp) !== Math.sign(next.perp);
      if (Math.abs(next.perp) < 6 || crossed) grabbed = true;
      pointer = next;
      wake();
    };
    const leave = () => {
      pointer = null;
      grabbed = false;
      wake();
    };
    root.addEventListener("pointermove", move);
    root.addEventListener("pointerleave", leave);

    // Twang once when the line first scrolls into view.
    let observer: IntersectionObserver | null = null;
    if (playOnView && !still() && typeof IntersectionObserver === "function") {
      observer = new IntersectionObserver(([entry]) => {
        if (!entry?.isIntersecting) return;
        observer?.disconnect();
        speed = reach() * 0.5;
        wake();
      });
      observer.observe(root);
    }

    return () => {
      root.removeEventListener("pointermove", move);
      root.removeEventListener("pointerleave", leave);
      observer?.disconnect();
      cancelAnimationFrame(frame);
    };
  }
</script>

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

  const base = "relative block";
  const orientations: Record<ElasticLineOrientation, string> = {
    horizontal: "h-[calc(var(--reach)*2)]",
    vertical: "w-[calc(var(--reach)*2)] self-stretch",
  };
  const colors = {
    line: "text-line",
    muted: "text-muted",
    ink: "text-ink",
    primary: "text-primary",
    success: "text-success",
    warning: "text-warning",
    danger: "text-danger",
  };
  const svgClass =
    "pointer-events-none absolute inset-0 size-full overflow-visible";
  const pathClass =
    "fill-none stroke-current [vector-effect:non-scaling-stroke]";

  type Props = HTMLAttributes<HTMLDivElement> & {
    /** How the line answers the pointer. */
    variant?: ElasticLineVariant;
    /** Direction of the line. */
    orientation?: ElasticLineOrientation;
    /** Px on each side of the line where the pointer bends it, and the most it can bend. */
    reach?: number;
    /** Line color token. */
    color?: keyof typeof colors;
    /** Line width in px. */
    strokeWidth?: number;
    /** Twangs once when the line first scrolls into view. */
    playOnView?: boolean;
    /** Hides the line from assistive tech instead of announcing a separator. */
    decorative?: boolean;
  };

  let {
    variant = "pull",
    orientation = "horizontal",
    reach = 24,
    color = "line",
    strokeWidth = 1.5,
    playOnView = false,
    decorative = false,
    class: className,
    ...rest
  }: Props = $props();

  const vertical = $derived(orientation === "vertical");
  let rootEl = $state<HTMLDivElement>();
  let pathEl = $state<SVGPathElement>();

  $effect(() =>
    rootEl && pathEl
      ? createLine(rootEl, pathEl, vertical, variant, playOnView)
      : undefined,
  );
</script>

<div
  role={decorative ? undefined : "separator"}
  aria-orientation={decorative ? undefined : orientation}
  aria-hidden={decorative ? "true" : undefined}
  {...rest}
  bind:this={rootEl}
  class={[base, orientations[orientation], colors[color], className]}
  style:--reach={`${reach}px`}
>
  <svg
    aria-hidden="true"
    viewBox="0 0 100 100"
    preserveAspectRatio="none"
    class={svgClass}
  >
    <path
      bind:this={pathEl}
      d={curve(vertical)}
      stroke-width={strokeWidth}
      stroke-linecap="round"
      class={pathClass}
    />
  </svg>
</div>
```

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

<h2 class="text-3xl font-semibold">Our services</h2>
<ElasticLine
  variant="pluck"
  color="primary"
  strokeWidth={3}
  reach={16}
  playOnView
  decorative
  class="w-40"
/>
```

### Astro

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

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

export type ElasticLineVariant = "pull" | "push" | "pluck";
export type ElasticLineOrientation = "horizontal" | "vertical";

const base = "relative block";
const orientations: Record<ElasticLineOrientation, string> = {
  horizontal: "h-[calc(var(--reach)*2)]",
  vertical: "w-[calc(var(--reach)*2)] self-stretch",
};
const colors = {
  line: "text-line",
  muted: "text-muted",
  ink: "text-ink",
  primary: "text-primary",
  success: "text-success",
  warning: "text-warning",
  danger: "text-danger",
};
const svgClass =
  "pointer-events-none absolute inset-0 size-full overflow-visible";
const pathClass = "fill-none stroke-current [vector-effect:non-scaling-stroke]";

/** Quadratic curve in a 0 to 100 box. The control sits at twice the bend so the line peaks at the bend. */
const curve = (vertical: boolean) => (vertical ? "M50 0Q50 50 50 100" : "M0 50Q50 50 100 50");

type Props = HTMLAttributes<"div"> & {
  /** How the line answers the pointer. */
  variant?: ElasticLineVariant;
  /** Direction of the line. */
  orientation?: ElasticLineOrientation;
  /** Px on each side of the line where the pointer bends it, and the most it can bend. */
  reach?: number;
  /** Line color token. */
  color?: keyof typeof colors;
  /** Line width in px. */
  strokeWidth?: number;
  /** Twangs once when the line first scrolls into view. */
  playOnView?: boolean;
  /** Hides the line from assistive tech instead of announcing a separator. */
  decorative?: boolean;
};

const {
  variant = "pull",
  orientation = "horizontal",
  reach = 24,
  color = "line",
  strokeWidth = 1.5,
  playOnView = false,
  decorative = false,
  class: className,
  style,
  ...rest
} = Astro.props;
---

<markas-elastic-line
  class="contents"
  data-variant={variant}
  data-orientation={orientation}
  data-play-on-view={playOnView ? "" : undefined}
>
  <div
    role={decorative ? undefined : "separator"}
    aria-orientation={decorative ? undefined : orientation}
    aria-hidden={decorative ? "true" : undefined}
    {...rest}
    class:list={[base, orientations[orientation], colors[color], className]}
    style={`--reach: ${reach}px;${typeof style === "string" ? ` ${style}` : ""}`}
  >
    <svg
      aria-hidden="true"
      viewBox="0 0 100 100"
      preserveAspectRatio="none"
      class={svgClass}
    >
      <path
        d={curve(orientation === "vertical")}
        stroke-width={strokeWidth}
        stroke-linecap="round"
        class={pathClass}
      ></path>
    </svg>
  </div>
</markas-elastic-line>

<script>
  type ElasticLineVariant = "pull" | "push" | "pluck";
  type ElasticLineOrientation = "horizontal" | "vertical";

  /** Spring per variant: k pulls toward the target, d keeps that share of the speed each frame. */
  const SPRINGS = {
    pull: { k: 0.12, d: 0.82 },
    push: { k: 0.1, d: 0.8 },
    pluck: { k: 0.3, d: 0.6 },
    release: { k: 0.18, d: 0.93 },
  };
  const REST = 0.05;

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

  /** Quadratic curve in a 0 to 100 box. The control sits at twice the bend so the line peaks at the bend. */
  const curve = (vertical: boolean, along = 50, bend = 0) =>
    vertical
      ? `M50 0Q${50 + 2 * bend} ${along} 50 100`
      : `M0 50Q${along} ${50 + 2 * bend} 100 50`;

  /**
   * Bend the line toward (pull), away from (push), or with the pointer until it slips (pluck), then spring
   * back. requestAnimationFrame only runs while the pointer is near or the line still moves.
   */
  function createLine(
    root: HTMLElement,
    path: SVGPathElement,
    vertical: boolean,
    variant: ElasticLineVariant,
    playOnView: boolean,
  ) {
    let pointer: { along: number; perp: number } | null = null;
    let along = 50;
    let bend = 0;
    let speed = 0;
    let grabbed = false;
    let frame = 0;
    const reach = () => {
      const rect = root.getBoundingClientRect();
      return (vertical ? rect.width : rect.height) / 2 || 1;
    };

    const step = () => {
      const half = reach();
      let target = 0;
      let spring = SPRINGS.release;
      if (pointer) {
        along = Math.min(Math.max(pointer.along, 10), 90);
        const perp = pointer.perp;
        if (variant === "pull") target = perp;
        if (variant === "push")
          target = -Math.sign(perp || 1) * (half - Math.abs(perp)) * 0.6;
        if (variant === "pluck") {
          if (Math.abs(perp) > half * 0.8) grabbed = false;
          if (grabbed) target = perp;
        }
        if (variant !== "pluck") spring = SPRINGS[variant];
        else if (grabbed) spring = SPRINGS.pluck;
      }
      speed = (speed + (target - bend) * spring.k) * spring.d;
      bend += speed;
      const settled = !pointer && Math.abs(bend) < REST && Math.abs(speed) < REST;
      if (settled) bend = speed = 0;
      path.setAttribute("d", curve(vertical, along, (bend / half) * 50));
      frame = settled ? 0 : requestAnimationFrame(step);
    };
    const wake = () => {
      frame ||= requestAnimationFrame(step);
    };

    const move = (event: PointerEvent) => {
      if (still()) return;
      const rect = root.getBoundingClientRect();
      const x = event.clientX - rect.left;
      const y = event.clientY - rect.top;
      const next = vertical
        ? { along: (y / rect.height) * 100, perp: x - rect.width / 2 }
        : { along: (x / rect.width) * 100, perp: y - rect.height / 2 };
      // Pluck grabs when the pointer touches or crosses the line, even between two frames.
      const crossed = pointer && Math.sign(pointer.perp) !== Math.sign(next.perp);
      if (Math.abs(next.perp) < 6 || crossed) grabbed = true;
      pointer = next;
      wake();
    };
    const leave = () => {
      pointer = null;
      grabbed = false;
      wake();
    };
    root.addEventListener("pointermove", move);
    root.addEventListener("pointerleave", leave);

    // Twang once when the line first scrolls into view.
    let observer: IntersectionObserver | null = null;
    if (playOnView && !still() && typeof IntersectionObserver === "function") {
      observer = new IntersectionObserver(([entry]) => {
        if (!entry?.isIntersecting) return;
        observer?.disconnect();
        speed = reach() * 0.5;
        wake();
      });
      observer.observe(root);
    }

    return () => {
      root.removeEventListener("pointermove", move);
      root.removeEventListener("pointerleave", leave);
      observer?.disconnect();
      cancelAnimationFrame(frame);
    };
  }

  // Each line runs its own spring, so it is a custom element: it also works for markup added
  // later and for pages reached through view transitions.
  class MarkasElasticLine extends HTMLElement {
    private stop?: () => void;

    connectedCallback() {
      const root = this.firstElementChild;
      const path = this.querySelector("path");
      if (this.stop || !(root instanceof HTMLElement) || !path) return;
      this.stop = createLine(
        root,
        path,
        this.dataset.orientation === "vertical",
        (this.dataset.variant ?? "pull") as ElasticLineVariant,
        this.dataset.playOnView !== undefined,
      );
    }

    disconnectedCallback() {
      this.stop?.();
      this.stop = undefined;
    }
  }

  if (!customElements.get("markas-elastic-line"))
    customElements.define("markas-elastic-line", MarkasElasticLine);
</script>
```

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

<h2 class="text-3xl font-semibold">Our services</h2>
<ElasticLine
  variant="pluck"
  color="primary"
  strokeWidth={3}
  reach={16}
  playOnView
  decorative
  class="w-40"
/>
```

Each line is a small custom element that runs its own spring, also after view transitions.

### Angular

Save at `src/app/markas/elastic-line.component.ts`. No extra dependencies.

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

export type ElasticLineVariant = "pull" | "push" | "pluck";
export type ElasticLineOrientation = "horizontal" | "vertical";

const base = "relative block";
const orientations: Record<ElasticLineOrientation, string> = {
  horizontal: "h-[calc(var(--reach)*2)]",
  vertical: "w-[calc(var(--reach)*2)] self-stretch",
};
const colors = {
  line: "text-line",
  muted: "text-muted",
  ink: "text-ink",
  primary: "text-primary",
  success: "text-success",
  warning: "text-warning",
  danger: "text-danger",
};
const svgClass =
  "pointer-events-none absolute inset-0 size-full overflow-visible";
const pathClass = "fill-none stroke-current [vector-effect:non-scaling-stroke]";

/** Spring per variant: k pulls toward the target, d keeps that share of the speed each frame. */
const SPRINGS = {
  pull: { k: 0.12, d: 0.82 },
  push: { k: 0.1, d: 0.8 },
  pluck: { k: 0.3, d: 0.6 },
  release: { k: 0.18, d: 0.93 },
};
const REST = 0.05;

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

/** Quadratic curve in a 0 to 100 box. The control sits at twice the bend so the line peaks at the bend. */
export const curve = (vertical: boolean, along = 50, bend = 0) =>
  vertical
    ? `M50 0Q${50 + 2 * bend} ${along} 50 100`
    : `M0 50Q${along} ${50 + 2 * bend} 100 50`;

/**
 * Bend the line toward (pull), away from (push), or with the pointer until it slips (pluck), then spring
 * back. requestAnimationFrame only runs while the pointer is near or the line still moves.
 */
function createLine(
  root: HTMLElement,
  path: SVGPathElement,
  vertical: boolean,
  variant: ElasticLineVariant,
  playOnView: boolean,
) {
  let pointer: { along: number; perp: number } | null = null;
  let along = 50;
  let bend = 0;
  let speed = 0;
  let grabbed = false;
  let frame = 0;
  const reach = () => {
    const rect = root.getBoundingClientRect();
    return (vertical ? rect.width : rect.height) / 2 || 1;
  };

  const step = () => {
    const half = reach();
    let target = 0;
    let spring = SPRINGS.release;
    if (pointer) {
      along = Math.min(Math.max(pointer.along, 10), 90);
      const perp = pointer.perp;
      if (variant === "pull") target = perp;
      if (variant === "push")
        target = -Math.sign(perp || 1) * (half - Math.abs(perp)) * 0.6;
      if (variant === "pluck") {
        if (Math.abs(perp) > half * 0.8) grabbed = false;
        if (grabbed) target = perp;
      }
      if (variant !== "pluck") spring = SPRINGS[variant];
      else if (grabbed) spring = SPRINGS.pluck;
    }
    speed = (speed + (target - bend) * spring.k) * spring.d;
    bend += speed;
    const settled = !pointer && Math.abs(bend) < REST && Math.abs(speed) < REST;
    if (settled) bend = speed = 0;
    path.setAttribute("d", curve(vertical, along, (bend / half) * 50));
    frame = settled ? 0 : requestAnimationFrame(step);
  };
  const wake = () => {
    frame ||= requestAnimationFrame(step);
  };

  const move = (event: PointerEvent) => {
    if (still()) return;
    const rect = root.getBoundingClientRect();
    const x = event.clientX - rect.left;
    const y = event.clientY - rect.top;
    const next = vertical
      ? { along: (y / rect.height) * 100, perp: x - rect.width / 2 }
      : { along: (x / rect.width) * 100, perp: y - rect.height / 2 };
    // Pluck grabs when the pointer touches or crosses the line, even between two frames.
    const crossed = pointer && Math.sign(pointer.perp) !== Math.sign(next.perp);
    if (Math.abs(next.perp) < 6 || crossed) grabbed = true;
    pointer = next;
    wake();
  };
  const leave = () => {
    pointer = null;
    grabbed = false;
    wake();
  };
  root.addEventListener("pointermove", move);
  root.addEventListener("pointerleave", leave);

  // Twang once when the line first scrolls into view.
  let observer: IntersectionObserver | null = null;
  if (playOnView && !still() && typeof IntersectionObserver === "function") {
    observer = new IntersectionObserver(([entry]) => {
      if (!entry?.isIntersecting) return;
      observer?.disconnect();
      speed = reach() * 0.5;
      wake();
    });
    observer.observe(root);
  }

  return () => {
    root.removeEventListener("pointermove", move);
    root.removeEventListener("pointerleave", leave);
    observer?.disconnect();
    cancelAnimationFrame(frame);
  };
}

/** Host stays out of layout; class moves to the line. */
@Component({
  selector: "markas-elastic-line",
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { class: "contents" },
  template: `
    <div
      #lineEl
      [attr.role]="decorative() ? null : 'separator'"
      [attr.aria-orientation]="decorative() ? null : orientation()"
      [attr.aria-hidden]="decorative() ? 'true' : null"
      [class]="rootClasses()"
      [style.--reach]="reach() + 'px'"
    >
      <svg
        aria-hidden="true"
        viewBox="0 0 100 100"
        preserveAspectRatio="none"
        [class]="svgClass"
      >
        <path
          #pathEl
          [attr.d]="straight()"
          [attr.stroke-width]="strokeWidth()"
          stroke-linecap="round"
          [class]="pathClass"
        />
      </svg>
    </div>
  `,
})
export class ElasticLine {
  /** How the line answers the pointer. */
  readonly variant = input<ElasticLineVariant>("pull");
  /** Direction of the line. */
  readonly orientation = input<ElasticLineOrientation>("horizontal");
  /** Px on each side of the line where the pointer bends it, and the most it can bend. */
  readonly reach = input(24, { transform: numberAttribute });
  /** Line color token. */
  readonly color = input<keyof typeof colors>("line");
  /** Line width in px. */
  readonly strokeWidth = input(1.5, { transform: numberAttribute });
  /** Twangs once when the line first scrolls into view. */
  readonly playOnView = input(false, { transform: booleanAttribute });
  /** Hides the line from assistive tech instead of announcing a separator. */
  readonly decorative = input(false, { transform: booleanAttribute });
  readonly userClass = input("", { alias: "class" });

  protected readonly svgClass = svgClass;
  protected readonly pathClass = pathClass;
  private readonly vertical = computed(() => this.orientation() === "vertical");
  protected readonly straight = computed(() => curve(this.vertical()));
  protected readonly rootClasses = computed(() =>
    [
      base,
      orientations[this.orientation()],
      colors[this.color()],
      this.userClass(),
    ]
      .filter(Boolean)
      .join(" "),
  );
  private readonly lineEl =
    viewChild.required<ElementRef<HTMLDivElement>>("lineEl");
  private readonly pathEl =
    viewChild.required<ElementRef<SVGPathElement>>("pathEl");

  constructor() {
    afterRenderEffect((onCleanup) => {
      const stop = createLine(
        this.lineEl().nativeElement,
        this.pathEl().nativeElement,
        this.vertical(),
        this.variant(),
        this.playOnView(),
      );
      onCleanup(stop);
    });
  }
}
```

```ts
import { Component } from "@angular/core";
import { ElasticLine } from "./markas/elastic-line.component";

@Component({
  selector: "app-services-heading",
  imports: [ElasticLine],
  template: `
    <h2 class="text-3xl font-semibold">Our services</h2>
    <markas-elastic-line
      variant="pluck"
      color="primary"
      [strokeWidth]="3"
      [reach]="16"
      playOnView
      decorative
      class="w-40"
    />
  `,
})
export class ServicesHeading {}
```

## Props

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `variant` | `"pull" \| "push" \| "pluck"` | "pull" | pull: the line bends toward the pointer. push: it bends away like a soft wall. pluck: it follows the pointer once touched, slips free, and vibrates. |
| `orientation` | `"horizontal" \| "vertical"` | "horizontal" | Direction of the line. A vertical line stretches to the height of its flex row. |
| `reach` | `number` | 24 | Px on each side of the line where the pointer bends it. Also the most it can bend. The component is twice this tall (or wide). |
| `color` | `"line" \| "muted" \| "ink" \| "primary" \| "success" \| "warning" \| "danger"` | "line" | Line color token. |
| `strokeWidth` | `number` | 1.5 | Line width in px. It stays the same however wide the line is. |
| `playOnView` | `boolean` | false | Twangs once when the line first scrolls into view. |
| `decorative` | `boolean` | false | Hides the line from assistive tech, for underlines and ornaments. Otherwise it is announced as a separator. |

## Accessibility

- By default the line has role="separator" with aria-orientation; use decorative for underlines so it is hidden instead.
- The bend is drawn by changing one SVG path; requestAnimationFrame only runs while the pointer is close or the line still moves.
- With reduced motion the line stays straight and never twangs.

## Notes

- The component is `reach` x 2 tall (or wide when vertical) and the line runs through its middle. The pointer bends it only inside that band.
- `pull` bends toward the pointer, `push` away from it, and `pluck` follows the pointer once touched until it slips free and vibrates.
- The curve is one quadratic SVG path. requestAnimationFrame only runs while the pointer is close or the line still moves. `playOnView` twangs it once when it first scrolls into view.
- By default it is a `separator`. Use `decorative` for underlines. With reduced motion the line stays straight. Attributes and `class` go to the wrapper.
