UNPKG

@bigfishtv/cockpit

Version:

105 lines (90 loc) 2.73 kB
import PropTypes from 'prop-types' import React, { Component } from 'react' import throttle from 'lodash/throttle' import { post } from 'axios' import encodeFormData from '../../utils/encodeFormData' import windowVisible from '../../decorators/windowVisible' // try and grab cspNonce from script in current document const cspNonce = document.scripts && document.scripts[0].nonce @windowVisible export default class PreviewFrame extends Component { static propTypes = { data: PropTypes.oneOfType([PropTypes.object, PropTypes.string]), enabled: PropTypes.bool, url: PropTypes.string, date: PropTypes.string, } constructor() { super() this.updatePreview = throttle(this.updatePreview, 1000) this.state = { dirty: true, } } componentWillUnmount() { this.updatePreview.cancel() } componentWillReceiveProps(nextProps) { const dataChanged = nextProps.data !== this.props.data || nextProps.url !== this.props.url || nextProps.date !== this.props.date if (dataChanged && !this.state.dirty) { this.setState({ dirty: true }) } } componentDidUpdate() { if (this.props.windowVisible && this.state.dirty && this.props.enabled && (this.props.url || this.props.data)) { this.updatePreview() } } updatePreview() { this.setState({ dirty: false }) this.saveScrollPosition() if (typeof this.props.data == 'string') { this.updateIframe(this.props.data) } else { this.requestHtml().then(res => this.updateIframe(res.data)) } } saveScrollPosition() { if (this.refs.frame.contentDocument) { this.scrollTop = this.refs.frame.contentDocument.defaultView.scrollY this.scrollLeft = this.refs.frame.contentDocument.defaultView.scrollX } else { console.warn("Couldn't save scroll position", this.refs.frame) } } requestHtml() { const data = { data: JSON.stringify(this.props.data), preview: 1, date: this.props.date, cspNonce, } return post(this.props.url, data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, responseType: 'text', transformRequest: [encodeFormData], }) } updateIframe(html) { html += '<script>window.scrollTo(' + this.scrollLeft + ', ' + this.scrollTop + ');</script>' this.refs.frame.contentDocument.open() this.refs.frame.contentDocument.write(html) this.refs.frame.contentDocument.close() var title = html.match(/<title>(.+?)<\/title>/) if (title) { this.props.onTitleChange(title[1]) } } render() { return ( <div className="preview-frame"> <div className="preview-frame-inner" style={{ maxWidth: this.props.deviceWidth, flexBasis: this.props.deviceWidth }}> <iframe className="preview-frame-iframe" ref="frame" /> </div> </div> ) } }