# Dock

Dock ala macOS. Ikon membesar halus mengikuti kursor atau fokus, label muncul di atas, item terbuka bertitik, dan memantul saat dibuka.

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

## Kapan dipakai

Peluncur atau bar aksi cepat yang playful untuk portofolio, aplikasi bergaya desktop, atau editor kanvas.

- Jaga label satu atau dua kata
- Tandai aplikasi terbuka atau halaman saat ini dengan active
- Kelompokkan item terkait dengan item separator
- Turunkan magnification ke sekitar 1.3 untuk alat kerja yang dipakai seharian

## Kode

### Blade

Simpan di `resources/views/components/markas/dock.blade.php`. Dependensi: alpinejs.

```blade
@props([
    'items' => [],
    'magnification' => 1.6,
    'dockLabel' => 'Dock',
])

@php
    $root = 'relative inline-flex h-[60px] max-w-full min-w-0 items-end gap-2 rounded-2xl border border-line bg-surface/80 px-2.5 pb-2.5 shadow-overlay backdrop-blur-md';
    $itemWrap = 'relative h-10 w-[calc(2.5rem*var(--dock-scale,1))] transition-[width] duration-150 ease-out motion-reduce:transition-none';
    $itemClass = 'group/dock absolute bottom-0 left-0 grid aspect-square w-full place-items-center rounded-xl border border-line bg-linear-to-b from-surface to-subtle text-ink transition-colors duration-150 ease-out hover:to-primary-soft focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none';
    $iconClass = 'size-[55%]';
    $tooltip = 'pointer-events-none absolute bottom-full left-1/2 mb-2 -translate-x-1/2 translate-y-1 rounded-md bg-primary px-2 py-1 text-xs font-medium whitespace-nowrap text-on-primary opacity-0 shadow-overlay transition-[opacity,translate] duration-150 ease-out group-hover/dock:translate-y-0 group-hover/dock:opacity-100 group-focus-visible/dock:translate-y-0 group-focus-visible/dock:opacity-100 motion-reduce:transition-none';
    $dot = 'absolute -bottom-1.5 left-1/2 size-1 -translate-x-1/2 rounded-full bg-ink';
    $separator = 'mx-0.5 mb-1 h-8 w-px shrink-0 bg-line';

    // Href with a scheme other than http, https, mailto, or tel (such as javascript:) becomes "#".
    $safeHref = fn (string $href): string => preg_match('/^(?!https?:|mailto:|tel:)[a-z][\w+.\-]*:/i', preg_replace('/[\x00-\x20]/', '', $href)) === 1 ? '#' : $href;
    $position = -1;
@endphp

{{-- Items grow with their distance to the pointer or the focused item. Pressing one dispatches a select event with its value. --}}
<div
    x-data="{
        focusIndex: 0,
        magnification: {{ (float) $magnification }},
        {{-- Pointer distance in px over which neighbours still grow, and the launch bounce. --}}
        range: 140,
        still() {
            return matchMedia('(prefers-reduced-motion: reduce)').matches;
        },
        controls() {
            return Array.from(this.$root.querySelectorAll('[data-dock-item] > :first-child'));
        },
        center(element) {
            const rect = element.getBoundingClientRect();
            return rect.left + rect.width / 2;
        },
        {{-- Grow every item by its distance to x with a cosine falloff. x null resets the dock. --}}
        magnify(x) {
            const off = x === null || this.still();
            for (const item of this.$root.querySelectorAll('[data-dock-item]')) {
                const rect = item.getBoundingClientRect();
                const distance = off ? this.range : Math.abs(x - rect.left - rect.width / 2);
                const scale = distance >= this.range ? 1 : 1 + ((this.magnification - 1) * (1 + Math.cos((Math.PI * distance) / this.range))) / 2;
                item.style.setProperty('--dock-scale', String(scale));
            }
        },
        move(event) {
            const all = this.controls();
            const index = all.indexOf(event.target);
            const targets = { ArrowRight: (index + 1) % all.length, ArrowLeft: (index - 1 + all.length) % all.length, Home: 0, End: all.length - 1 };
            const target = targets[event.key];
            if (index < 0 || target === undefined) return;
            event.preventDefault();
            all[target].focus();
        },
        focused(event) {
            const index = this.controls().indexOf(event.target);
            if (index < 0) return;
            this.focusIndex = index;
            this.magnify(this.center(event.target));
        },
        blurred(event) {
            if (!this.$root.contains(event.relatedTarget)) this.magnify(null);
        },
        left() {
            const focused = this.$root.contains(document.activeElement);
            this.magnify(focused ? this.center(document.activeElement) : null);
        },
        launch(event, value) {
            if (!this.still()) event.currentTarget.animate([{ transform: 'none' }, { transform: 'translateY(-12px)' }, { transform: 'none' }], { duration: 450, easing: 'cubic-bezier(0.3, 0, 0.3, 1)' });
            this.$dispatch('select', value);
        },
    }"
    role="toolbar"
    aria-label="{{ $dockLabel }}"
    aria-orientation="horizontal"
    x-on:keydown="move($event)"
    x-on:focusin="focused($event)"
    x-on:focusout="blurred($event)"
    x-on:pointermove="magnify($event.clientX)"
    x-on:pointerleave="left()"
    {{ $attributes->class([$root]) }}
>
    @foreach ($items as $item)
        @if ($item['separator'] ?? false)
            <div role="separator" aria-orientation="vertical" class="{{ $separator }}"></div>
        @else
            @php
                $position++;
                $tag = isset($item['href']) ? 'a' : 'button';
                $value = (string) ($item['value'] ?? $item['label']);
            @endphp
            <div data-dock-item class="{{ $itemWrap }}">
                <{{ $tag }}
                    @if ($tag === 'a') href="{{ $safeHref($item['href']) }}" @else type="button" @endif
                    tabindex="{{ $position === 0 ? '0' : '-1' }}"
                    x-bind:tabindex="focusIndex === {{ $position }} ? 0 : -1"
                    @if ($item['active'] ?? false) aria-current="true" @endif
                    x-on:click="launch($event, @js($value))"
                    class="{{ $itemClass }}"
                >
                    <svg class="{{ $iconClass }}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="{{ $item['icon'] }}" /></svg>
                    <span class="{{ $tooltip }}">{{ $item['label'] }}</span>
                </{{ $tag }}>
                @if ($item['active'] ?? false)
                    <span aria-hidden="true" class="{{ $dot }}"></span>
                @endif
            </div>
        @endif
    @endforeach
</div>
```

