-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathindex.js
More file actions
2067 lines (1807 loc) · 79.1 KB
/
Copy pathindex.js
File metadata and controls
2067 lines (1807 loc) · 79.1 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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable padded-blocks, no-multiple-empty-lines */
/* global edacFrontendHighlighterApp */
import { computePosition, autoUpdate } from '@floating-ui/dom';
import { createFocusTrap } from 'focus-trap';
import { isFocusable } from 'tabbable';
import { __, _n, sprintf } from '@wordpress/i18n';
import { saveFixSettings } from '../common/saveFixSettingsRest';
import { fillFixesModal, fixSettingsModalInit, openFixesModal } from './fixesModal';
import { getLandmarkType as getLandmarkTypeUtil } from './getLandmarkType';
class AccessibilityCheckerHighlight {
/**
* Constructor
* @param {Object} settings
*/
constructor( settings = {} ) {
const defaultSettings = {
showIgnored: false,
};
this.settings = { ...defaultSettings, ...settings };
this._scanAttempted = false;
this._isRescanning = false;
this._pendingRescanAnnouncement = false;
this._issuesCleared = false;
this.highlightPanel = this.addHighlightPanel();
this.nextButton = document.querySelector( '#edac-highlight-next' );
this.previousButton = document.querySelector( '#edac-highlight-previous' );
this.panelToggle = document.querySelector( '#edac-highlight-panel-toggle' );
this.closePanel = document.querySelector( '#edac-highlight-panel-controls-close' );
this.panelControls = document.querySelector( '#edac-highlight-panel-controls' );
this.contentArea = document.querySelector( '#edac-highlight-panel-controls-content' );
this.issues = null;
this.fixes = null;
this.currentButtonIndex = null;
this.urlParameter = this.get_url_parameter( 'edac' );
this.landmarkParameter = this.get_url_parameter( 'edac_landmark' );
this.currentIssueStatus = null;
this.explanationExpanded = false;
this.codeExpanded = false;
this.isDragged = false;
this.tooltips = [];
this.panelControlsFocusTrap = createFocusTrap( '#' + this.panelControls.id, {
clickOutsideDeactivates: true,
escapeDeactivates: () => {
this.panelClose();
},
initialFocus: () => {
return this.closePanel;
},
} );
this.disableStylesButton = document.querySelector( '#edac-highlight-disable-styles' );
this.rescanButton = document.querySelector( '#edac-highlight-rescan' );
this.clearIssuesButton = document.querySelector( '#edac-highlight-clear-issues' );
this.menuButton = document.querySelector( '#edac-highlight-menu-button' );
this.menu = document.querySelector( '#edac-highlight-menu' );
this.moveButton = document.querySelector( '#edac-highlight-move' );
this.dockButton = document.querySelector( '#edac-highlight-dock' );
this.srAnnouncer = document.querySelector( '#edac-highlight-announcer' );
this.isDocked = localStorage.getItem( 'edac-panel-docked' ) === '1';
this.stylesDisabled = false;
this.originalCss = [];
this.originalInlineStyles = [];
this.init();
}
/**
* This function initializes the component by setting up event listeners
* and managing the initial state of the panel based on the URL parameter.
*/
init() {
// Add event listeners for 'next' and 'previous' buttons
this.nextButton.addEventListener( 'click', () => {
this.highlightFocusNext();
} );
this.previousButton.addEventListener( 'click', () => {
this.highlightFocusPrevious();
} );
// Manage panel open/close operations
this.panelToggle.addEventListener( 'click', () => {
this.panelOpen();
this.focusTrapControls();
} );
this.closePanel.addEventListener( 'click', () => {
this.closeMenu();
this.panelClose();
this.panelControlsFocusTrap.deactivate();
// Only re-enable styles if they were disabled by the tool.
if ( this.stylesDisabled ) {
this.enableStyles();
}
} );
// Handle ellipsis menu toggle
this.menuButton.addEventListener( 'click', ( e ) => {
e.stopPropagation();
this.toggleMenu();
} );
// Close menu on outside click
document.addEventListener( 'click', ( e ) => {
if ( this.menu && ! this.menu.hidden && ! this.menu.contains( e.target ) && e.target !== this.menuButton ) {
this.closeMenu();
}
} );
// Keyboard navigation within menu
this.menu.addEventListener( 'keydown', ( e ) => {
const items = [ ...this.menu.querySelectorAll( '[role="menuitem"]' ) ];
const focused = document.activeElement;
const index = items.indexOf( focused );
if ( e.key === 'ArrowDown' ) {
e.preventDefault();
items[ ( index + 1 ) % items.length ]?.focus();
} else if ( e.key === 'ArrowUp' ) {
e.preventDefault();
items[ ( index - 1 + items.length ) % items.length ]?.focus();
} else if ( e.key === 'Escape' ) {
this.closeMenu();
this.menuButton.focus();
}
} );
// Handle move left/right / reset position
this.moveButton.addEventListener( 'click', () => {
this.togglePosition();
this.closeMenu();
} );
// Handle disable/enable styles
this.disableStylesButton.addEventListener( 'click', () => {
if ( this.stylesDisabled ) {
this.enableStyles();
} else {
this.disableStyles();
}
this.closeMenu();
} );
if ( this.rescanButton ) {
this.rescanButton.addEventListener( 'click', () => {
this.closeMenu();
this.rescanPage();
} );
}
if ( this.clearIssuesButton ) {
this.clearIssuesButton.addEventListener( 'click', () => {
this.closeMenu();
this.clearIssues();
} );
}
if ( this.dockButton ) {
this.dockButton.addEventListener( 'click', () => {
this.closeMenu();
this.toggleDock();
} );
}
// Reactivate the focus trap when the user clicks back into the panel.
this.panelControls.addEventListener( 'pointerdown', () => {
if ( ! this.panelControlsFocusTrap.active ) {
this.panelControlsFocusTrap.activate( { returnFocusOnDeactivate: false } );
}
} );
// Restore docked state if it was previously set.
if ( this.isDocked ) {
this.applyDock();
}
// Open panel if a URL parameter exists
if ( this.urlParameter ) {
this.panelOpen( this.urlParameter );
} else if ( this.landmarkParameter ) {
this.highlightLandmark( this.landmarkParameter );
} else if ( this.isDocked ) {
// Docked panel restored on page load — fetch issue data so the panel isn't empty.
this.panelOpen();
}
}
toggleMenu() {
const isOpen = ! this.menu.hidden;
if ( isOpen ) {
this.closeMenu();
} else {
this.menu.hidden = false;
this.menuButton.setAttribute( 'aria-expanded', 'true' );
this.menu.querySelector( '[role="menuitem"]' )?.focus();
}
}
closeMenu() {
this.menu.hidden = true;
this.menuButton.setAttribute( 'aria-expanded', 'false' );
}
/**
* Announce a message to screen readers using a live region.
*
* @param {string} message - The message to announce.
*/
announce( message ) {
if ( ! this.srAnnouncer ) {
return;
}
// Clear first so repeated identical messages are re-announced.
this.srAnnouncer.textContent = '';
// Use a timeout to ensure the DOM update is picked up by assistive technologies.
setTimeout( () => {
this.srAnnouncer.textContent = message;
}, 50 );
}
togglePosition() {
// Clear any drag-applied inline position so the panel repositions via CSS classes.
this.panelControls.style.position = '';
this.panelControls.style.width = '';
this.panelControls.style.left = '';
this.panelControls.style.top = '';
this.panelControls.style.right = '';
this.panelControls.style.bottom = '';
// If the panel was dragged, just reset — don't toggle the side.
if ( this.isDragged ) {
this.isDragged = false;
const isRight = this.highlightPanel.classList.contains( 'edac-highlight-panel--right' );
this.moveButton.querySelector( 'span' ).textContent = isRight
? __( 'Move to Left', 'accessibility-checker' )
: __( 'Move to Right', 'accessibility-checker' );
this.announce( __( 'Panel position reset.', 'accessibility-checker' ) );
return;
}
const isRight = this.highlightPanel.classList.contains( 'edac-highlight-panel--right' );
this.highlightPanel.classList.toggle( 'edac-highlight-panel--right', ! isRight );
this.highlightPanel.classList.toggle( 'edac-highlight-panel--left', isRight );
this.moveButton.querySelector( 'span' ).textContent = isRight
? __( 'Move to Right', 'accessibility-checker' )
: __( 'Move to Left', 'accessibility-checker' );
this.announce( isRight
? __( 'Panel moved to the left.', 'accessibility-checker' )
: __( 'Panel moved to the right.', 'accessibility-checker' )
);
// If docked, update body margin to match the new side.
if ( this.isDocked ) {
const panelWidth = this.panelControls.offsetWidth + 'px';
document.body.style.marginRight = '';
document.body.style.marginLeft = '';
document.body.style[ isRight ? 'marginLeft' : 'marginRight' ] = panelWidth;
}
}
/**
* This function tries to find an element on the page that matches a given HTML snippet.
* It tries multiple strategies in order: selector (most stable), ancestry (more specific),
* and HTML matching (fallback). If a match is found, it adds a tooltip and returns the element.
* If no matching element is found, it returns null.
*
* @param {Object} value - Object containing the HTML snippet and selectors.
* @param {number} index - Index of the element being searched.
* @return {HTMLElement|null} - Returns the matching HTML element, or null if no match is found.
*/
findElement( value, index ) {
// Try selector first (most stable - IDs/classes don't change with DOM structure)
if ( value.selector ) {
try {
const element = document.querySelector( value.selector );
if ( element ) {
const tooltip = this.addTooltip( element, value, index, this.issues.length );
this.issues[ index ].tooltip = tooltip.tooltip;
this.tooltips.push( tooltip );
return element;
}
} catch ( e ) {
// Selector may be invalid, fall back to ancestry
}
}
// Try ancestry selector (more specific than selector but less stable)
if ( value.ancestry ) {
try {
const element = document.querySelector( value.ancestry );
if ( element ) {
const tooltip = this.addTooltip( element, value, index, this.issues.length );
this.issues[ index ].tooltip = tooltip.tooltip;
this.tooltips.push( tooltip );
return element;
}
} catch ( e ) {
// Ancestry selector may be invalid, fall back to HTML matching
}
}
// Fall back to HTML matching
let htmlToFind = value.object;
const parser = new DOMParser();
const parsedHtml = parser.parseFromString( htmlToFind, 'text/html' );
const firstParsedElement = parsedHtml.body.firstElementChild;
if ( firstParsedElement ) {
htmlToFind = firstParsedElement.outerHTML;
}
// Compare the outer HTML of the parsed element with all elements on the page
const allElements = document.body.querySelectorAll( '*' );
for ( const element of allElements ) {
if ( element.outerHTML.replace( /\W/g, '' ) === htmlToFind.replace( /\W/g, '' ) ) {
const tooltip = this.addTooltip( element, value, index, this.issues.length );
this.issues[ index ].tooltip = tooltip.tooltip;
this.tooltips.push( tooltip );
return element;
}
}
// If no matching element is found, return null
return null;
}
/**
* This function makes an AJAX call to the server to retrieve the list of issues.
*
* Note: This function assumes that `edacFrontendHighlighterApp` is a global variable containing necessary data.
*/
highlightAjax() {
const self = this;
return new Promise( function( resolve, reject ) {
const xhr = new XMLHttpRequest();
const url = edacFrontendHighlighterApp.ajaxurl + '?action=edac_frontend_highlight_ajax&post_id=' + edacFrontendHighlighterApp.postID + '&nonce=' + edacFrontendHighlighterApp.nonce;
self.showWait( true );
xhr.open( 'GET', url );
xhr.onload = function() {
if ( xhr.status === 200 ) {
self.showWait( false );
const response = JSON.parse( xhr.responseText );
if ( true === response.success ) {
const responseJson = JSON.parse( response.data );
if ( self.settings.showIgnored ) {
resolve( {
issues: responseJson.issues,
fixes: responseJson.fixes,
} );
} else {
resolve(
{
issues: responseJson.issues.filter( ( item ) => {
// When rules are filtered off from php we can get null values for some properties
// here. This should be fixed upstream but handling it here as well for robustness.
if ( item.rule_type === null ) {
return false;
}
return ( item.id === self.urlParameter || item.rule_type !== 'ignored' );
} ),
fixes: responseJson.fixes,
},
);
}
} else if ( ! self._scanAttempted && response.data?.[ 0 ]?.code === -3 ) {
// Only try kickoffScan once per highlightAjax call
self._scanAttempted = true;
self.kickoffScan();
// After kickoffScan, try highlightAjax again, but only once
setTimeout( () => {
self.highlightAjax().then( resolve ).catch( reject );
}, 5000 ); // Wait 5s for scan to complete.
} else {
// Default: resolve with empty issues/fixes
resolve( { issues: [], fixes: [] } );
}
} else {
self.showWait( false );
reject( {
status: xhr.status,
statusText: xhr.statusText,
} );
}
};
xhr.onerror = function() {
self.showWait( false );
reject( {
status: xhr.status,
statusText: xhr.statusText,
} );
};
xhr.send();
} );
}
/**
* This function toggles showing Wait
* @param {boolean} status
*/
showWait( status = true ) {
if ( status ) {
document.querySelector( 'body' ).classList.add( 'edac-app-wait' );
} else {
document.querySelector( 'body' ).classList.remove( 'edac-app-wait' );
}
}
/**
* This function removes the highlight/tooltip buttons and runs cleanups for each.
*/
removeHighlightButtons() {
this.tooltips.forEach( ( item ) => {
//remove click listener
item.tooltip.removeEventListener( 'click', item.listeners.onClick );
//remove position/resize listener: https://floating-ui.com/docs/autoUpdate
item.listeners.cleanup();
} );
const buttons = document.querySelectorAll( '.edac-highlight-btn' );
buttons.forEach( ( button ) => {
button.remove();
} );
// Clean up any landmark labels
this.removeLandmarkLabels();
}
/**
* This function adds a new button element to the DOM, which acts as a tooltip for the highlighted element.
*
* @param {HTMLElement} element - The DOM element before which the tooltip button will be inserted.
* @param {Object} value - An object containing properties used to customize the tooltip button.
* @param {number} index - The index of the element being processed.
* @return {Object} - information about the tooltip
*/
/* eslint-disable no-unused-vars */
addTooltip( element, value, index, totalItems ) {
// Create the tooltip.
const tooltip = document.createElement( 'button' );
tooltip.classList = 'edac-highlight-btn edac-highlight-btn-' + value.rule_type;
tooltip.setAttribute( 'aria-label', sprintf( __( 'Open details for %1$s, %2$s of %3$s', 'accessibility-checker' ), value.rule_title, index + 1, totalItems ) );
tooltip.setAttribute( 'aria-expanded', 'false' );
tooltip.setAttribute( 'aria-haspopup', 'dialog' );
//add data-id to the tooltip/button so we can find it later.
tooltip.dataset.id = value.id;
const onClick = ( e ) => {
const id = e.currentTarget.dataset.id;
this.showIssue( id );
this.focusTrapControls();
};
tooltip.addEventListener( 'click', onClick );
// Add the tooltip to the page.
document.body.append( tooltip );
// Store a unique identifier for the target element
// Use a WeakMap-style unique identifier based on the actual element object
// This ensures that even if multiple elements have identical HTML, they get different identifiers
if ( ! element.__edacElementId ) {
element.__edacElementId = 'edac-' + Math.random().toString( 36 ).substr( 2, 9 );
}
tooltip.dataset.targetElement = element.__edacElementId;
// Add creation timestamp to track order of tooltip creation
tooltip.dataset.creationOrder = Date.now() + Math.random(); // Ensure uniqueness
const updatePosition = function() {
// Get the sorted index and element hash for this tooltip
const sortedIndex = parseInt( tooltip.dataset.sortedIndex || '0', 10 );
const currentElementHash = tooltip.dataset.targetElement;
// Calculate offset based on sorted position, not creation order
// Count how many tooltips for this same element have a LOWER sorted index
let tooltipOffset = 0;
const allTooltips = Array.from( document.querySelectorAll( '.edac-highlight-btn' ) );
for ( const btn of allTooltips ) {
if ( btn === tooltip ) {
break; // Stop counting when we reach this tooltip
}
const btnSortedIndex = parseInt( btn.dataset.sortedIndex || '0', 10 );
// Count only tooltips for the same element that come before this one in sorted order
if ( btn.dataset.targetElement === currentElementHash && btnSortedIndex < sortedIndex ) {
tooltipOffset++;
}
}
const TOOLTIP_GAP = 5; // Gap between tooltip buttons in pixels
computePosition( element, tooltip, {
placement: 'top-start',
middleware: [],
} ).then( ( { x, y } ) => {
const elRect = element.getBoundingClientRect();
const elHeight = element.offsetHeight === undefined ? 0 : element.offsetHeight;
const tooltipHeight = tooltip.offsetHeight === undefined ? 0 : tooltip.offsetHeight;
const tooltipWidth = tooltip.offsetWidth === undefined ? 0 : tooltip.offsetWidth;
// Calculate the horizontal offset for stacking multiple tooltips on the same element
const left = tooltipOffset * ( tooltipWidth + TOOLTIP_GAP );
// Start with the position from computePosition
const finalLeft = x + left;
let finalTop = y;
// Special handling for zero-height elements (like empty <p> tags)
// When an element has no height, computePosition may not calculate y correctly
// Use the element's bounding rect top position adjusted for tooltip height
if ( elHeight === 0 && elRect.height === 0 ) {
// Element has no visual height
// Position tooltip above where the element is in the document
finalTop = elRect.top + document.documentElement.scrollTop - tooltipHeight - 5;
}
// Note: We do NOT clamp to viewport boundaries
// Tooltips should follow their elements even when outside viewport
// They'll become visible when scrolling to the element
Object.assign( tooltip.style, {
left: `${ finalLeft }px`,
top: `${ finalTop }px`,
} );
} );
};
// Place the tooltip at the element's position on the page.
// See: https://floating-ui.com/docs/autoUpdate
const cleanup = autoUpdate(
element,
tooltip,
updatePosition, {
ancestorScroll: true,
ancestorResize: true,
elementResize: true,
layoutShift: true,
animationFrame: true, // TODO: Disable styles sometimes causes the toolbar to disappear until a scroll or resize event. This may help - but is expensive.
}
);
return {
element,
tooltip,
listeners: {
onClick,
cleanup,
},
};
}
/**
* This function adds a new div element to the DOM, which contains the accessibility checker panel.
*/
addHighlightPanel() {
const widgetPosition = edacFrontendHighlighterApp?.widgetPosition || 'right';
const userCanEdit = edacFrontendHighlighterApp && edacFrontendHighlighterApp?.userCanEdit && edacFrontendHighlighterApp?.loggedIn;
const moveLabel = widgetPosition === 'right'
? __( 'Move to Left', 'accessibility-checker' )
: __( 'Move to Right', 'accessibility-checker' );
const scanIcon = `<span class="edac-menu-icon edac-menu-icon--scan" aria-hidden="true"></span>`;
const refreshIcon = `<span class="edac-menu-icon edac-menu-icon--refresh" aria-hidden="true"></span>`;
const trashIcon = `<span class="edac-menu-icon edac-menu-icon--trash" aria-hidden="true"></span>`;
const moveIcon = `<span class="edac-menu-icon edac-menu-icon--move" aria-hidden="true"></span>`;
const stylesIcon = `<span class="edac-menu-icon edac-menu-icon--styles" aria-hidden="true"></span>`;
const dockIcon = `<span class="edac-menu-icon edac-menu-icon--dock" aria-hidden="true"></span>`;
const dockLabel = localStorage.getItem( 'edac-panel-docked' ) === '1'
? __( 'Undock Panel', 'accessibility-checker' )
: __( 'Dock Panel', 'accessibility-checker' );
const clearButtonMarkup = userCanEdit
? `<li role="none"><button id="edac-highlight-clear-issues" class="edac-highlight-clear-issues" role="menuitem"><span>${ __( 'Clear Issues', 'accessibility-checker' ) }</span>${ trashIcon }</button></li>`
: '';
const rescanButton = userCanEdit
? `<li role="none"><button id="edac-highlight-rescan" class="edac-highlight-rescan" role="menuitem"><span>${ __( 'Rescan This Page', 'accessibility-checker' ) }</span>${ refreshIcon }</button></li>`
: '';
const newElement = `
<div id="edac-highlight-announcer" class="edac-sr-only" role="status" aria-live="polite" aria-atomic="true"></div>
<div id="edac-highlight-panel" class="edac-highlight-panel edac-highlight-panel--${ widgetPosition }">
<button id="edac-highlight-panel-toggle" class="edac-highlight-panel-toggle" aria-haspopup="dialog" aria-label="${ __( 'Accessibility Checker Tools', 'accessibility-checker' ) }"></button>
<div id="edac-highlight-panel-controls" class="edac-highlight-panel-controls" tabindex="0" role="dialog" aria-labelledby="edac-highlight-panel-controls-title">
<div class="edac-highlight-panel-controls-header">
<div id="edac-highlight-panel-controls-title" class="edac-highlight-panel-controls-title" role="heading" aria-level="2"><span class="edac-highlight-panel-controls-title-icon" aria-hidden="true"></span>${ __( 'Accessibility Checker', 'accessibility-checker' ) }</div>
<div class="edac-highlight-panel-controls-header-actions">
<div class="edac-highlight-menu-container">
<button id="edac-highlight-menu-button" class="edac-highlight-menu-button" aria-haspopup="menu" aria-expanded="false" aria-label="${ __( 'More options', 'accessibility-checker' ) }">⋯</button>
<ul id="edac-highlight-menu" class="edac-highlight-menu" role="menu" aria-label="${ __( 'More options', 'accessibility-checker' ) }" hidden>
<li role="none"><button id="edac-highlight-move" class="edac-highlight-move" role="menuitem"><span>${ moveLabel }</span>${ moveIcon }</button></li>
<li role="none"><button id="edac-highlight-dock" class="edac-highlight-dock" role="menuitem"><span>${ dockLabel }</span>${ dockIcon }</button></li>
${ rescanButton }
${ clearButtonMarkup }
<li role="none"><button id="edac-highlight-disable-styles" class="edac-highlight-disable-styles" role="menuitem" aria-live="polite" aria-label="${ __( 'Disable Page Styles', 'accessibility-checker' ) }"><span>${ __( 'Disable Styles', 'accessibility-checker' ) }</span>${ stylesIcon }</button></li>
</ul>
</div>
<button id="edac-highlight-panel-controls-close" class="edac-highlight-panel-controls-close" aria-label="${ __( 'Close', 'accessibility-checker' ) }">×</button>
</div>
</div>
<div id="edac-highlight-panel-controls-content" class="edac-highlight-panel-controls-content">
<div id="edac-highlight-panel-controls-content-empty" class="edac-highlight-panel-controls-content-empty">
${ __( 'No issues found on this page.', 'accessibility-checker' ) }
</div>
<div class="edac-highlight-panel-controls-content-issue" style="display:none">
<div id="edac-highlight-panel-description-title" class="edac-highlight-panel-description-title"></div>
<div class="edac-highlight-panel-description-content"></div>
<div id="edac-highlight-panel-description-code" class="edac-highlight-panel-description-code"><code></code></div>
<div id="edac-highlight-panel-description-fix" class="edac-highlight-panel-description-fix"></div>
</div>
</div>
<div class="edac-highlight-panel-controls-footer">
<div class="edac-highlight-panel-controls-summary">${ __( 'Loading...', 'accessibility-checker' ) }</div>
<div class="edac-highlight-panel-controls-buttons">
<button id="edac-highlight-previous" disabled="true"><span aria-hidden="true">← </span>${ __( 'Previous', 'accessibility-checker' ) }</button>
<span class="edac-highlight-panel-controls-pagination" id="edac-highlight-pagination" aria-live="polite"></span>
<button id="edac-highlight-next" disabled="true">${ __( 'Next', 'accessibility-checker' ) }<span aria-hidden="true"> →</span></button>
</div>
</div>
</div>
</div>
`;
document.body.insertAdjacentHTML( 'afterbegin', newElement );
const panel = document.getElementById( 'edac-highlight-panel' );
// Override --wp-admin-theme-color with the correct value from the user's
// admin color scheme, since WordPress does not update this variable on the frontend.
if ( edacFrontendHighlighterApp?.adminThemeColor ) {
panel.style.setProperty( '--wp-admin-theme-color', edacFrontendHighlighterApp.adminThemeColor );
}
this.initDrag( panel );
return panel;
}
/**
* Makes the panel draggable by its header. Buttons in the header are excluded from triggering a drag.
*
* @param {HTMLElement} panel
*/
initDrag( panel ) {
const controls = panel.querySelector( '.edac-highlight-panel-controls' );
const header = panel.querySelector( '.edac-highlight-panel-controls-header' );
if ( ! header || ! controls ) {
return;
}
header.style.cursor = 'grab';
let startX, startY, startLeft, startTop, isDragging, hasMoved;
const resetControlsPosition = () => {
controls.style.position = '';
controls.style.width = '';
controls.style.left = '';
controls.style.top = '';
controls.style.right = '';
controls.style.bottom = '';
};
header.addEventListener( 'pointerdown', ( e ) => {
// Let buttons and links handle their own clicks.
if ( e.target.closest( 'button, a' ) ) {
return;
}
// Disable drag in docked mode.
if ( this.isDocked ) {
return;
}
const rect = controls.getBoundingClientRect();
startLeft = rect.left;
startTop = rect.top;
startX = e.clientX;
startY = e.clientY;
isDragging = true;
hasMoved = false;
// Detach controls from panel flow and position them independently.
controls.style.width = rect.width + 'px';
controls.style.position = 'fixed';
controls.style.left = startLeft + 'px';
controls.style.top = startTop + 'px';
controls.style.right = 'auto';
controls.style.bottom = 'auto';
// Capture pointer so pointermove/pointerup fire even outside the window.
header.setPointerCapture( e.pointerId );
document.body.style.userSelect = 'none';
header.style.cursor = 'grabbing';
e.preventDefault();
} );
header.addEventListener( 'pointermove', ( e ) => {
if ( ! isDragging ) {
return;
}
const dx = e.clientX - startX;
const dy = e.clientY - startY;
if ( ! hasMoved && Math.abs( dx ) <= 4 && Math.abs( dy ) <= 4 ) {
return;
}
hasMoved = true;
controls.style.left = ( startLeft + dx ) + 'px';
controls.style.top = ( startTop + dy ) + 'px';
} );
header.addEventListener( 'pointerup', ( e ) => {
if ( ! isDragging ) {
return;
}
isDragging = false;
header.releasePointerCapture( e.pointerId );
document.body.style.userSelect = '';
header.style.cursor = 'grab';
// Check final delta too — pointermove may have been skipped on a fast gesture.
const totalDx = e.clientX - startX;
const totalDy = e.clientY - startY;
const wasDrag = hasMoved || Math.abs( totalDx ) > 4 || Math.abs( totalDy ) > 4;
if ( wasDrag ) {
// Mark as dragged and update the menu action.
this.isDragged = true;
this.moveButton.querySelector( 'span' ).textContent = __( 'Reset Position', 'accessibility-checker' );
} else {
// Simple click — undo the fixed positioning applied on pointerdown.
resetControlsPosition();
}
} );
header.addEventListener( 'pointercancel', ( e ) => {
if ( ! isDragging ) {
return;
}
isDragging = false;
header.releasePointerCapture( e.pointerId );
document.body.style.userSelect = '';
header.style.cursor = 'grab';
if ( ! hasMoved ) {
resetControlsPosition();
}
} );
}
/**
* This function highlights the next element on the page. It uses the 'currentButtonIndex' property to keep track of the current element.
*/
highlightFocusNext = () => {
if ( this.currentButtonIndex === null ) {
this.currentButtonIndex = 0;
} else {
this.currentButtonIndex = ( this.currentButtonIndex + 1 ) % this.issues.length;
}
const id = this.issues[ this.currentButtonIndex ].id;
this.showIssue( id );
};
/**
* This function highlights the previous element on the page. It uses the 'currentButtonIndex' property to keep track of the current element.
*/
highlightFocusPrevious = () => {
if ( this.currentButtonIndex === null ) {
this.currentButtonIndex = this.issues.length - 1;
} else {
this.currentButtonIndex = ( this.currentButtonIndex - 1 + this.issues.length ) % this.issues.length;
}
const id = this.issues[ this.currentButtonIndex ].id;
this.showIssue( id );
};
/**
* This function sets a focus trap on the controls panel
*/
focusTrapControls = () => {
this.panelControlsFocusTrap.activate();
setTimeout( () => {
this.closePanel?.focus();
}, 100 ); //give render time to complete.
};
/**
* This function shows an issue related to an element.
* @param {string} id - The ID of the element.
*/
showIssue = ( id ) => {
this.removeSelectedClasses();
if ( id === undefined ) {
return;
}
const issue = this.issues.find( ( i ) => String( i.id ) === String( id ) );
if ( ! issue ) {
return;
}
this.currentButtonIndex = this.issues.findIndex( ( i ) => String( i.id ) === String( id ) );
// Keep the URL in sync so the current issue is bookmarkable / shareable.
const url = new URL( window.location.href );
url.searchParams.set( 'edac', id );
history.replaceState( null, '', url.toString() );
const pagination = document.getElementById( 'edac-highlight-pagination' );
if ( pagination ) {
const visiblePosition = sprintf(
// translators: %1$d is the current issue number, %2$d is the total number of issues.
__( '%1$d of %2$d', 'accessibility-checker' ),
this.currentButtonIndex + 1,
this.issues.length
);
const issueTitle = issue.rule_title || __( 'Untitled issue', 'accessibility-checker' );
const srAnnouncement = sprintf(
// translators: %1$d is the current issue number, %2$d is the total number of issues, %3$s is the issue title.
__( 'Issue %1$d of %2$d: %3$s', 'accessibility-checker' ),
this.currentButtonIndex + 1,
this.issues.length,
issueTitle
);
pagination.textContent = '';
const visiblePositionNode = document.createElement( 'span' );
visiblePositionNode.setAttribute( 'aria-hidden', 'true' );
visiblePositionNode.textContent = visiblePosition;
const srOnlyNode = document.createElement( 'span' );
srOnlyNode.className = 'edac-sr-only';
srOnlyNode.textContent = srAnnouncement;
pagination.append( visiblePositionNode, srOnlyNode );
}
const tooltip = issue.tooltip;
const element = issue.element;
if ( tooltip && element ) {
tooltip.classList.add( 'edac-highlight-btn-selected' );
element.classList.add( 'edac-highlight-element-selected' );
if ( element.offsetWidth < 20 ) {
element.classList.add( 'edac-highlight-element-selected-min-width' );
}
if ( element.offsetHeight < 5 ) {
element.classList.add( 'edac-highlight-element-selected-min-height' );
}
element.scrollIntoView( { block: 'center' } );
if ( isFocusable( tooltip ) ) {
//issueElement.focus();
if ( ! this.checkVisibility( tooltip ) || ! this.checkVisibility( element ) ) {
this.currentIssueStatus = __( 'The element is not visible. Try disabling styles.', 'accessibility-checker' );
//TODO: console.log(`Element with id ${id} is not visible!`);
} else {
this.currentIssueStatus = null;
}
} else {
this.currentIssueStatus = __( 'The element is not focusable. Try disabling styles.', 'accessibility-checker' );
//TODO: console.log(`Element with id ${id} is not focusable!`);
}
} else {
this.currentIssueStatus = __( 'The element was not found on the page.', 'accessibility-checker' );
//TODO: console.log(`Element with id ${id} not found in the document!`);
}
this.descriptionOpen( id );
};
/**
* This function checks if a given element is visible on the page.
*
* @param {HTMLElement} el The element to check for visibility
* @return {boolean} isVisible
*/
checkVisibility = ( el ) => {
//checkVisibility is still in draft but well supported on many browsers.
//See: https://drafts.csswg.org/cssom-view-1/#dom-element-checkvisibility
//See: https://caniuse.com/mdn-api_element_checkvisibility
if ( typeof ( el.checkVisibility ) !== 'function' ) {
//See: https://github.com/jquery/jquery/blob/main/src/css/hiddenVisibleSelectors.js
return !! ( el.offsetWidth || el.offsetHeight || el.getClientRects().length );
}
return el.checkVisibility( {
checkOpacity: true, // Check CSS opacity property too
checkVisibilityCSS: true, // Check CSS visibility property too
} );
};
/**
* This function opens the accessibility checker panel.
* @param {number} id of the issue
*/
panelOpen( id ) {
this.highlightPanel.classList.add( 'edac-highlight-panel-visible' );
this.panelControls.style.display = 'flex';
this.panelToggle.style.display = 'none';
// previous and next buttons are disabled until we have issues to show.
this.nextButton.disabled = true;
this.previousButton.disabled = true;
// If issues were cleared, trigger a fresh scan instead of loading stale data.
if ( this._issuesCleared ) {
this._issuesCleared = false;
this.rescanPage();
return;
}
// Get the issues for this page.
this.highlightAjax().then(
( json ) => {
this.issues = json.issues;
this.fixes = json.fixes;
json.issues.forEach( function( value, index ) {
const element = this.findElement( value, index );
if ( element !== null ) {
this.issues[ index ].element = element;
}
}.bind( this ) );
// Sort issues by DOM order using native compareDocumentPosition
this.issues.sort( ( a, b ) => {
// If elements weren't found, push to end
if ( ! a.element && b.element ) {
return 1;
}
if ( a.element && ! b.element ) {
return -1;
}
if ( ! a.element && ! b.element ) {
return 0;
}
// Use DOM compareDocumentPosition for accurate ordering
const position = a.element.compareDocumentPosition( b.element );
// DOCUMENT_POSITION_FOLLOWING (4) means b comes after a in DOM
// eslint-disable-next-line no-bitwise
if ( position & Node.DOCUMENT_POSITION_FOLLOWING ) {
return -1;
}
// DOCUMENT_POSITION_PRECEDING (2) means b comes before a in DOM
// eslint-disable-next-line no-bitwise
if ( position & Node.DOCUMENT_POSITION_PRECEDING ) {
return 1;
}
// Elements are the same (or in different documents)
// When elements are the same, sort by issue ID for consistent ordering
// This ensures multiple issues on the same element appear in predictable order
const idA = parseInt( a.id, 10 );
const idB = parseInt( b.id, 10 );
return idA - idB;
} );
// Update tooltip aria-labels to reflect sorted order
this.issues.forEach( ( issue, sortedIndex ) => {
if ( issue.tooltip ) {
// Store the sorted index on the tooltip for debugging
issue.tooltip.dataset.sortedIndex = sortedIndex;
issue.tooltip.setAttribute(
'aria-label',
sprintf(
__( 'Open details for %1$s, %2$s of %3$s', 'accessibility-checker' ),
issue.rule_title,
sortedIndex + 1,
this.issues.length
)
);
}