DocumentationGlowHighlight

GlowHighlight

Traces soft, layered candy-colored rings around the words that matter.

Svelte

Shared live previews stay running while you switch code examples and API documentation.

One word that glows · Make it yours

Calm at rest. Playful the moment you mean it.

Finish
Palette
#E94F86
#FFE1EC
#FFD76A
#FF8A3D
1.00×

Soft layered bands traced around the letters. Spread scales every ring together.

600 ms

Time to grow or fold away. Reversing mid-flight continues from the current frame.

Trigger

Make it yours. Every color is a CSS custom property.

Place the words in the default slot. Native attributes use Vue spelling, and component refs expose element.

Quick start

Add to your project

Copy the component and everything it needs into your Vue 3.5+ project.

RecommendedUse the shadcn-vue CLI
npx shadcn-vue@2.8.2 add https://kida-ui.onrender.com/r/vue/glow-highlight.json

Run this from a project with components.json. The CLI creates all required files and installs the declared runtime dependencies. New to shadcn? Follow theinstallation guide first.

View registry JSON
Copy manually6 files

1. Create the source files

Keep this directory structure so the component's relative imports continue to work.

src/components/ui/kida/glow-highlight.vue
<script setup lang="ts">
import './glow-highlight.css'
/*
 * AI agent notes: GlowHighlight
 *
 * Change the look with props only; the component has no runtime controls. Do not edit the
 * motion engine or glow-highlight.css to restyle one usage: they apply to every instance.
 *
 * Settings and defaults:
 *   finish    'glow' | 'sticker' | 'halo'                    default 'glow'
 *   palette   'candy' | 'sorbet' | 'berry' | 'after-dark'    default 'candy'
 *   spread    ring size multiplier, clamped 0–3              default 1
 *   duration  ms to grow or fold away                        default 600
 *   trigger   'view' | 'hover' | 'manual'                    default 'view'
 *   once      view: stay lit after the first entry           default true
 *   amount    view: visible fraction (0–1) needed to start   default 0.6
 *   active    manual: whether the glow is on                 default false
 *
 * To reproduce a docs look exactly, copy finish, palette, spread, duration, and trigger.
 * Any setting left out falls back to its default.
 *   Playful     <GlowHighlight>Playful</GlowHighlight>
 *   Sticker     <GlowHighlight finish="sticker" :spread="0.8">Sticker</GlowHighlight>
 *   Halo        <GlowHighlight finish="halo" :spread="1.2" :duration="900">Halo</GlowHighlight>
 *   After dark  <GlowHighlight finish="sticker" palette="after-dark">after dark</GlowHighlight>
 *               Use on a dark surface with light text.
 *
 * Colors beyond the palettes: set --kida-glow-core, --kida-glow-rim, --kida-glow-band, and
 * --kida-glow-fringe in `style` on the component. A class loaded before this component's
 * CSS does not override them.
 *
 * The slot renders twice: once as the traced copy and once as the readable text. Keep it on
 * the same line as its tags, because surrounding line breaks become spaces in both copies.
 * `hover` follows the nearest link, button, label, summary, or [tabindex] element, including
 * the highlight itself, so keyboard focus lights it too. Keep it to a word or short phrase:
 * every growing instance redraws its filter each frame. Reduced motion is handled inside;
 * do not add your own checks.
 */
import { type GlowHighlightControls, glowHighlight } from './glow-highlight.motion.js'
import { shallowRef, watch } from 'vue'
import type { GlowHighlightProps } from './glow-highlight.types.js'

defineOptions({ name: 'KidaGlowHighlight', inheritAttrs: false })
const props = withDefaults(defineProps<GlowHighlightProps>(), {
  finish: 'glow',
  palette: 'candy',
  spread: 1,
  duration: 600,
  trigger: 'view',
  once: true,
  amount: 0.6,
  active: false,
})
const element = shallowRef<HTMLSpanElement | null>(null)
let controls: GlowHighlightControls | null = null
defineExpose({ element })

// Visual options and the manual state update the live controller; only these restart it.
watch(
  [() => element.value, () => props.trigger, () => props.once, () => props.amount],
  (_, __, onCleanup) => {
    const node = element.value
    if (!node) return
    const created = glowHighlight(node, { ...props })
    controls = created
    onCleanup(() => {
      created.destroy()
      if (controls === created) controls = null
    })
  },
  { flush: 'post' },
)