```blade
<x-markas.dock
    dock-label="Dok aplikasi"
    :magnification="1.6"
    x-on:select="bukaAplikasi($event.detail)"
    :items="[
        ['label' => 'Berkas', 'value' => 'files', 'icon' => 'M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z', 'active' => true],
        ['label' => 'Surel', 'value' => 'mail', 'icon' => 'M3 7a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2zM3 7l9 6 9-6'],
        ['separator' => true],
        ['label' => 'Blog', 'href' => '/blog', 'icon' => 'M12 20h9M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4z'],
    ]"
/>
```

### React

Simpan di `src/components/markas/Dock.tsx`. Tanpa dependensi tambahan.

```tsx
"use client";

import {
  useRef,
  useState,
  type ComponentProps,
  type FocusEvent,
  type KeyboardEvent,
  type MouseEvent,
} from "react";

const root =
  "relative inline-flex h-[60px] max-w-full min-w-0 items-end gap-2 rounded-2xl border border-line bg-surface/80 px-2.5 pb-2.5 shadow-overlay backdrop-blur-md";
const itemWrap =
  "relative h-10 w-[calc(2.5rem*var(--dock-scale,1))] transition-[width] duration-150 ease-out motion-reduce:transition-none";
const itemClass =
  "group/dock absolute bottom-0 left-0 grid aspect-square w-full place-items-center rounded-xl border border-line bg-linear-to-b from-surface to-subtle text-ink transition-colors duration-150 ease-out hover:to-primary-soft focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
const iconClass = "size-[55%]";
const tooltip =
  "pointer-events-none absolute bottom-full left-1/2 mb-2 -translate-x-1/2 translate-y-1 rounded-md bg-primary px-2 py-1 text-xs font-medium whitespace-nowrap text-on-primary opacity-0 shadow-overlay transition-[opacity,translate] duration-150 ease-out group-hover/dock:translate-y-0 group-hover/dock:opacity-100 group-focus-visible/dock:translate-y-0 group-focus-visible/dock:opacity-100 motion-reduce:transition-none";
const dot =
  "absolute -bottom-1.5 left-1/2 size-1 -translate-x-1/2 rounded-full bg-ink";
const separator = "mx-0.5 mb-1 h-8 w-px shrink-0 bg-line";

/** Pointer distance in px over which neighbours still grow, and the launch bounce. */
const RANGE = 140;
const BOUNCE = [
  { transform: "none" },
  { transform: "translateY(-12px)" },
  { transform: "none" },
];
const BOUNCE_TIMING = { duration: 450, easing: "cubic-bezier(0.3, 0, 0.3, 1)" };

/** Href with a scheme other than http, https, mailto, or tel (such as javascript:) becomes "#". */
const safeHref = (href: string) =>
  /^(?!https?:|mailto:|tel:)[a-z][\w+.-]*:/i.test(href.replace(/[\0- ]/g, ""))
    ? "#"
    : href;

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

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

/** Grow every item by its distance to x with a cosine falloff. x null resets the dock. */
function magnify(
  root: HTMLElement | null,
  magnification: number,
  x: number | null,
) {
  const off = x === null || still();
  for (const item of root?.querySelectorAll<HTMLElement>("[data-dock-item]") ??
    []) {
    const rect = item.getBoundingClientRect();
    const distance = off ? RANGE : Math.abs(x - rect.left - rect.width / 2);
    const scale =
      distance >= RANGE
        ? 1
        : 1 +
          ((magnification - 1) * (1 + Math.cos((Math.PI * distance) / RANGE))) /
            2;
    item.style.setProperty("--dock-scale", String(scale));
  }
}

const centerOf = (element: Element) => {
  const rect = element.getBoundingClientRect();
  return rect.left + rect.width / 2;
};

export type DockItem =
  | {
      separator?: false;
      label: string;
      /** Path data (the d attribute) for a 24x24 stroked icon. */
      icon: string;
      value?: string;
      href?: string;
      /** Shows the dot under the item, like an open app. */
      active?: boolean;
    }
  | { separator: true };

export type DockProps = Omit<ComponentProps<"div">, "onSelect"> & {
  items: DockItem[];
  /** How large the item under the pointer or focus grows. 1 turns it off. */
  magnification?: number;
  onItemSelect?: (value: string) => void;
  dockLabel?: string;
};

export function Dock({
  items,
  magnification = 1.6,
  onItemSelect,
  dockLabel = "Dock",
  className,
  ...props
}: DockProps) {
  const rootRef = useRef<HTMLDivElement>(null);
  const [focusIndex, setFocusIndex] = useState(0);
  const controls = () =>
    Array.from(
      rootRef.current?.querySelectorAll<HTMLElement>(
        "[data-dock-item] > :first-child",
      ) ?? [],
    );

  const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
    const all = controls();
    const index = all.indexOf(event.target as HTMLElement);
    const targets: Record<string, number> = {
      ArrowRight: (index + 1) % all.length,
      ArrowLeft: (index - 1 + all.length) % all.length,
      Home: 0,
      End: all.length - 1,
    };
    const target = targets[event.key];
    if (index < 0 || target === undefined) return;
    event.preventDefault();
    all[target]?.focus();
  };
  const onFocus = (event: FocusEvent<HTMLDivElement>) => {
    const index = controls().indexOf(event.target);
    if (index < 0) return;
    setFocusIndex(index);
    magnify(rootRef.current, magnification, centerOf(event.target));
  };
  const onBlur = (event: FocusEvent<HTMLDivElement>) => {
    if (!event.currentTarget.contains(event.relatedTarget))
      magnify(rootRef.current, magnification, null);
  };
  const onLeave = () => {
    const focused = rootRef.current?.contains(document.activeElement);
    magnify(
      rootRef.current,
      magnification,
      focused ? centerOf(document.activeElement!) : null,
    );
  };
  const launch = (event: MouseEvent<HTMLElement>, value: string) => {
    if (!still()) event.currentTarget.animate?.(BOUNCE, BOUNCE_TIMING);
    onItemSelect?.(value);
  };

  /** Position of each item among the focusable ones, -1 for separators. */
  const positions = items.reduce<number[]>(
    (list, item) => [
      ...list,
      item.separator ? -1 : list.filter((position) => position >= 0).length,
    ],
    [],
  );
  return (
    <div
      ref={rootRef}
      role="toolbar"
      aria-label={dockLabel}
      aria-orientation="horizontal"
      className={cx(root, className)}
      onKeyDown={onKeyDown}
      onFocus={onFocus}
      onBlur={onBlur}
      onPointerMove={(event) =>
        magnify(rootRef.current, magnification, event.clientX)
      }
      onPointerLeave={onLeave}
      {...props}
    >
      {items.map((item, index) => {
        if (item.separator)
          return (
            <div
              key={index}
              role="separator"
              aria-orientation="vertical"
              className={separator}
            />
          );
        const shared = {
          tabIndex: positions[index] === focusIndex ? 0 : -1,
          "aria-current": item.active ? ("true" as const) : undefined,
          className: itemClass,
          onClick: (event: MouseEvent<HTMLElement>) =>
            launch(event, item.value ?? item.label),
        };
        const content = (
          <>
            <svg
              className={iconClass}
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="1.5"
              strokeLinecap="round"
              strokeLinejoin="round"
              aria-hidden="true"
            >
              <path d={item.icon} />
            </svg>
            <span className={tooltip}>{item.label}</span>
          </>
        );
        return (
          <div key={index} data-dock-item="" className={itemWrap}>
            {item.href ? (
              <a href={safeHref(item.href)} {...shared}>
                {content}
              </a>
            ) : (
              <button type="button" {...shared}>
                {content}
              </button>
            )}
            {item.active && <span aria-hidden="true" className={dot} />}
          </div>
        );
      })}
    </div>
  );
}
```

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

