UNPKG

@bigfishtv/cockpit

Version:

91 lines (77 loc) 2.77 kB
/** * 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'; var previewWindow = null; var 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(function () { var div = previewWindow.document.createElement('div'); previewWindow.document.body.appendChild(div); // when preview window closes, notify primary window previewWindow.addEventListener('beforeunload', function () { 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(React.createElement( Provider, { store: store }, React.createElement(PreviewWindow, { onTitleChange: function onTitleChange(title) { return previewWindow.document.title = '[PREVIEW] ' + title; } }) ), 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) { var stylesheets = fromWindow.document.head.querySelectorAll('link[rel=stylesheet]'); for (var i = 0; i < stylesheets.length; i++) { var 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); } }