-
-
Notifications
You must be signed in to change notification settings - Fork 649
/
Copy pathmeasure-element.tsx
72 lines (59 loc) · 1.43 KB
/
measure-element.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import React, {useState, useRef, useEffect} from 'react';
import test from 'ava';
import delay from 'delay';
import stripAnsi from 'strip-ansi';
import {
Box,
Text,
render,
measureElement,
type DOMElement,
} from '../src/index.js';
import createStdout from './helpers/create-stdout.js';
test('measure element', async t => {
const stdout = createStdout();
function Test() {
const [width, setWidth] = useState(0);
const ref = useRef<DOMElement>(null);
useEffect(() => {
if (!ref.current) {
return;
}
setWidth(measureElement(ref.current).width);
}, []);
return (
<Box ref={ref}>
<Text>Width: {width}</Text>
</Box>
);
}
render(<Test />, {stdout, debug: true});
t.is((stdout.write as any).firstCall.args[0], 'Width: 0');
await delay(100);
t.is((stdout.write as any).lastCall.args[0], 'Width: 100');
});
test.serial('calculate layout while rendering is throttled', async t => {
const stdout = createStdout();
function Test() {
const [width, setWidth] = useState(0);
const ref = useRef<DOMElement>(null);
useEffect(() => {
if (!ref.current) {
return;
}
setWidth(measureElement(ref.current).width);
}, []);
return (
<Box ref={ref}>
<Text>Width: {width}</Text>
</Box>
);
}
const {rerender} = render(null, {stdout, patchConsole: false});
rerender(<Test />);
await delay(50);
t.is(
stripAnsi((stdout.write as any).lastCall.firstArg as string).trim(),
'Width: 100',
);
});