Number Animation
Digit Swap
DigitSwap.vue<script setup lang="ts">
import { computed, ref } from 'vue'
import { DigitSwap } from 'beui-vue'
const CARD_NUMBER = ['4242', '4242', '4242', '0806'].join(' ')
const MASKED_NUMBER = '•••• •••• •••• 0806'
const revealed = ref(false)
const value = computed(() => (revealed.value ? CARD_NUMBER : MASKED_NUMBER))
</script>
<template>
<div class="swap-demo">
<div class="swap-field">
<span class="swap-label">Card number</span>
<DigitSwap
:value="value"
:animation-key="revealed ? 'revealed' : 'masked'"
:direction="revealed ? 'up' : 'down'"
:suffix-length="4"
:glyph-class-name="revealed ? 'swap-on' : 'swap-off'"
suffix-class-name="swap-on"
class-name="swap-number"
/>
</div>
<button type="button" :aria-label="revealed ? 'Animate masked number' : 'Animate card number'" :aria-pressed="revealed" @click="revealed = !revealed">Animate</button>
</div>
</template>
<style scoped>
.swap-demo { display: flex; width: 20rem; flex-direction: column; gap: 1.25rem; }
.swap-field { display: flex; flex-direction: column; gap: .5rem; }
.swap-label { font-size: .75rem; line-height: 1rem; font-weight: 500; color: var(--beui-muted-foreground); }
:deep(.swap-number) { font-family: var(--font-mono, 'Geist Mono Variable', ui-monospace, monospace); font-size: 1.125rem; line-height: 1.75rem; letter-spacing: .08em; font-variant-numeric: tabular-nums; }
:deep(.swap-off) { color: var(--beui-muted-foreground); }
/* After swap-off so the suffix (which carries both classes) stays foreground, like tailwind-merge upstream. */
:deep(.swap-on) { color: var(--beui-foreground); }
button { height: 2.5rem; align-self: flex-start; padding: 0 .75rem; border: 1px solid var(--beui-border); border-radius: .5rem; background: transparent; color: var(--beui-foreground); font: inherit; font-size: .875rem; font-weight: 500; cursor: pointer; outline: none; transition: background-color .15s; }
button:hover { background: var(--beui-muted); }
button:focus-visible { box-shadow: 0 0 0 2px var(--beui-ring); }
</style><script setup lang="ts">
import { AnimatePresence, motion } from 'motion-v'
import { useReducedMotion } from '../core/reduced-motion'
import { computed } from 'vue'
import { easeOut } from '../core/motion'
export type DigitSwapDirection = 'up' | 'down'
const props = defineProps<{
/** Numeric or masked value rendered in fixed character slots. */
value: string | number
/** Replays every glyph when the value itself contains unchanged characters. */
animationKey?: string | number
/** Direction the next glyph enters from. */
direction?: DigitSwapDirection
/** Per-glyph transition duration in seconds. */
duration?: number
/** Delay in seconds between neighbouring glyphs. */
stagger?: number
/** Number of final characters that receive `suffixClassName`. */
suffixLength?: number
className?: string
glyphClassName?: string
suffixClassName?: string
}>()
const { duration = .18, stagger = .006, suffixLength = 0 } = props
const reduceMotion = useReducedMotion() ?? computed(() => false)
const reduce = computed(() => Boolean(reduceMotion.value))
const text = computed(() => String(props.value))
const suffixStart = computed(() => Math.max(0, text.value.length - Math.max(0, suffixLength)))
const glyphs = computed(() =>
Array.from(text.value, (character, position) => ({ character, id: `glyph-${position}`, position })),
)
/**
* The slots clip with `clip-path`, which — unlike `overflow: hidden` — leaves
* the text baseline alone. An invisible in-flow copy of each character gives
* the slot its natural width (punctuation) or a fixed 1ch cell (digits).
*/
type GlyphMotionContext = { direction: DigitSwapDirection; reduceMotion: boolean }
// The leaving glyph is kept from its last render, so its direction travels as `custom`: the exit
// then follows the direction at the time of the change, not the one it was rendered with.
const GLYPH_VARIANTS = {
enter: ({ direction, reduceMotion }: GlyphMotionContext) => ({
opacity: 0,
transform: reduceMotion ? 'none' : `translateY(${direction === 'up' ? '45%' : '-45%'})`,
}),
visible: { opacity: 1, transform: 'translateY(0%)' },
exit: ({ direction, reduceMotion }: GlyphMotionContext) => ({
opacity: 0,
transform: reduceMotion ? 'none' : `translateY(${direction === 'up' ? '-45%' : '45%'})`,
}),
}
const motionContext = computed<GlyphMotionContext>(() => ({ direction: props.direction ?? 'up', reduceMotion: reduce.value }))
function glyphKey(glyph: { id: string; character: string }) {
return props.animationKey === undefined ? `${glyph.id}-${glyph.character}` : `${glyph.id}-${glyph.character}-${props.animationKey}`
}
function glyphTransition(glyph: { position: number }) {
return {
duration: reduce.value ? Math.min(duration, .12) : duration,
delay: reduce.value ? 0 : glyph.position * stagger,
ease: easeOut,
}
}
</script>
<template>
<span class="be-digit-swap" :class="className" :data-direction="direction ?? 'up'">
<span class="be-digit-swap-spoken">{{ text }}</span>
<span aria-hidden="true" class="be-digit-swap-row">
<template v-for="glyph in glyphs" :key="glyph.id">
<span v-if="glyph.character === ' '" class="be-digit-swap-space" />
<span
v-else
class="be-digit-swap-glyph"
:class="/\d/.test(glyph.character) && 'be-digit-swap-digit'"
>
<span class="be-digit-swap-reserve">{{ glyph.character }}</span>
<AnimatePresence :initial="false" :custom="motionContext">
<motion.span
:key="glyphKey(glyph)"
class="be-digit-swap-glyph-text"
:class="[glyphClassName, glyph.position >= suffixStart ? suffixClassName : undefined]"
:custom="motionContext"
:variants="GLYPH_VARIANTS"
initial="enter"
animate="visible"
exit="exit"
:transition="glyphTransition(glyph)"
>
{{ glyph.character }}
</motion.span>
</AnimatePresence>
</span>
</template>
</span>
</span>
</template>
<style scoped>
.be-digit-swap { display: inline-flex; align-items: baseline; white-space: nowrap; }
.be-digit-swap-spoken { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
.be-digit-swap-row { display: inline-flex; align-items: baseline; }
.be-digit-swap-space { display: inline-block; width: .7ch; }
.be-digit-swap-glyph { position: relative; display: inline-block; height: 1.1em; flex: none; line-height: 1.1em; clip-path: inset(0); }
.be-digit-swap-digit { width: 1ch; text-align: center; }
.be-digit-swap-reserve { visibility: hidden; }
.be-digit-swap-glyph-text { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; line-height: 1; }
</style>Install
Run it in a project set up with shadcn-vue. The source is copied to components/beui and its dependencies are added to your package.json. Read the shadcn-vue guide
$ bunx --bun shadcn-vue@latest add @beui-vue/digit-swap$ bun add beui-vueDownload the release archive to your project root, then install the local file.
$ bun add ./beui-vue-0.1.0.tgzImport the shared styles once in your application.
import DigitSwap from '@/components/beui/numeric/DigitSwap.vue'
import '@/components/beui/styles.css'API Reference
valuestring | numberNumeric or masked value rendered in fixed character slots.
—animationKey?string | numberReplays every glyph when the value itself contains unchanged characters.
—direction?DigitSwapDirectionDirection the next glyph enters from.
—duration?numberPer-glyph transition duration in seconds.
—stagger?numberDelay in seconds between neighbouring glyphs.
—suffixLength?numberNumber of final characters that receive `suffixClassName`.
—className?string—glyphClassName?string—suffixClassName?string—Number Ticker
NumberTicker.vueActive users
48,2730012345678900123456789,001234567890012345678900123456789live · updates every 2.5s
<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref } from 'vue'
import { NumberTicker } from 'beui-vue'
const value = ref(48273)
let timer: ReturnType<typeof setInterval> | undefined
onMounted(() => { timer = setInterval(() => { value.value += Math.floor(Math.random() * 50) }, 2500) })
onBeforeUnmount(() => clearInterval(timer))
const format = (n: number) => n.toLocaleString('en-US')
</script>
<template>
<div class="ticker-demo">
<p>Active users</p>
<NumberTicker :value="value" prefix="" class-name="ticker-value" :format="format" />
<p>live · updates every 2.5s</p>
</div>
</template>
<style scoped>
.ticker-demo { display: flex; flex-direction: column; align-items: center; gap: .75rem; }
p { margin: 0; font-size: .75rem; line-height: 1rem; color: var(--beui-muted-foreground); }
:deep(.ticker-value) { font-size: 2.25rem; line-height: 2.5rem; font-weight: 600; letter-spacing: -.025em; color: var(--beui-foreground); font-variant-numeric: tabular-nums; }
</style><script lang="ts">
/**
* English defaults for `NumberTicker`. The visible text is the formatted
* number; the const exists so callers can supply a spoken form per locale.
*/
export const numberTickerMessages = {
value: '{value}',
}
export type NumberTickerMessages = typeof numberTickerMessages
</script>
<script setup lang="ts">
import { useInView } from 'motion-v'
import { computed, onBeforeUnmount, shallowRef, useTemplateRef, watch } from 'vue'
import TickColumn from './TickColumn.vue'
/** Height of one digit cell, in `em`. The rolling column repeats this ten times. */
const DIGIT_HEIGHT_EM = 1.1
const props = withDefaults(defineProps<{
value: number
/** Digits to pad to (left). */
pad?: number
/** Fraction digits to keep. The value is rounded before `format` runs. */
decimals?: number
/** Per-digit roll duration in seconds. */
duration?: number
/** Stagger between digits. */
stagger?: number
/** Render only after the element enters the viewport. */
startOnView?: boolean
prefix?: string
suffix?: string
/** Add a small blur during digit rolls. */
blur?: boolean
className?: string
digitClassName?: string
/** Locale group separators. `true` uses the runtime locale; a tag pins it. */
locale?: boolean | string
/** Custom formatter. */
format?: (value: number) => string
}>(), { decimals: 0, duration: 0.9, stagger: 0.04, startOnView: true, blur: false })
const root = useTemplateRef<HTMLElement>('root')
const inView = useInView(root, { once: true, amount: 0.6 })
const armed = shallowRef(!props.startOnView)
const entered = shallowRef(false)
let enteredTimer: ReturnType<typeof setTimeout> | undefined
const text = computed(() => {
const places = Math.max(0, Math.floor(props.decimals))
const factor = 10 ** places
// Round before formatting so `format` sees the same number the slots render.
const rounded = Math.round(props.value * factor) / factor
const formatted = props.format
? props.format(rounded)
: props.locale
? rounded.toLocaleString(typeof props.locale === 'string' ? props.locale : undefined, {
minimumFractionDigits: places,
maximumFractionDigits: places,
})
: rounded.toFixed(places)
return props.pad ? formatted.padStart(props.pad, '0') : formatted
})
// Key by place value (position from the right): a changing digit keeps its
// identity and rolls to the new value instead of remounting and replaying from
// 0. Growing numbers add glyphs on the left without re-keying the ones, tens
// and hundreds already on screen.
const glyphs = computed(() => {
const chars = text.value.split('')
return chars.map((char, index) => ({ char, id: `g-${chars.length - 1 - index}` }))
})
const readableText = computed(() => `${props.prefix ?? ''}${text.value}${props.suffix ?? ''}`)
watch(
armed,
value => {
// Stagger is an entrance flourish. Once the reveal has played, value
// changes roll every digit immediately — a per-digit delay on live updates
// reads as lag.
if (!value || entered.value) return
clearTimeout(enteredTimer)
enteredTimer = setTimeout(() => (entered.value = true), (props.duration + glyphs.value.length * props.stagger) * 1000)
},
{ immediate: true },
)
watch(inView, value => {
if (props.startOnView && value) armed.value = true
})
onBeforeUnmount(() => clearTimeout(enteredTimer))
</script>
<template>
<span ref="root" class="be-ticker" :class="className">
<span class="be-ticker-spoken">{{ readableText }}</span>
<span aria-hidden="true" class="be-ticker-row">
<span v-if="prefix">{{ prefix }}</span>
<template v-for="(glyph, index) in glyphs" :key="glyph.id">
<span v-if="!/\d/.test(glyph.char)" class="be-ticker-char">{{ glyph.char }}</span>
<span
v-else
class="be-ticker-digit"
:class="digitClassName"
:style="{ height: `${DIGIT_HEIGHT_EM}em`, lineHeight: `${DIGIT_HEIGHT_EM}em`, width: '1ch' }"
>
<!-- The invisible in-flow digit gives the slot a real text baseline,
so it lines up with surrounding text; clip-path clips the rolling
column without moving that baseline the way overflow would. -->
<span class="be-ticker-slot-text">{{ armed ? glyph.char : 0 }}</span>
<TickColumn :digit="armed ? Number(glyph.char) : 0" :delay="entered ? 0 : index * stagger" :duration="duration" :blur="blur" />
</span>
</template>
<span v-if="suffix">{{ suffix }}</span>
</span>
</span>
</template>
<style scoped>
.be-ticker { display: inline-flex; align-items: baseline; font-variant-numeric: tabular-nums; }
.be-ticker-spoken { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
.be-ticker-row { display: inline-flex; align-items: baseline; }
.be-ticker-char { display: inline-block; }
.be-ticker-digit { position: relative; display: inline-block; flex: none; text-align: center; clip-path: inset(0); }
.be-ticker-slot-text { visibility: hidden; }
</style>Install
Run it in a project set up with shadcn-vue. The source is copied to components/beui and its dependencies are added to your package.json. Read the shadcn-vue guide
$ bunx --bun shadcn-vue@latest add @beui-vue/number-ticker$ bun add beui-vueDownload the release archive to your project root, then install the local file.
$ bun add ./beui-vue-0.1.0.tgzImport the shared styles once in your application.
import NumberTicker from '@/components/beui/numeric/NumberTicker.vue'
import '@/components/beui/styles.css'API Reference
valuenumber—pad?numberDigits to pad to (left).
—decimals?numberFraction digits to keep. The value is rounded before `format` runs.
0duration?numberPer-digit roll duration in seconds.
0.9stagger?numberStagger between digits.
0.04startOnView?booleanRender only after the element enters the viewport.
trueprefix?string—suffix?string—blur?booleanAdd a small blur during digit rolls.
falseclassName?string—digitClassName?string—locale?boolean | stringLocale group separators. `true` uses the runtime locale; a tag pins it.
—format?(value: number) => stringCustom formatter.
—Animated Number
AnimatedNumber.vueMonthly recurring revenue
+12.4% vs last month
<script setup lang="ts">
import { AnimatedNumber } from 'beui-vue'
const format = (n: number) => `$${Math.round(n).toLocaleString()}`
</script>
<template>
<div class="number-demo">
<p class="number-label">Monthly recurring revenue</p>
<div class="number-value"><AnimatedNumber :value="129480" :format="format" /></div>
<p class="number-delta">+12.4% vs last month</p>
</div>
</template>
<style scoped>
.number-demo { display: flex; flex-direction: column; align-items: center; gap: .75rem; }
p { margin: 0; font-size: .75rem; line-height: 1rem; }
.number-label { color: var(--beui-muted-foreground); }
.number-value { font-size: 2.25rem; line-height: 2.5rem; font-weight: 600; letter-spacing: -.025em; color: var(--beui-foreground); font-variant-numeric: tabular-nums; }
.number-delta { color: oklch(70% .18 155); }
</style><script setup lang="ts">
import { animate, useInView } from 'motion-v'
import { useReducedMotion } from '../core/reduced-motion'
import { onBeforeUnmount, shallowRef, useTemplateRef, watch } from 'vue'
import { easeOut } from '../core/motion'
const props = withDefaults(defineProps<{
value: number
duration?: number
format?: (n: number) => string
className?: string
startOnView?: boolean
}>(), {
duration: 1.2,
startOnView: true,
format: (n: number) => Math.round(n).toLocaleString(),
})
const target = useTemplateRef<HTMLElement>('target')
const inView = useInView(target, { once: true, amount: .6 })
const reduce = useReducedMotion()
const display = shallowRef(0)
// Tween from wherever the last run settled, so a value change counts up from
// the shown number instead of restarting at zero.
let from = 0
let controls: ReturnType<typeof animate> | undefined
function run() {
controls?.stop()
if (props.startOnView && !inView.value) return
if (reduce.value) {
from = props.value
display.value = props.value
return
}
controls = animate(from, props.value, {
duration: props.duration,
ease: easeOut,
onUpdate: value => (display.value = value),
})
from = props.value
}
watch([() => props.value, () => props.duration, inView, () => props.startOnView, reduce], run, { immediate: true })
onBeforeUnmount(() => controls?.stop())
</script>
<template>
<span ref="target" class="be-animated-number" :class="className">{{ format(display) }}</span>
</template>
<style scoped>
.be-animated-number { font-variant-numeric: tabular-nums; }
</style>Install
Run it in a project set up with shadcn-vue. The source is copied to components/beui and its dependencies are added to your package.json. Read the shadcn-vue guide
$ bunx --bun shadcn-vue@latest add @beui-vue/animated-number$ bun add beui-vueDownload the release archive to your project root, then install the local file.
$ bun add ./beui-vue-0.1.0.tgzImport the shared styles once in your application.
import AnimatedNumber from '@/components/beui/numeric/AnimatedNumber.vue'
import '@/components/beui/styles.css'API Reference
valuenumber—duration?number1.2format?(n: number) => stringMath.round(n).toLocaleString()className?string—startOnView?booleantrueRelated components
Action Swap
CTA button and slot primitives for swapping text and icons with blur motion.
Text Animation
Animated text primitives for spring reveals, chromatic sweeps, shimmer loading states, letter-cascade swaps and character scrambles.
Loader
Loading indicator with seventeen variants: spinner, dots, bars, dot-matrix, dither, morph, comet, scramble, metaballs, newton, helix, percent, and five terminal-style ascii spinners. Scales from one size prop, uses currentColor, and reduced-motion swaps every transform for a calm opacity pulse.
Updated