Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use document.write to write html files #702

Merged
merged 23 commits into from
May 20, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions packages/app/src/app/components/CodeEditor/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,7 @@ export default class CodeEditor extends React.PureComponent<Props, State> {
render() {
const props = this.props;

const settings = props.settings;
const module = props.currentModule;
const sandbox = props.sandbox;
const { isModuleSynced, sandbox, currentModule: module, settings } = props;
const dependencies = getDependencies(sandbox);

const template = getDefinition(sandbox.template);
Expand Down Expand Up @@ -142,6 +140,13 @@ export default class CodeEditor extends React.PureComponent<Props, State> {
bottom: 0,
}}
>
{!isModuleSynced &&
module.title === 'index.html' && (
<Icons style={{ fontSize: '.875rem' }}>
You may have to save this file and refresh the preview to see
changes
</Icons>
)}
{config &&
(getUI(config.type) ? (
<Icons>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,8 @@ class Preview extends React.Component<Props, State> {
};

handleModuleSyncedChange = (preview, change) => {
if (change) {
const settings = this.props.store.preferences.settings;
if (!settings.livePreviewEnabled && change) {
preview.executeCodeImmediately();
}
};
Expand Down
3 changes: 3 additions & 0 deletions packages/app/src/app/pages/Sandbox/Editor/Content/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -403,6 +403,9 @@ class EditorPreview extends React.Component<Props, State> {
onInitialized={this.onInitialized}
sandbox={sandbox}
currentModule={currentModule}
isModuleSynced={store.editor.isModuleSynced(
currentModule.shortid
)}
width={editorWidth}
height={editorHeight}
settings={settings(store)}
Expand Down
1 change: 1 addition & 0 deletions packages/app/src/embed/components/Content/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,7 @@ export default class Content extends React.PureComponent<Props, State> {
<CodeEditor
onInitialized={this.onCodeEditorInitialized}
currentModule={currentModule || mainModule}
isModuleSynced
sandbox={sandbox}
settings={this.getPreferences()}
canSave={false}
Expand Down
88 changes: 69 additions & 19 deletions packages/app/src/sandbox/compile.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import createCodeSandboxOverlay from './codesandbox-overlay';
import handleExternalResources from './external-resources';

import defaultBoilerplates from './boilerplates/default-boilerplates';
import resizeEventListener from './resize-event-listener';

import {
getBoilerplates,
evalBoilerplates,
Expand All @@ -41,8 +41,24 @@ export function getCurrentManager(): ?Manager {
return manager;
}

export function getHTMLParts(html: string) {
if (html.includes('<body>')) {
const bodyMatcher = /<body>([\s\S]*)<\/body>/m;
const headMatcher = /<head>([\s\S]*)<\/head>/m;
const body = html.match(bodyMatcher)[1];
const head = html.match(headMatcher)[1];

return { body, head };
}

return { head: '', body: html };
}

let firstLoad = true;
let hadError = false;
let lastHeadHTML = null;
let lastBodyHTML = null;
let lastHeight = 0;
let changedModuleCount = 0;

const DEPENDENCY_ALIASES = {
Expand Down Expand Up @@ -259,16 +275,37 @@ async function updateManager(
});
}

function initializeResizeListener() {
const listener = resizeEventListener();
listener.addResizeListener(document.body, () => {
function getDocumentHeight() {
const body = document.body;
const html = document.documentElement;

const height = Math.max(
body.scrollHeight,
body.offsetHeight,
html.clientHeight,
html.scrollHeight,
html.offsetHeight
);
}

function sendResize() {
const height = getDocumentHeight();

if (lastHeight !== height) {
if (document.body) {
dispatch({
type: 'resize',
height: document.body.getBoundingClientRect().height,
height,
});
}
});
}

lastHeight = height;
}

function initializeResizeListener() {
setInterval(sendResize, 5000);

initializedResizeListener = true;
}

Expand Down Expand Up @@ -331,7 +368,6 @@ async function compile({
hadError = false;

actionsEnabled = hasActions;
handleExternalResources(externalResources);

let managerModuleToTranspile = null;
try {
Expand Down Expand Up @@ -413,7 +449,6 @@ async function compile({
dispatch({ type: 'status', status: 'transpiling' });

await manager.verifyTreeTranspiled();
await manager.preset.setup(manager);
await manager.transpileModules(managerModuleToTranspile);

const managerTranspiledModuleToTranspile = manager.getTranspiledModule(
Expand Down Expand Up @@ -459,24 +494,39 @@ async function compile({
}
}

if ((!manager.webpackHMR || firstLoad) && !manager.preset.htmlDisabled) {
if (!managerTranspiledModuleToTranspile.compilation || isModuleView) {
const htmlModule =
modules[
templateDefinition
.getHTMLEntries(configurations)
.find(p => modules[p])
];
if (!manager.webpackHMR && !manager.preset.htmlDisabled) {
const htmlModulePath = templateDefinition
.getHTMLEntries(configurations)
.find(p => modules[p]);
const htmlModule = modules[htmlModulePath];

const html = htmlModule
const { head, body } = getHTMLParts(
htmlModule
? htmlModule.code
: template === 'vue-cli'
? '<div id="app"></div>'
: '<div id="root"></div>';
document.body.innerHTML = html;
: '<div id="root"></div>'
);

document.body.innerHTML = body;

if (lastHeadHTML && lastHeadHTML !== head) {
document.location.reload();
}
if (manager && lastBodyHTML && lastBodyHTML !== body) {
manager.clearCompiledCache();
}

lastBodyHTML = body;
lastHeadHTML = head;
}

const extDate = Date.now();
await handleExternalResources(externalResources);
debug('Loaded external resources in ' + (Date.now() - extDate) + 'ms');

await manager.preset.setup(manager);

const tt = Date.now();
const oldHTML = document.body.innerHTML;
const evalled = manager.evaluateModule(
Expand Down
33 changes: 26 additions & 7 deletions packages/app/src/sandbox/external-resources.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ function addCSS(resource: string) {
link.href = resource;
link.media = 'all';
head.appendChild(link);

return link;
}

function addJS(resource: string) {
Expand All @@ -30,25 +32,42 @@ function addJS(resource: string) {
script.async = false;
script.setAttribute('id', 'external-js');
document.head.appendChild(script);

return script;
}

function addResource(resource: string) {
const match = resource.match(/\.([^.]*)$/);

if (match && match[1] === 'css') {
addCSS(resource);
} else {
addJS(resource);
}
const el = match && match[1] === 'css' ? addCSS(resource) : addJS(resource);

return new Promise(r => {
el.onload = r;
el.onerror = r;
});
}

function waitForLoaded() {
return new Promise(resolve => {
if (document.readyState !== 'complete') {
window.addEventListener('load', resolve);
} else {
resolve();
}
});
}

let cachedExternalResources = '';

export default function handleExternalResources(externalResources) {
export default async function handleExternalResources(externalResources) {
const extResString = getExternalResourcesConcatenation(externalResources);
if (extResString !== cachedExternalResources) {
clearExternalResources();
externalResources.forEach(addResource);
await Promise.all(externalResources.map(addResource));
cachedExternalResources = extResString;

return waitForLoaded();
}

return Promise.resolve();
}
13 changes: 9 additions & 4 deletions packages/app/src/sandbox/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ requirePolyfills().then(() => {
history.back();
} else if (data.type === 'urlforward') {
history.forward();
} else if (data.type === 'refresh') {
document.location.reload();
} else if (data.type === 'evaluate') {
let result = null;
let error = false;
Expand Down Expand Up @@ -110,11 +112,14 @@ requirePolyfills().then(() => {
}
}

listen(handleMessage);
if (!isStandalone) {
listen(handleMessage);

sendReady();
setupHistoryListeners();
setupConsole();
sendReady();

setupHistoryListeners();
setupConsole();
}

if (process.env.NODE_ENV === 'test' || isStandalone) {
// We need to fetch the sandbox ourselves...
Expand Down