domrect_visualizer.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /**
  2. * @author mlewand
  3. * @see https://gist.github.com/mlewand/56237c19050d27f61b807ed384dff2db
  4. *
  5. * A helper function to visualize DOMRect or set of DOMRect instances.
  6. *
  7. * Subsequent calls will remove previously marked elements.
  8. *
  9. * Debug a element currently focused in your devtools inspector.
  10. * window.markRect( $0.getBoundingClientRect() );
  11. * // Debug a selection.
  12. * window.markRect( document.getSelection().getRangeAt( 0 ).getClientRects() );
  13. *
  14. *
  15. * Original source: https://gist.github.com/mlewand/56237c19050d27f61b807ed384dff2db
  16. * Updated by [Sv443](https://github.com/Sv443)
  17. *
  18. * Styling example:
  19. * ```js
  20. * const [ mark ] = window.markRect(new DOMRect());
  21. * markElem.style.backgroundColor = "red";
  22. * ```
  23. */
  24. ( () => {
  25. const drawnRect = [];
  26. const createRectDraw = () => {
  27. const ret = document.createElement( 'div' );
  28. ret.style.position = 'absolute';
  29. ret.style.outline = '2px solid red';
  30. ret.classList.add('debug-rect-marker');
  31. document.body.appendChild( ret );
  32. return ret;
  33. };
  34. /**
  35. * Creates an element that marks the passed DOMRectangle(s)
  36. * These elements get the class `debug-rect-marker`
  37. * @param {DOMRect|DOMRect[]} rectangles Accepts a DOMRectangle or an array of them
  38. * @returns {HTMLElement[]} Returns array of marker elements
  39. */
  40. const markRect = ( rectangles ) => {
  41. const marks = [];
  42. // Cleanup.
  43. drawnRect.forEach( ( oldRect ) => oldRect.remove() );
  44. // Unify format.
  45. if ( !Array.isArray(rectangles) ) {
  46. rectangles = [ rectangles ];
  47. }
  48. rectangles.forEach( ( rect ) => {
  49. const curDrawing = createRectDraw(),
  50. dims = [ 'top', 'left', 'width', 'height' ];
  51. dims.forEach( ( property ) => {
  52. curDrawing.style[ property ] = `${rect[ property ]}px`;
  53. } );
  54. console.info( 'created debug rect:', curDrawing );
  55. drawnRect.push( curDrawing );
  56. marks.push( curDrawing );
  57. } );
  58. return marks;
  59. };
  60. /**
  61. * Deletes all rectangles that have been previously created
  62. * @returns {void}
  63. * @author Sv443
  64. */
  65. const deleteRects = () => {
  66. const markers = document.querySelectorAll(".debug-rect-marker");
  67. markers.forEach(elem => {
  68. elem.innerHTML = "";
  69. elem.outerHTML = "";
  70. });
  71. console.warn(`Deleted ${markers.length} markers`);
  72. };
  73. window.markRect = markRect;
  74. window.deleteRects = deleteRects;
  75. } )();