-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathcheckPage.js
More file actions
193 lines (160 loc) · 6.12 KB
/
Copy pathcheckPage.js
File metadata and controls
193 lines (160 loc) · 6.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
/* eslint-disable padded-blocks, no-multiple-empty-lines */
/* global edac_editor_app */
import { info, debug } from './helpers';
import { showNotice } from './../common/helpers';
const postData = async ( url = '', data = {} ) => {
return await fetch( url, {
method: 'POST',
headers: {
// eslint-disable-next-line camelcase
'X-WP-Nonce': edac_script_vars.restNonce,
'Content-Type': 'application/json',
},
body: JSON.stringify( data ),
} ).then( ( res ) => {
return res.json();
} ).catch( () => {
return {};
} );
};
const saveScanResults = ( postId, violations, densityMetrics ) => {
document.querySelector( '.edac-panel' )?.classList.add( 'edac-panel-loading' );
// eslint-disable-next-line camelcase
postData( edac_editor_app.edacApiUrl + '/post-scan-results/' + postId, {
violations,
densityMetrics,
} ).then( ( data ) => {
info( 'Saving ' + postId + ': done' );
// Create and dispatch an event to tell legacy admin.js to refresh tabs. Refactor this.
const customEvent = new CustomEvent( 'edac_js_scan_save_complete' );
top.dispatchEvent( customEvent );
if ( ! data.success ) {
info( 'Saving ' + postId + ': error' );
showNotice( {
msg: 'Whoops! It looks like there was a problem updating. Please try again.',
type: 'warning',
} );
}
document.querySelector( '.edac-panel' )?.classList.remove( 'edac-panel-loading' );
} );
};
/**
* Inject an iframe into the page and load the previewUrl for scanning.
*
* @param {string} previewUrl The URL to load in the iframe.
* @param {number} postID The post ID to pass to the iframe.
*/
const injectIframe = ( previewUrl, postID ) => {
// Gen unique id for this iframe
const timestamp = new Date().getTime();
const randomNumber = Math.floor( Math.random() * 1000 );
const uniqueId = 'iframe' + '_' + timestamp + '_' + randomNumber;
// inject the iframe
const iframe = document.createElement( 'iframe' );
iframe.setAttribute( 'id', uniqueId );
iframe.setAttribute( 'src', previewUrl );
iframe.style.width = screen.width + 'px';
iframe.style.height = screen.height + 'px';
iframe.style.position = 'absolute';
iframe.style.left = '-' + screen.width + 'px';
document.body.append( iframe );
// Wait for the preview to load & inject the pageScanner script.
iframe.addEventListener( 'load', function() {
// Detect if the iframe was redirected away from the expected scan URL.
// When a post type redirects requests (e.g., a non-publicly-queryable
// post type redirecting to the homepage), the final URL will no longer
// contain 'edac_pageScanner'. In that case, abort the scan and remove
// the iframe.
try {
const loadedUrl = iframe.contentWindow.location.href;
if ( loadedUrl && ! loadedUrl.includes( 'edac_pageScanner' ) ) {
// eslint-disable-next-line no-console
console.warn( 'EDAC: Scan aborted — iframe redirected away from expected scan URL.', loadedUrl );
iframe.remove();
return;
}
} catch ( e ) {
// Cross-origin means the iframe was redirected off-site.
// We cannot scan a cross-origin document, so abort.
iframe.remove();
return;
}
// Access the contentDocument of the iframe.
const iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
// Pass the postID and iframe id into the document so we can reference them from the document.
const body = iframeDocument.querySelector( 'body' );
body.setAttribute( 'data-iframe-id', uniqueId );
body.setAttribute( 'data-iframe-event-name', 'edac_scan_complete' );
body.setAttribute( 'data-iframe-post-id', postID );
if ( iframeDocument ) {
if ( window?.edac_editor_app?.maxAltLength || window?.edac_editor_app?.ruleExclusions ) {
if ( ! iframeDocument.defaultView.scanOptions ) {
iframeDocument.defaultView.scanOptions = {};
}
iframeDocument.defaultView.scanOptions = {
maxAltLength: window.edac_editor_app.maxAltLength,
ruleExclusions: window.edac_editor_app.ruleExclusions,
};
}
// inject the scanner app.
const scannerScriptElement = iframeDocument.createElement( 'script' );
// eslint-disable-next-line camelcase
scannerScriptElement.src = edac_editor_app.baseurl + '/build/pageScanner.bundle.js?v=' + edac_editor_app.version;
iframeDocument.head.appendChild( scannerScriptElement );
}
} );
};
top.edacScanCompleteListenerAdded = false;
export const init = () => {
// Listen for completed scans.
if ( ! top.edacScanCompleteListenerAdded ) {
top.edacScanCompleteListenerAdded = true;
top.addEventListener( 'edac_scan_complete', function( event ) {
const postId = event.detail.postId;
const violations = event.detail.violations;
const iframeId = event.detail.iframeId;
// remove the iframe.
setTimeout( function() {
document.getElementById( iframeId )?.remove();
}, 1000 );
// save the scan results.
saveScanResults( postId, violations, event?.detail?.densityMetrics );
} );
}
//Listen for dispatches from the wp data store so we can trap the update/publish event
let saving = false;
let autosaving = false;
top.edacPostSaveStateSubscribed = top.edacPostSaveStateSubscribed || false;
if ( wp.data !== undefined && wp.data.subscribe !== undefined && ! top.edacPostSaveStateSubscribed ) {
wp.data.subscribe( () => {
top.edacPostSaveStateSubscribed = true;
if ( wp.data.select( 'core/editor' ) === undefined ) {
return;
}
if ( wp.data.select( 'core/editor' ).isAutosavingPost() ) {
autosaving = true;
}
// Rescan the page if user saves post
if ( wp.data.select( 'core/editor' ).isSavingPost() ) {
saving = true;
} else if ( saving ) {
saving = false;
if ( ! autosaving ) {
// eslint-disable-next-line camelcase
injectIframe( edac_editor_app.scanUrl, edac_editor_app.postID );
} else {
autosaving = false;
}
}
} );
} else {
debug( 'Gutenberg is not enabled.' );
}
const editor = wp?.data?.select?.( 'core/editor' );
const postStatus = editor?.getEditedPostAttribute( 'status' ) ?? window?.edac_editor_app?.postStatus;
if ( ! postStatus || postStatus === 'auto-draft' ) {
return;
}
// eslint-disable-next-line camelcase
injectIframe( edac_editor_app.scanUrl, edac_editor_app.postID );
};