Skip to content

Commit be0c3bf

Browse files
authored
Merge pull request #3 from tailpress/non-iframe-editor-vite-injection
Vite script injection for non iframe version of block editor
2 parents 6b68066 + 3f7153c commit be0c3bf

File tree

1 file changed

+43
-7
lines changed

1 file changed

+43
-7
lines changed

src/Assets/ViteCompiler.php

Lines changed: 43 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -65,13 +65,49 @@ public function enqueueEditorStyle(): void
6565
}
6666
?>
6767
<script type="module">
68-
wp.domReady(() => {
69-
wp.data.subscribe(() => {
70-
const editorIframe = document.querySelector('iframe[name="editor-canvas"]');
71-
if (!editorIframe) return;
72-
73-
const doc = editorIframe.contentDocument || editorIframe.contentWindow.document;
74-
if (doc.querySelector('script[src$="/@vite/client"]')) return;
68+
const { select, subscribe } = wp.data;
69+
70+
function whenEditorIsReady() {
71+
return new Promise((resolve) => {
72+
const unsubscribe = subscribe(() => {
73+
if (select('core/editor').isCleanNewPost() || select('core/block-editor').getBlockCount() > 0) {
74+
unsubscribe()
75+
resolve()
76+
}
77+
})
78+
})
79+
}
80+
81+
function whenEditorIframeIsReady() {
82+
const editorCanvasIframeElement = document.querySelector('[name="editor-canvas"]');
83+
84+
return new Promise((resolve) => {
85+
if(!editorCanvasIframeElement.loading) {
86+
resolve(editorCanvasIframeElement);
87+
}
88+
89+
editorCanvasIframeElement.onload = () => {
90+
resolve(editorCanvasIframeElement);
91+
};
92+
});
93+
}
94+
95+
whenEditorIsReady().then(() => {
96+
const editorIframe = document.querySelector('iframe[name="editor-canvas"]');
97+
let docPromise;
98+
99+
if (editorIframe) {
100+
console.info('[TailPress] Injecting Vite in editor iframe')
101+
docPromise = whenEditorIframeIsReady().then(() => editorIframe.contentDocument || editorIframe.contentWindow.document);
102+
} else {
103+
console.info('[TailPress] Injecting Vite in main document')
104+
docPromise = Promise.resolve(document);
105+
}
106+
107+
docPromise.then((doc) => {
108+
if (doc.querySelector('script[src$="/@vite/client"]')) {
109+
return;
110+
}
75111

76112
const viteScript = doc.createElement('script');
77113
viteScript.type = 'module';

0 commit comments

Comments
 (0)