# GitHub Stars Button

Link to a GitHub repository with the GitHub mark and a star count that counts up when it scrolls into view. No fetch.

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

## When to use

A star call to action in a landing page header or docs navbar of an open source project.

- Pass the star count from your server or build step, the component never fetches
- Without a label give the link an aria-label
- Use one per page, usually in the header

## Code

### Blade

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

```blade
@props([
    'href' => '#',
    'stars' => 0,
    'variant' => 'secondary',
    'size' => 'md',
    'starsLabel' => '{count} stars',
])

@php
    $base = 'inline-flex items-center justify-center gap-2 font-medium whitespace-nowrap transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary 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',
    ];
    $icon = 'size-4 shrink-0';
    $divider = 'h-4 w-px bg-current opacity-25';
    $count = 'inline-flex items-center gap-1 tabular-nums';
    $star = 'size-3.5 shrink-0';
    $srOnly = 'sr-only';

    // Href with a scheme other than http, https, mailto, or tel (javascript:, for example) becomes "#".
    $safeHref = function (string $href): string {
        $value = ltrim(str_replace(["\t", "\n", "\r"], '', $href), "\x00..\x20");
        $hasScheme = preg_match('/^[a-z][a-z0-9+.\-]*:/i', $value) === 1;

        return $hasScheme && preg_match('/^(https?|mailto|tel):/i', $value) !== 1 ? '#' : $href;
    };
    // 980, 12.4k, 1.2M. Same rule as the React and Vue versions.
    $compact = fn (int|float $n): string => $n >= 1e6
        ? (round($n / 1e5) / 10).'M'
        : ($n >= 1e3 ? (round($n / 100) / 10).'k' : (string) round($n));

    $stars = (int) $stars;
@endphp

{{-- Counts up from zero the first time the button scrolls into view. Never fetches. --}}
<a
    x-data="{
        stop() {},
        init() {
            const number = this.$refs.number;
            if (typeof IntersectionObserver === 'undefined') return;
            if (window.matchMedia?.('(prefers-reduced-motion: reduce)').matches) return;
            const stars = {{ $stars }};
            const compact = (n) =>
                n >= 1e6 ? `${Math.round(n / 1e5) / 10}M` : n >= 1e3 ? `${Math.round(n / 100) / 10}k` : String(Math.round(n));
            let frame = 0;
            number.textContent = '0';
            const observer = new IntersectionObserver(([entry]) => {
                if (!entry?.isIntersecting) return;
                observer.disconnect();
                const begin = performance.now();
                const step = (now) => {
                    const t = Math.min((now - begin) / 1200, 1);
                    number.textContent = compact(stars * (1 - (1 - t) ** 3));
                    if (t < 1) frame = requestAnimationFrame(step);
                };
                frame = requestAnimationFrame(step);
            });
            observer.observe(number);
            this.stop = () => {
                observer.disconnect();
                cancelAnimationFrame(frame);
            };
        },
        destroy() {
            this.stop();
        },
    }"
    {{ $attributes->merge(['href' => $safeHref((string) $href)])->class([$base, $variants[$variant], $sizes[$size]]) }}
>
    <svg class="{{ $icon }}" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M12 2C6.48 2 2 6.58 2 12.25c0 4.53 2.87 8.37 6.84 9.73.5.09.68-.22.68-.49l-.01-1.7c-2.78.62-3.37-1.37-3.37-1.37-.46-1.18-1.11-1.5-1.11-1.5-.91-.64.07-.62.07-.62 1 .07 1.53 1.06 1.53 1.06.9 1.57 2.35 1.12 2.92.85.09-.66.35-1.12.64-1.37-2.22-.26-4.56-1.14-4.56-5.07 0-1.12.39-2.03 1.03-2.75-.1-.26-.45-1.3.1-2.71 0 0 .84-.28 2.75 1.05A9.4 9.4 0 0 1 12 6.94c.85 0 1.7.12 2.5.34 1.91-1.33 2.75-1.05 2.75-1.05.55 1.41.2 2.45.1 2.71.64.72 1.03 1.63 1.03 2.75 0 3.94-2.34 4.81-4.57 5.06.36.32.68.94.68 1.9l-.01 2.82c0 .27.18.59.69.49A10.2 10.2 0 0 0 22 12.25C22 6.58 17.52 2 12 2Z" /></svg>
    {{ $slot }}
    <span class="{{ $divider }}" aria-hidden="true"></span>
    <span class="{{ $count }}">
        <svg class="{{ $star }}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m12 3 2.78 5.63 6.22.9-4.5 4.39 1.06 6.19L12 17.2l-5.56 2.91 1.06-6.19L3 9.53l6.22-.9L12 3Z" /></svg>
        <span x-ref="number" aria-hidden="true">{{ $compact($stars) }}</span>
        <span class="{{ $srOnly }}">{{ str_replace('{count}', number_format($stars), $starsLabel) }}</span>
    </span>
</a>
```