watch(
  [() => props.finish, () => props.spread, () => props.duration],
  () => controls?.update({ finish: props.finish, spread: props.spread, duration: props.duration }),
  { flush: 'post' },
)

watch(
  [() => props.active, () => props.trigger],
  () => {
    if (props.trigger === 'manual') controls?.setActive(props.active)
  },
  { flush: 'post' },
)
</script>

<template>
  <!-- The traced copy is aria-hidden and made inert by the engine, so content is read once. -->
  <span v-bind="$attrs" ref="element" data-kida-glow="" :data-finish="props.finish" :data-palette="props.palette" data-state="off">
    <span data-kida-glow-layer="" aria-hidden="true"><slot /></span>
    <span data-kida-glow-content=""><slot /></span>
    <svg data-kida-glow-defs="" aria-hidden="true" focusable="false" />
  </span>
</template>
src/components/ui/kida/glow-highlight.types.ts
import type { GlowHighlightOptions, GlowHighlightPalette } from './glow-highlight.motion.js';

export type { GlowHighlightFinish, GlowHighlightPalette, GlowHighlightTrigger } from './glow-highlight.motion.js';

export interface GlowHighlightProps extends GlowHighlightOptions {
    /** Named color set. Inline --kida-glow-* values override it. @default 'candy' */
    palette?: GlowHighlightPalette;
}

/** Vue component refs expose the root DOM element, null when presence removes it. */
export interface KidaElement {
    element: HTMLElement | null;
}
src/components/ui/kida/glow-highlight.css
/*
 * GlowHighlight. Every colour is a custom property, so palettes are compositions, not props.
 * Defaults: a Cherry core with a blush rim, then butter and tangerine bands. Ink on Cherry is
 * about 4.75:1.
 */
[data-kida-glow] {
  --kida-glow-core: #e94f86;
  --kida-glow-rim: #ffe1ec;
  --kida-glow-band: #ffd76a;
  --kida-glow-fringe: #ff8a3d;
  --kida-glow-shadow: rgb(33 28 36 / 0.2);

  /* Breathing room so the outer band does not paint over neighbouring letters. */
  --kida-glow-gap: 0.1em;

  position: relative;
  display: inline-block;
  margin-inline: var(--kida-glow-gap);
  isolation: isolate;
}

[data-kida-glow] [data-kida-glow-layer] {
  position: absolute;
  z-index: -1;
  /* Exactly the text's box, so wrapped lines trace identically. The engine's filter region
     paints the rings outside it without adding to the page's scrollable area. */
  inset: 0;
  /* Only alpha is read. If a browser drops the filter, an opaque copy exactly under the text
     is the least visible failure. */
  color: #000;
  pointer-events: none;
  user-select: none;
  /* Hidden until the engine runs, so server markup never shows a raw copy. */
  visibility: hidden;
}

[data-kida-glow] [data-kida-glow-content] {
  position: relative;
}

[data-kida-glow] [data-kida-glow-defs] {
  position: absolute;
  width: 0;
  height: 0;
  overflow: hidden;
}

/* Named palettes, selected with `palette` (data-palette). Candy is the default above. Inline
   --kida-glow-* values still override any palette. Mirrored by GLOW_PALETTES in the motion
   package; a test keeps the two identical. */
[data-kida-glow][data-palette="sorbet"] {
  --kida-glow-core: #ffb07a;
  --kida-glow-rim: #fff0e4;
  --kida-glow-band: #ffd76a;
  --kida-glow-fringe: #e94f86;
}

[data-kida-glow][data-palette="berry"] {
  --kida-glow-core: #cdbdff;
  --kida-glow-rim: #f6f1ff;
  --kida-glow-band: #f9a8c9;
  --kida-glow-fringe: #e94f86;
}

/* For dark surfaces: a deeper core keeps light text readable. */
[data-kida-glow][data-palette="after-dark"] {
  --kida-glow-core: #8f2350;
  --kida-glow-rim: #c23a6e;
  --kida-glow-band: #ffd76a;
  --kida-glow-fringe: #ff8a3d;
}

