-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
92 lines (82 loc) · 1.78 KB
/
app.js
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import React, { Component } from 'react';
import { render } from 'react-dom';
class App extends Component {
state = {
text: `JAVASCRIPT\nIS\nAWESOME`,
};
handleChange = ({ target }) => {
this.setState({ text: target.value });
};
render() {
const { text } = this.state;
const lines = text.split(/\n/);
return (
<div
style={{
width: '30%',
margin: 'auto',
}}
>
<textarea
onChange={this.handleChange}
value={text}
rows="8"
style={{ position: 'absolute', left: '10px' }}
/>
<div style={{ border: '4px solid', padding: '1.5em 2em' }}>
{lines.map(line => (
<div key={Math.random()}>
<TextAutofitter
style={{
fontFamily: 'sans-serif',
lineHeight: 0.8,
}}
>
{line}
</TextAutofitter>
</div>
))}
</div>
</div>
);
}
}
class TextAutofitter extends Component {
state = {
fontSize: 100,
};
setElementRef = ref => {
this.elementRef = ref;
};
calcFontSize = () => {
const { elementRef } = this;
const rect = elementRef.getBoundingClientRect();
const parentRect = elementRef.parentElement.getBoundingClientRect();
const wishfulWidth = parentRect.width;
const k = rect.width / this.state.fontSize;
const fontSize = wishfulWidth / k;
return fontSize;
};
componentDidMount() {
this.setState({
fontSize: this.calcFontSize(),
});
}
render() {
const { children, style } = this.props;
if (typeof children !== 'string') {
console.warn('TextAutofitter: expected text in children');
return null;
}
const { fontSize } = this.state;
return (
<span
style={{ ...style, fontSize, whiteSpace: 'pre' }}
ref={this.setElementRef}
>
{children}
</span>
);
}
}
render(<App />, document.getElementById('app'));