```blade
<x-markas.github-stars-button href="https://github.com/markasui/markasui" :stars="12480">Star on GitHub</x-markas.github-stars-button>
```

### React

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

```tsx
"use client";

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

const base =
  "inline-flex items-center justify-center gap-2 font-medium whitespace-nowrap transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary 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 icon = "size-4 shrink-0";
const divider = "h-4 w-px bg-current opacity-25";
const count = "inline-flex items-center gap-1 tabular-nums";
const star = "size-3.5 shrink-0";
const srOnly = "sr-only";

const COUNT_DURATION = 1200;

const HAS_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
const SAFE_SCHEME = /^(https?|mailto|tel):/i;

/** Href with a scheme other than http, https, mailto, or tel (javascript:, for example) becomes "#". */
const safeHref = (href: string) => {
  const cleaned = href.replace(/[\t\n\r]/g, "");
  const start = [...cleaned].findIndex((char) => char > " ");
  const value = cleaned.slice(Math.max(start, 0));
  return HAS_SCHEME.test(value) && !SAFE_SCHEME.test(value) ? "#" : href;
};
/** 980, 12.4k, 1.2M. Same rule as the Blade version. */
const compact = (n: number) =>
  n >= 1e6
    ? `${Math.round(n / 1e5) / 10}M`
    : n >= 1e3
      ? `${Math.round(n / 100) / 10}k`
      : String(Math.round(n));
const cx = (...c: (string | false | null | undefined)[]) =>
  c.filter(Boolean).join(" ");
const reducedMotion = () =>
  typeof window.matchMedia === "function" &&
  window.matchMedia("(prefers-reduced-motion: reduce)").matches;

export type GithubStarsButtonProps = ComponentProps<"a"> & {
  /** Repository URL, for example https://github.com/owner/repo. */
  href: string;
  /** Star count. Pass it in, the component never fetches. */
  stars: number;
  variant?: keyof typeof variants;
  size?: keyof typeof sizes;
  /** Hidden text for the count. {count} is replaced by the full number. */
  starsLabel?: string;
};

export function GithubStarsButton({
  href,
  stars,
  variant = "secondary",
  size = "md",
  starsLabel = "{count} stars",
  className,
  children,
  ...props
}: GithubStarsButtonProps) {
  const numberRef = useRef<HTMLSpanElement>(null);

  // Count up from zero the first time the button scrolls into view.
  useEffect(() => {
    const number = numberRef.current;
    if (!number || typeof IntersectionObserver === "undefined") return;
    if (reducedMotion()) return;
    let frame = 0;
    number.textContent = "0";
    const observer = new IntersectionObserver(([entry]) => {
      if (!entry?.isIntersecting) return;
      observer.disconnect();
      const begin = performance.now();
      const step = (now: number) => {
        const t = Math.min((now - begin) / COUNT_DURATION, 1);
        number.textContent = compact(stars * (1 - (1 - t) ** 3));
        if (t < 1) frame = requestAnimationFrame(step);
      };
      frame = requestAnimationFrame(step);
    });
    observer.observe(number);
    return () => {
      observer.disconnect();
      cancelAnimationFrame(frame);
      number.textContent = compact(stars);
    };
  }, [stars]);

  return (
    <a
      href={safeHref(href)}
      className={cx(base, variants[variant], sizes[size], className)}
      {...props}
    >
      <svg
        className={icon}
        viewBox="0 0 24 24"
        fill="currentColor"
        aria-hidden="true"
      >
        <path d="M12 2C6.48 2 2 6.58 2 12.25c0 4.53 2.87 8.37 6.84 9.73.5.09.68-.22.68-.49l-.01-1.7c-2.78.62-3.37-1.37-3.37-1.37-.46-1.18-1.11-1.5-1.11-1.5-.91-.64.07-.62.07-.62 1 .07 1.53 1.06 1.53 1.06.9 1.57 2.35 1.12 2.92.85.09-.66.35-1.12.64-1.37-2.22-.26-4.56-1.14-4.56-5.07 0-1.12.39-2.03 1.03-2.75-.1-.26-.45-1.3.1-2.71 0 0 .84-.28 2.75 1.05A9.4 9.4 0 0 1 12 6.94c.85 0 1.7.12 2.5.34 1.91-1.33 2.75-1.05 2.75-1.05.55 1.41.2 2.45.1 2.71.64.72 1.03 1.63 1.03 2.75 0 3.94-2.34 4.81-4.57 5.06.36.32.68.94.68 1.9l-.01 2.82c0 .27.18.59.69.49A10.2 10.2 0 0 0 22 12.25C22 6.58 17.52 2 12 2Z" />
      </svg>
      {children}
      <span className={divider} aria-hidden="true" />
      <span className={count}>
        <svg
          className={star}
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="1.5"
          strokeLinecap="round"
          strokeLinejoin="round"
          aria-hidden="true"
        >
          <path d="m12 3 2.78 5.63 6.22.9-4.5 4.39 1.06 6.19L12 17.2l-5.56 2.91 1.06-6.19L3 9.53l6.22-.9L12 3Z" />
        </svg>
        <span ref={numberRef} aria-hidden="true">
          {compact(stars)}
        </span>
        <span className={srOnly}>
          {starsLabel.replace("{count}", stars.toLocaleString("en-US"))}
        </span>
      </span>
    </a>
  );
}
```

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