/* System colours replace the palette; the decoration would only fight them. */
@media (forced-colors: active) {
  [data-kida-glow] [data-kida-glow-layer] {
    display: none;
  }
}
src/components/ui/kida/glow-highlight.motion.ts
/**
 * GlowHighlight engine. Framework-agnostic; adapters render the markup contract and forward
 * options.
 *
 *   <span data-kida-glow>
 *     <span data-kida-glow-layer aria-hidden>text</span>         ← filtered copy, behind
 *     <span data-kida-glow-content>text</span>                   ← the real, readable text
 *     <svg data-kida-glow-defs aria-hidden></svg>                ← the engine fills this
 *   </span>
 *
 * The rings are an SVG filter on the hidden copy, built from its alpha, so any text, font
 * or size works and late-loading fonts re-trace for free. Motion is one progress value per
 * instance driven by an on-demand rAF loop that stops when settled. At rest the layer is
 * `visibility: hidden` when off, so an idle highlight costs no filter work.
 */
import {
  GLOW_CLOSING,
  type GlowHighlightFinish,
  type GlowRingPx,
  glowRingsPx,
  ringFrame,
  stepProgress,
} from './glow-highlight-math.motion.js'
import { prefersReducedMotion, watchReducedMotion } from './reduced-motion.motion.js'

export {
  GLOW_PALETTES,
  type GlowHighlightFinish,
  type GlowHighlightPalette,
  type GlowPaletteColors,
} from './glow-highlight-math.motion.js'

export type GlowHighlightTrigger = 'view' | 'hover' | 'manual'

export interface GlowHighlightOptions {
  /** Ring treatment. @default 'glow' */
  finish?: GlowHighlightFinish
  /** Multiplier on ring size, from 0 to 3. @default 1 */
  spread?: number
  /** Time to fully grow or collapse, in ms. @default 600 */
  duration?: number
  /** What turns the glow on. @default 'view' */
  trigger?: GlowHighlightTrigger
  /** For `view`: glow once and stay lit. @default true */
  once?: boolean
  /** For `view`: visible fraction needed to start, from 0 to 1. @default 0.6 */
  amount?: number
  /** For `manual`: the initial state, applied without animation. @default false */
  active?: boolean
}

export interface GlowHighlightControls {
  /** Animate toward on or off. Interrupts and reverses any motion in progress. */
  setActive(active: boolean): void
  /** Apply new visual options without restarting or losing the current state. */
  update(options: Pick<GlowHighlightOptions, 'finish' | 'spread' | 'duration'>): void
  destroy(): void
}

const SVG = 'http://www.w3.org/2000/svg'
/**
 * Corner-rounding blur as a fraction of the ring radius. Thresholding the blur at 50% turns
 * feMorphology's square corners round and fills small counters (the bowls of P, a, e).
 */
const ROUNDING = 0.65
let nextId = 0

interface RingNodes {
  spec: GlowRingPx
  morph: SVGFEMorphologyElement
  close: SVGFEMorphologyElement
  smooth: SVGFEGaussianBlurElement
  round: SVGFEGaussianBlurElement
  flood: SVGFEFloodElement
}

function el<K extends keyof SVGElementTagNameMap>(
  name: K,
  attrs: Record<string, string | number>,
): SVGElementTagNameMap[K] {
  const node = document.createElementNS(SVG, name)
  for (const [key, value] of Object.entries(attrs)) node.setAttribute(key, String(value))
  return node
}

const px = (value: number) => Math.round(value * 100) / 100

const finite = (value: number | undefined, fallback: number, min: number, max: number) =>
  value !== undefined && Number.isFinite(value) ? Math.min(max, Math.max(min, value)) : fallback