<Dock
  dockLabel="Dok aplikasi"
  items={[
    { label: "Berkas", value: "files", icon: folderPath, active: true },
    { label: "Surel", value: "mail", icon: mailPath },
    { separator: true },
    { label: "Blog", href: "/blog", icon: penPath },
  ]}
  onItemSelect={bukaAplikasi}
/>;
```

### Vue

Simpan di `src/components/markas/Dock.vue`. Tanpa dependensi tambahan.

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

export type DockItem =
  | {
      separator?: false;
      label: string;
      /** Path data (the d attribute) for a 24x24 stroked icon. */
      icon: string;
      value?: string;
      href?: string;
      /** Shows the dot under the item, like an open app. */
      active?: boolean;
    }
  | { separator: true };

const props = withDefaults(
  defineProps<{
    items: DockItem[];
    /** How large the item under the pointer or focus grows. 1 turns it off. */
    magnification?: number;
    dockLabel?: string;
  }>(),
  { magnification: 1.6, dockLabel: "Dock" },
);
const emit = defineEmits<{ select: [value: string] }>();

const root =
  "relative inline-flex h-[60px] max-w-full min-w-0 items-end gap-2 rounded-2xl border border-line bg-surface/80 px-2.5 pb-2.5 shadow-overlay backdrop-blur-md";
const itemWrap =
  "relative h-10 w-[calc(2.5rem*var(--dock-scale,1))] transition-[width] duration-150 ease-out motion-reduce:transition-none";
const itemClass =
  "group/dock absolute bottom-0 left-0 grid aspect-square w-full place-items-center rounded-xl border border-line bg-linear-to-b from-surface to-subtle text-ink transition-colors duration-150 ease-out hover:to-primary-soft focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
const iconClass = "size-[55%]";
const tooltip =
  "pointer-events-none absolute bottom-full left-1/2 mb-2 -translate-x-1/2 translate-y-1 rounded-md bg-primary px-2 py-1 text-xs font-medium whitespace-nowrap text-on-primary opacity-0 shadow-overlay transition-[opacity,translate] duration-150 ease-out group-hover/dock:translate-y-0 group-hover/dock:opacity-100 group-focus-visible/dock:translate-y-0 group-focus-visible/dock:opacity-100 motion-reduce:transition-none";
const dot =
  "absolute -bottom-1.5 left-1/2 size-1 -translate-x-1/2 rounded-full bg-ink";
const separator = "mx-0.5 mb-1 h-8 w-px shrink-0 bg-line";

/** Pointer distance in px over which neighbours still grow, and the launch bounce. */
const RANGE = 140;
const BOUNCE = [
  { transform: "none" },
  { transform: "translateY(-12px)" },
  { transform: "none" },
];
const BOUNCE_TIMING = { duration: 450, easing: "cubic-bezier(0.3, 0, 0.3, 1)" };

/** Href with a scheme other than http, https, mailto, or tel (such as javascript:) becomes "#". */
const safeHref = (href: string) =>
  /^(?!https?:|mailto:|tel:)[a-z][\w+.-]*:/i.test(href.replace(/[\0- ]/g, ""))
    ? "#"
    : href;

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

const rootEl = ref<HTMLElement>();
const focusIndex = ref(0);

/** Grow every item by its distance to x with a cosine falloff. x null resets the dock. */
function magnify(x: number | null) {
  const off = x === null || still();
  for (const item of rootEl.value?.querySelectorAll<HTMLElement>(
    "[data-dock-item]",
  ) ?? []) {
    const rect = item.getBoundingClientRect();
    const distance = off ? RANGE : Math.abs(x - rect.left - rect.width / 2);
    const scale =
      distance >= RANGE
        ? 1
        : 1 +
          ((props.magnification - 1) *
            (1 + Math.cos((Math.PI * distance) / RANGE))) /
            2;
    item.style.setProperty("--dock-scale", String(scale));
  }
}

const centerOf = (element: Element) => {
  const rect = element.getBoundingClientRect();
  return rect.left + rect.width / 2;
};
const controls = () =>
  Array.from(
    rootEl.value?.querySelectorAll<HTMLElement>(
      "[data-dock-item] > :first-child",
    ) ?? [],
  );

/** Position of each item among the focusable ones, -1 for separators. */
const positions = computed(() => {
  let position = -1;
  return props.items.map((item) => (item.separator ? -1 : ++position));
});

function onKeydown(event: KeyboardEvent) {
  const all = controls();
  const index = all.indexOf(event.target as HTMLElement);
  const targets: Record<string, number> = {
    ArrowRight: (index + 1) % all.length,
    ArrowLeft: (index - 1 + all.length) % all.length,
    Home: 0,
    End: all.length - 1,
  };
  const target = targets[event.key];
  if (index < 0 || target === undefined) return;
  event.preventDefault();
  all[target]?.focus();
}
function onFocusin(event: FocusEvent) {
  const index = controls().indexOf(event.target as HTMLElement);
  if (index < 0) return;
  focusIndex.value = index;
  magnify(centerOf(event.target as Element));
}
function onFocusout(event: FocusEvent) {
  if (!rootEl.value?.contains(event.relatedTarget as Node | null))
    magnify(null);
}
function onLeave() {
  const focused = rootEl.value?.contains(document.activeElement);
  magnify(focused ? centerOf(document.activeElement!) : null);
}
function launch(event: MouseEvent, value: string) {
  if (!still())
    (event.currentTarget as HTMLElement).animate?.(BOUNCE, BOUNCE_TIMING);
  emit("select", value);
}
</script>

<template>
  <div
    ref="rootEl"
    role="toolbar"
    :aria-label="props.dockLabel"
    aria-orientation="horizontal"
    :class="root"
    @keydown="onKeydown"
    @focusin="onFocusin"
    @focusout="onFocusout"
    @pointermove="magnify($event.clientX)"
    @pointerleave="onLeave"
  >
    <template v-for="(item, index) in props.items" :key="index">
      <div
        v-if="item.separator"
        role="separator"
        aria-orientation="vertical"
        :class="separator"
      />
      <div v-else data-dock-item="" :class="itemWrap">
        <component
          :is="item.href ? 'a' : 'button'"
          :href="item.href ? safeHref(item.href) : undefined"
          :type="item.href ? undefined : 'button'"
          :tabindex="positions[index] === focusIndex ? 0 : -1"
          :aria-current="item.active ? 'true' : undefined"
          :class="itemClass"
          @click="launch($event, item.value ?? item.label)"
        >
          <svg
            :class="iconClass"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="1.5"
            stroke-linecap="round"
            stroke-linejoin="round"
            aria-hidden="true"
          >
            <path :d="item.icon" />
          </svg>
          <span :class="tooltip">{{ item.label }}</span>
        </component>
        <span v-if="item.active" aria-hidden="true" :class="dot" />
      </div>
    </template>
  </div>
</template>
```

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

