@bigfishtv/cockpit
Version:
91 lines (76 loc) • 2.67 kB
JavaScript
/**
* Preview Utilities
* @module Utilities/previewUtils
*/
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import PreviewWindow from '../components/preview/PreviewWindow'
import { disablePreview } from '../actions/preview'
let previewWindow = null
let store = null
/**
* Makes a reference to redux store for notification dispatches
* @param {Object} store
*/
export function init(_store) {
store = _store
}
/**
* Opens preview window and creates react instance, PreviewWindow is wrapped with store
*/
export function openPreviewWindow() {
// create preview window and the root div
try {
previewWindow = window.open('about:blank', 'preview' + Math.round(Math.random() * 100000000))
} catch (e) {
return alert('Unable to open preview window, check if you have any popup blockers active')
}
if (!previewWindow) alert('Unable to open preview window, check if you have any popup blockers active')
// render into preview window after a brief timeout (firefox is slow)
setTimeout(() => {
const div = previewWindow.document.createElement('div')
previewWindow.document.body.appendChild(div)
// when preview window closes, notify primary window
previewWindow.addEventListener('beforeunload', () => {
store.dispatch(disablePreview())
})
// when primary window closes, also close preview window
window.addEventListener('beforeunload', closePreviewWindow)
// copy cockpit styles from primary window to preview window
cloneStylesheets(window, previewWindow)
// stop scrolling on body
previewWindow.document.body.style.overflow = 'hidden'
// render the preview window content
ReactDOM.render(
<Provider store={store}>
<PreviewWindow onTitleChange={title => (previewWindow.document.title = '[PREVIEW] ' + title)} />
</Provider>,
div
)
}, 50)
}
/**
* Closes preview window
*/
export function closePreviewWindow() {
if (previewWindow && previewWindow.close) {
previewWindow.close()
previewWindow = null
}
}
/**
* Clones styles from ones window to another
* @param {Object} fromWindow - reference to a window object
* @param {Object} toWindow - reference to a window object
*/
function cloneStylesheets(fromWindow, toWindow) {
const stylesheets = fromWindow.document.head.querySelectorAll('link[rel=stylesheet]')
for (let i = 0; i < stylesheets.length; i++) {
const stylesheet = toWindow.document.createElement('link')
stylesheet.rel = 'stylesheet'
stylesheet.href = stylesheets.item(i).href
stylesheet.href = stylesheet.href // this is required to add protocol & hostname
toWindow.document.head.appendChild(stylesheet)
}
}