Certainly! To encapsulate the constants within the DndPlugin class and optimize for speed, we can refactor the code by:
Moving Constants Inside the Class: Define all constants, including action types and the ACTION_TABLE, as static properties within the class. This prevents polluting the global namespace and allows the constants to be tightly coupled with the class logic.
Using Numeric Constants: Replace string constants with numeric values for faster comparisons and switch-case operations.
Optimizing Event Handlers: Ensure that event handlers are bound efficiently and avoid unnecessary computations within frequently called methods like onMouseMove.
Here's the refactored code implementing these optimizations:
javascript
class DndPlugin extends RectLifecycleInterface {
// Define action type constants as static properties
static ACTION = {
NULL: 0,
MOVE: 1,
RESIZE_NW: 2,
RESIZE_NE: 3,
RESIZE_SW: 4,
RESIZE_SE: 5,
RESIZE_N: 6,
RESIZE_S: 7,
RESIZE_W: 8,
RESIZE_E: 9,
};
// Define the ACTION_TABLE as a static property for quick lookup
static ACTION_TABLE = [
[DndPlugin.ACTION.RESIZE_NW, DndPlugin.ACTION.RESIZE_NW, DndPlugin.ACTION.RESIZE_NW, DndPlugin.ACTION.NULL, DndPlugin.ACTION.RESIZE_NE, DndPlugin.ACTION.RESIZE_NE, DndPlugin.ACTION.RESIZE_NE ],
[DndPlugin.ACTION.RESIZE_NW, DndPlugin.ACTION.RESIZE_NW, DndPlugin.ACTION.RESIZE_NW, DndPlugin.ACTION.RESIZE_N, DndPlugin.ACTION.RESIZE_NE, DndPlugin.ACTION.RESIZE_NE, DndPlugin.ACTION.RESIZE_NE ],
[DndPlugin.ACTION.RESIZE_NW, DndPlugin.ACTION.RESIZE_NW, DndPlugin.ACTION.RESIZE_NW, DndPlugin.ACTION.MOVE, DndPlugin.ACTION.RESIZE_NE, DndPlugin.ACTION.RESIZE_NE, DndPlugin.ACTION.RESIZE_NE ],
[DndPlugin.ACTION.NULL, DndPlugin.ACTION.RESIZE_W, DndPlugin.ACTION.MOVE, DndPlugin.ACTION.MOVE, DndPlugin.ACTION.MOVE, DndPlugin.ACTION.RESIZE_E, DndPlugin.ACTION.NULL ],
[DndPlugin.ACTION.RESIZE_SW, DndPlugin.ACTION.RESIZE_SW, DndPlugin.ACTION.RESIZE_SW, DndPlugin.ACTION.MOVE, DndPlugin.ACTION.RESIZE_SE, DndPlugin.ACTION.RESIZE_SE, DndPlugin.ACTION.RESIZE_SE ],
[DndPlugin.ACTION.RESIZE_SW, DndPlugin.ACTION.RESIZE_SW, DndPlugin.ACTION.RESIZE_SW, DndPlugin.ACTION.RESIZE_S, DndPlugin.ACTION.RESIZE_SE, DndPlugin.ACTION.RESIZE_SE, DndPlugin.ACTION.RESIZE_SE ],
[DndPlugin.ACTION.RESIZE_SW, DndPlugin.ACTION.RESIZE_SW, DndPlugin.ACTION.RESIZE_SW, DndPlugin.ACTION.NULL, DndPlugin.ACTION.RESIZE_SE, DndPlugin.ACTION.RESIZE_SE, DndPlugin.ACTION.RESIZE_SE ],
];
constructor() {
super();
this.currentRect = null;
this.action = DndPlugin.ACTION.NULL;
this.host = null;
this.startX = 0;
this.startY = 0;
this.startRect = null;
this.boundOnMouseMove = this.onMouseMove.bind(this);
this.boundOnMouseUp = this.onMouseUp.bind(this);
this.listeners = new WeakMap();
// Optimization for requestAnimationFrame
this.isAnimating = false;
this.latestRect = null;
// Minimum size constraints
this.MIN_WIDTH = 50; // Minimum width in pixels
this.MIN_HEIGHT = 50; // Minimum height in pixels
}
attach(host) {
if (host) {
this.host = host;
}
return null;
}
onRectCreate(rect, element) {
const callback = this.onMouseDown.bind(this, rect);
this.listeners.set(element, callback);
element.addEventListener('mousedown', callback);
}
onRectRemove(rect, element) {
const callback = this.listeners.get(element);
if (callback) {
element.removeEventListener('mousedown', callback);
this.listeners.delete(element);
}
}
onMouseDown(rect, e) {
const rectElement = e.target;
if (!rectElement) return;
const rectStyle = rectElement.style;
const width = parseInt(rectStyle.getPropertyValue('--width'), 10);
const height = parseInt(rectStyle.getPropertyValue('--height'), 10);
const borderSize = parseInt(rectStyle.getPropertyValue('--border-size') || getComputedStyle(this.host).getPropertyValue('--border-size'), 10) || 6;
const vertexSize = parseInt(rectStyle.getPropertyValue('--vertex-size') || getComputedStyle(this.host).getPropertyValue('--vertex-size'), 10) || 0;
const bbox = rectElement.getBoundingClientRect();
const cursorOffsetX = e.clientX - bbox.left;
const cursorOffsetY = e.clientY - bbox.top;
const xOffset = width - borderSize;
const yOffset = height - borderSize;
const halfVertexMinusBorder = (vertexSize - borderSize) / 2;
const halfVertexPlusBorder = (vertexSize + borderSize) / 2;
const minX = -halfVertexMinusBorder;
const maxX = halfVertexPlusBorder + xOffset;
// Sorted array excluding the first and last elements
const x_sorted = [
0, // 0
borderSize, // 1
halfVertexPlusBorder, // 2
-halfVertexMinusBorder + xOffset, // 3
width - borderSize, // 4
width // 5
// 6
];
// Check if cursorOffsetX is outside the boundaries
if (cursorOffsetX < minX || cursorOffsetX > maxX) {
return;
}
// Find the appropriate index in the sorted X array using a fast linear search
let xi = 0;
const xLength = x_sorted.length;
while (xi < xLength && cursorOffsetX >= x_sorted[xi]) {
xi++;
}
const minY = minX;
const maxY = halfVertexPlusBorder + yOffset;
const y_sorted = [
0, // 0
borderSize, // 1
halfVertexPlusBorder, // 2
-halfVertexMinusBorder + yOffset, // 3
height - borderSize, // 4
height // 5
// 6
];
// Check if cursorOffsetY is outside the boundaries
if (cursorOffsetY < minY || cursorOffsetY > maxY) {
return;
}
// Find the appropriate index in the sorted Y array using a fast linear search
let yi = 0;
const yLength = y_sorted.length;
while (yi < yLength && cursorOffsetY >= y_sorted[yi]) {
yi++;
}
this.action = DndPlugin.ACTION_TABLE[yi][xi];
if (this.action === DndPlugin.ACTION.NULL) {
return;
}
this.startX = e.clientX;
this.startY = e.clientY;
this.currentRect = rect;
this.startRect = {
x: parseInt(rectStyle.left, 10),
y: parseInt(rectStyle.top, 10),
width,
height
};
e.preventDefault();
document.addEventListener('mousemove', this.boundOnMouseMove);
document.addEventListener('mouseup', this.boundOnMouseUp);
}
onMouseMove(e) {
if (!this.currentRect) return;
const dx = e.clientX - this.startX;
const dy = e.clientY - this.startY;
let { x: newX, y: newY, width: newWidth, height: newHeight } = this.startRect;
const action = this.action;
switch(action) {
case DndPlugin.ACTION.MOVE:
newX += dx;
newY += dy;
break;
case DndPlugin.ACTION.RESIZE_NW:
newX += dx;
newY += dy;
newWidth -= dx;
newHeight -= dy;
break;
case DndPlugin.ACTION.RESIZE_NE:
newY += dy;
newWidth += dx;
newHeight -= dy;
break;
case DndPlugin.ACTION.RESIZE_SW:
newX += dx;
newWidth -= dx;
newHeight += dy;
break;
case DndPlugin.ACTION.RESIZE_SE:
newWidth += dx;
newHeight += dy;
break;
case DndPlugin.ACTION.RESIZE_N:
newY += dy;
newHeight -= dy;
break;
case DndPlugin.ACTION.RESIZE_S:
newHeight += dy;
break;
case DndPlugin.ACTION.RESIZE_W:
newX += dx;
newWidth -= dx;
break;
case DndPlugin.ACTION.RESIZE_E:
newWidth += dx;
break;
default:
return; // No action
}
// Apply minimum size constraints
newWidth = Math.max(newWidth, this.MIN_WIDTH);
newHeight = Math.max(newHeight, this.MIN_HEIGHT);
// Adjust position if resizing from the west or north
if ([DndPlugin.ACTION.RESIZE_NW, DndPlugin.ACTION.RESIZE_SW, DndPlugin.ACTION.RESIZE_W].includes(action)) {
newX = this.startRect.x + (this.startRect.width - newWidth);
}
if ([DndPlugin.ACTION.RESIZE_NW, DndPlugin.ACTION.RESIZE_NE, DndPlugin.ACTION.RESIZE_N].includes(action)) {
newY = this.startRect.y + (this.startRect.height - newHeight);
}
// Store the latest desired rectangle state
this.latestRect = { x: newX, y: newY, width: newWidth, height: newHeight };
// Schedule an update via requestAnimationFrame if not already scheduled
if (!this.isAnimating) {
this.isAnimating = true;
requestAnimationFrame(() => {
this.updateRect(this.latestRect);
this.isAnimating = false;
this.latestRect = null;
});
}
}
updateRect(newRect) {
const updates = {};
for (const key in newRect) {
if (newRect[key] !== this.startRect[key]) {
updates[key] = newRect[key];
}
}
if (Object.keys(updates).length > 0) {
this.currentRect.update(updates);
}
}
onMouseUp() {
document.removeEventListener('mousemove', this.boundOnMouseMove);
document.removeEventListener('mouseup', this.boundOnMouseUp);
this.currentRect = null;
this.action = DndPlugin.ACTION.NULL;
// Reset animation flags
this.isAnimating = false;
this.latestRect = null;
}
}
Explanation of Changes:
Action Type Constants:
All action types (RESIZE_NW, MOVE, etc.) are defined within a static ACTION object inside the DndPlugin class. This encapsulates them and prevents global namespace pollution.
Numeric values are assigned to each action type for faster comparisons and switch-case performance.
ACTION_TABLE:
The ACTION_TABLE is moved inside the class as a static property. This ensures it's only initialized once per class, not per instance, saving memory and initialization time.
The table references the static ACTION constants for better readability and maintainability.
Event Handlers:
The event listeners for mousemove and mouseup are bound once in the constructor using .bind(this), ensuring the correct this context without repeatedly binding during each onMouseDown event.
Optimized Loops:
Replaced the for loops with while loops for potentially faster iteration when finding the appropriate index in x_sorted and y_sorted arrays.
Cached the length of sorted arrays to avoid recalculating .length during each iteration.
Action Handling:
Used a switch statement to handle different actions efficiently based on the numeric constants.
Grouped similar actions for position adjustments to reduce redundant code.
Animation Optimization:
Ensured that only one animation frame is requested at a time by using the isAnimating flag.
Stored the latest rectangle state to apply all changes in a single update, reducing layout thrashing.
Minimum Size Constraints:
Applied minimum width and height constraints to prevent the rectangle from becoming too small during resizing.
Code Cleanliness:
Removed unnecessary comments and organized the code for better readability.
Ensured that all dynamic properties are updated only when necessary to minimize DOM interactions.
Benefits of This Refactoring:
Encapsulation: By moving constants inside the class, we reduce the risk of naming collisions and improve modularity.
Performance: Numeric constants and optimized loops can lead to faster execution, especially during frequent events like mousemove.
Maintainability: Having all related constants and logic within the class makes the code easier to understand and maintain.
Memory Efficiency: Static properties ensure that constants are shared across all instances, saving memory.
This refactored version maintains the original functionality while improving performance and code organization.