export function glowHighlight(
  root: HTMLElement,
  options: GlowHighlightOptions = {},
): GlowHighlightControls {
  const foundLayer = root.querySelector<HTMLElement>('[data-kida-glow-layer]')
  const defs = root.querySelector<SVGSVGElement>('[data-kida-glow-defs]')
  if (!foundLayer || !defs) throw new Error('glowHighlight: missing layer or defs markup')
  const layer: HTMLElement = foundLayer

  let finish: GlowHighlightFinish = options.finish ?? 'glow'
  let spread = finite(options.spread, 1, 0, 3)
  let duration = finite(options.duration, 600, 0, Number.POSITIVE_INFINITY)
  const trigger = options.trigger ?? 'view'

  const id = `kida-glow-${++nextId}`
  // The region is set in pixels around the layer's box (see fitRegion). The rings paint
  // outside the text without enlarging any box, so they never cause page overflow.
  const filter = el('filter', {
    id,
    filterUnits: 'userSpaceOnUse',
    'color-interpolation-filters': 'sRGB',
  })
  defs.append(filter)
  layer.style.filter = `url(#${id})`
  // Links or buttons inside the copy must not be focused twice. Set here rather than in markup
  // because React 18 and 19 serialize `inert` differently; until now the copy was
  // `visibility: hidden`, which also keeps it out of the tab order.
  layer.inert = true

  let rings: RingNodes[] = []
  let fontSize = 0
  let progress = trigger === 'manual' && options.active ? 1 : 0
  let target = progress
  let frame = 0
  let last = 0

  function build() {
    filter.replaceChildren()
    rings = []
    const specs = glowRingsPx(finish, fontSize, spread)
    const merge = el('feMerge', {})
    specs.forEach((spec, i) => {
      // Grow past the ring, round the square corners feMorphology leaves (blur, then a steep
      // threshold at 50%), and only then shrink back. Rounding while oversized keeps the
      // bridges that close counters, word spaces and line gaps; rounding after the shrink
      // would cut them again.
      const morph = el('feMorphology', { in: 'SourceAlpha', operator: 'dilate', radius: 0 })
      morph.setAttribute('result', `m${i}`)
      const round = el('feGaussianBlur', { in: `m${i}`, stdDeviation: 0, result: `r${i}` })
      const threshold = el('feComponentTransfer', { in: `r${i}`, result: `t${i}` })
      threshold.append(el('feFuncA', { type: 'linear', slope: 24, intercept: -11.5 }))
      const close = el('feMorphology', { in: `t${i}`, operator: 'erode', radius: 0 })
      close.setAttribute('result', `e${i}`)
      // The square erode kernel leaves boxy notches; a light second rounding removes them
      // without cutting the much wider bridges.
      const smooth = el('feGaussianBlur', { in: `e${i}`, stdDeviation: 0, result: `b${i}` })
      const edge = el('feComponentTransfer', { in: `b${i}`, result: `n${i}` })
      edge.append(el('feFuncA', { type: 'linear', slope: 24, intercept: -11.5 }))
      filter.append(morph, round, threshold, close, smooth, edge)

      let shape = `n${i}`
      if (spec.soft > 0) {
        filter.append(
          el('feGaussianBlur', { in: shape, stdDeviation: px(spec.soft), result: `s${i}` }),
        )
        shape = `s${i}`
      }
      if (spec.dy) {
        filter.append(el('feOffset', { in: shape, dy: px(spec.dy), result: `o${i}` }))
        shape = `o${i}`
      }
      const flood = el('feFlood', { 'flood-opacity': 0, result: `f${i}` })
      flood.style.setProperty('flood-color', `var(${spec.color})`)
      filter.append(
        flood,
        el('feComposite', { in: `f${i}`, in2: shape, operator: 'in', result: `c${i}` }),
      )
      rings.push({ spec, morph, close, round, smooth, flood })
    })
    // Outermost ring underneath, core on top.
    for (let i = specs.length - 1; i >= 0; i--) merge.append(el('feMergeNode', { in: `c${i}` }))
    filter.append(merge)
  }

  function render() {
    layer.style.visibility = progress > 0 ? 'visible' : 'hidden'
    if (progress <= 0) return
    rings.forEach(({ spec, ...nodes }, i) => {
      const { grow, alpha } = ringFrame(progress, i, rings.length)
      const radius = spec.radius * grow
      const em = fontSize * Math.min(1, grow)
      const cx = GLOW_CLOSING.x * em
      const cy = GLOW_CLOSING.y * em
      nodes.morph.setAttribute('radius', `${px(radius + cx)} ${px(radius + cy)}`)
      nodes.close.setAttribute('radius', `${px(cx)} ${px(cy)}`)
      nodes.smooth.setAttribute('stdDeviation', String(px(Math.max(0.3, cx * 0.4))))
      nodes.round.setAttribute('stdDeviation', String(px(Math.max(0.3, radius * ROUNDING))))
      nodes.flood.setAttribute('flood-opacity', String(px(spec.opacity * alpha)))
    })
  }

  function settleState() {
    root.dataset.state =
      progress === target ? (target === 1 ? 'on' : 'off') : target === 1 ? 'entering' : 'leaving'
  }

  function tick(now: number) {
    // A hidden tab pauses rAF; clamp so returning does not count the whole absence twice.
    const elapsed = Math.min(now - last, 100)
    last = now
    progress = stepProgress(progress, target, elapsed, duration)
    render()
    settleState()
    frame = progress === target ? 0 : requestAnimationFrame(tick)
  }

  function jump() {
    cancelAnimationFrame(frame)
    frame = 0
    progress = target
    render()
    settleState()
  }

  function setActive(active: boolean) {
    target = active ? 1 : 0
    if (prefersReducedMotion() || duration <= 0) {
      jump()
      return
    }
    if (!frame && progress !== target) {
      last = performance.now()
      frame = requestAnimationFrame(tick)
    }
    settleState()
  }

  /**
   * Sizes the filter region to the furthest ring plus the closing grow, which happens before
   * the shrink and would be clipped by a tighter region. Smaller than a percentage region on
   * long phrases, so there are fewer pixels to filter.
   */
  function fitRegion() {
    const reach =
      Math.max(0, ...rings.map(({ spec }) => spec.radius + spec.soft * 3 + Math.abs(spec.dy))) +
      (Math.max(GLOW_CLOSING.x, GLOW_CLOSING.y) + 0.1) * fontSize +
      4
    filter.setAttribute('x', String(px(-reach)))
    filter.setAttribute('y', String(px(-reach)))
    filter.setAttribute('width', String(px(layer.offsetWidth + reach * 2)))
    filter.setAttribute('height', String(px(layer.offsetHeight + reach * 2)))
  }

  function measure() {
    const next = Number.parseFloat(getComputedStyle(root).fontSize)
    if (next !== fontSize) {
      fontSize = next
      build()
      render()
    }
    fitRegion()
  }

  measure()
  settleState()

  // Font size can change with the viewport (clamp(), container queries), and wrapping changes
  // the box the region surrounds; either way the root resizes.
  const resize = new ResizeObserver(measure)
  resize.observe(root)

  // Turning reduced motion on mid-flight settles immediately instead of finishing the growth.
  const cleanups: Array<() => void> = [
    () => resize.disconnect(),
    watchReducedMotion((reduced) => {
      if (reduced && frame) jump()
    }),
  ]

  if (trigger === 'view') {
    const once = options.once ?? true
    const io = new IntersectionObserver(
      (entries) => {
        if (entries.some((entry) => entry.isIntersecting)) {
          setActive(true)
          if (once) io.disconnect()
        } else if (!once) {
          setActive(false)
        }
      },
      { threshold: finite(options.amount, 0.6, 0, 1) },
    )
    io.observe(root)
    cleanups.push(() => io.disconnect())
  }

  if (trigger === 'hover') {
    // Highlights inside links and buttons respond to the control, not just the word.
    const host = root.closest<HTMLElement>('a, button, label, summary, [tabindex]') ?? root
    let hovered = false
    let focused = false
    const sync = () => setActive(hovered || focused)
    const enter = () => {
      hovered = true
      sync()
    }
    const leave = () => {
      hovered = false
      sync()
    }
    const focus = () => {
      focused = true
      sync()
    }
    const blur = () => {
      focused = false
      sync()
    }
    host.addEventListener('pointerenter', enter)
    host.addEventListener('pointerleave', leave)
    host.addEventListener('focusin', focus)
    host.addEventListener('focusout', blur)
    cleanups.push(() => {
      host.removeEventListener('pointerenter', enter)
      host.removeEventListener('pointerleave', leave)
      host.removeEventListener('focusin', focus)
      host.removeEventListener('focusout', blur)
    })
  }

  return {
    setActive,
    update(next) {
      const nextFinish = next.finish ?? finish
      const nextSpread = finite(next.spread, spread, 0, 3)
      const rebuild = nextFinish !== finish || nextSpread !== spread
      finish = nextFinish
      spread = nextSpread
      duration = finite(next.duration, duration, 0, Number.POSITIVE_INFINITY)
      if (rebuild) {
        build()
        render()
        fitRegion()
      }
    },
    destroy() {
      cancelAnimationFrame(frame)
      frame = 0
      for (const cleanup of cleanups) cleanup()
      filter.remove()
      layer.style.removeProperty('filter')
      layer.style.removeProperty('visibility')
      layer.inert = false
      root.dataset.state = 'off'
    },
  }
}
src/components/ui/kida/glow-highlight-math.motion.ts
/**
 * Pure geometry and timing for GlowHighlight. No DOM, so it is unit-testable.
 *
 * A glow is a stack of rings traced around the glyphs. Each ring is the text's alpha grown
 * outward by `radius`, rounded, then softened by `soft`. Lengths are in em so the effect
 * follows the font size; the engine converts them to CSS pixels for the SVG filter.
 */

