# Hold Button

Press-and-hold button for risky actions. A fill tracks progress, releasing early cancels, and a complete event fires.

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

## When to use

Confirming a destructive or costly action without opening a dialog, such as delete, publish, or transfer.

- Run the action in onComplete, not in onClick
- Say hold in the label, for example Hold to delete
- Keep duration between 1000 and 3000 ms

## Code

### Blade

Save at `resources/views/components/markas/hold-button.blade.php`. Dependencies: alpinejs.

```blade
@props([
    'variant' => 'primary',
    'size' => 'md',
    'duration' => 1500,
    'holdLabel' => 'Press and hold to confirm',
])

@php
    $wrapper = 'contents';
    $base = 'group relative isolate inline-flex items-center justify-center gap-2 overflow-hidden font-medium whitespace-nowrap select-none transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none';
    $variants = [
        'primary' => 'bg-primary text-on-primary hover:bg-primary-strong',
        'secondary' => 'border border-line bg-surface text-ink hover:bg-subtle',
        'ghost' => 'text-ink hover:bg-subtle',
        'danger' => 'bg-danger text-on-primary hover:bg-danger/90',
    ];
    $sizes = [
        'sm' => 'h-8 rounded-md px-3 text-sm',
        'md' => 'h-10 rounded-lg px-4 text-sm',
        'lg' => 'h-12 rounded-lg px-6 text-base',
    ];
    $fill = 'pointer-events-none absolute inset-0 -z-10 origin-left scale-x-0 transition-transform duration-200 ease-out group-data-[state=complete]:scale-x-100 group-data-[state=holding]:scale-x-100 group-data-[state=holding]:duration-(--hold-duration) group-data-[state=holding]:ease-linear';
    $fillVariants = [
        'primary' => 'bg-on-primary/25',
        'secondary' => 'bg-primary/10',
        'ghost' => 'bg-primary/10',
        'danger' => 'bg-on-primary/25',
    ];
    $srOnly = 'sr-only';

    $duration = (int) $duration;
    // Same id on every render, so Livewire's morph (which matches elements by id) keeps the element. Pass `id` to set it.
    $idKey = 'markas-hold-button|'.(isset($this) && $this instanceof \Livewire\Component ? $this->getId() : '').'|'.($attributes->get('wire:key') ?? $attributes->whereStartsWith('wire:model')->first() ?? $attributes->get('name')).'|';
    for ($idIndex = 0; $__env->hasRenderedOnce($idKey.$idIndex); $idIndex++);
    $__env->markAsRenderedOnce($idKey.$idIndex);
    $hintId = 'markas-hold-button-'.hash('xxh32', $idKey.$idIndex);
@endphp

{{-- Holding Space, Enter, or the pointer for the full duration dispatches a "complete" event. Releasing early cancels. --}}
<span class="{{ $wrapper }}">
    <button
        x-data="{
            state: 'idle',
            timer: null,
            start() {
                if (this.state !== 'idle') return;
                this.state = 'holding';
                this.timer = setTimeout(() => {
                    this.state = 'complete';
                    this.$dispatch('complete');
                }, {{ $duration }});
            },
            cancel() {
                clearTimeout(this.timer);
                this.state = 'idle';
            },
            destroy() {
                clearTimeout(this.timer);
            },
        }"
        data-state="idle"
        x-bind:data-state="state"
        aria-describedby="{{ $hintId }}"
        x-on:pointerdown="$event.button === 0 && start()"
        x-on:pointerup="cancel()"
        x-on:pointerleave="cancel()"
        x-on:pointercancel="cancel()"
        x-on:keydown.space.prevent="$event.repeat || start()"
        x-on:keydown.enter.prevent="$event.repeat || start()"
        x-on:keyup.space="cancel()"
        x-on:keyup.enter="cancel()"
        x-on:blur="cancel()"
        x-on:contextmenu.prevent
        {{ $attributes->merge(['type' => 'button', 'style' => "--hold-duration: {$duration}ms"])->class([$base, $variants[$variant], $sizes[$size]]) }}
    >
        <span class="{{ $fill }} {{ $fillVariants[$variant] }}" aria-hidden="true"></span>
        {{ $slot }}
    </button>
    <span id="{{ $hintId }}" class="{{ $srOnly }}">{{ $holdLabel }}</span>
</span>
```

