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 KB),用于包裹现有内容,并非完整的框架。
怎样把它添加到 React 项目中?可以从 npm 安装,也可以直接从 GitHub 安装(已提交构建好的 dist/ 文件,无需构建步骤);然后用该组件包裹你的内容,挂载时即会显示动画。
除了 React 之外还需要其他东西吗?需要 React 17 或更高版本作为对等依赖;没有其他运行时依赖。
解码效果在处理图片或布局变化时有哪些需要注意的地方?没有 CORS 响应头的跨域图片无法取样,会退回到中性的字形纹理;如果包裹元素在显示过程中改变大小,动画会立即结束,而不会在错误的位置重新绘制。
解码效果有哪些预设样式可以选择?开箱即用提供四种预设:decode(字形收拢为真实文字,为默认值)、dither(用于图片的色块阴影)、terminal(带光标的二进制风格乱码效果)和 blueprint(以强调色显示线条字形);也可以自定义预设。
加载吉祥物是什么?除了普通的闪烁效果,你还可以在数据加载时显示动画 ASCII 吉祥物(蜘蛛、幽灵、南瓜、蝙蝠,或你自己的 SVG/绘制函数),随着真实内容解码完成,吉祥物会逐渐消散。
内容多快可以被读取?默认情况下,数据到达后约 400 毫秒即可读取;在 4 倍 CPU 节流下,v0.3 的基准测试回放帧率达到 16.6 fps,主线程任务均在 20 毫秒以内;而 v0.2 为 8.4 fps,主线程任务最长可达 297 毫秒。
它能否与服务端渲染的 React(Next.js)良好配合?可以,它支持 Next.js App Router。服务端渲染的内容会立即可见,默认情况下在水合时不会重新播放动画(设置 revealOnHydrate 可强制播放);而 AsciiSkeleton 会在任何 JS 运行之前即时绘制。
大小
16.6 MB
星标
700
更新
提交Nov 10
时长
28天
提交 · 90 天