Characters sharpen into focus as they fade in from a blur.
export function blurIn(el) {
const _reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches
const _duration = _reducedMotion ? 0.01 : 0.5
const _stagger = _reducedMotion ? 0 : 0.02
const _delay = _reducedMotion ? 0 : 0
const split = splitChars(el)
const easing = 'linear(0.0000,0.0750,0.1461,0.2135,0.2772,0.3374,0.3942,0.4476,0.4978,0.5448,0.5889,0.6299,0.6682,0.7037,0.7366,0.7670,0.7949,0.8205,0.8439,0.8651,0.8844,0.9017,0.9172,0.9309,0.9431,0.9537,0.9630,0.9709,0.9776,0.9831,0.9877,0.9914,0.9942,0.9964,0.9979,0.9989,0.9995,0.9999,1.0000,1.0000)'
const anims = split.chars.map((c, i) =>
c.animate(
[
{ filter: 'blur(12px)', opacity: 0 },
{ filter: 'blur(0px)', opacity: 1 },
],
{
duration: _duration * 1000,
delay: (_delay + i * _stagger) * 1000,
easing,
fill: 'backwards',
},
),
)
return () => {
anims.forEach((a) => a.cancel())
split.revert()
}
}
function splitChars(el) {
const text = el.textContent ?? ''
if (el.children.length > 0) {
return { chars: [el], words: [el], revert: () => {} }
}
const escape = (s) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
const segmenter =
typeof Intl !== 'undefined' && 'Segmenter' in Intl
? new Intl.Segmenter(undefined, { granularity: 'grapheme' })
: null
const toChars = (s) => (segmenter ? Array.from(segmenter.segment(s), (seg) => seg.segment) : Array.from(s))
const tokens = text.match(/\S+|\s+/g) ?? []
el.setAttribute('aria-label', text)
el.innerHTML = tokens
.map((token) => {
if (/^\s+$/.test(token)) return token
const chars = toChars(token)
.map((c) => `<span class="k-char">${escape(c)}</span>`)
.join('')
return `<span class="k-word" aria-hidden="true">${chars}</span>`
})
.join('')
return {
chars: [...el.querySelectorAll('.k-char')],
words: [...el.querySelectorAll('.k-word')],
revert: () => {
el.textContent = text
el.removeAttribute('aria-label')
},
}
}
/* CSS */
.k-word {
display: inline-block;
white-space: nowrap;
}
.k-char {
display: inline-block;
}