1
1
mirror of https://github.com/primer/css.git synced 2024-12-01 04:21:12 +03:00
css/docs/src/Frame.js

59 lines
1.6 KiB
JavaScript
Raw Normal View History

2019-01-15 22:23:15 +03:00
import React from 'react'
import ReactDOM from 'react-dom'
2019-01-16 01:16:25 +03:00
import PropTypes from 'prop-types'
import Document, {Head} from 'next/document'
2019-01-15 22:23:15 +03:00
import {BorderBox} from '@primer/components'
2019-01-16 01:16:25 +03:00
import {assetPrefix} from './utils'
2019-01-15 22:23:15 +03:00
const DEFAULT_IFRAME_HEIGHT = 150
2019-01-15 22:23:15 +03:00
export default class Frame extends React.Component {
2019-01-16 01:16:25 +03:00
static defaultProps = {
border: 0,
borderRadius: 0,
minHeight: 0,
2019-01-16 01:16:25 +03:00
width: '100%'
}
constructor(props) {
super(props)
this.state = {files: [], height: props.height}
}
2019-01-15 22:23:15 +03:00
componentDidMount() {
this.doc = this.node.contentDocument
const files = JSON.parse(document.body.dataset.files || '[]')
this.setState({files})
this.node.addEventListener('load', () => this.setState({loaded: true}))
2019-01-15 22:23:15 +03:00
}
2019-01-16 01:16:25 +03:00
getCssLinks() {
const {files} = this.state
return files
? files
.filter(file => file.endsWith('.css'))
.map(file => <link rel="stylesheet" href={`${assetPrefix}/_next/${file}`} key={file} />)
: null
}
getHeight() {
if (!this.node) return null
this.node.style.height = 'max-content'
const {body} = this.node.contentDocument
return body.offsetHeight > DEFAULT_IFRAME_HEIGHT ? body.offsetHeight : body.scrollHeight
2019-01-16 01:16:25 +03:00
}
2019-01-15 22:23:15 +03:00
render() {
2019-01-16 01:16:25 +03:00
const {children, ...rest} = this.props
const height = this.getHeight()
const style = height ? {height} : null
2019-01-15 22:23:15 +03:00
return (
<BorderBox as="iframe" style={style} {...rest} ref={node => (this.node = node)}>
{this.doc
? [ReactDOM.createPortal(this.getCssLinks(), this.doc.head), ReactDOM.createPortal(children, this.doc.body)]
: null}
2019-01-15 22:23:15 +03:00
</BorderBox>
)
}
}