-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathindex.js
62 lines (48 loc) · 1.62 KB
/
index.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
import url from 'url';
import React from 'react';
import PropTypes from 'prop-types';
class Gist extends React.PureComponent {
componentDidMount() {
this._updateIframeContent();
}
componentDidUpdate(prevProps, prevState) {
this._updateIframeContent();
}
_defineUrl() {
let { id, file, url } = this.props;
if (url) {
const gistUrl = new URL(url);
id = gistUrl.pathname.split('/')[2];
}
const fileArg = file ? `?file=${file}` : '';
return `https://gist.github.com/${id}.js${fileArg}`;
}
_updateIframeContent() {
const { id, file } = this.props;
const iframe = this.iframeNode;
let doc = iframe.document;
if (iframe.contentDocument) doc = iframe.contentDocument;
else if (iframe.contentWindow) doc = iframe.contentWindow.document;
const gistLink = this._defineUrl();
const gistScript = `<script type="text/javascript" src="${gistLink}"></script>`;
const styles = '<style>*{font-size:12px;}</style>';
const elementId = file ? `gist-${id}-${file}` : `gist-${id}`;
const resizeScript = `onload="parent.document.getElementById('${elementId}').style.height=document.body.scrollHeight + 'px'"`;
const iframeHtml = `<html><head><base target="_parent">${styles}</head><body ${resizeScript}>${gistScript}</body></html>`;
doc.open();
doc.writeln(iframeHtml);
doc.close();
}
render() {
const { id, file } = this.props;
return (
<iframe
ref={(n) => { this.iframeNode = n; }}
width="100%"
frameBorder={0}
id={file ? `gist-${id}-${file}` : `gist-${id}`}
/>
);
}
}
export default Gist;