ascii-reveal README

README проекта с github.com/quanhoangindex/ascii-reveal. Одним файлом markdown: README.md.

ascii-reveal

Three cards load as ASCII skeletons, then their real content decodes in through a character grid

Recorded from the real component: <AsciiSkeleton> while loading, then <AsciiReveal> decodes the data in. Try the live demo →

<AsciiReveal loading={!data}>
  {data ? <Profile data={data} /> : <AsciiSkeleton lines={3} />}
</AsciiReveal>

A loading effect for React. Text, images and whole cards decode into place through a character grid, in one wave across the page.

Install

From npm:

npm i ascii-reveal

Straight from GitHub (no npm publish needed):

npm i github:quanhoangindex/ascii-reveal

React 17 or newer is a peer dependency. The built files in dist/ are committed, so the GitHub install works without a build step.

Quick start

import { AsciiReveal } from 'ascii-reveal';

export function Page() {
  return (
    <AsciiReveal preset="decode">
      <article className="card" data-ascii="surface">
        <img src="/cover.jpg" alt="" />
        <h2>Hello world</h2>
        <button data-ascii="fade">Read more</button>
      </article>
    </AsciiReveal>
  );
}

The content reveals when the component mounts.

Loading states

const { data, isLoading } = useQuery(...);

<AsciiReveal loading={isLoading} selector="[data-value]" revealOnMount={false}>
  <dd data-value>{data?.latency ?? '—'}</dd>
</AsciiReveal>

When loading turns true, the matching content scrambles out and a shimmer runs in its place. When it turns false, the new content decodes in.

Skeletons

Skeletons exist to paint instantly while data loads. AsciiSkeleton does exactly that, in ASCII. There are two ways to use it (live demo):

1. Skeleton only. A drop-in replacement for a gray skeleton. Content appears as normal when it arrives.

Three cards show ASCII dither skeletons, then the real content appears as each card's data arrives
import { AsciiSkeleton } from 'ascii-reveal';

{data ? <Profile data={data} /> : <AsciiSkeleton lines={3} />}

2. Skeleton + reveal. The skeleton paints first; when the data arrives, the real content decodes in (about 400 ms).

Three cards show ASCII dither skeletons, then the real content decodes in through a character grid
import { AsciiReveal, AsciiSkeleton } from 'ascii-reveal';

<AsciiReveal loading={!data}>
  {data ? <Profile data={data} /> : <AsciiSkeleton lines={3} />}
</AsciiReveal>

The reveal never animates the skeleton itself. It leaves it alone while loading, and decodes the content that replaces it.

Pick a style with variant:

variant Look
dither (default) Shaded blocks ░▒▓█ that read as soft bars, with a darker dither band scanning across.
scan Faint dots with a band of dense, scrambling glyphs. Matches the decode preset.
braille Fine braille dot texture; the band fills the dots in.
terminal Faint 0s and 1s, lit up in --ascii-accent as the band passes.
<AsciiSkeleton variant="braille" lines={3} />
<AsciiSkeleton variant="dither" rows={6} width={64} height={64} circle />
<AsciiSkeleton animate={false} lines={2} />   {/* still pattern: cheapest, for long lists */}

Without React: el.innerHTML = asciiSkeletonHTML({ lines: 3 }), then animateSkeletons(el), both from ascii-reveal/core.

How much does it cost?

A skeleton only does its job if it shows up as fast as a gray box and never delays the data, so we measured it against one. Pre-rendered pages, no JavaScript needed to paint, Chromium on a machine without a GPU (so all drawing is done in software, the worst case), median of 7–11 runs:

12 cards, normal CPU Gray skeleton AsciiSkeleton AsciiSkeleton animate={false}
First paint 48 ms 44 ms 36 ms
Style + layout at load 2 ms 9 ms 5 ms
Browser CPU while waiting 15% 21% 0%
HTML (gzipped) 0.5 KB 3.2 KB 3 KB