```blade
<form method="POST" action="/workspace" x-data x-on:complete="$el.submit()">
    @csrf
    @method('DELETE')
    <x-markas.hold-button variant="danger" :duration="2000">Hold to delete</x-markas.hold-button>
</form>
```

### React

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

```tsx
"use client";

import {
  useEffect,
  useId,
  useRef,
  useState,
  type ComponentProps,
  type CSSProperties,
  type KeyboardEvent,
  type PointerEvent,
} from "react";

const wrapper = "contents";
const base =
  "group relative isolate inline-flex items-center justify-center gap-2 overflow-hidden font-medium whitespace-nowrap select-none transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none";
const variants = {
  primary: "bg-primary text-on-primary hover:bg-primary-strong",
  secondary: "border border-line bg-surface text-ink hover:bg-subtle",
  ghost: "text-ink hover:bg-subtle",
  danger: "bg-danger text-on-primary hover:bg-danger/90",
};
const sizes = {
  sm: "h-8 rounded-md px-3 text-sm",
  md: "h-10 rounded-lg px-4 text-sm",
  lg: "h-12 rounded-lg px-6 text-base",
};
const fill =
  "pointer-events-none absolute inset-0 -z-10 origin-left scale-x-0 transition-transform duration-200 ease-out group-data-[state=complete]:scale-x-100 group-data-[state=holding]:scale-x-100 group-data-[state=holding]:duration-(--hold-duration) group-data-[state=holding]:ease-linear";
const fillVariants = {
  primary: "bg-on-primary/25",
  secondary: "bg-primary/10",
  ghost: "bg-primary/10",
  danger: "bg-on-primary/25",
};
const srOnly = "sr-only";

const HOLD_KEYS = new Set([" ", "Enter"]);

const cx = (...c: (string | false | null | undefined)[]) =>
  c.filter(Boolean).join(" ");

type HoldState = "idle" | "holding" | "complete";

export type HoldButtonProps = ComponentProps<"button"> & {
  variant?: keyof typeof variants;
  size?: keyof typeof sizes;
  /** How long the button must be held, in milliseconds. */
  duration?: number;
  /** Hidden hint read by screen readers. */
  holdLabel?: string;
  /** Called once the hold reaches the full duration. */
  onComplete?: () => void;
};

export function HoldButton({
  variant = "primary",
  size = "md",
  duration = 1500,
  holdLabel = "Press and hold to confirm",
  onComplete,
  type = "button",
  className,
  style,
  children,
  onPointerDown,
  onPointerUp,
  onPointerLeave,
  onPointerCancel,
  onKeyDown,
  onKeyUp,
  onBlur,
  ...props
}: HoldButtonProps) {
  const hintId = useId();
  const [state, setState] = useState<HoldState>("idle");
  const timer = useRef<ReturnType<typeof setTimeout>>(undefined);
  useEffect(() => () => clearTimeout(timer.current), []);

  const start = () => {
    if (state !== "idle") return;
    setState("holding");
    timer.current = setTimeout(() => {
      setState("complete");
      onComplete?.();
    }, duration);
  };
  const cancel = () => {
    clearTimeout(timer.current);
    setState("idle");
  };

  return (
    <span className={wrapper}>
      <button
        type={type}
        data-state={state}
        aria-describedby={hintId}
        style={
          { ...style, "--hold-duration": `${duration}ms` } as CSSProperties
        }
        className={cx(base, variants[variant], sizes[size], className)}
        onPointerDown={(event: PointerEvent<HTMLButtonElement>) => {
          onPointerDown?.(event);
          if (event.button === 0) start();
        }}
        onPointerUp={(event: PointerEvent<HTMLButtonElement>) => {
          onPointerUp?.(event);
          cancel();
        }}
        onPointerLeave={(event: PointerEvent<HTMLButtonElement>) => {
          onPointerLeave?.(event);
          cancel();
        }}
        onPointerCancel={(event: PointerEvent<HTMLButtonElement>) => {
          onPointerCancel?.(event);
          cancel();
        }}
        onKeyDown={(event: KeyboardEvent<HTMLButtonElement>) => {
          onKeyDown?.(event);
          if (!HOLD_KEYS.has(event.key)) return;
          event.preventDefault();
          if (!event.repeat) start();
        }}
        onKeyUp={(event: KeyboardEvent<HTMLButtonElement>) => {
          onKeyUp?.(event);
          if (HOLD_KEYS.has(event.key)) cancel();
        }}
        onBlur={(event) => {
          onBlur?.(event);
          cancel();
        }}
        onContextMenu={(event) => event.preventDefault()}
        {...props}
      >
        <span className={cx(fill, fillVariants[variant])} aria-hidden="true" />
        {children}
      </button>
      <span id={hintId} className={srOnly}>
        {holdLabel}
      </span>
    </span>
  );
}
```

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