<template>
  <Dock
    :items="items"
    dock-label="Dok aplikasi"
    :magnification="1.6"
    @select="bukaAplikasi"
  />
</template>
```

### Svelte

Simpan di `src/lib/components/markas/Dock.svelte`. Tanpa dependensi tambahan.

```svelte
<script lang="ts" module>
  export type DockItem =
    | {
        separator?: false;
        label: string;
        /** Path data (the d attribute) for a 24x24 stroked icon. */
        icon: string;
        value?: string;
        href?: string;
        /** Shows the dot under the item, like an open app. */
        active?: boolean;
      }
    | { separator: true };
</script>

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

  const root =
    "relative inline-flex h-[60px] max-w-full min-w-0 items-end gap-2 rounded-2xl border border-line bg-surface/80 px-2.5 pb-2.5 shadow-overlay backdrop-blur-md";
  const itemWrap =
    "relative h-10 w-[calc(2.5rem*var(--dock-scale,1))] transition-[width] duration-150 ease-out motion-reduce:transition-none";
  const itemClass =
    "group/dock absolute bottom-0 left-0 grid aspect-square w-full place-items-center rounded-xl border border-line bg-linear-to-b from-surface to-subtle text-ink transition-colors duration-150 ease-out hover:to-primary-soft focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
  const iconClass = "size-[55%]";
  const tooltip =
    "pointer-events-none absolute bottom-full left-1/2 mb-2 -translate-x-1/2 translate-y-1 rounded-md bg-primary px-2 py-1 text-xs font-medium whitespace-nowrap text-on-primary opacity-0 shadow-overlay transition-[opacity,translate] duration-150 ease-out group-hover/dock:translate-y-0 group-hover/dock:opacity-100 group-focus-visible/dock:translate-y-0 group-focus-visible/dock:opacity-100 motion-reduce:transition-none";
  const dot =
    "absolute -bottom-1.5 left-1/2 size-1 -translate-x-1/2 rounded-full bg-ink";
  const separator = "mx-0.5 mb-1 h-8 w-px shrink-0 bg-line";

  /** Pointer distance in px over which neighbours still grow, and the launch bounce. */
  const RANGE = 140;
  const BOUNCE = [
    { transform: "none" },
    { transform: "translateY(-12px)" },
    { transform: "none" },
  ];
  const BOUNCE_TIMING = {
    duration: 450,
    easing: "cubic-bezier(0.3, 0, 0.3, 1)",
  };

  /** Href with a scheme other than http, https, mailto, or tel (such as javascript:) becomes "#". */
  const safeHref = (href: string) =>
    /^(?!https?:|mailto:|tel:)[a-z][\w+.-]*:/i.test(href.replace(/[\0- ]/g, ""))
      ? "#"
      : href;

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

  /** Grow every item by its distance to x with a cosine falloff. x null resets the dock. */
  function magnify(
    root: HTMLElement | undefined,
    magnification: number,
    x: number | null,
  ) {
    const off = x === null || still();
    for (const item of root?.querySelectorAll<HTMLElement>(
      "[data-dock-item]",
    ) ?? []) {
      const rect = item.getBoundingClientRect();
      const distance = off ? RANGE : Math.abs(x - rect.left - rect.width / 2);
      const scale =
        distance >= RANGE
          ? 1
          : 1 +
            ((magnification - 1) *
              (1 + Math.cos((Math.PI * distance) / RANGE))) /
              2;
      item.style.setProperty("--dock-scale", String(scale));
    }
  }

  const centerOf = (element: Element) => {
    const rect = element.getBoundingClientRect();
    return rect.left + rect.width / 2;
  };

  type Props = HTMLAttributes<HTMLDivElement> & {
    items: DockItem[];
    /** How large the item under the pointer or focus grows. 1 turns it off. */
    magnification?: number;
    onItemSelect?: (value: string) => void;
    dockLabel?: string;
  };

  let {
    items,
    magnification = 1.6,
    onItemSelect,
    dockLabel = "Dock",
    class: className,
    ...rest
  }: Props = $props();

  let rootEl = $state<HTMLDivElement>();
  let focusIndex = $state(0);
  const controls = () =>
    Array.from(
      rootEl?.querySelectorAll<HTMLElement>(
        "[data-dock-item] > :first-child",
      ) ?? [],
    );

  /** Position of each item among the focusable ones, -1 for separators. */
  const positions = $derived(
    items.reduce<number[]>(
      (list, item) => [
        ...list,
        item.separator ? -1 : list.filter((position) => position >= 0).length,
      ],
      [],
    ),
  );

  function handleKeydown(event: KeyboardEvent) {
    const all = controls();
    const index = all.indexOf(event.target as HTMLElement);
    const targets: Record<string, number> = {
      ArrowRight: (index + 1) % all.length,
      ArrowLeft: (index - 1 + all.length) % all.length,
      Home: 0,
      End: all.length - 1,
    };
    const target = targets[event.key];
    if (index < 0 || target === undefined) return;
    event.preventDefault();
    all[target]?.focus();
  }

  function handleFocusin(event: FocusEvent) {
    const index = controls().indexOf(event.target as HTMLElement);
    if (index < 0) return;
    focusIndex = index;
    magnify(rootEl, magnification, centerOf(event.target as Element));
  }

  function handleFocusout(
    event: FocusEvent & { currentTarget: HTMLDivElement },
  ) {
    if (!event.currentTarget.contains(event.relatedTarget as Node | null))
      magnify(rootEl, magnification, null);
  }

  function handlePointerleave() {
    const focused = rootEl?.contains(document.activeElement);
    magnify(
      rootEl,
      magnification,
      focused ? centerOf(document.activeElement!) : null,
    );
  }

  function launch(event: MouseEvent, value: string) {
    if (!still())
      (event.currentTarget as HTMLElement).animate?.(BOUNCE, BOUNCE_TIMING);
    onItemSelect?.(value);
  }
