-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathPrettierCodeTag.js
92 lines (91 loc) · 2.63 KB
/
PrettierCodeTag.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 from 'react'
import { render } from 'react-dom'
import SyntaxHighlighter from 'react-syntax-highlighter'
import ReactResizeDetector from 'react-resize-detector'
import prettier from 'prettier'
export default class PrettierCodeTag extends React.Component {
constructor() {
super()
this.me = null
this.state = {
charWidth: 8,
charHeight: 16,
textWidth: 30
}
}
updateSize(width, height) {
this.setState({ textWidth: width })
}
updateFontSize(width, height) {
if (!this.cw) {
return setTimeout(this.updateFontSize.bind(this), 100)
} else {
width = this.cw
.querySelector('.single-character-measurement code')
.getBoundingClientRect().width
height = this.cw
.querySelector('.single-character-measurement code')
.getBoundingClientRect().height
}
this.setState({ charWidth: width, charHeight: height })
}
render() {
// Extract props
let {
debug,
code,
options,
subtract,
...syntaxHighlighterProps
} = this.props
// The subtract prop lets us offset for line number width manually
subtract = subtract ? parseInt(subtract) : 0
// This kinda takes into account the 0.5em margin on both sides
let columns =
Math.floor(this.state.textWidth / this.state.charWidth) - 2 - subtract
// prettier-ignore
debug = `${this.state.textWidth} / ${this.state.charWidth} = ${columns} chars\n${'-'.repeat(Math.max(1, columns - 1))}*`
options = Object.assign({}, options, { printWidth: columns })
code = prettier.format(code, options)
return (
<div
style={{
width: '100%'
}}
ref={el => (this.el = el)}
>
<ReactResizeDetector
handleWidth
onResize={this.updateSize.bind(this)}
/>
<div
className="single-character-measurement"
style={{
visibility: 'hidden',
position: 'absolute',
top: 0,
left: 0
}}
ref={el => (this.cw = el)}
>
<ReactResizeDetector
handleWidth
onResize={this.updateFontSize.bind(this)}
/>
<SyntaxHighlighter
language="javascript"
{...syntaxHighlighterProps}
showLineNumbers={false}
>
M
</SyntaxHighlighter>
</div>
<div className="responsive-prettier-code-box">
<SyntaxHighlighter language="javascript" {...syntaxHighlighterProps}>
{`${this.props.debug ? debug : code}`}
</SyntaxHighlighter>
</div>
</div>
)
}
}