export type GlowHighlightFinish = 'glow' | 'sticker' | 'halo'

export type GlowHighlightPalette = 'candy' | 'sorbet' | 'berry' | 'after-dark'

export interface GlowPaletteColors {
  core: string
  rim: string
  band: string
  fringe: string
}

/**
 * Named colour sets. The stylesheet applies them through `data-palette`; these values mirror
 * it for tooling and docs, and a test keeps the two identical. Candy is the default.
 */
export const GLOW_PALETTES: Record<GlowHighlightPalette, GlowPaletteColors> = {
  candy: { core: '#e94f86', rim: '#ffe1ec', band: '#ffd76a', fringe: '#ff8a3d' },
  sorbet: { core: '#ffb07a', rim: '#fff0e4', band: '#ffd76a', fringe: '#e94f86' },
  berry: { core: '#cdbdff', rim: '#f6f1ff', band: '#f9a8c9', fringe: '#e94f86' },
  // Deeper core so light text keeps its contrast on dark surfaces.
  'after-dark': { core: '#8f2350', rim: '#c23a6e', band: '#ffd76a', fringe: '#ff8a3d' },
}

export interface GlowRing {
  /** Custom property that supplies the ring colour. */
  color: string
  /** Distance grown outward from the glyph edge, in em. */
  radius: number
  /** Edge blur, in em. `0` keeps a crisp, die-cut edge. */
  soft: number
  /** Peak opacity of the ring. */
  opacity: number
  /** Vertical offset, in em. Used for the sticker's paper shadow. */
  dy?: number
}