<GithubStarsButton href="https://github.com/markasui/markasui" stars={12480}>
  Star on GitHub
</GithubStarsButton>;
```

### Vue

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

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

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 props = withDefaults(
  defineProps<{
    /** Repository URL, for example https://github.com/owner/repo. */
    href: string;
    /** Star count. Pass it in, the component never fetches. */
    stars: number;
    variant?: keyof typeof variants;
    size?: keyof typeof sizes;
    /** Hidden text for the count. {count} is replaced by the full number. */
    starsLabel?: string;
  }>(),
  { variant: "secondary", size: "md", starsLabel: "{count} stars" },
);

const base =
  "inline-flex items-center justify-center gap-2 font-medium whitespace-nowrap transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
const icon = "size-4 shrink-0";
const divider = "h-4 w-px bg-current opacity-25";
const count = "inline-flex items-center gap-1 tabular-nums";
const star = "size-3.5 shrink-0";
const srOnly = "sr-only";

const COUNT_DURATION = 1200;

const HAS_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
const SAFE_SCHEME = /^(https?|mailto|tel):/i;

/** Href with a scheme other than http, https, mailto, or tel (javascript:, for example) becomes "#". */
const safeHref = (href: string) => {
  const cleaned = href.replace(/[\t\n\r]/g, "");
  const start = [...cleaned].findIndex((char) => char > " ");
  const value = cleaned.slice(Math.max(start, 0));
  return HAS_SCHEME.test(value) && !SAFE_SCHEME.test(value) ? "#" : href;
};
/** 980, 12.4k, 1.2M. Same rule as the Blade version. */
const compact = (n: number) =>
  n >= 1e6
    ? `${Math.round(n / 1e5) / 10}M`
    : n >= 1e3
      ? `${Math.round(n / 100) / 10}k`
      : String(Math.round(n));
const reducedMotion = () =>
  typeof window.matchMedia === "function" &&
  window.matchMedia("(prefers-reduced-motion: reduce)").matches;

const numberRef = useTemplateRef<HTMLSpanElement>("number");
let stop = () => {};

// Count up from zero the first time the button scrolls into view.
onMounted(() => {
  const number = numberRef.value;
  if (!number || typeof IntersectionObserver === "undefined") return;
  if (reducedMotion()) return;
  let frame = 0;
  number.textContent = "0";
  const observer = new IntersectionObserver(([entry]) => {
    if (!entry?.isIntersecting) return;
    observer.disconnect();
    const begin = performance.now();
    const step = (now: number) => {
      const t = Math.min((now - begin) / COUNT_DURATION, 1);
      number.textContent = compact(props.stars * (1 - (1 - t) ** 3));
      if (t < 1) frame = requestAnimationFrame(step);
    };
    frame = requestAnimationFrame(step);
  });
  observer.observe(number);
  stop = () => {
    observer.disconnect();
    cancelAnimationFrame(frame);
  };
});
onBeforeUnmount(() => stop());
</script>

<template>
  <a
    :href="safeHref(props.href)"
    :class="[base, variants[props.variant], sizes[props.size]]"
  >
    <svg
      :class="icon"
      viewBox="0 0 24 24"
      fill="currentColor"
      aria-hidden="true"
    >
      <path
        d="M12 2C6.48 2 2 6.58 2 12.25c0 4.53 2.87 8.37 6.84 9.73.5.09.68-.22.68-.49l-.01-1.7c-2.78.62-3.37-1.37-3.37-1.37-.46-1.18-1.11-1.5-1.11-1.5-.91-.64.07-.62.07-.62 1 .07 1.53 1.06 1.53 1.06.9 1.57 2.35 1.12 2.92.85.09-.66.35-1.12.64-1.37-2.22-.26-4.56-1.14-4.56-5.07 0-1.12.39-2.03 1.03-2.75-.1-.26-.45-1.3.1-2.71 0 0 .84-.28 2.75 1.05A9.4 9.4 0 0 1 12 6.94c.85 0 1.7.12 2.5.34 1.91-1.33 2.75-1.05 2.75-1.05.55 1.41.2 2.45.1 2.71.64.72 1.03 1.63 1.03 2.75 0 3.94-2.34 4.81-4.57 5.06.36.32.68.94.68 1.9l-.01 2.82c0 .27.18.59.69.49A10.2 10.2 0 0 0 22 12.25C22 6.58 17.52 2 12 2Z"
      />
    </svg>
    <slot />
    <span :class="divider" aria-hidden="true" />
    <span :class="count">
      <svg
        :class="star"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        stroke-width="1.5"
        stroke-linecap="round"
        stroke-linejoin="round"
        aria-hidden="true"
      >
        <path
          d="m12 3 2.78 5.63 6.22.9-4.5 4.39 1.06 6.19L12 17.2l-5.56 2.91 1.06-6.19L3 9.53l6.22-.9L12 3Z"
        />
      </svg>
      <span ref="number" aria-hidden="true">{{ compact(props.stars) }}</span>
      <span :class="srOnly">{{
        props.starsLabel.replace("{count}", props.stars.toLocaleString("en-US"))
      }}</span>
    </span>
  </a>
</template>
```

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