How it stays cheap:

Run it yourself: node scripts/skeleton-bench/build.cjs && node scripts/skeleton-bench/bench.cjs.

Server rendering

Content that arrives in server-rendered HTML is never hidden on hydration: it's already readable, so hiding it to animate it would make the page slower. Set revealOnHydrate if you want the effect anyway. Client-side navigations and loading transitions animate as usual.

Loading mascots

Swap the shimmer for an animated ASCII mascot while data loads. It dissolves as the new content decodes in.

A spider, a ghost and a pumpkin drawn in ASCII play while three cards load, then dissolve as the content decodes in
<AsciiReveal loading={isLoading} mascot="spider">  {/* spider | ghost | pumpkin | bat */}
  <Stats data={data} />
</AsciiReveal>

<AsciiReveal loading={isLoading} mascot="/logo.svg">…</AsciiReveal>      {/* your own SVG */}

Pass an SVG URL, SVG markup, or a draw function (ctx, w, h, t, color) => void for full control. Set --ascii-mascot to change the color of the line-art mascots.

Replay from code

const ref = useRef<AsciiRevealHandle>(null);

<AsciiReveal ref={ref}>…</AsciiReveal>

// replay one card from where it was clicked
ref.current?.reveal({ within: cardElement, origin: { x: e.clientX, y: e.clientY } });
ref.current?.hide();

Props

Prop Type Default What it does
preset 'decode' | 'dither' | 'terminal' | 'blueprint' | Preset 'decode' Glyph set, timing and image style.
duration 'fast' | 'cinematic' 'fast' fast makes data readable in ~400 ms. cinematic is the slower, showier wave for hero sections.
speed number 1 Playback speed multiplier on top of duration.
origin 'center' | 'top-left' | 'pointer' | { x, y } 'center' Where the wave starts. { x, y } is in viewport pixels.
selector string – Only animate content inside elements matching this selector.
revealOnMount boolean true Reveal when the component mounts.
loading boolean – Scramble out and shimmer while true; decode in when it turns false.
shimmer boolean true Show the glyph shimmer while loading.
lazy boolean true Sections below the fold decode as they scroll into view instead of all at once.
revealOnHydrate boolean false Also animate content that was server-rendered.
fallback boolean true If frames take too long, finish the animation and use a short fade for the next 10 s.
mascot 'spider' | 'ghost' | 'pumpkin' | 'bat' | string | MascotDraw – Animated ASCII mascot instead of the shimmer while loading.
onRevealComplete () => void – Called when a reveal finishes.
as ElementType 'div' Element used for the wrapper.

All other props pass through to the wrapper element.

Marking elements

Attribute Effect
data-ascii="surface" Cards and panels. A dot field and corner frame appear first, then the surface fades in.
data-ascii="fade" Buttons, chips, badges. Fades in on the wave.
data-ascii="media" Treat any element as media (rendered as a glyph texture).
data-ascii="skip" Leave this subtree alone, for example a toolbar that must stay usable.
data-ascii-digits Scramble only through digits (applied automatically to numeric text).

Theming

The effect reads these CSS custom properties from the wrapper:

.my-app {
  --ascii-accent: #5b8cff;   /* cursor and blueprint glyphs */
  --ascii-skeleton: #888;    /* AsciiSkeleton glyph color (defaults to the text color) */
  --ascii-flash: #5b8cff;    /* optional: brief color as each character lands */
  --ascii-glyph: #888;       /* scramble glyph color (defaults to the text's own color at 50%) */
  --ascii-font: "Geist Mono", ui-monospace, monospace;
  --ascii-surface: #0b0b0d;  /* color behind transparent images, if detection is wrong */
}

Without React

import { createAsciiReveal } from 'ascii-reveal/core';

const reveal = createAsciiReveal(document.querySelector('#app')!, { preset: 'dither' });
reveal.reveal();
// later
await reveal.hide();
reveal.shimmer(true);