/** Rings from the innermost (drawn on top) to the outermost (drawn underneath). */
export const GLOW_RINGS: Record<GlowHighlightFinish, readonly GlowRing[]> = {
  // Closest to the reference: a filled core, a pale rim, then warmer bands that soften outward.
  glow: [
    { color: '--kida-glow-core', radius: 0.075, soft: 0.005, opacity: 1 },
    { color: '--kida-glow-rim', radius: 0.11, soft: 0.006, opacity: 1 },
    { color: '--kida-glow-band', radius: 0.17, soft: 0.014, opacity: 1 },
    { color: '--kida-glow-fringe', radius: 0.225, soft: 0.045, opacity: 0.95 },
  ],
  // Cut-paper: crisp edges and a small, hard shadow instead of an ambient glow.
  sticker: [
    { color: '--kida-glow-core', radius: 0.07, soft: 0, opacity: 1 },
    { color: '--kida-glow-rim', radius: 0.11, soft: 0, opacity: 1 },
    { color: '--kida-glow-fringe', radius: 0.145, soft: 0, opacity: 1 },
    { color: '--kida-glow-shadow', radius: 0.145, soft: 0.006, opacity: 1, dy: 0.045 },
  ],
  // No fill behind the letters: a quiet light that stays legible inside body copy.
  halo: [
    { color: '--kida-glow-rim', radius: 0.05, soft: 0.05, opacity: 0.95 },
    { color: '--kida-glow-band', radius: 0.11, soft: 0.08, opacity: 0.8 },
    { color: '--kida-glow-fringe', radius: 0.18, soft: 0.12, opacity: 0.55 },
  ],
}

/**
 * Extra grow-then-shrink, in em, so the core reads as one shape. Horizontally it closes
 * counters and word spaces but keeps the notches that make the outline follow the letters.
 * Vertically it is larger to bridge the line gap of wrapped text; otherwise the core joins
 * only where ascenders and descenders reach across and the rim shows through as holes.
 */