<template>
  <GithubStarsButton href="https://github.com/markasui/markasui" :stars="12480">
    Star on GitHub
  </GithubStarsButton>
</template>
```

### Svelte

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

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

  const base =
    "inline-flex items-center justify-center gap-2 font-medium whitespace-nowrap transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary 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 icon = "size-4 shrink-0";
  const divider = "h-4 w-px bg-current opacity-25";
  const count = "inline-flex items-center gap-1 tabular-nums";
  const star = "size-3.5 shrink-0";
  const srOnly = "sr-only";

  const COUNT_DURATION = 1200;

  const HAS_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
  const SAFE_SCHEME = /^(https?|mailto|tel):/i;

  /** Href with a scheme other than http, https, mailto, or tel (javascript:, for example) becomes "#". */
  const safeHref = (href: string) => {
    const cleaned = href.replace(/[\t\n\r]/g, "");
    const start = [...cleaned].findIndex((char) => char > " ");
    const value = cleaned.slice(Math.max(start, 0));
    return HAS_SCHEME.test(value) && !SAFE_SCHEME.test(value) ? "#" : href;
  };
  /** 980, 12.4k, 1.2M. Same rule as the Blade version. */
  const compact = (n: number) =>
    n >= 1e6
      ? `${Math.round(n / 1e5) / 10}M`
      : n >= 1e3
        ? `${Math.round(n / 100) / 10}k`
        : String(Math.round(n));
  const reducedMotion = () =>
    typeof window.matchMedia === "function" &&
    window.matchMedia("(prefers-reduced-motion: reduce)").matches;

  type Props = Omit<HTMLAnchorAttributes, "href"> & {
    /** Repository URL, for example https://github.com/owner/repo. */
    href: string;
    /** Star count. Pass it in, the component never fetches. */
    stars: number;
    variant?: keyof typeof variants;
    size?: keyof typeof sizes;
    /** Hidden text for the count. {count} is replaced by the full number. */
    starsLabel?: string;
    children?: Snippet;
  };

  let {
    href,
    stars,
    variant = "secondary",
    size = "md",
    starsLabel = "{count} stars",
    class: className,
    children,
    ...rest
  }: Props = $props();

  let number = $state<HTMLSpanElement>();

  // Count up from zero the first time the button scrolls into view.
  $effect(() => {
    const element = number;
    const total = stars;
    if (!element) return;
    // The effect owns the text, so a new stars value always lands.
    element.textContent = compact(total);
    if (typeof IntersectionObserver === "undefined" || reducedMotion()) return;
    let frame = 0;
    element.textContent = "0";
    const observer = new IntersectionObserver(([entry]) => {
      if (!entry?.isIntersecting) return;
      observer.disconnect();
      const begin = performance.now();
      const step = (now: number) => {
        const t = Math.min((now - begin) / COUNT_DURATION, 1);
        element.textContent = compact(total * (1 - (1 - t) ** 3));
        if (t < 1) frame = requestAnimationFrame(step);
      };
      frame = requestAnimationFrame(step);
    });
    observer.observe(element);
    return () => {
      observer.disconnect();
      cancelAnimationFrame(frame);
    };
  });
</script>

<a
  href={safeHref(href)}
  class={[base, variants[variant], sizes[size], className]}
  {...rest}
>
  <svg class={icon} viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
    <path
      d="M12 2C6.48 2 2 6.58 2 12.25c0 4.53 2.87 8.37 6.84 9.73.5.09.68-.22.68-.49l-.01-1.7c-2.78.62-3.37-1.37-3.37-1.37-.46-1.18-1.11-1.5-1.11-1.5-.91-.64.07-.62.07-.62 1 .07 1.53 1.06 1.53 1.06.9 1.57 2.35 1.12 2.92.85.09-.66.35-1.12.64-1.37-2.22-.26-4.56-1.14-4.56-5.07 0-1.12.39-2.03 1.03-2.75-.1-.26-.45-1.3.1-2.71 0 0 .84-.28 2.75 1.05A9.4 9.4 0 0 1 12 6.94c.85 0 1.7.12 2.5.34 1.91-1.33 2.75-1.05 2.75-1.05.55 1.41.2 2.45.1 2.71.64.72 1.03 1.63 1.03 2.75 0 3.94-2.34 4.81-4.57 5.06.36.32.68.94.68 1.9l-.01 2.82c0 .27.18.59.69.49A10.2 10.2 0 0 0 22 12.25C22 6.58 17.52 2 12 2Z"
    />
  </svg>
  {@render children?.()}
  <span class={divider} aria-hidden="true"></span>
  <span class={count}>
    <svg
      class={star}
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      stroke-width="1.5"
      stroke-linecap="round"
      stroke-linejoin="round"
      aria-hidden="true"
    >
      <path
        d="m12 3 2.78 5.63 6.22.9-4.5 4.39 1.06 6.19L12 17.2l-5.56 2.91 1.06-6.19L3 9.53l6.22-.9L12 3Z"
      />
    </svg>
    <span bind:this={number} aria-hidden="true">{compact(stars)}</span>
    <span class={srOnly}
      >{starsLabel.replace("{count}", stars.toLocaleString("en-US"))}</span
    >
  </span>
</a>
```

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