<HoldButton variant="danger" duration={2000} onComplete={deleteWorkspace}>
  Hold to delete
</HoldButton>;
```

### Vue

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

```vue
<script setup lang="ts">
import { onBeforeUnmount, ref, useId } from "vue";

defineOptions({ inheritAttrs: false });

const variants = {
  primary: "bg-primary text-on-primary hover:bg-primary-strong",
  secondary: "border border-line bg-surface text-ink hover:bg-subtle",
  ghost: "text-ink hover:bg-subtle",
  danger: "bg-danger text-on-primary hover:bg-danger/90",
};
const sizes = {
  sm: "h-8 rounded-md px-3 text-sm",
  md: "h-10 rounded-lg px-4 text-sm",
  lg: "h-12 rounded-lg px-6 text-base",
};
const fillVariants = {
  primary: "bg-on-primary/25",
  secondary: "bg-primary/10",
  ghost: "bg-primary/10",
  danger: "bg-on-primary/25",
};

const props = withDefaults(
  defineProps<{
    variant?: keyof typeof variants;
    size?: keyof typeof sizes;
    /** How long the button must be held, in milliseconds. */
    duration?: number;
    /** Hidden hint read by screen readers. */
    holdLabel?: string;
  }>(),
  {
    variant: "primary",
    size: "md",
    duration: 1500,
    holdLabel: "Press and hold to confirm",
  },
);
const emit = defineEmits<{ complete: [] }>();

const wrapper = "contents";
const base =
  "group relative isolate inline-flex items-center justify-center gap-2 overflow-hidden font-medium whitespace-nowrap select-none transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none";
const fill =
  "pointer-events-none absolute inset-0 -z-10 origin-left scale-x-0 transition-transform duration-200 ease-out group-data-[state=complete]:scale-x-100 group-data-[state=holding]:scale-x-100 group-data-[state=holding]:duration-(--hold-duration) group-data-[state=holding]:ease-linear";
const srOnly = "sr-only";

const HOLD_KEYS = new Set([" ", "Enter"]);

const hintId = useId();
const state = ref<"idle" | "holding" | "complete">("idle");
let timer: ReturnType<typeof setTimeout> | undefined;
onBeforeUnmount(() => clearTimeout(timer));

function start() {
  if (state.value !== "idle") return;
  state.value = "holding";
  timer = setTimeout(() => {
    state.value = "complete";
    emit("complete");
  }, props.duration);
}
function cancel() {
  clearTimeout(timer);
  state.value = "idle";
}
function onKeydown(event: KeyboardEvent) {
  if (!HOLD_KEYS.has(event.key)) return;
  event.preventDefault();
  if (!event.repeat) start();
}
function onKeyup(event: KeyboardEvent) {
  if (HOLD_KEYS.has(event.key)) cancel();
}
</script>

<template>
  <span :class="wrapper">
    <button
      type="button"
      :data-state="state"
      :aria-describedby="hintId"
      :style="{ '--hold-duration': `${props.duration}ms` }"
      :class="[base, variants[props.variant], sizes[props.size]]"
      v-bind="$attrs"
      @pointerdown="$event.button === 0 && start()"
      @pointerup="cancel"
      @pointerleave="cancel"
      @pointercancel="cancel"
      @keydown="onKeydown"
      @keyup="onKeyup"
      @blur="cancel"
      @contextmenu.prevent
    >
      <span :class="[fill, fillVariants[props.variant]]" aria-hidden="true" />
      <slot />
    </button>
    <span :id="hintId" :class="srOnly">{{ props.holdLabel }}</span>
  </span>