export const GLOW_CLOSING = { x: 0.14, y: 0.3 } as const

/** The ring furthest from the glyphs, including blur. Used to size the filter region. */
export function glowExtent(finish: GlowHighlightFinish, spread = 1): number {
  return Math.max(
    ...GLOW_RINGS[finish].map((ring) => ring.radius * spread + ring.soft * 3 + (ring.dy ?? 0)),
  )
}

export interface GlowRingPx {
  color: string
  radius: number
  soft: number
  opacity: number
  dy: number
}

/** Converts the em-based rings to CSS pixels for a font size and spread multiplier. */
export function glowRingsPx(
  finish: GlowHighlightFinish,
  fontSize: number,
  spread = 1,
): GlowRingPx[] {
  return GLOW_RINGS[finish].map((ring) => ({
    color: ring.color,
    radius: ring.radius * spread * fontSize,
    soft: ring.soft * Math.sqrt(spread) * fontSize,
    opacity: ring.opacity,
    dy: (ring.dy ?? 0) * fontSize,
  }))
}

export const clamp01 = (value: number) => Math.min(1, Math.max(0, value))

/** Ease-out with a small overshoot. `overshoot` 1.2 peaks at roughly 5%. */
export function easeOutBack(x: number, overshoot = 1.2): number {
  const t = x - 1
  return 1 + (overshoot + 1) * t * t * t + overshoot * t * t
}

const easeOutCubic = (x: number) => 1 - (1 - x) ** 3

/** Fraction of the timeline between one ring starting and the next. */
export const GLOW_STAGGER = 0.14

/** The slice of the 0..1 timeline in which ring `index` grows. Inner rings lead. */
export function ringWindow(index: number, count: number, stagger = GLOW_STAGGER) {
  const length = 1 - stagger * Math.max(0, count - 1)
  const start = stagger * index
  return { start, end: start + length }
}

export interface RingFrame {
  /** Multiplier on the ring radius. Overshoots slightly past 1 while growing. */
  grow: number
  /** Multiplier on the ring opacity, 0..1. */
  alpha: number
}

/**
 * The state of one ring at timeline position `progress`.
 *
 * The mapping is a pure function of progress, so reversing mid-flight is just moving progress
 * the other way: the outer rings collapse first and the glow folds back into the letters.
 */
export function ringFrame(progress: number, index: number, count: number): RingFrame {
  const { start, end } = ringWindow(index, count)
  const local = clamp01((progress - start) / (end - start))
  return {
    grow: local === 0 ? 0 : easeOutBack(local),
    alpha: easeOutCubic(clamp01(local / 0.55)),
  }
}

/** Advances progress linearly toward `target` at a rate set by `duration` (ms). */
export function stepProgress(
  progress: number,
  target: number,
  elapsed: number,
  duration: number,
): number {
  if (duration <= 0) return target
  const delta = elapsed / duration
  return target > progress ? Math.min(target, progress + delta) : Math.max(target, progress - delta)
}
src/components/ui/kida/reduced-motion.motion.ts
const QUERY = '(prefers-reduced-motion: reduce)'

/**
 * Whether the user has asked for reduced motion.
 *
 * SSR-safe: returns `false` when there is no `window`, matching the CSS default
 * (the `prefers-reduced-motion` media query in `@kida-ui/styles` is the real guard;
 * this is for the JS-driven paths that CSS cannot express).
 */
export function prefersReducedMotion(): boolean {
  if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return false
  return window.matchMedia(QUERY).matches
}

/**
 * Subscribe to changes of the reduced-motion preference.
 * Returns an unsubscribe function. No-op (and immediately unsubscribable) on the server.
 */
export function watchReducedMotion(onChange: (reduced: boolean) => void): () => void {
  if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return () => {}

  const list = window.matchMedia(QUERY)
  const handler = (event: MediaQueryListEvent) => onChange(event.matches)
  list.addEventListener('change', handler)
  return () => list.removeEventListener('change', handler)
}
<script setup lang="ts">
import GlowHighlight from '@/components/ui/kida/glow-highlight.vue'
</script>

<template>
  <h1>Calm at rest. <GlowHighlight>Playful</GlowHighlight> the moment you mean it.</h1>
</template>

Customization