Presets

Make your own by passing an object with the Preset shape (ramp, scramble, mode, color, cells, tick).

Performance

Measured on the demo page with Playwright and Chromium, CPU throttled 4×, on a machine with no GPU (so every frame is drawn in software, which caps even the idle page at ~19 fps). Run it yourself with scripts/bench.cjs (instructions at the top of the file).

v0.2 v0.3
Frame rate during Replay (page idle rate in brackets) 8.4 fps (12.5) 16.6 fps (19)
95th percentile frame 372 ms 133 ms
Longest main-thread task 297 ms 174 ms
Data readable after it arrives ~920 ms ~350 ms

Without throttling, v0.3 Replay runs at the page's idle frame rate and the longest task drops from 68 ms to under 20 ms. Note that v0.3's demo also replays only the card grid rather than the whole page.

What changed:

Notes

Develop

npm install
npm run build        # builds dist/
npm test             # browser smoke test (npx playwright install chromium first)
npm run demo         # runs the demo site (cd demo && npm install first)

See CHANGELOG.md for what changed between versions.

License

MIT

ascii-reveal (quanhoangindex/ascii-reveal)

Ищем в базе…

Что это такое?ascii-reveal — это библиотека для React, которая добавляет эффект загрузки и появления: текст, изображения и целые карточки «расшифровываются» на своё место через сетку символов, а анимация проходит по странице одной волной.
Это фреймворк или легковесный компонент, который можно добавить в существующее приложение?Это небольшая библиотека компонентов для React без внешних зависимостей (около 15 КБ в gzip вместе с маскотами и скелетонами). Её оборачивают вокруг уже существующего контента, а полноценным фреймворком она не является.
Как добавить это в проект на React?Установите библиотеку через npm или напрямую из GitHub, так как собранные файлы dist/ уже есть в репозитории и сборка не нужна. Затем оберните контент в компонент, и он появится при монтировании.
Нужно ли что-то кроме React?Нужен React версии 17 или новее как peer dependency. Других зависимостей во время работы нет.
Какие есть подводные камни у эффекта декодирования с картинками или при изменении верстки?Изображения с другого источника без заголовков CORS нельзя проанализировать, и вместо них показывается нейтральная текстура из символов. Если обёртка меняет размер во время появления, анимация сразу завершается и не перерисовывается в неверном месте.
Какие готовые стили можно выбрать для эффекта декодирования?Из коробки есть четыре пресета: decode (символы сгущаются в настоящий текст, он используется по умолчанию), dither (блочная штриховка для изображений), terminal (перебор в духе двоичного кода с курсором) и blueprint (линейные символы в акцентном цвете). Можно также задать свои пресеты.
Что такое маскоты для загрузки?Вместо обычного мерцания можно показать анимированного маскота из символов ASCII, например паука, призрака, тыкву или летучую мышь, либо свой SVG или функцию рисования. Маскот растворяется по мере того, как настоящий контент расшифровывается.
Как быстро контент становится читаемым?По умолчанию данные становятся читаемыми примерно через 400 мс после поступления. В тестах v0.3 при замедлении CPU в 4 раза воспроизведение достигало 16.6fps, а задачи основного потока занимали менее 20 мс. В v0.2 было 8.4fps и задачи длились до 297 мс.
Хорошо ли это работает с серверным рендерингом React (Next.js)?Да, это работает с Next.js App Router. Контент, отрисованный на сервере, сразу виден и по умолчанию не анимируется повторно при гидратации (чтобы включить анимацию, задайте revealOnHydrate). AsciiSkeleton отображается мгновенно, ещё до запуска любого JS.
Какие есть похожие проекты?chakra-ui, anime, loadersz-core, drawably, emotion, arc-library, rare-ui, GSAP
Автор
quanhoangindex
Размер
16.6 MB
Звёзды
700
Обновлён
КоммитNov 10
Возраст
28 д
Коммиты · 90 дней