</template>
```

```vue
<script setup lang="ts">
import HoldButton from "@/components/markas/HoldButton.vue";
</script>

<template>
  <HoldButton variant="danger" :duration="2000" @complete="deleteWorkspace">
    Hold to delete
  </HoldButton>
</template>
```

### Svelte

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

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

  const wrapper = "contents";
  const base =
    "group relative isolate inline-flex items-center justify-center gap-2 overflow-hidden font-medium whitespace-nowrap select-none transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none";
  const variants = {
    primary: "bg-primary text-on-primary hover:bg-primary-strong",
    secondary: "border border-line bg-surface text-ink hover:bg-subtle",
    ghost: "text-ink hover:bg-subtle",
    danger: "bg-danger text-on-primary hover:bg-danger/90",
  };
  const sizes = {
    sm: "h-8 rounded-md px-3 text-sm",
    md: "h-10 rounded-lg px-4 text-sm",
    lg: "h-12 rounded-lg px-6 text-base",
  };
  const fill =
    "pointer-events-none absolute inset-0 -z-10 origin-left scale-x-0 transition-transform duration-200 ease-out group-data-[state=complete]:scale-x-100 group-data-[state=holding]:scale-x-100 group-data-[state=holding]:duration-(--hold-duration) group-data-[state=holding]:ease-linear";
  const fillVariants = {
    primary: "bg-on-primary/25",
    secondary: "bg-primary/10",
    ghost: "bg-primary/10",
    danger: "bg-on-primary/25",
  };
  const srOnly = "sr-only";

  const HOLD_KEYS = new Set([" ", "Enter"]);

  type Props = HTMLButtonAttributes & {
    variant?: keyof typeof variants;
    size?: keyof typeof sizes;
    /** How long the button must be held, in milliseconds. */
    duration?: number;
    /** Hidden hint read by screen readers. */
    holdLabel?: string;
    /** Called once the hold reaches the full duration. */
    oncomplete?: () => void;
    children?: Snippet;
  };

  let {
    variant = "primary",
    size = "md",
    duration = 1500,
    holdLabel = "Press and hold to confirm",
    oncomplete,
    type = "button",
    class: className,
    style,
    children,
    onpointerdown,
    onpointerup,
    onpointerleave,
    onpointercancel,
    onkeydown,
    onkeyup,
    onblur,
    ...rest
  }: Props = $props();

  const hintId = $props.id();
  let state = $state<"idle" | "holding" | "complete">("idle");
  let timer: ReturnType<typeof setTimeout> | undefined;
  onDestroy(() => clearTimeout(timer));

  type Handler<E extends Event> = E & {
    currentTarget: EventTarget & HTMLButtonElement;
  };

  function start() {
    if (state !== "idle") return;
    state = "holding";
    timer = setTimeout(() => {
      state = "complete";
      oncomplete?.();
    }, duration);
  }
  function cancel() {
    clearTimeout(timer);
    state = "idle";
  }
</script>

<span class={wrapper}>
  <button
    {type}
    data-state={state}
    aria-describedby={hintId}
    style={`${style ? `${style};` : ""}--hold-duration: ${duration}ms`}
    class={[base, variants[variant], sizes[size], className]}
    onpointerdown={(event: Handler<PointerEvent>) => {
      onpointerdown?.(event);
      if (event.button === 0) start();
    }}
    onpointerup={(event: Handler<PointerEvent>) => {
      onpointerup?.(event);
      cancel();
    }}
    onpointerleave={(event: Handler<PointerEvent>) => {
      onpointerleave?.(event);
      cancel();
    }}
    onpointercancel={(event: Handler<PointerEvent>) => {
      onpointercancel?.(event);
      cancel();
    }}
    onkeydown={(event: Handler<KeyboardEvent>) => {
      onkeydown?.(event);
      if (!HOLD_KEYS.has(event.key)) return;
      event.preventDefault();
      if (!event.repeat) start();
    }}
    onkeyup={(event: Handler<KeyboardEvent>) => {
      onkeyup?.(event);
      if (HOLD_KEYS.has(event.key)) cancel();
    }}
    onblur={(event: Handler<FocusEvent>) => {
      onblur?.(event);
      cancel();
    }}
    oncontextmenu={(event) => event.preventDefault()}
    {...rest}
  >
    <span class={[fill, fillVariants[variant]]} aria-hidden="true"></span>
    {@render children?.()}
  </button>
  <span id={hintId} class={srOnly}>{holdLabel}</span>
</span>
```

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