The playground above is for exploring only. The installed component has no controls: choose everything in code with props and CSS custom properties. Glow draws soft layered bands; Sticker cuts a crisp edge with a small paper shadow; Halo leaves the letters unfilled, so it suits running text. spread scales the rings and duration sets how long they take to grow. Rings grow outward from the core in a short stagger, and reversing mid-flight continues from the current frame instead of jumping.

Finishes in code

Glow for a headline

Sticker for a label

Halo for running text

<script setup lang="ts">
import { GlowHighlight } from '@kida-ui/vue'
</script>

<template>
  <div class="demo-glow-finishes">
    <p><GlowHighlight finish="glow">Glow</GlowHighlight> for a headline</p>
    <p><GlowHighlight finish="sticker" :spread="0.8">Sticker</GlowHighlight> for a label</p>
    <p><GlowHighlight finish="halo" :spread="1.2" :duration="900">Halo</GlowHighlight> for running text</p>
  </div>
</template>

Pick a named palette: Candy (the default), Sorbet, Berry, or After dark, which has a deeper core so light text stays readable on dark surfaces. The rings are traced from the text itself, so any font, size, or wrapped phrase works. For colors beyond the palettes, bind the CSS custom properties below with :style on the component; they override the palette.

After dark

Open late, after dark.

<script setup lang="ts">
import { GlowHighlight } from '@kida-ui/vue'
</script>

<template>
  <p class="glow-highlight-dark">Open late, <GlowHighlight finish="sticker" palette="after-dark">after dark</GlowHighlight>.</p>
</template>

API

Props

Prop Type Default Description
finish 'glow' | 'sticker' | 'halo' 'glow' Ring treatment. Changes rebuild the rings without restarting.
palette 'candy' | 'sorbet' | 'berry' | 'after-dark' 'candy' Named color set. Inline custom properties override it.
spread number 1 Multiplier on ring size, clamped to 0–3.
duration number 600 Milliseconds to fully grow or fold away.
trigger 'view' | 'hover' | 'manual' 'view' What turns the glow on.
once boolean true For view: stay lit after the first entry. With :once="false", the glow folds away on exit.
amount number 0.6 For view: visible fraction, from 0–1, required to start.
active boolean false For manual: whether the glow is on. The initial value applies without animating.

hover follows the nearest enclosing link, button, label, summary, or element with tabindex, so keyboard focus lights the glow as well as the pointer. Native span attributes, class, style, event listeners, and a component ref exposing element are passed to the root. Changing trigger, once, or amount recreates the controller; the other options update in place.

CSS custom properties

Defaults below are the Candy palette.

Property Default Description
--kida-glow-core #e94f86 Fill closest to the letters. Keep enough contrast with the text color.
--kida-glow-rim #ffe1ec Thin pale outline around the core.
--kida-glow-band #ffd76a Middle band.
--kida-glow-fringe #ff8a3d Outermost, softest band.
--kida-glow-shadow rgb(33 28 36 / 0.2) Sticker paper shadow.
--kida-glow-gap 0.1em Inline margin that keeps the rings off neighboring words.

Accessibility and input behavior

The text is rendered once for reading, selection, and copying. The traced copy behind it is hidden from assistive technology and made inert, so links inside the highlight are focused once. The SVG filter is decorative. In forced-colors mode the decoration is removed and system colors apply. Color is never the only signal: the highlighted words remain ordinary text.

Reduced motion switches the glow on and off without growing, including when the preference changes mid-animation. Each instance runs a short frame loop only while growing or folding, then stops; a settled or idle highlight does no work. Observers, listeners, frames, and the filter are released on unmount.

Server markup is deterministic and shows the plain text; the glow appears after hydration. Filter IDs are created in the browser, so repeated instances never collide. The rings paint outside the text’s box without enlarging it, so a highlight at the edge of a narrow screen does not cause horizontal scrolling. Modern browsers with SVG filters on HTML content are required for the effect; without them the text renders normally.

Troubleshooting

Use GlowHighlight for a word or short phrase. Every animating instance re-renders its filter on each frame, so dozens growing at once can drop frames on modest GPUs; once settled they cost nothing. If the outer band touches the next word, increase --kida-glow-gap or lower spread. On dark surfaces, choose a deeper core so light text keeps its contrast. Keep the slot content on one line with the tags, as in the examples: whitespace inside the tags becomes part of the highlighted text.