Glow Button for Astro
An Astro button with an animated glow behind the control.
Installation
bunx --bun shadcn@latest add @gnostic/glow-buttonnpx shadcn@latest add @gnostic/glow-buttonpnpm dlx shadcn@latest add @gnostic/glow-buttonComplete the Installation guide first. Then copy the component files below.
Install component packages
bun add motionCopy the files
src/components/ui/glow-button/glow-animation.ts
import type { AnimationOptions, DOMKeyframesDefinition } from 'motion'
import type { GlowMode } from './types.ts'
/** Palette used when a caller does not pass colors. */
export const DEFAULT_GLOW_COLORS: string[] = [
'#FF5733', // red
'#33FF57', // green
'#3357FF', // blue
'#F1C40F', // yellow
]
/** Modes the shell accepts from a data attribute. */
export const GLOW_MODES = [
'rotate',
'pulse',
'breathe',
'colorShift',
'flowHorizontal',
'static',
] as const satisfies readonly GlowMode[]
/** Keyframes plus the options for `animate(element, keyframes, options)`. */
export type GlowAnimation = {
keyframes: DOMKeyframesDefinition
options?: AnimationOptions
}
type GlowAnimationInput = {
colors: string[]
mode: GlowMode
scale: number
duration: number
}
/**
* Build the glow keyframes for one mode.
* The React port kept `transition` on the animate object.
* The element API takes keyframes and options as separate arguments.
*/
export function buildGlowAnimation({
colors = DEFAULT_GLOW_COLORS,
mode,
scale,
duration,
}: GlowAnimationInput): GlowAnimation {
const cycle = duration > 0 ? duration : 5
const loop: AnimationOptions = {
duration: cycle,
ease: 'linear',
repeat: Infinity,
}
const mirror: AnimationOptions = {
...loop,
repeatType: 'mirror',
}
const list = colors.join(', ')
switch (mode) {
case 'rotate':
return {
keyframes: {
background: [
`conic-gradient(from 0deg at 50% 50%, ${list})`,
`conic-gradient(from 360deg at 50% 50%, ${list})`,
],
},
options: loop,
}
case 'pulse':
return {
keyframes: {
background: colors.map(
(color) =>
`radial-gradient(circle at 50% 50%, ${color} 0%, transparent 100%)`,
),
opacity: [0.5, 0.8, 0.5],
scale: [scale, scale * 1.1, scale],
} as DOMKeyframesDefinition,
options: mirror,
}
case 'breathe':
return {
keyframes: {
background: colors.map(
(color) =>
`radial-gradient(circle at 50% 50%, ${color} 0%, transparent 100%)`,
),
scale: [scale, scale * 1.05, scale],
} as DOMKeyframesDefinition,
options: mirror,
}
case 'colorShift':
return {
keyframes: {
background: colors.map((color, index) => {
const next = colors[(index + 1) % colors.length]!
return `conic-gradient(from 0deg at 50% 50%, ${color} 0%, ${next} 50%, ${color} 100%)`
}),
},
options: mirror,
}
case 'flowHorizontal':
return {
keyframes: {
background: colors.map((color, index) => {
const next = colors[(index + 1) % colors.length]!
return `linear-gradient(to right, ${color}, ${next})`
}),
},
options: mirror,
}
case 'static':
return {
keyframes: {
background: `linear-gradient(to right, ${list})`,
},
}
}
}
/**
* First painted frame.
* The effect renders this before the shell script starts.
*/
export function initialGlowBackground(
mode: GlowMode,
colors: string[],
): string {
const background = buildGlowAnimation({
colors,
duration: 1,
mode,
scale: 1,
}).keyframes.background
if (Array.isArray(background)) {
const first = background[0]
return typeof first === 'string' ? first : ''
}
return typeof background === 'string' ? background : ''
}
/** Read a mode attribute. Unknown text falls back to rotate. */
export function parseGlowMode(value: string | null | undefined): GlowMode {
if (value && (GLOW_MODES as readonly string[]).includes(value)) {
return value as GlowMode
}
return 'rotate'
}
/** Read a colors attribute. The value is a JSON string array. */
export function parseGlowColors(value: string | null | undefined): string[] {
if (!value) return [...DEFAULT_GLOW_COLORS]
try {
const parsed: unknown = JSON.parse(value)
if (
Array.isArray(parsed) &&
parsed.length > 0 &&
parsed.every((color) => typeof color === 'string' && color !== '')
) {
return parsed
}
} catch {
// Attribute text that is not JSON keeps the default palette.
}
return [...DEFAULT_GLOW_COLORS]
}
/** Read a numeric data attribute. Blank or invalid text keeps the fallback. */
export function parseGlowNumber(
value: string | null | undefined,
fallback: number,
): number {
if (value == null || value.trim() === '') return fallback
const parsed = Number(value)
return Number.isFinite(parsed) ? parsed : fallback
}
src/components/ui/glow-button/glow-button-effect.astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
import { mergeStyles } from "../../../lib/merge-styles.ts"
import { DEFAULT_GLOW_COLORS, initialGlowBackground } from "./glow-animation.ts"
import type { GlowBlur, GlowButtonEffectProps } from "./types.ts"
/** Div attributes pass through. Glow fields come from `GlowButtonEffectProps`. */
type Props = HTMLAttributes<"div"> & GlowButtonEffectProps
/**
* Named blur steps. Each value is a full Tailwind class so the build can see it.
* A number uses an inline filter because a built class name cannot include the pixel value.
*/
const BLUR_CLASS = {
softest: "blur-xs",
soft: "blur-sm",
medium: "blur-md",
strong: "blur-lg",
stronger: "blur-xl",
strongest: "blur-2xl",
none: "blur-none",
} as const satisfies Record<Exclude<GlowBlur, number>, string>
/** Tailwind blur class for a named step. A pixel blur returns no class. */
function blurClass(blur: GlowBlur) {
if (typeof blur === "number") return undefined
return BLUR_CLASS[blur]
}
const {
colors = DEFAULT_GLOW_COLORS,
mode = "rotate",
blur = "strong",
scale = 1,
duration = 5,
class: className,
style: styleProp,
...props
} = Astro.props
const style = mergeStyles(
{
"--glow-scale": String(scale),
background: initialGlowBackground(mode, colors),
...(typeof blur === "number" ? { filter: `blur(${blur}px)` } : {}),
},
styleProp,
)
---
<div
data-slot="glow-button-effect"
data-mode={mode}
data-colors={JSON.stringify(colors)}
data-duration={duration}
data-scale={scale}
class={cn(
"pointer-events-none absolute inset-0 size-full scale-(--glow-scale) transform-gpu rounded-lg will-change-transform",
blurClass(blur),
className,
)}
style={style}
{...props}
/>
src/components/ui/glow-button/glow-button.astro
---
import type { HTMLTag, Polymorphic } from "astro/types"
import { cn } from "cn"
import { Button } from "../button/index.ts"
import { DEFAULT_GLOW_COLORS } from "./glow-animation.ts"
import GlowButtonEffect from "./glow-button-effect.astro"
import type { GlowButtonProps } from "./types.ts"
/**
* Button attributes pass through to the inner button.
* `href` selects an anchor when `as` is omitted.
*/
type Props<Tag extends HTMLTag = "button"> = Polymorphic<{ as: Tag }> &
GlowButtonProps
/**
* True when the caller disabled the control.
* An empty string still counts. `false` does not.
*/
function disabledProp(props: object) {
if (!("disabled" in props)) return false
const value = (props as { disabled?: unknown }).disabled
return value !== false && value != null
}
const {
as: Tag = "href" in Astro.props ? "a" : "button",
class: className,
variant = "default",
size = "default",
withLoader = false,
mode = "rotate",
colors = DEFAULT_GLOW_COLORS,
blur = "strong",
duration = 5,
glowScale = 1,
...props
} = Astro.props
const isDisabled = disabledProp(Astro.props)
const resolvedGlowScale = Number.isFinite(glowScale) ? glowScale : 1
const elementProps: Record<string, unknown> = {
...(Tag === "button" ? { type: "button" as const } : {}),
...props,
...(isDisabled && Tag !== "button"
? { "aria-disabled": "true", tabindex: -1 }
: {}),
}
// Anchors have no disabled attribute. The shell blocks the link instead.
if (Tag !== "button") delete elementProps.disabled
---
<div
data-slot="glow-button"
data-glow-scale={resolvedGlowScale}
data-disabled={isDisabled ? "true" : undefined}
class={cn(
"relative inline-flex",
isDisabled && "pointer-events-none opacity-50",
)}
>
<div
aria-hidden="true"
data-slot="glow-button-scale"
class="pointer-events-none absolute inset-0"
style={`scale: ${resolvedGlowScale}`}
>
<GlowButtonEffect
colors={colors}
mode={mode}
blur={blur}
duration={duration}
scale={1}
/>
</div>
<Button
as={Tag}
variant={variant}
size={size}
withLoader={withLoader}
class={cn("relative", isDisabled && "disabled:opacity-100", className)}
{...elementProps}
>
<slot />
{Astro.slots.has("button-loading-indicator") && (
<slot name="button-loading-indicator" slot="button-loading-indicator" />
)}
</Button>
</div>
<script>
import { animate, hover } from "motion"
import {
buildGlowAnimation,
parseGlowColors,
parseGlowMode,
parseGlowNumber,
} from "./glow-animation.ts"
/** Roots already bound on this page. A later page load skips them. */
const bound = new WeakSet<HTMLElement>()
/** Stops animations and hover listeners before the next page replaces them. */
const stops: Array<() => void> = []
/** Spring used for the hover scale. Matches the original motion transition. */
const hoverSpring = { type: "spring" as const, stiffness: 300, damping: 20 }
/**
* Start the mode animation and the hover scale for one shell.
* The effect element holds the mode, colors, duration, and layer scale.
* The shell holds the hover scale.
*/
function bindGlowButton(root: HTMLElement) {
if (bound.has(root)) return
const scaleLayer = root.querySelector<HTMLElement>(
":scope > [data-slot='glow-button-scale']",
)
const effect = scaleLayer?.querySelector<HTMLElement>(
":scope > [data-slot='glow-button-effect']",
)
if (!scaleLayer || !effect) return
bound.add(root)
const colors = parseGlowColors(effect.dataset.colors)
const mode = parseGlowMode(effect.dataset.mode)
const duration = parseGlowNumber(effect.dataset.duration, 5)
const scale = parseGlowNumber(effect.dataset.scale, 1)
const glowScale = parseGlowNumber(root.dataset.glowScale, 1)
const reduced = window.matchMedia(
"(prefers-reduced-motion: reduce)",
).matches
// A static frame is already painted. Reduced motion keeps that frame.
if (!reduced && mode !== "static") {
const animation = buildGlowAnimation({ colors, duration, mode, scale })
const playback = animate(effect, animation.keyframes, animation.options)
stops.push(() => playback.stop())
}
if (reduced || root.dataset.disabled === "true") return
const stopHover = hover(root, () => {
animate(scaleLayer, { scale: glowScale * 1.05 }, hoverSpring)
return () => {
animate(scaleLayer, { scale: glowScale }, hoverSpring)
}
})
stops.push(stopHover)
}
/** Bind every shell currently in the document. */
const start = () => {
document
.querySelectorAll<HTMLElement>("[data-slot='glow-button']")
.forEach(bindGlowButton)
}
start()
document.addEventListener("astro:page-load", start)
document.addEventListener("astro:before-swap", () => {
for (const stop of stops) stop()
stops.length = 0
})
</script>
src/components/ui/glow-button/index.ts
export { default as GlowButton } from './glow-button.astro'
export { default as GlowButtonEffect } from './glow-button-effect.astro'
export type {
GlowBlur,
GlowButtonEffectProps,
GlowButtonProps,
GlowMode,
} from './types.ts'
src/components/ui/glow-button/types.ts
import type { ButtonProps } from '../button/types.ts'
/**
* How the glow layer moves.
* `static` paints one gradient and does not loop.
*/
export type GlowMode =
| 'rotate'
| 'pulse'
| 'breathe'
| 'colorShift'
| 'flowHorizontal'
| 'static'
/**
* Blur of the glow layer.
* A number is a pixel radius. A name selects a Tailwind blur step.
*/
export type GlowBlur =
| number
| 'softest'
| 'soft'
| 'medium'
| 'strong'
| 'stronger'
| 'strongest'
| 'none'
/**
* Props for the painted glow layer.
* The shell reads these values and runs the animation.
* Div attributes such as `class` and `style` pass through.
*/
export interface GlowButtonEffectProps {
/**
* Glow colors. Use at least two colors for a visible shift.
* @default ["#FF5733", "#33FF57", "#3357FF", "#F1C40F"]
*/
colors?: string[]
/**
* Glow animation mode.
* @default "rotate"
*/
mode?: GlowMode
/**
* Blur strength of the glow layer.
* @default "strong"
*/
blur?: GlowBlur
/**
* Scale of this layer before the shell hover scale.
* Pulse and breathe animate around this value.
* @default 1
*/
scale?: number
/**
* Duration of one animation cycle, in seconds.
* @default 5
*/
duration?: number
}
/**
* Props for a button with an animated glow behind it.
* Button attributes such as `class`, `disabled`, `type`, and `href` pass through.
*/
export interface GlowButtonProps extends ButtonProps {
/**
* Glow animation mode.
* @default "rotate"
*/
mode?: GlowMode
/**
* Glow colors. Use at least two colors for a visible shift.
* A theme token such as `var(--primary)` follows the active preset.
* @default ["#FF5733", "#33FF57", "#3357FF", "#F1C40F"]
*/
colors?: string[]
/**
* Blur strength of the glow layer.
* @default "strong"
*/
blur?: GlowBlur
/**
* Duration of one animation cycle, in seconds.
* @default 5
*/
duration?: number
/**
* Scale of the glow layer relative to the button.
* Values above 1 spread the glow past the button edges.
* @default 1
*/
glowScale?: number
}
Usage
---
import { GlowButton } from "@/components/ui/glow-button"
---
<GlowButton>Get started</GlowButton>
GlowButton is the outer shell. It renders a Button,
a scale layer, and a glow layer. The shell script reads the glow layer and
runs the animation. The glow layer does not start its own animation.
class merges onto the button. variant, size, and withLoader use the
Button props. Set type="submit" for a form action. Without as, an href
selects an anchor. Otherwise the component renders a button with type="button".
The root uses data-slot="glow-button". The painted layer uses
data-slot="glow-button-effect".
Examples
Modes
rotate is the default. pulse and breathe change scale and color.
colorShift and flowHorizontal move through the palette. static paints
one gradient and does not loop.
Theme colors
Pass var(--primary) and other theme tokens to follow the active preset.
Use at least two colors.
Link
Use as="a" and href for a destination.
Props
GlowButtonProps
mode?GlowMode
Glow animation mode.
GlowMode"rotate"colors?string[]
Glow colors. Use at least two colors for a visible shift. A theme token such as `var(--primary)` follows the active preset.
string[]["#FF5733", "#33FF57", "#3357FF", "#F1C40F"]blur?GlowBlur
Blur strength of the glow layer.
GlowBlur"strong"duration?number
Duration of one animation cycle, in seconds.
number5glowScale?number
Scale of the glow layer relative to the button. Values above 1 spread the glow past the button edges.
number1as?HTMLTag
The HTML tag to render the button as.
HTMLTag'button'withLoader?boolean
Add the built-in loading indicator. It will remain hidden until the button's `data-loading` attribute is set to `true`.
booleanfalsevariant?"outline" | "default" | "glass" | "surface" | "destructive-outline" | "destructive" | "ghost" | "link" | "secondary" | null | undefined
"outline" | "default" | "glass" | "surface" | "destructive-outline" | "destructive" | "ghost" | "link" | "secondary" | null | undefinedsize?"icon" | "icon-xs" | "icon-sm" | "icon-lg" | "icon-xl" | "default" | "lg" | "sm" | "xl" | "xs" | null | undefined
"icon" | "icon-xs" | "icon-sm" | "icon-lg" | "icon-xl" | "default" | "lg" | "sm" | "xl" | "xs" | null | undefinedGlowButtonEffectProps
colors?string[]
Glow colors. Use at least two colors for a visible shift.
string[]["#FF5733", "#33FF57", "#3357FF", "#F1C40F"]mode?GlowMode
Glow animation mode.
GlowMode"rotate"blur?GlowBlur
Blur strength of the glow layer.
GlowBlur"strong"scale?number
Scale of this layer before the shell hover scale. Pulse and breathe animate around this value.
number1duration?number
Duration of one animation cycle, in seconds.
number5Read the installed source for the complete prop types.
GlowButtonEffect is the painted layer. Use it only inside GlowButton.
The shell owns the animation.
Slots
| Slot | Content |
|---|---|
| Default | The visible action label. |
button-loading-indicator |
A custom loader. Shown when the button has data-loading. |
Keyboard and behavior
A native button supports Enter and Space. A link supports Enter and normal
browser link actions. The glow is decorative and is hidden from assistive
technology. disabled fades the shell and blocks pointer input. On a link,
the shell also sets aria-disabled and removes the link from the tab order.
The animation respects prefers-reduced-motion: reduce. That setting keeps
the first gradient and skips the hover scale.
Theme and layout
The button uses the shared Button recipe. The default glow palette is
independent of the preset. Pass theme tokens in colors when the glow should
follow the preset. blur selects the halo strength. glowScale above 1
spreads the halo past the button edges. Give the preview or parent some
padding so the halo is not clipped.