Skip to content

Commit a0d1aa1

Browse files
committed
⚡️ perf: memoize StreamTail and StreamdownStyles to skip no-op renders
1 parent 09d1083 commit a0d1aa1

4 files changed

Lines changed: 95 additions & 38 deletions

File tree

‎src/StreamTail.test.tsx‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,14 @@
11
import { render } from '@testing-library/react';
2-
import { describe, expect, it } from 'vitest';
2+
import { describe, expect, it, vi } from 'vitest';
33

4+
import { getNow } from './internal';
45
import { createStreamTailNode, StreamTail } from './StreamTail';
56

7+
vi.mock('./internal', async (importOriginal) => {
8+
const actual = await importOriginal<typeof import('./internal')>();
9+
return { ...actual, getNow: vi.fn(actual.getNow) };
10+
});
11+
612
const delayOf = (el: Element) => Number.parseFloat((el as HTMLElement).style.animationDelay);
713

814
describe('StreamTail', () => {
@@ -41,4 +47,27 @@ describe('StreamTail', () => {
4147
const span = container.querySelector('.stream-char-revealed') as HTMLElement;
4248
expect(span.style.animationDelay).toBe('');
4349
});
50+
51+
it('skips rendering when a fresh node carries the same tail data', () => {
52+
const data = () => ({
53+
items: ['x', { birth: 10, key: 4, value: 'y' }],
54+
text: 'ab',
55+
});
56+
const { container, rerender } = render(<StreamTail node={createStreamTailNode(data())} />);
57+
const renders = vi.mocked(getNow).mock.calls.length;
58+
59+
rerender(<StreamTail node={createStreamTailNode(data())} />);
60+
expect(vi.mocked(getNow).mock.calls.length).toBe(renders);
61+
62+
rerender(
63+
<StreamTail
64+
node={createStreamTailNode({
65+
...data(),
66+
items: [...data().items, { birth: 20, key: 5, value: 'z' }],
67+
})}
68+
/>,
69+
);
70+
expect(vi.mocked(getNow).mock.calls.length).toBe(renders + 1);
71+
expect(container.textContent).toBe('abxyz');
72+
});
4473
});

‎src/StreamTail.tsx‎

Lines changed: 48 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { type Element } from 'hast';
2-
import { type CSSProperties, useRef } from 'react';
2+
import { type CSSProperties, memo, useRef } from 'react';
33

4-
import { getNow } from './internal';
4+
import { getNow, isDeepEqual } from './internal';
55
import { STREAM_FADE_DURATION } from './styles';
66

77
// hast-util-to-jsx-runtime keys siblings as `<tag>-<n>`, so dropping a faded
@@ -47,43 +47,56 @@ export const createStreamTailNode = (data: StreamTailData): Element => ({
4747
export const readStreamTailData = (node?: Element): StreamTailData | undefined =>
4848
(node?.data as StreamTailElementData | undefined)?.streamdown;
4949

50+
interface StreamTailProps {
51+
node?: Element;
52+
}
53+
5054
// Delays are frozen per mounted instance, not in the plugin runtime: a
5155
// structural remount (a paragraph turning into a setext heading swaps <p>
5256
// for <h2>) restarts every CSS animation, and the fresh instance has to
5357
// resume each char from its real elapsed time instead of replaying the
5458
// delay captured at its first ever render.
55-
export const StreamTail = ({ node }: { node?: Element }) => {
56-
const delaysRef = useRef<Map<number, CSSProperties | null>>(new Map());
57-
const data = readStreamTailData(node);
58-
if (!data) return null;
59+
//
60+
// Every rehype run rebuilds the node, so memo compares the tail data it
61+
// carries. Skipping a render is safe: per-key delays are already frozen in
62+
// delaysRef, so an equal tail would produce identical output.
63+
export const StreamTail = memo<StreamTailProps>(
64+
({ node }) => {
65+
const delaysRef = useRef<Map<number, CSSProperties | null>>(new Map());
66+
const data = readStreamTailData(node);
67+
if (!data) return null;
68+
69+
const now = getNow();
70+
const styleOf = (item: StreamCharItem): CSSProperties | null => {
71+
if (item.birth === null) return null;
72+
const cached = delaysRef.current.get(item.key);
73+
if (cached !== undefined) return cached;
74+
const elapsed = now - item.birth;
75+
const style = elapsed >= STREAM_FADE_DURATION ? null : { animationDelay: `${-elapsed}ms` };
76+
delaysRef.current.set(item.key, style);
77+
return style;
78+
};
5979

60-
const now = getNow();
61-
const styleOf = (item: StreamCharItem): CSSProperties | null => {
62-
if (item.birth === null) return null;
63-
const cached = delaysRef.current.get(item.key);
64-
if (cached !== undefined) return cached;
65-
const elapsed = now - item.birth;
66-
const style = elapsed >= STREAM_FADE_DURATION ? null : { animationDelay: `${-elapsed}ms` };
67-
delaysRef.current.set(item.key, style);
68-
return style;
69-
};
80+
return (
81+
<>
82+
{data.text}
83+
{data.items.map((item) => {
84+
if (typeof item === 'string') return item;
85+
const style = styleOf(item);
86+
return (
87+
<span
88+
className={style ? 'stream-char' : 'stream-char stream-char-revealed'}
89+
key={item.key}
90+
style={style ?? undefined}
91+
>
92+
{item.value}
93+
</span>
94+
);
95+
})}
96+
</>
97+
);
98+
},
99+
(prev, next) => isDeepEqual(readStreamTailData(prev.node), readStreamTailData(next.node)),
100+
);
70101

71-
return (
72-
<>
73-
{data.text}
74-
{data.items.map((item) => {
75-
if (typeof item === 'string') return item;
76-
const style = styleOf(item);
77-
return (
78-
<span
79-
className={style ? 'stream-char' : 'stream-char stream-char-revealed'}
80-
key={item.key}
81-
style={style ?? undefined}
82-
>
83-
{item.value}
84-
</span>
85-
);
86-
})}
87-
</>
88-
);
89-
};
102+
StreamTail.displayName = 'StreamTail';

‎src/styles.test.tsx‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { describe, expect, it } from 'vitest';
2+
3+
import { StreamdownStyles } from './styles';
4+
5+
describe('StreamdownStyles', () => {
6+
it('is memoised so parent re-renders do not re-render the static style tag', () => {
7+
expect((StreamdownStyles as unknown as { $$typeof: symbol }).$$typeof).toBe(
8+
Symbol.for('react.memo'),
9+
);
10+
});
11+
});

‎src/styles.tsx‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { memo } from 'react';
2+
13
export const STREAM_FADE_DURATION = 180;
24

35
export const STREAMDOWN_ANIMATED_CLASS = 'streamdown-animated';
@@ -33,8 +35,10 @@ const css = `
3335

3436
// React 19 hoists and dedupes <style href precedence> into <head>, which
3537
// keeps this SSR-safe without any manual DOM injection.
36-
export const StreamdownStyles = () => (
38+
export const StreamdownStyles = memo(() => (
3739
<style href="lobehub-streamdown" precedence="default">
3840
{css}
3941
</style>
40-
);
42+
));
43+
44+
StreamdownStyles.displayName = 'StreamdownStyles';

0 commit comments

Comments
 (0)