<HoldButton variant="danger" duration={2000} oncomplete={deleteWorkspace}>
  Hold to delete
</HoldButton>
```

### Astro

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

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

const wrapper = "contents";
const base =
  "group relative isolate inline-flex items-center justify-center gap-2 overflow-hidden font-medium whitespace-nowrap select-none transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none";
const variants = {
  primary: "bg-primary text-on-primary hover:bg-primary-strong",
  secondary: "border border-line bg-surface text-ink hover:bg-subtle",
  ghost: "text-ink hover:bg-subtle",
  danger: "bg-danger text-on-primary hover:bg-danger/90",
};
const sizes = {
  sm: "h-8 rounded-md px-3 text-sm",
  md: "h-10 rounded-lg px-4 text-sm",
  lg: "h-12 rounded-lg px-6 text-base",
};
const fill =
  "pointer-events-none absolute inset-0 -z-10 origin-left scale-x-0 transition-transform duration-200 ease-out group-data-[state=complete]:scale-x-100 group-data-[state=holding]:scale-x-100 group-data-[state=holding]:duration-(--hold-duration) group-data-[state=holding]:ease-linear";
const fillVariants = {
  primary: "bg-on-primary/25",
  secondary: "bg-primary/10",
  ghost: "bg-primary/10",
  danger: "bg-on-primary/25",
};
const srOnly = "sr-only";

type Props = HTMLAttributes<"button"> & {
  variant?: keyof typeof variants;
  size?: keyof typeof sizes;
  /** How long the button must be held, in milliseconds. */
  duration?: number;
  /** Hidden hint read by screen readers. */
  holdLabel?: string;
};

const {
  variant = "primary",
  size = "md",
  duration = 1500,
  holdLabel = "Press and hold to confirm",
  type = "button",
  class: className,
  style,
  ...rest
} = Astro.props;
const hintId = `markas-hold-button-${crypto.randomUUID().slice(0, 8)}`;
const holdDuration = `--hold-duration: ${Number(duration)}ms`;
---

<span class={wrapper}>
  <button
    type={type}
    data-state="idle"
    data-markas-hold-button={Number(duration)}
    aria-describedby={hintId}
    style={typeof style === "string" && style ? `${style};${holdDuration}` : holdDuration}
    class:list={[base, variants[variant], sizes[size], className]}
    {...rest}
  >
    <span class:list={[fill, fillVariants[variant]]} aria-hidden="true"></span>
    <slot />
  </button>
  <span id={hintId} class={srOnly}>{holdLabel}</span>
</span>

<script>
  // One set of listeners per page serves every hold button. Holding Space, Enter, or the
  // pointer for the full duration dispatches a bubbling "complete" event. Releasing early cancels.
  const SELECTOR = "[data-markas-hold-button]";
  const HOLD_KEYS = new Set([" ", "Enter"]);
  const timers = new WeakMap<HTMLElement, ReturnType<typeof setTimeout>>();

  const closest = (event: Event) =>
    event.target instanceof Element
      ? event.target.closest<HTMLElement>(SELECTOR)
      : null;
  /** Leave and blur do not bubble: only react when the hold button itself is the target. */
  const self = (event: Event) =>
    event.target instanceof HTMLElement && event.target.matches(SELECTOR)
      ? event.target
      : null;

  const start = (button: HTMLElement) => {
    if (button.dataset.state !== "idle") return;
    button.dataset.state = "holding";
    timers.set(
      button,
      setTimeout(() => {
        button.dataset.state = "complete";
        button.dispatchEvent(new CustomEvent("complete", { bubbles: true }));
      }, Number(button.dataset.markasHoldButton)),
    );
  };
  const cancel = (button: HTMLElement | null) => {
    if (!button) return;
    clearTimeout(timers.get(button));
    button.dataset.state = "idle";
  };

  document.addEventListener("pointerdown", (event) => {
    const button = closest(event);
    if (button && event.button === 0) start(button);
  });
  for (const type of ["pointerup", "pointercancel"])
    document.addEventListener(type, (event) => cancel(closest(event)));
  for (const type of ["pointerleave", "blur"])
    document.addEventListener(type, (event) => cancel(self(event)), true);
  document.addEventListener("keydown", (event) => {
    const button = closest(event);
    if (!button || !HOLD_KEYS.has(event.key)) return;
    event.preventDefault();
    if (!event.repeat) start(button);
  });
  document.addEventListener("keyup", (event) => {
    if (HOLD_KEYS.has(event.key)) cancel(closest(event));
  });
  document.addEventListener("contextmenu", (event) => {
    if (closest(event)) event.preventDefault();
  });
</script>
```

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