<GithubStarsButton href="https://github.com/markasui/markasui" stars={12480}>
  Star on GitHub
</GithubStarsButton>
```

### Astro

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

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

const base =
  "inline-flex items-center justify-center gap-2 font-medium whitespace-nowrap transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary 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 icon = "size-4 shrink-0";
const divider = "h-4 w-px bg-current opacity-25";
const count = "inline-flex items-center gap-1 tabular-nums";
const star = "size-3.5 shrink-0";
const srOnly = "sr-only";

const HAS_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
const SAFE_SCHEME = /^(https?|mailto|tel):/i;

/** Href with a scheme other than http, https, mailto, or tel (javascript:, for example) becomes "#". */
const safeHref = (href: string) => {
  const cleaned = href.replace(/[\t\n\r]/g, "");
  const start = [...cleaned].findIndex((char) => char > " ");
  const value = cleaned.slice(Math.max(start, 0));
  return HAS_SCHEME.test(value) && !SAFE_SCHEME.test(value) ? "#" : href;
};
/** 980, 12.4k, 1.2M. Same rule as the Blade version. */
const compact = (n: number) =>
  n >= 1e6
    ? `${Math.round(n / 1e5) / 10}M`
    : n >= 1e3
      ? `${Math.round(n / 100) / 10}k`
      : String(Math.round(n));

type Props = Omit<HTMLAttributes<"a">, "href"> & {
  /** Repository URL, for example https://github.com/owner/repo. */
  href: string;
  /** Star count. Pass it in, the component never fetches. */
  stars: number;
  variant?: keyof typeof variants;
  size?: keyof typeof sizes;
  /** Hidden text for the count. {count} is replaced by the full number. */
  starsLabel?: string;
};

const {
  href,
  stars,
  variant = "secondary",
  size = "md",
  starsLabel = "{count} stars",
  class: className,
  ...rest
} = Astro.props;
---

<markas-github-stars-button class="contents" data-stars={stars}>
  <a
    href={safeHref(href)}
    class:list={[base, variants[variant], sizes[size], className]}
    {...rest}
  >
    <svg class={icon} viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
      <path
        d="M12 2C6.48 2 2 6.58 2 12.25c0 4.53 2.87 8.37 6.84 9.73.5.09.68-.22.68-.49l-.01-1.7c-2.78.62-3.37-1.37-3.37-1.37-.46-1.18-1.11-1.5-1.11-1.5-.91-.64.07-.62.07-.62 1 .07 1.53 1.06 1.53 1.06.9 1.57 2.35 1.12 2.92.85.09-.66.35-1.12.64-1.37-2.22-.26-4.56-1.14-4.56-5.07 0-1.12.39-2.03 1.03-2.75-.1-.26-.45-1.3.1-2.71 0 0 .84-.28 2.75 1.05A9.4 9.4 0 0 1 12 6.94c.85 0 1.7.12 2.5.34 1.91-1.33 2.75-1.05 2.75-1.05.55 1.41.2 2.45.1 2.71.64.72 1.03 1.63 1.03 2.75 0 3.94-2.34 4.81-4.57 5.06.36.32.68.94.68 1.9l-.01 2.82c0 .27.18.59.69.49A10.2 10.2 0 0 0 22 12.25C22 6.58 17.52 2 12 2Z"
      ></path>
    </svg>
    <slot />
    <span class={divider} aria-hidden="true"></span>
    <span class={count}>
      <svg
        class={star}
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        stroke-width="1.5"
        stroke-linecap="round"
        stroke-linejoin="round"
        aria-hidden="true"
      >
        <path
          d="m12 3 2.78 5.63 6.22.9-4.5 4.39 1.06 6.19L12 17.2l-5.56 2.91 1.06-6.19L3 9.53l6.22-.9L12 3Z"
        ></path>
      </svg>
      <span data-markas-stars-number aria-hidden="true">{compact(stars)}</span>
      <span class={srOnly}>
        {starsLabel.replace("{count}", stars.toLocaleString("en-US"))}
      </span>
    </span>
  </a>
</markas-github-stars-button>

<script>
  const COUNT_DURATION = 1200;
  const compact = (n: number) =>
    n >= 1e6
      ? `${Math.round(n / 1e5) / 10}M`
      : n >= 1e3
        ? `${Math.round(n / 100) / 10}k`
        : String(Math.round(n));

  // Counts up from zero the first time the button scrolls into view. Never fetches.
  class GithubStarsButton extends HTMLElement {
    #stop = () => {};

    connectedCallback() {
      const number = this.querySelector<HTMLElement>("[data-markas-stars-number]");
      if (!number || typeof IntersectionObserver === "undefined") return;
      if (window.matchMedia?.("(prefers-reduced-motion: reduce)").matches) return;
      const stars = Number(this.dataset.stars) || 0;
      let frame = 0;
      number.textContent = "0";
      const observer = new IntersectionObserver(([entry]) => {
        if (!entry?.isIntersecting) return;
        observer.disconnect();
        const begin = performance.now();
        const step = (now: number) => {
          const t = Math.min((now - begin) / COUNT_DURATION, 1);
          number.textContent = compact(stars * (1 - (1 - t) ** 3));
          if (t < 1) frame = requestAnimationFrame(step);
        };
        frame = requestAnimationFrame(step);
      });
      observer.observe(number);
      this.#stop = () => {
        observer.disconnect();
        cancelAnimationFrame(frame);
        number.textContent = compact(stars);
      };
    }

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

  if (!customElements.get("markas-github-stars-button"))
    customElements.define("markas-github-stars-button", GithubStarsButton);
</script>
```

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

