Files
freeCodeCamp/client/commonFramework/update-preview.js

65 lines
1.8 KiB
JavaScript
Raw Normal View History

window.common = (function(global) {
const {
2015-12-01 08:01:51 -08:00
Rx: { BehaviorSubject, Observable },
common = { init: [] }
} = global;
2015-11-17 21:25:16 -08:00
var libraryIncludes = `
<link
rel='stylesheet'
href='//cdnjs.cloudflare.com/ajax/libs/animate.css/3.2.0/animate.min.css'
/>
<link
rel='stylesheet'
href='//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css'
/>
<link
rel='stylesheet'
href='//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css'
/>
<style>
body { padding: 0px 3px 0px 3px; }
</style>
`;
2015-11-22 19:42:53 -08:00
const iFrameScript$ =
common.getScriptContent$('/js/iFrameScripts.js').shareReplay();
2015-11-17 21:25:16 -08:00
2015-12-01 08:01:51 -08:00
// behavior subject allways remembers the last value
// we use this to determine if runPreviewTest$ is defined
// and prime it with false
common.previewReady$ = new BehaviorSubject(false);
2015-11-22 19:42:53 -08:00
// runPreviewTests$ should be set up in the preview window
common.runPreviewTests$ =
() => Observable.throw({ err: new Error('run preview not enabled') });
2015-11-17 21:25:16 -08:00
2015-11-22 19:42:53 -08:00
common.updatePreview$ = function updatePreview$(code = '') {
2015-11-17 21:25:16 -08:00
const previewFrame = document.getElementById('preview');
const preview = previewFrame.contentDocument ||
previewFrame.contentWindow.document;
if (!preview) {
2015-11-22 19:42:53 -08:00
return Observable.just(code);
2015-11-17 21:25:16 -08:00
}
2015-11-22 19:42:53 -08:00
return iFrameScript$
.map(script => `<script>${script}</script>`)
.flatMap(script => {
2015-12-01 08:01:51 -08:00
// we make sure to override the last value in the
// subject to false here.
common.previewReady$.onNext(false);
2015-11-22 19:42:53 -08:00
preview.open();
preview.write(libraryIncludes + code + '<!-- -->' + script);
2015-11-22 19:42:53 -08:00
preview.close();
2015-12-01 08:01:51 -08:00
// now we filter false values and wait for the first true
return common.previewReady$
.filter(ready => ready)
.first();
2015-11-22 19:42:53 -08:00
})
.map(() => code);
2015-11-17 21:25:16 -08:00
};
return common;
}(window));