<HoldButton id="delete-workspace" variant="danger" duration={2000}>
  Hold to delete
</HoldButton>

<script>
  document
    .getElementById("delete-workspace")
    ?.addEventListener("complete", () => deleteWorkspace());
</script>
```

### Angular

Save at `src/app/markas/hold-button.component.ts`. No extra dependencies.

```ts
import {
  booleanAttribute,
  ChangeDetectionStrategy,
  Component,
  computed,
  DestroyRef,
  inject,
  input,
  numberAttribute,
  output,
  signal,
} from "@angular/core";

const wrapper = "contents";
const base =
  "group relative isolate inline-flex items-center justify-center gap-2 overflow-hidden font-medium whitespace-nowrap select-none transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none";
const variants = {
  primary: "bg-primary text-on-primary hover:bg-primary-strong",
  secondary: "border border-line bg-surface text-ink hover:bg-subtle",
  ghost: "text-ink hover:bg-subtle",
  danger: "bg-danger text-on-primary hover:bg-danger/90",
};
const sizes = {
  sm: "h-8 rounded-md px-3 text-sm",
  md: "h-10 rounded-lg px-4 text-sm",
  lg: "h-12 rounded-lg px-6 text-base",
};
const fill =
  "pointer-events-none absolute inset-0 -z-10 origin-left scale-x-0 transition-transform duration-200 ease-out group-data-[state=complete]:scale-x-100 group-data-[state=holding]:scale-x-100 group-data-[state=holding]:duration-(--hold-duration) group-data-[state=holding]:ease-linear";
const fillVariants = {
  primary: "bg-on-primary/25",
  secondary: "bg-primary/10",
  ghost: "bg-primary/10",
  danger: "bg-on-primary/25",
};
const srOnly = "sr-only";

const HOLD_KEYS = new Set([" ", "Enter"]);

let nextId = 0;

export type HoldButtonVariant = keyof typeof variants;
export type HoldButtonSize = keyof typeof sizes;
type HoldState = "idle" | "holding" | "complete";

/**
 * Host stays out of layout (display: contents). id, aria-label, title, and class move to the
 * button. Holding Space, Enter, or the pointer for the full duration emits `complete`.
 */