<GithubStarsButton href="https://github.com/markasui/markasui" stars={12480}>
  Star on GitHub
</GithubStarsButton>
```

### Angular

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

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

const base =
  "inline-flex items-center justify-center gap-2 font-medium whitespace-nowrap transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary 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 icon = "size-4 shrink-0";
const divider = "h-4 w-px bg-current opacity-25";
const count = "inline-flex items-center gap-1 tabular-nums";
const star = "size-3.5 shrink-0";
const srOnly = "sr-only";

const COUNT_DURATION = 1200;

const HAS_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
const SAFE_SCHEME = /^(https?|mailto|tel):/i;

/** Href with a scheme other than http, https, mailto, or tel (javascript:, for example) becomes "#". */
const safeHref = (href: string) => {
  const cleaned = href.replace(/[\t\n\r]/g, "");
  const start = [...cleaned].findIndex((char) => char > " ");
  const value = cleaned.slice(Math.max(start, 0));
  return HAS_SCHEME.test(value) && !SAFE_SCHEME.test(value) ? "#" : href;
};
/** 980, 12.4k, 1.2M. Same rule as the Blade version. */
const compact = (n: number) =>
  n >= 1e6
    ? `${Math.round(n / 1e5) / 10}M`
    : n >= 1e3
      ? `${Math.round(n / 100) / 10}k`
      : String(Math.round(n));
const reducedMotion = () =>
  typeof window.matchMedia === "function" &&
  window.matchMedia("(prefers-reduced-motion: reduce)").matches;

export type GithubStarsButtonVariant = keyof typeof variants;
export type GithubStarsButtonSize = keyof typeof sizes;

/**
 * Attribute selector on the native link, so aria-*, target, rel, and the user's class stay on it.
 * The href is checked: a scheme other than http, https, mailto, or tel becomes "#".
 */
@Component({
  selector: "a[markas-github-stars-button]",
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { "[attr.href]": "safeHref()", "[class]": "classes()" },
  template: `
    <svg
      [class]="icon"
      viewBox="0 0 24 24"
      fill="currentColor"
      aria-hidden="true"
    >
      <path
        d="M12 2C6.48 2 2 6.58 2 12.25c0 4.53 2.87 8.37 6.84 9.73.5.09.68-.22.68-.49l-.01-1.7c-2.78.62-3.37-1.37-3.37-1.37-.46-1.18-1.11-1.5-1.11-1.5-.91-.64.07-.62.07-.62 1 .07 1.53 1.06 1.53 1.06.9 1.57 2.35 1.12 2.92.85.09-.66.35-1.12.64-1.37-2.22-.26-4.56-1.14-4.56-5.07 0-1.12.39-2.03 1.03-2.75-.1-.26-.45-1.3.1-2.71 0 0 .84-.28 2.75 1.05A9.4 9.4 0 0 1 12 6.94c.85 0 1.7.12 2.5.34 1.91-1.33 2.75-1.05 2.75-1.05.55 1.41.2 2.45.1 2.71.64.72 1.03 1.63 1.03 2.75 0 3.94-2.34 4.81-4.57 5.06.36.32.68.94.68 1.9l-.01 2.82c0 .27.18.59.69.49A10.2 10.2 0 0 0 22 12.25C22 6.58 17.52 2 12 2Z"
      />
    </svg>
    <ng-content />
    <span [class]="divider" aria-hidden="true"></span>
    <span [class]="count">
      <svg
        [class]="star"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        stroke-width="1.5"
        stroke-linecap="round"
        stroke-linejoin="round"
        aria-hidden="true"
      >
        <path
          d="m12 3 2.78 5.63 6.22.9-4.5 4.39 1.06 6.19L12 17.2l-5.56 2.91 1.06-6.19L3 9.53l6.22-.9L12 3Z"
        />
      </svg>
      <span #number aria-hidden="true">{{ compactStars() }}</span>
      <span [class]="srOnly">{{ label() }}</span>
    </span>
  `,
})
export class GithubStarsButton {
  /** Repository URL, for example https://github.com/owner/repo. */
  readonly href = input.required<string>();
  /** Star count. Pass it in, the component never fetches. */
  readonly stars = input.required({ transform: numberAttribute });
  readonly variant = input<GithubStarsButtonVariant>("secondary");
  readonly size = input<GithubStarsButtonSize>("md");
  /** Hidden text for the count. {count} is replaced by the full number. */
  readonly starsLabel = input("{count} stars");

  protected readonly icon = icon;
  protected readonly divider = divider;
  protected readonly count = count;
  protected readonly star = star;
  protected readonly srOnly = srOnly;
  protected readonly safeHref = computed(() => safeHref(this.href()));
  protected readonly classes = computed(
    () => `${base} ${variants[this.variant()]} ${sizes[this.size()]}`,
  );
  protected readonly compactStars = computed(() => compact(this.stars()));
  protected readonly label = computed(() =>
    this.starsLabel().replace("{count}", this.stars().toLocaleString("en-US")),
  );
  private readonly number =
    viewChild.required<ElementRef<HTMLSpanElement>>("number");

  constructor() {
    let stop = () => {};
    // Count up from zero the first time the button scrolls into view.
    afterNextRender(() => {
      const number = this.number().nativeElement;
      if (typeof IntersectionObserver === "undefined" || reducedMotion())
        return;
      const stars = this.stars();
      let frame = 0;
      number.textContent = "0";
      const observer = new IntersectionObserver(([entry]) => {
        if (!entry?.isIntersecting) return;
        observer.disconnect();
        const begin = performance.now();
        const step = (now: number) => {
          const t = Math.min((now - begin) / COUNT_DURATION, 1);
          number.textContent = compact(stars * (1 - (1 - t) ** 3));
          if (t < 1) frame = requestAnimationFrame(step);
        };
        frame = requestAnimationFrame(step);
      });
      observer.observe(number);
      stop = () => {
        observer.disconnect();
        cancelAnimationFrame(frame);
      };
    });
    inject(DestroyRef).onDestroy(() => stop());
  }
}
```

