Char Mask Up

entrance

Each character slides up from behind a tight clipping mask.

I Love Bangladesh

17/120
Align
Ease
Duration
s
0.13
Stagger
s
00.2
Delay
s
02
export function charMaskUp(el) {
  const _reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches
  const _duration = _reducedMotion ? 0.01 : 0.5
  const _stagger = _reducedMotion ? 0 : 0.025
  const _delay = _reducedMotion ? 0 : 0

  const split = splitChars(el)
  split.chars.forEach((c) => {
    const mask = document.createElement('span')
    mask.className = 'k-char-clip'
    c.before(mask)
    mask.append(c)
  })
  const easing = 'linear(0.0000,0.1624,0.2977,0.4108,0.5056,0.5852,0.6522,0.7088,0.7565,0.7968,0.8309,0.8597,0.8841,0.9046,0.9219,0.9363,0.9484,0.9585,0.9668,0.9736,0.9792,0.9837,0.9874,0.9903,0.9926,0.9944,0.9958,0.9969,0.9977,0.9983,0.9988,0.9991,0.9994,0.9996,0.9997,0.9998,0.9999,0.9999,1.0000,1.0000)'
  const anims = split.chars.map((c, i) =>
    c.animate([{ transform: 'translateY(100%)' }, { transform: 'none' }], {
      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, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')

  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-clip {
  display: inline-block;
  overflow: hidden;
}

.k-char-mask {
  display: inline-block;
}