@Component({
  selector: "markas-hold-button",
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: {
    class: "contents",
    "[attr.id]": "null",
    "[attr.aria-label]": "null",
    "[attr.title]": "null",
  },
  template: `
    <span [class]="wrapper">
      <button
        [attr.type]="type()"
        [attr.id]="id() ?? null"
        [attr.aria-label]="ariaLabel() ?? null"
        [attr.title]="title() ?? null"
        [disabled]="disabled()"
        [attr.data-state]="state()"
        [attr.aria-describedby]="hintId"
        [style.--hold-duration]="duration() + 'ms'"
        [class]="classes()"
        (pointerdown)="$event.button === 0 && start()"
        (pointerup)="cancel()"
        (pointerleave)="cancel()"
        (pointercancel)="cancel()"
        (keydown)="onKeydown($event)"
        (keyup)="onKeyup($event)"
        (blur)="cancel()"
        (contextmenu)="$event.preventDefault()"
      >
        <span [class]="fillClasses()" aria-hidden="true"></span>
        <ng-content />
      </button>
      <span [id]="hintId" [class]="srOnly">{{ holdLabel() }}</span>
    </span>
  `,
})
export class HoldButton {
  readonly variant = input<HoldButtonVariant>("primary");
  readonly size = input<HoldButtonSize>("md");
  /** How long the button must be held, in milliseconds. */
  readonly duration = input(1500, { transform: numberAttribute });
  /** Hidden hint read by screen readers. */
  readonly holdLabel = input("Press and hold to confirm");
  readonly type = input<"button" | "submit" | "reset">("button");
  readonly disabled = input(false, { transform: booleanAttribute });
  readonly id = input<string>();
  readonly title = input<string>();
  readonly ariaLabel = input<string | undefined>(undefined, {
    alias: "aria-label",
  });
  readonly userClass = input("", { alias: "class" });
  /** Emits once the hold reaches the full duration. */
  readonly complete = output<void>();

  protected readonly wrapper = wrapper;
  protected readonly srOnly = srOnly;
  protected readonly hintId = `markas-hold-button-${nextId++}`;
  protected readonly state = signal<HoldState>("idle");
  protected readonly classes = computed(() =>
    [base, variants[this.variant()], sizes[this.size()], this.userClass()]
      .filter(Boolean)
      .join(" "),
  );
  protected readonly fillClasses = computed(
    () => `${fill} ${fillVariants[this.variant()]}`,
  );
  private timer: ReturnType<typeof setTimeout> | undefined;

  constructor() {
    inject(DestroyRef).onDestroy(() => clearTimeout(this.timer));
  }

  protected start() {
    if (this.state() !== "idle") return;
    this.state.set("holding");
    this.timer = setTimeout(() => {
      this.state.set("complete");
      this.complete.emit();
    }, this.duration());
  }

  protected cancel() {
    clearTimeout(this.timer);
    this.state.set("idle");
  }

  protected onKeydown(event: KeyboardEvent) {
    if (!HOLD_KEYS.has(event.key)) return;
    event.preventDefault();
    if (!event.repeat) this.start();
  }

  protected onKeyup(event: KeyboardEvent) {
    if (HOLD_KEYS.has(event.key)) this.cancel();
  }
}
```

```ts
import { Component } from "@angular/core";
import { HoldButton } from "./markas/hold-button.component";

@Component({
  selector: "app-dangerzone",
  imports: [HoldButton],
  template: `
    <markas-hold-button
      variant="danger"
      [duration]="2000"
      (complete)="deleteWorkspace()"
    >
      Hold to delete
    </markas-hold-button>
  `,
})
export class DangerZone {
  deleteWorkspace() {}
}
```

Astro dispatches a bubbling `complete` DOM event from the button. Angular moves `id`, `aria-label`, `title`, and `class` from `markas-hold-button` to the inner button.

## Props

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `variant` | `'primary' \| 'secondary' \| 'ghost' \| 'danger'` | primary | Visual style, the same set as Button. |
| `size` | `'sm' \| 'md' \| 'lg'` | md | Height 32, 40, or 48px, the same as Button. |
| `duration` | `number` | 1500 | How long the button must be held, in milliseconds. |
| `holdLabel` | `string` | Press and hold to confirm | Hidden hint linked with aria-describedby. |
| `onComplete / @complete / oncomplete / (complete)` | `() => void` | - | Fires once the hold reaches the full duration (React, Vue, Svelte, Angular). Blade and Astro dispatch a bubbling complete DOM event. |

## Accessibility

- Holding Space or Enter works like holding the pointer, releasing the key cancels.
- holdLabel is linked with aria-describedby so screen readers explain the gesture.
- The state is exposed as data-state idle, holding, or complete.
- The progress fill keeps running with reduced motion because it carries meaning, it is a linear fill without movement.

## Notes

- Run the action in the complete event. A short click does nothing.
- Pointer up, pointer leave, blur, or releasing Space or Enter before the end cancels and the fill slides back.
- The button keeps data-state="complete" until it is released. Blade dispatches a bubbling `complete` DOM event and needs Alpine.js.
