Certainly! Below is the updated full UserScript that adds the ability to resize rectangles by dragging the left, top, right, and bottom edges, in addition to the existing corner (vertex) resize handles. This enhancement improves the flexibility and usability of the rectangle drawer tool.
Key Updates:
-
Added Edge Resize Handles:
- Created four new resize handles:
n (top), s (bottom), e (right), and w (left).
-
Updated CSS:
- Styled the new edge resize handles to ensure they are easily accessible and visually consistent with the corner handles.
-
Enhanced Resize Logic:
- Modified the
onMouseMove and initResize methods to handle resizing based on both corner and edge handles.
-
Dynamic Cursor Changes:
- Assigned appropriate cursor styles for edge handles to indicate the direction of resizing.
-
Code Organization:
- Ensured the code remains clean and maintainable by handling all resize scenarios effectively.
Here is the complete updated script:
// ==UserScript==
// @name Enhanced Rectangle Drawer Tool with Trusted Types and Edge Resizing
// @namespace http://your.namespace.here/
// @version 2.1
// @description Draw, manage, and interact with rectangles on any webpage with Trusted Types compliance. Now includes edge resizing for enhanced usability.
// @author Your Name
// @match *://*/*
// @grant none
// @run-at document-end
// ==/UserScript==
(function () {
'use strict';
let TTP;
// **Trusted Types Policy Creation**
if (window.trustedTypes && window.trustedTypes.createPolicy) {
TTP = window.trustedTypes.createPolicy('default', {
createHTML: (input) => input, // Allow all HTML strings (use with caution)
createScriptURL: (input) => input,
createScript: (input) => input,
emptyScript: () => '',
});
}
// **Logging to Verify Script Execution**
console.log("Enhanced Rectangle Drawer Tool with Trusted Types is running!");
/**
* Debounce Function
* Limits the rate at which a function can fire.
*/
function debounce(func, wait) {
let timeout;
return function (...args) {
const later = () => {
clearTimeout(timeout);
func.apply(this, args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
/**
* RectangleDrawer Class
* Handles creation, management, and interaction of rectangles on the webpage.
*/
class RectangleDrawer {
static cssInjected = false;
constructor(options = {}) {
this.options = {
persistent: true, // Whether rectangles remain after drawing
...options,
};
this.rects = new Map();
this.currentRect = null;
this.isDrawing = false;
this.isResizing = false;
this.resizingInfo = null;
this.isDragging = false;
this.draggingInfo = null;
this.drawingMode = false;
this.startX = 0;
this.startY = 0;
this.rectIdCounter = 0;
this.injectCSS();
this.initEvents();
if (this.options.persistent) {
this.loadRects();
}
}
/**
* Inject necessary CSS styles into the webpage.
* Uses Trusted Types to safely inject CSS if policies are enforced.
*/
injectCSS() {
if (RectangleDrawer.cssInjected) return;
const style = document.createElement('style');
const cssContent = `
.rectangle-drawer-rect {
position: absolute;
border: 2px solid #3498db;
background-color: rgba(52, 152, 219, 0.2);
box-sizing: border-box;
z-index: 9999;
cursor: move;
transition: box-shadow 0.2s;
}
.rectangle-drawer-rect:hover {
box-shadow: 0 0 10px rgba(52, 152, 219, 0.7);
}
.rectangle-drawer-rect .delete-btn {
position: absolute;
top: 4px;
right: 4px;
background: rgba(231, 76, 60, 0.8);
color: white;
border: none;
border-radius: 50%;
width: 20px;
height: 20px;
display: none;
cursor: pointer;
align-items: center;
justify-content: center;
padding: 0;
box-shadow: 0 0 5px rgba(0,0,0,0.3);
transition: background 0.2s, transform 0.2s, opacity 0.3s ease;
opacity: 0;
}
.rectangle-drawer-rect .delete-btn:hover {
background: rgba(192, 57, 43, 0.9);
transform: scale(1.1);
}
.rectangle-drawer-rect:hover .delete-btn {
display: flex;
opacity: 1;
}
.rectangle-drawer-rect .resize-handle {
position: absolute;
width: 12px;
height: 12px;
background: #3498db;
cursor: nwse-resize;
border: 1px solid white;
box-sizing: border-box;
}
/* Corner Handles */
.rectangle-drawer-rect .resize-handle.nw {
top: -6px;
left: -6px;
cursor: nwse-resize;
}
.rectangle-drawer-rect .resize-handle.ne {
top: -6px;
right: -6px;
cursor: nesw-resize;
}
.rectangle-drawer-rect .resize-handle.sw {
bottom: -6px;
left: -6px;
cursor: nesw-resize;
}
.rectangle-drawer-rect .resize-handle.se {
bottom: -6px;
right: -6px;
cursor: nwse-resize;
}
/* Edge Handles */
.rectangle-drawer-rect .resize-handle.n {
top: -6px;
left: 50%;
transform: translateX(-50%);
cursor: ns-resize;
}
.rectangle-drawer-rect .resize-handle.s {
bottom: -6px;
left: 50%;
transform: translateX(-50%);
cursor: ns-resize;
}
.rectangle-drawer-rect .resize-handle.e {
top: 50%;
right: -6px;
transform: translateY(-50%);
cursor: ew-resize;
}
.rectangle-drawer-rect .resize-handle.w {
top: 50%;
left: -6px;
transform: translateY(-50%);
cursor: ew-resize;
}
/* UI Container Styles */
.rectangle-drawer-ui {
position: fixed;
top: 20px;
right: 20px;
background: rgba(0, 0, 0, 0.7);
padding: 10px;
border-radius: 8px;
z-index: 10000;
display: flex;
flex-direction: column;
gap: 10px;
box-shadow: 0 0 10px rgba(0,0,0,0.5);
}
.rectangle-drawer-ui button {
padding: 8px 12px;
background: #3498db;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
transition: background 0.2s;
}
.rectangle-drawer-ui button:hover {
background: #2980b9;
}
`;
if (TTP) {
// Use Trusted Types to safely inject CSS
style.textContent = TTP.createHTML(cssContent);
} else {
// Fallback if Trusted Types are not enforced
style.textContent = cssContent;
}
document.head.appendChild(style);
RectangleDrawer.cssInjected = true;
}
/**
* Initialize event listeners for drawing, resizing, and dragging rectangles.
*/
initEvents() {
this.mouseDownHandler = this.onMouseDown.bind(this);
this.mouseMoveHandler = this.onMouseMove.bind(this);
this.mouseUpHandler = this.onMouseUp.bind(this);
document.addEventListener('mousedown', this.mouseDownHandler);
document.addEventListener('mousemove', this.mouseMoveHandler);
document.addEventListener('mouseup', this.mouseUpHandler);
// Handle window resize with debounce to keep rectangles in view
window.addEventListener('resize', debounce(() => {
this.rects.forEach((data, id) => {
const rectElem = document.querySelector(`.rectangle-drawer-rect[data-id="${id}"]`);
if (rectElem) {
rectElem.style.left = `${data.left}px`;
rectElem.style.top = `${data.top}px`;
rectElem.style.width = `${data.width}px`;
rectElem.style.height = `${data.height}px`;
}
});
}, 100));
}
/**
* Activate drawing mode. The user can draw rectangles until they exit the mode.
*/
activateDrawingMode() {
this.drawingMode = true;
// Indicate drawing mode via cursor change
document.body.style.cursor = 'crosshair';
console.log("Drawing mode activated. Click and drag to draw a new rectangle.");
}
/**
* Handle mouse down event to start drawing, resizing, or dragging.
*/
onMouseDown(e) {
// Only respond to left mouse button
if (e.button !== 0) return;
// If not in drawing mode, check if clicking on a rectangle for dragging
if (!this.drawingMode) {
const rectElem = e.target.closest('.rectangle-drawer-rect');
if (rectElem) {
// Prevent initiating drag if clicking on resize handle or delete button
if (e.target.classList.contains('resize-handle') || e.target.classList.contains('delete-btn')) {
return;
}
this.isDragging = true;
this.draggingInfo = {
rect: rectElem,
startX: e.pageX,
startY: e.pageY,
startLeft: parseInt(rectElem.style.left, 10),
startTop: parseInt(rectElem.style.top, 10),
};
return;
}
}
// If in drawing mode, start drawing a new rectangle
if (this.drawingMode) {
// Prevent drawing if clicked on existing rectangle or UI
if (e.target.closest('.rectangle-drawer-rect') || e.target.closest('.rectangle-drawer-ui')) return;
this.isDrawing = true;
this.startX = e.pageX;
this.startY = e.pageY;
const rect = document.createElement('div');
rect.classList.add('rectangle-drawer-rect');
rect.style.left = `${this.startX}px`;
rect.style.top = `${this.startY}px`;
rect.style.width = `0px`;
rect.style.height = `0px`;
rect.style.cursor = 'crosshair';
// Create delete button using DOM methods
const deleteBtn = document.createElement('button');
deleteBtn.classList.add('delete-btn');
deleteBtn.setAttribute('aria-label', 'Delete Rectangle');
deleteBtn.title = 'Delete Rectangle';
deleteBtn.innerHTML = `
<svg width="12" height="12" viewBox="0 0 12 12" xmlns="http://www.w3.org/2000/svg">
<line x1="1" y1="1" x2="11" y2="11" stroke="white" stroke-width="2"/>
<line x1="11" y1="1" x2="1" y2="11" stroke="white" stroke-width="2"/>
</svg>
`;
deleteBtn.addEventListener('click', (event) => {
event.stopPropagation();
const rectId = rect.getAttribute('data-id');
this.removeRect(rectId);
});
rect.appendChild(deleteBtn);
// Create resize handles
['nw', 'ne', 'sw', 'se', 'n', 's', 'e', 'w'].forEach((position) => {
const handle = document.createElement('div');
handle.classList.add('resize-handle', position);
rect.appendChild(handle);
// Handle resizing
handle.addEventListener('mousedown', (event) => this.initResize(event, rect, position));
});
document.body.appendChild(rect);
this.currentRect = rect;
}
}
/**
* Handle mouse move event to draw, resize, or drag a rectangle.
*/
onMouseMove(e) {
const { pageX, pageY } = e;
// Drawing a new rectangle
if (this.isDrawing && this.currentRect) {
let width = pageX - this.startX;
let height = pageY - this.startY;
// Enforce minimum size
width = Math.abs(width) < 20 ? (width < 0 ? -20 : 20) : width;
height = Math.abs(height) < 20 ? (height < 0 ? -20 : 20) : height;
this.currentRect.style.width = `${Math.abs(width)}px`;
this.currentRect.style.height = `${Math.abs(height)}px`;
this.currentRect.style.left = `${width < 0 ? pageX : this.startX}px`;
this.currentRect.style.top = `${height < 0 ? pageY : this.startY}px`;
return;
}
// Resizing an existing rectangle
if (this.isResizing && this.resizingInfo) {
const { rect, handle, startX, startY, startWidth, startHeight, startLeft, startTop } = this.resizingInfo;
let deltaX = pageX - startX;
let deltaY = pageY - startY;
let newWidth = startWidth;
let newHeight = startHeight;
let newLeft = startLeft;
let newTop = startTop;
switch (handle) {
// Corner Handles
case 'nw':
newWidth = startWidth - deltaX;
newHeight = startHeight - deltaY;
newLeft = startLeft + deltaX;
newTop = startTop + deltaY;
break;
case 'ne':
newWidth = startWidth + deltaX;
newHeight = startHeight - deltaY;
newTop = startTop + deltaY;
break;
case 'sw':
newWidth = startWidth - deltaX;
newHeight = startHeight + deltaY;
newLeft = startLeft + deltaX;
break;
case 'se':
newWidth = startWidth + deltaX;
newHeight = startHeight + deltaY;
break;
// Edge Handles
case 'n':
newHeight = startHeight - deltaY;
newTop = startTop + deltaY;
break;
case 's':
newHeight = startHeight + deltaY;
break;
case 'e':
newWidth = startWidth + deltaX;
break;
case 'w':
newWidth = startWidth - deltaX;
newLeft = startLeft + deltaX;
break;
default:
break;
}
const MIN_SIZE = 20;
if (newWidth >= MIN_SIZE) {
rect.style.width = `${newWidth}px`;
rect.style.left = `${newLeft}px`;
}
if (newHeight >= MIN_SIZE) {
rect.style.height = `${newHeight}px`;
rect.style.top = `${newTop}px`;
}
return;
}
// Dragging an existing rectangle
if (this.isDragging && this.draggingInfo) {
let deltaX = pageX - this.draggingInfo.startX;
let deltaY = pageY - this.draggingInfo.startY;
let newLeft = this.draggingInfo.startLeft + deltaX;
let newTop = this.draggingInfo.startTop + deltaY;
// Constrain within the viewport
const rectElem = this.draggingInfo.rect;
const rectWidth = parseInt(rectElem.style.width, 10);
const rectHeight = parseInt(rectElem.style.height, 10);
const maxLeft = window.innerWidth - rectWidth;
const maxTop = window.innerHeight - rectHeight;
newLeft = Math.max(0, Math.min(newLeft, maxLeft));
newTop = Math.max(0, Math.min(newTop, maxTop));
rectElem.style.left = `${newLeft}px`;
rectElem.style.top = `${newTop}px`;
return;
}
}
/**
* Handle mouse up event to finalize drawing, resizing, or dragging.
*/
onMouseUp(e) {
if (this.isDrawing && this.currentRect) {
this.isDrawing = false;
this.drawingMode = false; // Exit drawing mode after drawing one rectangle
document.body.style.cursor = 'default';
const rect = this.currentRect;
const id = `rect-${++this.rectIdCounter}`;
rect.setAttribute('data-id', id);
rect.style.cursor = 'move';
if (this.options.persistent) {
this.rects.set(id, this.getRectData(rect));
this.saveRects();
} else {
rect.remove();
}
this.currentRect = null;
return;
}
if (this.isResizing) {
this.isResizing = false;
this.resizingInfo = null;
const rect = this.currentlyResizing;
const id = rect.getAttribute('data-id');
if (id && this.rects.has(id)) {
this.rects.set(id, this.getRectData(rect));
this.saveRects();
}
this.currentlyResizing = null;
return;
}
if (this.isDragging) {
this.isDragging = false;
const rect = this.draggingInfo.rect;
const id = rect.getAttribute('data-id');
if (id && this.rects.has(id)) {
this.rects.set(id, this.getRectData(rect));
this.saveRects();
}
this.draggingInfo = null;
return;
}
}
/**
* Initialize resizing of a rectangle.
*/
initResize(event, rect, handle) {
event.stopPropagation(); // Prevent triggering other events
this.isResizing = true;
this.currentlyResizing = rect;
this.resizingInfo = {
rect,
handle,
startX: event.pageX,
startY: event.pageY,
startWidth: parseInt(window.getComputedStyle(rect).width, 10),
startHeight: parseInt(window.getComputedStyle(rect).height, 10),
startLeft: parseInt(window.getComputedStyle(rect).left, 10),
startTop: parseInt(window.getComputedStyle(rect).top, 10),
};
}
/**
* Remove a rectangle by its ID.
*/
removeRect(id) {
const rect = this.rects.get(id);
if (rect) {
const elem = document.querySelector(`.rectangle-drawer-rect[data-id="${id}"]`);
if (elem) elem.remove();
this.rects.delete(id);
this.saveRects();
}
}
/**
* Remove all rectangles from the page.
*/
clearAllRects() {
this.rects.forEach((_, id) => this.removeRect(id));
}
/**
* Retrieve all rectangles with their IDs and coordinates.
*/
getAllRects() {
const rectData = [];
this.rects.forEach((data, id) => {
rectData.push({ id, ...data });
});
return rectData;
}
/**
* Get rectangle data (position and size).
*/
getRectData(rect) {
const id = rect.getAttribute('data-id');
const left = parseInt(rect.style.left, 10);
const top = parseInt(rect.style.top, 10);
const width = parseInt(rect.style.width, 10);
const height = parseInt(rect.style.height, 10);
return { left, top, width, height };
}
/**
* Create a rectangle from saved data.
*/
createRectFromData(data) {
const rect = document.createElement('div');
rect.classList.add('rectangle-drawer-rect');
rect.style.left = `${data.left}px`;
rect.style.top = `${data.top}px`;
rect.style.width = `${data.width}px`;
rect.style.height = `${data.height}px`;
rect.setAttribute('data-id', data.id);
rect.style.cursor = 'move';
// Create delete button
const deleteBtn = document.createElement('button');
deleteBtn.classList.add('delete-btn');
deleteBtn.setAttribute('aria-label', 'Delete Rectangle');
deleteBtn.title = 'Delete Rectangle';
deleteBtn.innerHTML = `
<svg width="12" height="12" viewBox="0 0 12 12" xmlns="http://www.w3.org/2000/svg">
<line x1="1" y1="1" x2="11" y2="11" stroke="white" stroke-width="2"/>
<line x1="11" y1="1" x2="1" y2="11" stroke="white" stroke-width="2"/>
</svg>
`;
deleteBtn.addEventListener('click', (event) => {
event.stopPropagation();
this.removeRect(data.id);
});
rect.appendChild(deleteBtn);
// Create resize handles
['nw', 'ne', 'sw', 'se', 'n', 's', 'e', 'w'].forEach((position) => {
const handle = document.createElement('div');
handle.classList.add('resize-handle', position);
rect.appendChild(handle);
handle.addEventListener('mousedown', (event) => this.initResize(event, rect, position));
});
document.body.appendChild(rect);
this.rects.set(data.id, data);
}
/**
* Save rectangles to localStorage.
*/
saveRects() {
const rectData = this.getAllRects();
localStorage.setItem('rectangleDrawerRects', JSON.stringify(rectData));
}
/**
* Load rectangles from localStorage.
*/
loadRects() {
const rectData = JSON.parse(localStorage.getItem('rectangleDrawerRects') || '[]');
rectData.forEach(data => {
this.createRectFromData(data);
});
}
/**
* Clean up event listeners and remove all rectangles.
*/
destroy() {
document.removeEventListener('mousedown', this.mouseDownHandler);
document.removeEventListener('mousemove', this.mouseMoveHandler);
document.removeEventListener('mouseup', this.mouseUpHandler);
window.removeEventListener('resize', this.onWindowResize);
this.clearAllRects();
}
}
/**
* UIManager Class
* Handles the creation and management of the user interface.
*/
class UIManager {
constructor(drawerInstance) {
this.drawer = drawerInstance;
this.createUI();
}
/**
* Create the fixed UI container with buttons.
* Uses Trusted Types to safely inject HTML if policies are enforced.
*/
createUI() {
const uiContainer = document.createElement('div');
uiContainer.classList.add('rectangle-drawer-ui');
// Create New Rect Button using DOM methods
const newRectBtn = document.createElement('button');
newRectBtn.innerText = 'New Rect';
newRectBtn.title = 'Start drawing a new rectangle';
newRectBtn.addEventListener('click', () => this.drawer.activateDrawingMode());
// Create Clear All Button using DOM methods
const clearAllBtn = document.createElement('button');
clearAllBtn.innerText = 'Clear All';
clearAllBtn.title = 'Remove all rectangles';
clearAllBtn.addEventListener('click', () => {
if (confirm('Are you sure you want to remove all rectangles?')) {
this.drawer.clearAllRects();
}
});
// Optional: Add Toggle Visibility Button
const toggleVisibilityBtn = document.createElement('button');
toggleVisibilityBtn.innerText = 'Toggle Visibility';
toggleVisibilityBtn.title = 'Show or hide all rectangles';
toggleVisibilityBtn.addEventListener('click', () => {
const allRects = document.querySelectorAll('.rectangle-drawer-rect');
allRects.forEach(rect => {
rect.style.display = rect.style.display === 'none' ? 'block' : 'none';
});
});
// Append buttons to the UI container
uiContainer.appendChild(newRectBtn);
uiContainer.appendChild(clearAllBtn);
uiContainer.appendChild(toggleVisibilityBtn);
// Append UI container to the body using Trusted Types if available
document.body.appendChild(uiContainer);
}
}
// Instantiate the RectangleDrawer
const drawer = new RectangleDrawer({
persistent: true, // Set to false if rectangles should not remain after drawing
});
// Instantiate the UI Manager
const uiManager = new UIManager(drawer);
// Optional: Expose drawer and uiManager to the global scope for debugging
window.RectangleDrawer = drawer;
window.UIManager = uiManager;
})();
Detailed Breakdown of the Changes:
-
Added Edge Resize Handles (n, s, e, w):
- HTML Structure: When creating or loading rectangles, the script now includes four additional
div elements with classes resize-handle n, resize-handle s, resize-handle e, and resize-handle w.
['nw', 'ne', 'sw', 'se', 'n', 's', 'e', 'w'].forEach((position) => {
const handle = document.createElement('div');
handle.classList.add('resize-handle', position);
rect.appendChild(handle);
handle.addEventListener('mousedown', (event) => this.initResize(event, rect, position));
});
-
Updated CSS for Edge Handles:
- Positioning: Edge handles are positioned at the center of each edge.
- Cursor Styles: Appropriate cursor styles (
ns-resize for vertical edges and ew-resize for horizontal edges) are assigned to indicate the resizing direction.
/* Edge Handles */
.rectangle-drawer-rect .resize-handle.n {
top: -6px;
left: 50%;
transform: translateX(-50%);
cursor: ns-resize;
}
.rectangle-drawer-rect .resize-handle.s {
bottom: -6px;
left: 50%;
transform: translateX(-50%);
cursor: ns-resize;
}
.rectangle-drawer-rect .resize-handle.e {
top: 50%;
right: -6px;
transform: translateY(-50%);
cursor: ew-resize;
}
.rectangle-drawer-rect .resize-handle.w {
top: 50%;
left: -6px;
transform: translateY(-50%);
cursor: ew-resize;
}
-
Enhanced Resizing Logic in onMouseMove:
- Handling Edge Resize: The
switch statement within onMouseMove method now includes cases for n, s, e, and w handles, allowing users to resize the rectangle by dragging its edges.
switch (handle) {
// Corner Handles
case 'nw':
newWidth = startWidth - deltaX;
newHeight = startHeight - deltaY;
newLeft = startLeft + deltaX;
newTop = startTop + deltaY;
break;
case 'ne':
newWidth = startWidth + deltaX;
newHeight = startHeight - deltaY;
newTop = startTop + deltaY;
break;
case 'sw':
newWidth = startWidth - deltaX;
newHeight = startHeight + deltaY;
newLeft = startLeft + deltaX;
break;
case 'se':
newWidth = startWidth + deltaX;
newHeight = startHeight + deltaY;
break;
// Edge Handles
case 'n':
newHeight = startHeight - deltaY;
newTop = startTop + deltaY;
break;
case 's':
newHeight = startHeight + deltaY;
break;
case 'e':
newWidth = startWidth + deltaX;
break;
case 'w':
newWidth = startWidth - deltaX;
newLeft = startLeft + deltaX;
break;
default:
break;
}
Usage Instructions:
-
Activating Drawing Mode:
- Click the "New Rect" button in the UI to enter drawing mode. The cursor will change to a crosshair.
- Click and drag on the webpage to draw a new rectangle. Release the mouse button to finalize.
-
Resizing Rectangles:
- Corner Resizing: Hover over the corners of a rectangle until the resize cursor appears. Click and drag to resize.
- Edge Resizing: Hover over the edges (top, bottom, left, right) of a rectangle until the appropriate resize cursor appears. Click and drag to resize.
-
Dragging Rectangles:
- Click and hold anywhere inside a rectangle (excluding the resize handles and delete button) to drag it around the page.
-
Deleting a Rectangle:
- Hover over a rectangle to reveal the delete button (a small "X" icon) in the top-right corner. Click it to remove the rectangle.
-
Clearing All Rectangles:
- Click the "Clear All" button in the UI to remove all rectangles after confirming.
-
Toggling Visibility:
- Click the "Toggle Visibility" button to show or hide all existing rectangles.
Conclusion:
With these enhancements, the rectangle drawer tool now offers more flexibility by allowing users to resize rectangles from both the corners and the edges. This makes the tool more intuitive and user-friendly for various use cases, such as annotations, highlighting, or UI design prototyping on any webpage.
Feel free to further customize the script to better suit your specific needs!