</script>

<!-- svelte-ignore a11y_interactive_supports_focus -->
<div
  bind:this={rootEl}
  role="toolbar"
  aria-label={dockLabel}
  aria-orientation="horizontal"
  class={[root, className]}
  onkeydown={handleKeydown}
  onfocusin={handleFocusin}
  onfocusout={handleFocusout}
  onpointermove={(event) => magnify(rootEl, magnification, event.clientX)}
  onpointerleave={handlePointerleave}
  {...rest}
>
  {#each items as item, index (index)}
    {#if item.separator}
      <div role="separator" aria-orientation="vertical" class={separator}></div>
    {:else}
      {@const tabindex = positions[index] === focusIndex ? 0 : -1}
      {@const value = item.value ?? item.label}
      <div data-dock-item="" class={itemWrap}>
        {#if item.href}
          <a
            href={safeHref(item.href)}
            {tabindex}
            aria-current={item.active ? "true" : undefined}
            class={itemClass}
            onclick={(event) => launch(event, value)}
            >{@render content(item.icon, item.label)}</a
          >
        {:else}
          <button
            type="button"
            {tabindex}
            aria-current={item.active ? "true" : undefined}
            class={itemClass}
            onclick={(event) => launch(event, value)}
            >{@render content(item.icon, item.label)}</button
          >
        {/if}
        {#if item.active}
          <span aria-hidden="true" class={dot}></span>
        {/if}
      </div>
    {/if}
  {/each}
</div>

{#snippet content(icon: string, label: string)}
  <svg
    class={iconClass}
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    stroke-width="1.5"
    stroke-linecap="round"
    stroke-linejoin="round"
    aria-hidden="true"
  >
    <path d={icon} />
  </svg>
  <span class={tooltip}>{label}</span>
{/snippet}
```

```svelte
<script lang="ts">
  import Dock, { type DockItem } from "$lib/components/markas/Dock.svelte";

  const items: DockItem[] = [
    { label: "Files", value: "files", icon: folderPath, active: true },
    { label: "Mail", value: "mail", icon: mailPath },
    { separator: true },
    { label: "Blog", href: "/blog", icon: penPath },
  ];
</script>

<Dock {items} onItemSelect={openApp} />
```

### Astro

Simpan di `src/components/markas/Dock.astro`. Tanpa dependensi tambahan.

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

export type DockItem =
  | {
      separator?: false;
      label: string;
      /** Path data (the d attribute) for a 24x24 stroked icon. */
      icon: string;
      value?: string;
      href?: string;
      /** Shows the dot under the item, like an open app. */
      active?: boolean;
    }
  | { separator: true };

const root =
  "relative inline-flex h-[60px] max-w-full min-w-0 items-end gap-2 rounded-2xl border border-line bg-surface/80 px-2.5 pb-2.5 shadow-overlay backdrop-blur-md";
const itemWrap =
  "relative h-10 w-[calc(2.5rem*var(--dock-scale,1))] transition-[width] duration-150 ease-out motion-reduce:transition-none";
const itemClass =
  "group/dock absolute bottom-0 left-0 grid aspect-square w-full place-items-center rounded-xl border border-line bg-linear-to-b from-surface to-subtle text-ink transition-colors duration-150 ease-out hover:to-primary-soft focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
const iconClass = "size-[55%]";
const tooltip =
  "pointer-events-none absolute bottom-full left-1/2 mb-2 -translate-x-1/2 translate-y-1 rounded-md bg-primary px-2 py-1 text-xs font-medium whitespace-nowrap text-on-primary opacity-0 shadow-overlay transition-[opacity,translate] duration-150 ease-out group-hover/dock:translate-y-0 group-hover/dock:opacity-100 group-focus-visible/dock:translate-y-0 group-focus-visible/dock:opacity-100 motion-reduce:transition-none";
const dot =
  "absolute -bottom-1.5 left-1/2 size-1 -translate-x-1/2 rounded-full bg-ink";
const separator = "mx-0.5 mb-1 h-8 w-px shrink-0 bg-line";

/** Href with a scheme other than http, https, mailto, or tel (such as javascript:) becomes "#". */
const safeHref = (href: string) =>
  /^(?!https?:|mailto:|tel:)[a-z][\w+.-]*:/i.test(href.replace(/[\0- ]/g, ""))
    ? "#"
    : href;

type Props = HTMLAttributes<"div"> & {
  items: DockItem[];
  /** How large the item under the pointer or focus grows. 1 turns it off. */
  magnification?: number;
  dockLabel?: string;
};

const {
  items,
  magnification = 1.6,
  dockLabel = "Dock",
  class: className,
  ...rest
} = Astro.props;

let position = 0;
---

<markas-dock class="contents" data-magnification={magnification}>
  <div
    role="toolbar"
    aria-label={dockLabel}
    aria-orientation="horizontal"
    class:list={[root, className]}
    {...rest}
  >
    {
      items.map((item) => {
        if (item.separator)
          return <div role="separator" aria-orientation="vertical" class={separator} />;
        const Tag = item.href ? "a" : "button";
        const tabindex = position++ === 0 ? "0" : "-1";
        return (
          <div data-dock-item="" class={itemWrap}>
            <Tag
              href={item.href ? safeHref(item.href) : undefined}
              type={item.href ? undefined : "button"}
              tabindex={tabindex}
              aria-current={item.active ? "true" : undefined}
              data-value={item.value ?? item.label}
              class={itemClass}
            >
              <svg
                class={iconClass}
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="1.5"
                stroke-linecap="round"
                stroke-linejoin="round"
                aria-hidden="true"
              >
                <path d={item.icon} />
              </svg>
              <span class={tooltip}>{item.label}</span>
            </Tag>
            {item.active && <span aria-hidden="true" class={dot} />}
          </div>
        );
      })
    }
  </div>
</markas-dock>

<script>
  /** Pointer distance in px over which neighbours still grow, and the launch bounce. */
  const RANGE = 140;
  const BOUNCE = [
    { transform: "none" },
    { transform: "translateY(-12px)" },
    { transform: "none" },
  ];
  const BOUNCE_TIMING = { duration: 450, easing: "cubic-bezier(0.3, 0, 0.3, 1)" };

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

  const centerOf = (element: Element) => {
    const rect = element.getBoundingClientRect();
    return rect.left + rect.width / 2;
  };

  // Each dock tracks the pointer and its own tab stop, so it is a custom element: it also
  // works for markup added later and for pages reached through view transitions.
  class MarkasDock extends HTMLElement {
    private ready = false;

    connectedCallback() {
      const toolbar = this.querySelector<HTMLElement>("[role=toolbar]");
      if (this.ready || !toolbar) return;
      this.ready = true;
      toolbar.addEventListener("keydown", (event) => {
        const all = this.controls();
        const index = all.indexOf(event.target as HTMLElement);
        const targets: Record<string, number> = {
          ArrowRight: (index + 1) % all.length,
          ArrowLeft: (index - 1 + all.length) % all.length,
          Home: 0,
          End: all.length - 1,
        };
        const target = targets[event.key];
        if (index < 0 || target === undefined) return;
        event.preventDefault();
        all[target]?.focus();
      });
      toolbar.addEventListener("focusin", (event) => {
        const all = this.controls();
        const index = all.indexOf(event.target as HTMLElement);
        if (index < 0) return;
        all.forEach((control, i) => (control.tabIndex = i === index ? 0 : -1));
        this.magnify(centerOf(event.target as Element));
      });
      toolbar.addEventListener("focusout", (event) => {
        if (!toolbar.contains(event.relatedTarget as Node | null))
          this.magnify(null);
      });
      toolbar.addEventListener("pointermove", (event) =>
        this.magnify(event.clientX),
      );
      toolbar.addEventListener("pointerleave", () => {
        const focused = toolbar.contains(document.activeElement);
        this.magnify(focused ? centerOf(document.activeElement!) : null);
      });
      toolbar.addEventListener("click", (event) => {
        const control = (event.target as Element).closest<HTMLElement>(
          "[data-value]",
        );
        if (!control) return;
        if (!still()) control.animate?.(BOUNCE, BOUNCE_TIMING);
        this.dispatchEvent(
          new CustomEvent("markas-select", {
            detail: control.dataset.value,
            bubbles: true,
          }),
        );
      });
    }

    private controls() {
      return Array.from(
        this.querySelectorAll<HTMLElement>("[data-dock-item] > :first-child"),
      );
    }

    /** Grow every item by its distance to x with a cosine falloff. x null resets the dock. */
    private magnify(x: number | null) {
      const magnification = Number(this.dataset.magnification);
      const off = x === null || still();
      for (const item of this.querySelectorAll<HTMLElement>("[data-dock-item]")) {
        const rect = item.getBoundingClientRect();
        const distance = off ? RANGE : Math.abs(x - rect.left - rect.width / 2);
        const scale =
          distance >= RANGE
            ? 1
            : 1 +
              ((magnification - 1) * (1 + Math.cos((Math.PI * distance) / RANGE))) /
                2;
        item.style.setProperty("--dock-scale", String(scale));
      }
    }
  }

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

```astro
---
import Dock, { type DockItem } from "@/components/markas/Dock.astro";

const items: DockItem[] = [
  { label: "Files", value: "files", icon: folderPath, active: true },
  { separator: true },
  { label: "Blog", href: "/blog", icon: penPath },
];
---

<Dock items={items} />
```

Custom element kecil memperbesar item dan memindahkan tab stop. Menekan item mengirim event `markas-select` yang menggelembung dengan value-nya sebagai detail.

### Angular

Simpan di `src/app/markas/dock.component.ts`. Tanpa dependensi tambahan.

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

export type DockItem =
  | {
      separator?: false;
      label: string;
      /** Path data (the d attribute) for a 24x24 stroked icon. */
      icon: string;
      value?: string;
      href?: string;
      /** Shows the dot under the item, like an open app. */
      active?: boolean;
    }
  | { separator: true };

const root =
  "relative inline-flex h-[60px] max-w-full min-w-0 items-end gap-2 rounded-2xl border border-line bg-surface/80 px-2.5 pb-2.5 shadow-overlay backdrop-blur-md";
const itemWrap =
  "relative h-10 w-[calc(2.5rem*var(--dock-scale,1))] transition-[width] duration-150 ease-out motion-reduce:transition-none";
const itemClass =
  "group/dock absolute bottom-0 left-0 grid aspect-square w-full place-items-center rounded-xl border border-line bg-linear-to-b from-surface to-subtle text-ink transition-colors duration-150 ease-out hover:to-primary-soft focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
const iconClass = "size-[55%]";
const tooltip =
  "pointer-events-none absolute bottom-full left-1/2 mb-2 -translate-x-1/2 translate-y-1 rounded-md bg-primary px-2 py-1 text-xs font-medium whitespace-nowrap text-on-primary opacity-0 shadow-overlay transition-[opacity,translate] duration-150 ease-out group-hover/dock:translate-y-0 group-hover/dock:opacity-100 group-focus-visible/dock:translate-y-0 group-focus-visible/dock:opacity-100 motion-reduce:transition-none";
const dot =
  "absolute -bottom-1.5 left-1/2 size-1 -translate-x-1/2 rounded-full bg-ink";
const separator = "mx-0.5 mb-1 h-8 w-px shrink-0 bg-line";

/** Pointer distance in px over which neighbours still grow, and the launch bounce. */
const RANGE = 140;
const BOUNCE = [
  { transform: "none" },
  { transform: "translateY(-12px)" },
  { transform: "none" },
];
const BOUNCE_TIMING = { duration: 450, easing: "cubic-bezier(0.3, 0, 0.3, 1)" };

/** Href with a scheme other than http, https, mailto, or tel (such as javascript:) becomes "#". */
const safeHref = (href: string) =>
  /^(?!https?:|mailto:|tel:)[a-z][\w+.-]*:/i.test(href.replace(/[\0- ]/g, ""))
    ? "#"
    : href;

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

const centerOf = (element: Element) => {
  const rect = element.getBoundingClientRect();
  return rect.left + rect.width / 2;
};

/** Host stays out of layout; class moves to the toolbar. */
@Component({
  selector: "markas-dock",
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [NgTemplateOutlet],
  host: { class: "contents" },
  template: `
    <ng-template #content let-item>
      <svg
        [class]="iconClass"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        stroke-width="1.5"
        stroke-linecap="round"
        stroke-linejoin="round"
        aria-hidden="true"
      >
        <path [attr.d]="item.icon" />
      </svg>
      <span [class]="tooltip">{{ item.label }}</span>
    </ng-template>
    <div
      role="toolbar"
      [attr.aria-label]="dockLabel()"
      aria-orientation="horizontal"
      [class]="rootClasses()"
      (keydown)="handleKeydown($event)"
      (focusin)="handleFocusin($event)"
      (focusout)="handleFocusout($event)"
      (pointermove)="magnify($event.clientX)"
      (pointerleave)="handlePointerleave()"
    >
      @for (item of items(); track $index) {
        @if (item.separator) {
          <div
            role="separator"
            aria-orientation="vertical"
            [class]="separator"
          ></div>
        } @else {
          <div data-dock-item="" [class]="itemWrap">
            @if (item.href) {
              <a
                [attr.href]="safeHref(item.href)"
                [tabIndex]="positions()[$index] === focusIndex() ? 0 : -1"
                [attr.aria-current]="item.active ? 'true' : null"
                [class]="itemClass"
                (click)="launch($event, item.value ?? item.label)"
                ><ng-container
                  [ngTemplateOutlet]="content"
                  [ngTemplateOutletContext]="{ $implicit: item }"
              /></a>
            } @else {
              <button
                type="button"
                [tabIndex]="positions()[$index] === focusIndex() ? 0 : -1"
                [attr.aria-current]="item.active ? 'true' : null"
                [class]="itemClass"
                (click)="launch($event, item.value ?? item.label)"
              >
                <ng-container
                  [ngTemplateOutlet]="content"
                  [ngTemplateOutletContext]="{ $implicit: item }"
                />
              </button>
            }
            @if (item.active) {
              <span aria-hidden="true" [class]="dot"></span>
            }
          </div>
        }
      }
    </div>
  `,
})
export class Dock {
  readonly items = input.required<DockItem[]>();
  /** How large the item under the pointer or focus grows. 1 turns it off. */
  readonly magnification = input(1.6, { transform: numberAttribute });
  readonly dockLabel = input("Dock");
  readonly userClass = input("", { alias: "class" });
  readonly itemSelect = output<string>();

  protected readonly itemWrap = itemWrap;
  protected readonly itemClass = itemClass;
  protected readonly iconClass = iconClass;
  protected readonly tooltip = tooltip;
  protected readonly dot = dot;
  protected readonly separator = separator;
  protected readonly safeHref = safeHref;
  protected readonly focusIndex = signal(0);
  protected readonly rootClasses = computed(() =>
    [root, this.userClass()].filter(Boolean).join(" "),
  );
  /** Position of each item among the focusable ones, -1 for separators. */
  protected readonly positions = computed(() =>
    this.items().reduce<number[]>(
      (list, item) => [
        ...list,
        item.separator ? -1 : list.filter((position) => position >= 0).length,
      ],
      [],
    ),
  );
  private readonly host: HTMLElement = inject(ElementRef).nativeElement;

  private controls() {
    return Array.from(
      this.host.querySelectorAll<HTMLElement>(
        "[data-dock-item] > :first-child",
      ),
    );
  }

  /** Grow every item by its distance to x with a cosine falloff. x null resets the dock. */
  protected magnify(x: number | null) {
    const magnification = this.magnification();
    const off = x === null || still();
    for (const item of this.host.querySelectorAll<HTMLElement>(
      "[data-dock-item]",
    )) {
      const rect = item.getBoundingClientRect();
      const distance = off ? RANGE : Math.abs(x - rect.left - rect.width / 2);
      const scale =
        distance >= RANGE
          ? 1
          : 1 +
            ((magnification - 1) *
              (1 + Math.cos((Math.PI * distance) / RANGE))) /
              2;
      item.style.setProperty("--dock-scale", String(scale));
    }
  }

  protected handleKeydown(event: KeyboardEvent) {
    const all = this.controls();
    const index = all.indexOf(event.target as HTMLElement);
    const targets: Record<string, number> = {
      ArrowRight: (index + 1) % all.length,
      ArrowLeft: (index - 1 + all.length) % all.length,
      Home: 0,
      End: all.length - 1,
    };
    const target = targets[event.key];
    if (index < 0 || target === undefined) return;
    event.preventDefault();
    all[target]?.focus();
  }

  protected handleFocusin(event: FocusEvent) {
    const index = this.controls().indexOf(event.target as HTMLElement);
    if (index < 0) return;
    this.focusIndex.set(index);
    this.magnify(centerOf(event.target as Element));
  }

  protected handleFocusout(event: FocusEvent) {
    const toolbar = event.currentTarget as HTMLElement;
    if (!toolbar.contains(event.relatedTarget as Node | null))
      this.magnify(null);
  }

  protected handlePointerleave() {
    const focused = this.host.contains(document.activeElement);
    this.magnify(focused ? centerOf(document.activeElement!) : null);
  }

  protected launch(event: MouseEvent, value: string) {
    if (!still())
      (event.currentTarget as HTMLElement).animate?.(BOUNCE, BOUNCE_TIMING);
    this.itemSelect.emit(value);
  }
}
```

```ts
import { Component } from "@angular/core";
import { Dock, type DockItem } from "./markas/dock.component";

@Component({
  selector: "app-dock",
  imports: [Dock],
  template: `<markas-dock [items]="items" (itemSelect)="openApp($event)" />`,
})
export class AppDock {
  items: DockItem[] = [
    { label: "Files", value: "files", icon: "M3 7h18v12H3z", active: true },
    { separator: true },
    { label: "Blog", href: "/blog", icon: "M12 20h9" },
  ];
  openApp(value: string) {}
}
```

## Props

| Nama | Tipe | Default | Keterangan |
| --- | --- | --- | --- |
| `items` | `({ label: string; icon: string; value?: string; href?: string; active?: boolean } \| { separator: true })[]` | [] | Item dock berurutan. icon adalah atribut d path SVG 24x24 bergaris. { separator: true } menggambar pemisah. Item dengan href menjadi link. |
| `magnification` | `number` | 1.6 | Seberapa besar item di bawah kursor atau fokus membesar. Tetangga dalam 140px membesar lebih sedikit. 1 mematikannya. |
| `onItemSelect / @select / x-on:select` | `(value: string) => void` | - | Dipicu saat item ditekan, dengan value atau label-nya. Blade mengirim event DOM select dengan value sebagai detail. |
| `dockLabel` | `string` | Dock | Nama aksesibel toolbar. |
| `(itemSelect)` | `output<string>` | - | Khusus Angular. Memancarkan value (atau label) item yang ditekan. Svelte memakai onItemSelect seperti React. |
| `markas-select` | `CustomEvent<string>` | - | Khusus Astro. Event menggelembung dengan value item yang ditekan sebagai detail. |

## Aksesibilitas

- Dock adalah toolbar bernama dockLabel. Hanya satu item di urutan tab, Panah Kiri, Panah Kanan, Home, dan End berpindah antar item (roving tabindex).
- Label di dalam setiap item menjadi nama aksesibelnya dan tampil sebagai tooltip saat hover dan fokus keyboard.
- Item bertitik memakai aria-current="true". Pemisah memakai role="separator".
- Dengan reduced motion, pembesaran dan pantulan mati, item tetap di ukuran dasar.

## Catatan

- Item membesar dengan kurva kosinus dalam jarak 140px di sekitar kursor, dan di sekitar item yang difokus saat memakai keyboard.
- Dock adalah toolbar dengan roving tabindex: Tab masuk sekali, panah berpindah antar item.
- Menekan item memutar pantulan singkat dan memicu select. Item dengan href berpindah halaman seperti link biasa.
- Reduced motion menjaga setiap item di ukuran dasar dan melewati pantulan.
- Dock tidak pernah lebih lebar dari wadahnya. Di wadah yang sempit, item mengecil merata supaya semuanya tetap terlihat.