```ts
import { Component } from "@angular/core";
import { GithubStarsButton } from "./markas/github-stars-button.component";

@Component({
  selector: "app-repo",
  imports: [GithubStarsButton],
  template: `
    <a
      markas-github-stars-button
      href="https://github.com/markasui/markasui"
      [stars]="12480"
    >
      Star on GitHub
    </a>
  `,
})
export class Repo {}
```

Angular uses an attribute selector on the native link, so `target`, `rel`, and `aria-*` stay on it.

## Props

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `href` | `string` | - | Repository URL. Unsafe schemes such as javascript: become #. |
| `stars` | `number` | 0 | Star count, passed in by you. Shown as 980, 12.5k, or 1.2M. |
| `variant` | `'primary' \| 'secondary' \| 'ghost' \| 'danger'` | secondary | Visual style, the same set as Button. |
| `size` | `'sm' \| 'md' \| 'lg'` | md | Height 32, 40, or 48px, the same as Button. |
| `starsLabel` | `string` | {count} stars | Hidden text for the count. {count} becomes the full number, for example 12,480. |

## Accessibility

- A native a element with a 2px primary focus outline.
- The animated number is aria-hidden, screen readers hear starsLabel with the full count.
- The GitHub mark and star icon are aria-hidden.
- With prefers-reduced-motion the final number shows right away.

## Notes

- The component never calls the GitHub API. Read the count at build time or on the server and pass it in.
- The visible number is compact (980, 12.5k, 1.2M). `{count}` in `starsLabel` gets the full number with thousands separators.
- The count-up starts the first time the link scrolls into view. Blade needs Alpine.js for the animation and renders the final number without it.
