To extend your existing rectangle management system with drag-and-drop (DnD) functionality, we'll implement three new plugins:
- DndPlugin: Handles the setup of drag-and-drop listeners on rectangles and emits custom events during drag operations.
- DndMovePlugin: Listens to DndPlugin's events to handle moving rectangles.
- DndResizePlugin: Listens to DndPlugin's events to handle resizing rectangles.
These plugins will interact via the Shadow DOM's event system using CustomEvent. This ensures that plugins remain independent and communicate effectively without being tightly coupled.
Below is the complete implementation, including the new plugins and their integration into your existing system.
1. Implementing the DnD Plugins
a. DndPlugin
This plugin sets up mouse event listeners (mousedown, mousemove, mouseup) on each rectangle to detect drag operations and emits corresponding custom events (dragstart, dragmove, dragend).
// DndPlugin Implementation
class DndPlugin extends PluginInterface {
constructor(options = {}) {
super();
this.listeners = new WeakMap(); // To keep track of event handlers per rectangle
this.host = null;
}
/**
* Attaches the plugin by setting up necessary event listeners.
* @param {HTMLElement} host - The shadow host element.
* @returns [base, additional] - An array containing 'base' and 'additional' CSS rules.
*/
attach(host) {
this.host = host;
// No global CSS needed for DnD
return ['', ''];
}
/**
* Detaches the plugin by cleaning up all event listeners.
* @param {HTMLElement} host - The shadow host element.
*/
detach(host) {
// Assuming we have references to all rectangles elsewhere,
// but since we don't, this method won't remove individual listeners.
// Alternatively, manage a registry of rectangles if needed.
}
/**
* Provides no additional CSS.
* @returns [base, additional] - An array containing empty CSS rules.
*/
getCSS() {
return ['', ''];
}
/**
* Called when a rectangle is created. Sets up event listeners for drag operations.
* @param {HTMLElement} rect - The rectangle element.
*/
onRectCreate(rect) {
const onMouseDown = (e) => {
if (e.button !== 0) return; // Only respond to left-click
const rectInitial = rect.getBoundingClientRect();
const containerRect = this.host.getBoundingClientRect();
const startX = e.clientX - containerRect.left;
const startY = e.clientY - containerRect.top;
const onMouseMove = (moveEvent) => {
const currentX = moveEvent.clientX - containerRect.left;
const currentY = moveEvent.clientY - containerRect.top;
const deltaX = currentX - startX;
const deltaY = currentY - startY;
this.host.dispatchEvent(new CustomEvent('dragmove', {
detail: { rect, deltaX, deltaY },
bubbles: true,
composed: true,
}));
};
const onMouseUp = () => {
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', onMouseUp);
this.host.dispatchEvent(new CustomEvent('dragend', {
detail: { rect },
bubbles: true,
composed: true,
}));
};
this.host.dispatchEvent(new CustomEvent('dragstart', {
detail: { rect, startX, startY },
bubbles: true,
composed: true,
}));
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mouseup', onMouseUp);
};
rect.addEventListener('mousedown', onMouseDown);
this.listeners.set(rect, onMouseDown);
}
/**
* Cleans up event listeners when a rectangle is removed.
* @param {HTMLElement} rect - The rectangle element.
*/
onRectRemove(rect) {
const onMouseDown = this.listeners.get(rect);
if (onMouseDown) {
rect.removeEventListener('mousedown', onMouseDown);
this.listeners.delete(rect);
}
}
/**
* Updates global configurations (not needed for DndPlugin).
* @param {Object} options - Options to update.
* @returns [base, additional] - An array containing empty CSS rules.
*/
updateGlobal(options = {}) {
// No global configurations to update
return ['', ''];
}
/**
* Updates per-rectangle configurations (not needed for DndPlugin).
* @param {HTMLElement} rect - The rectangle element.
* @param {Object} options - Options to update.
*/
updateRect(rect, options = {}) {
// No per-rectangle configurations to update
}
}
b. DndMovePlugin
This plugin listens for dragstart, dragmove, and dragend events emitted by DndPlugin to handle moving rectangles.
// DndMovePlugin Implementation
class DndMovePlugin extends PluginInterface {
constructor(options = {}) {
super();
this.host = null;
this.draggingRect = null;
this.initialX = 0;
this.initialY = 0;
}
/**
* Attaches the plugin and sets up event listeners.
* @param {HTMLElement} host - The shadow host element.
* @returns [base, additional] - An array containing 'base' and 'additional' CSS rules.
*/
attach(host) {
this.host = host;
this.handleDragStart = this.onDragStart.bind(this);
this.handleDragMove = this.onDragMove.bind(this);
this.handleDragEnd = this.onDragEnd.bind(this);
host.addEventListener('dragstart', this.handleDragStart);
host.addEventListener('dragmove', this.handleDragMove);
host.addEventListener('dragend', this.handleDragEnd);
return ['', ''];
}
/**
* Detaches the plugin by removing event listeners.
* @param {HTMLElement} host - The shadow host element.
*/
detach(host) {
host.removeEventListener('dragstart', this.handleDragStart);
host.removeEventListener('dragmove', this.handleDragMove);
host.removeEventListener('dragend', this.handleDragEnd);
}
/**
* Provides no additional CSS.
* @returns [base, additional] - An array containing empty CSS rules.
*/
getCSS() {
return ['', ''];
}
/**
* Handles the drag start event.
* @param {CustomEvent} e - The custom dragstart event.
*/
onDragStart(e) {
this.draggingRect = e.detail.rect;
const rectStyle = window.getComputedStyle(this.draggingRect);
this.initialX = parseFloat(rectStyle.left);
this.initialY = parseFloat(rectStyle.top);
}
/**
* Handles the drag move event.
* @param {CustomEvent} e - The custom dragmove event.
*/
onDragMove(e) {
if (!this.draggingRect) return;
const { deltaX, deltaY } = e.detail;
this.draggingRect.style.left = `${this.initialX + deltaX}px`;
this.draggingRect.style.top = `${this.initialY + deltaY}px`;
}
/**
* Handles the drag end event.
* @param {CustomEvent} e - The custom dragend event.
*/
onDragEnd(e) {
this.draggingRect = null;
}
/**
* Updates global configurations (not needed for DndMovePlugin).
* @param {Object} options - Options to update.
* @returns [base, additional] - An array containing empty CSS rules.
*/
updateGlobal(options = {}) {
// No global configurations to update
return ['', ''];
}
/**
* Updates per-rectangle configurations (not needed for DndMovePlugin).
* @param {HTMLElement} rect - The rectangle element.
* @param {Object} options - Options to update.
*/
updateRect(rect, options = {}) {
// No per-rectangle configurations to update
}
}
c. DndResizePlugin
This plugin listens for dragstart, dragmove, and dragend events emitted by DndPlugin to handle resizing rectangles when dragging their edges or vertices.
// DndResizePlugin Implementation
class DndResizePlugin extends PluginInterface {
constructor(options = {}) {
super();
this.host = null;
this.resizingRect = null;
this.startX = 0;
this.startY = 0;
this.startWidth = 0;
this.startHeight = 0;
this.resizeDir = 'bottom-right'; // Default resize direction
}
/**
* Attaches the plugin and sets up event listeners.
* @param {HTMLElement} host - The shadow host element.
* @returns [base, additional] - An array containing 'base' and 'additional' CSS rules.
*/
attach(host) {
this.host = host;
this.handleDragStart = this.onDragStart.bind(this);
this.handleDragMove = this.onDragMove.bind(this);
this.handleDragEnd = this.onDragEnd.bind(this);
host.addEventListener('dragstart', this.handleDragStart);
host.addEventListener('dragmove', this.handleDragMove);
host.addEventListener('dragend', this.handleDragEnd);
return ['', ''];
}
/**
* Detaches the plugin by removing event listeners.
* @param {HTMLElement} host - The shadow host element.
*/
detach(host) {
host.removeEventListener('dragstart', this.handleDragStart);
host.removeEventListener('dragmove', this.handleDragMove);
host.removeEventListener('dragend', this.handleDragEnd);
}
/**
* Provides no additional CSS.
* @returns [base, additional] - An array containing empty CSS rules.
*/
getCSS() {
return ['', ''];
}
/**
* Determines if the drag start position is on an edge or vertex for resizing.
* @param {HTMLElement} rect - The rectangle element.
* @param {Object} pos - The position where drag started.
* @returns {Boolean} - True if applicable for resize, else false.
*/
isApplicable(rect, pos) {
const rectBound = rect.getBoundingClientRect();
const margin = 10; // Pixels within the edge to detect resizing
const { startX, startY } = pos;
const inLeft = Math.abs(startX - rect.offsetLeft) < margin;
const inRight = Math.abs(startX - (rect.offsetLeft + rect.offsetWidth)) < margin;
const inTop = Math.abs(startY - rect.offsetTop) < margin;
const inBottom = Math.abs(startY - (rect.offsetTop + rect.offsetHeight)) < margin;
if ((inLeft || inRight) && (inTop || inBottom)) {
this.resizeDir = `${inLeft ? 'left' : 'right'}-${inTop ? 'top' : 'bottom'}`;
return true;
}
return false;
}
/**
* Handles the drag start event for resizing.
* @param {CustomEvent} e - The custom dragstart event.
*/
onDragStart(e) {
const { rect, startX, startY } = e.detail;
if (this.isApplicable(rect, { startX, startY })) {
this.resizingRect = rect;
this.startX = startX;
this.startY = startY;
const rectStyle = window.getComputedStyle(this.resizingRect);
this.startWidth = parseFloat(rectStyle.getPropertyValue('--width'));
this.startHeight = parseFloat(rectStyle.getPropertyValue('--height'));
e.preventDefault(); // Prevent move plugin from handling this drag
}
}
/**
* Handles the drag move event for resizing.
* @param {CustomEvent} e - The custom dragmove event.
*/
onDragMove(e) {
if (!this.resizingRect) return;
const { deltaX, deltaY } = e.detail;
let newWidth = this.startWidth;
let newHeight = this.startHeight;
let newLeft = parseFloat(this.resizingRect.style.left || '0');
let newTop = parseFloat(this.resizingRect.style.top || '0');
if (this.resizeDir.includes('right')) {
newWidth += deltaX;
}
if (this.resizeDir.includes('left')) {
newWidth -= deltaX;
newLeft += deltaX;
}
if (this.resizeDir.includes('bottom')) {
newHeight += deltaY;
}
if (this.resizeDir.includes('top')) {
newHeight -= deltaY;
newTop += deltaY;
}
// Minimum size constraints
newWidth = Math.max(newWidth, 50);
newHeight = Math.max(newHeight, 50);
this.resizingRect.style.setProperty('--width', `${newWidth}px`);
this.resizingRect.style.setProperty('--height', `${newHeight}px`);
this.resizingRect.style.left = `${newLeft}px`;
this.resizingRect.style.top = `${newTop}px`;
}
/**
* Handles the drag end event for resizing.
* @param {CustomEvent} e - The custom dragend event.
*/
onDragEnd(e) {
this.resizingRect = null;
}
/**
* Updates global configurations (not needed for DndResizePlugin).
* @param {Object} options - Options to update.
* @returns [base, additional] - An array containing empty CSS rules.
*/
updateGlobal(options = {}) {
// No global configurations to update
return ['', ''];
}
/**
* Updates per-rectangle configurations (not needed for DndResizePlugin).
* @param {HTMLElement} rect - The rectangle element.
* @param {Object} options - Options to update.
*/
updateRect(rect, options = {}) {
// No per-rectangle configurations to update
}
}
2. Integrating DnD Plugins into the System
To integrate the new plugins, follow these steps:
- Instantiate the Plugins: Create instances of the new plugins.
- Register the Plugins with the Factory: Update the factory to include the new plugins.
- Handle Rectangle Creation: Ensure that
DndPlugin sets up event listeners when rectangles are created.
a. Extending the Rectangle Factory to Notify Plugins on Creation
Modify the RectWrapper to notify all plugins when a rectangle is created or removed. Specifically, call onRectCreate and onRectRemove on each plugin during these lifecycle events.
// Updated Rectangle Wrapper
class RectWrapper {
/**
* Creates a RectWrapper instance.
* @param {HTMLElement} rect - The rectangle element.
* @param {RectRegionShapeFactory} factory - Reference to the factory.
*/
constructor(rect, factory) {
this.rect = rect;
this.factory = factory;
this.pluginOptions = new Map(); // To keep track of per-plugin options for this rectangle
// Notify all plugins about the creation of this rectangle
this.factory.plugins.forEach((plugin) => {
if (typeof plugin.onRectCreate === 'function') {
plugin.onRectCreate(this.rect);
}
});
}
/**
* Removes the rectangle from the DOM and cleans up plugin-specific settings.
*/
remove() {
// Clean up plugin-specific settings
this.factory.plugins.forEach((plugin) => {
if (typeof plugin.onRectRemove === 'function') {
plugin.onRectRemove(this.rect);
}
});
// Remove the rectangle from the DOM
this.rect.remove();
}
/**
* Updates the rectangle's properties and applies plugin-specific updates.
* @param {Object} positionalOptions - New positional and size properties.
* @param {Array} pluginUpdates - Array of plugin updates in the format [[PluginClass, options], ...].
*/
update(positionalOptions = {}, pluginUpdates = []) {
const { x, y, width, height } = positionalOptions;
// Update position
if (x !== undefined) {
this.rect.style.left = typeof x === 'number' ? `${x}px` : x;
}
if (y !== undefined) {
this.rect.style.top = typeof y === 'number' ? `${y}px` : y;
}
// Update size
if (width !== undefined) {
this.rect.style.setProperty('--width', typeof width === 'number' ? `${width}px` : width);
}
if (height !== undefined) {
this.rect.style.setProperty('--height', typeof height === 'number' ? `${height}px` : height);
}
// Apply plugin-specific updates
pluginUpdates.forEach(([PluginClass, options]) => {
const plugin = this.factory.plugins.get(PluginClass);
if (plugin) {
plugin.updateRect(this.rect, options);
// Store the options for potential future use or cleanup
if (!this.pluginOptions.has(PluginClass)) {
this.pluginOptions.set(PluginClass, {});
}
const existingOptions = this.pluginOptions.get(PluginClass);
this.pluginOptions.set(PluginClass, { ...existingOptions, ...options });
} else {
console.warn(`Plugin ${PluginClass.name} not found.`);
}
});
// Note: No need to re-render global CSS for per-rectangle updates
}
}
b. Registering All Plugins with the Factory
Instantiate all plugins, including the new DnD-related plugins, and pass them to the RectRegionShapeFactory.
// Usage Example
// Instantiate plugins
const plugins = [
new BorderPlugin({ size: '3px', color: '#2c3e50' }),
new VertexPlugin({ size: '20px', color: '#e74c3c' }),
new DndPlugin(),
new DndMovePlugin(),
new DndResizePlugin(),
];
// Get the container element
const container = document.getElementById('rectangle-container');
// Instantiate the factory with all plugins
const factory = new RectRegionShapeFactory(container, plugins);
// Create multiple rectangles with different properties
const rect1 = factory.createRect(50, 50, 200, 100);
const rect2 = factory.createRect(300, 150, 150, 150);
3. Handling Plugin Dependencies and Independence
To maintain the independence of plugins while allowing DndMovePlugin and DndResizePlugin to depend on events emitted by DndPlugin, we utilize the Shadow DOM's event system. DndPlugin emits dragstart, dragmove, and dragend events on the shadow host, which other plugins listen to without direct references.
This approach ensures that plugins remain decoupled and only communicate through a standardized event interface.
4. Final Complete Code
Combining all the components, here's the comprehensive code integrating the new DnD functionality:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Rectangle Manager with DnD Plugins</title>
<style>
/* Basic styles for the container */
#rectangle-container {
width: 800px;
height: 600px;
border: 1px solid #ccc;
position: relative;
margin: 20px auto;
}
</style>
</head>
<body>
<div id="rectangle-container"></div>
<script>
// PluginInterface Implementation
class PluginInterface {
/**
* Attaches the plugin to the system by setting global CSS variables and returning CSS rules.
* @param {HTMLElement} host - The shadow host element.
* @returns [base, additional] - An array containing 'base' and 'additional' CSS rules.
*/
attach(host) {
throw new Error('attach method must be implemented by the plugin.');
}
/**
* Detaches the plugin from the system by removing global CSS variables and performing cleanup.
* @param {HTMLElement} host - The shadow host element.
*/
detach(host) {
throw new Error('detach method must be implemented by the plugin.');
}
/**
* Updates global configurations and returns the updated CSS.
* @param {Object} options - Options to update.
* @returns [base, additional] - An array containing 'base' and 'additional' CSS rules.
*/
updateGlobal(options = {}) {
throw new Error('updateGlobal method must be implemented by the plugin.');
}
/**
* Updates per-rectangle configurations.
* @param {HTMLElement} rect - The rectangle element.
* @param {Object} options - Options to update.
*/
updateRect(rect, options = {}) {
throw new Error('updateRect method must be implemented by the plugin.');
}
/**
* Cleans up per-rectangle configurations if necessary.
* @param {HTMLElement} rect - The rectangle element.
*/
onRectRemove(rect) {
throw new Error('onRectRemove method must be implemented by the plugin.');
}
}
// BorderPlugin Implementation (Same as provided previously)
class BorderPlugin extends PluginInterface {
constructor(options = {}) {
super();
this.size = options.size || '2px';
this.color = options.color || '#000';
this.host = null;
this.updateCSS();
}
/**
* Updates the CSS rules based on current configurations.
*/
updateCSS() {
this.baseRule = `
border: var(--border-size, ${this.size}) solid var(--border-color, ${this.color});
`;
// BorderPlugin doesn't have additional CSS rules
this.additionalCSS = '';
}
/**
* Attaches the plugin by setting global CSS variables and returning CSS rules.
* @param {HTMLElement} host - The shadow host element.
* @returns [base, additional] - An array containing 'base' and 'additional' CSS rules.
*/
attach(host) {
if (host) {
this.host = host;
}
host = this.host;
host.style.setProperty('--border-size', this.size);
host.style.setProperty('--border-color', this.color);
this.updateCSS();
return [this.baseRule, this.additionalCSS];
}
/**
* Detaches the plugin by removing global CSS variables.
* @param {HTMLElement} host - The shadow host element.
*/
detach(host) {
host.style.removeProperty('--border-size');
host.style.removeProperty('--border-color');
}
/**
* Provides the updated CSS rules for borders.
* @returns [base, additional] - An array containing 'base' and 'additional' CSS rules.
*/
getCSS() {
return [this.baseRule, this.additionalCSS];
}
/**
* Updates global configurations and returns the updated CSS.
* @param {Object} options - Options to update.
* @returns [base, additional] - An array containing 'base' and 'additional' CSS rules.
*/
updateGlobal(options = {}) {
if (options.size) this.size = options.size;
if (options.color) this.color = options.color;
return this.attach();
}
/**
* Updates per-rectangle configurations by setting CSS variables on the rectangle.
* @param {HTMLElement} rect - The rectangle element.
* @param {Object} options - Options to update.
*/
updateRect(rect, options = {}) {
if (options.size) {
rect.style.setProperty('--border-size', typeof options.size === 'number' ? `${options.size}px` : options.size);
}
if (options.color) {
rect.style.setProperty('--border-color', options.color);
}
}
/**
* Cleans up per-rectangle configurations by removing CSS variables.
* @param {HTMLElement} rect - The rectangle element.
*/
onRectRemove(rect) {
rect.style.removeProperty('--border-size');
rect.style.removeProperty('--border-color');
}
}
// VertexPlugin Implementation (Same as provided previously)
class VertexPlugin extends PluginInterface {
constructor(options = {}) {
super();
this.size = options.size || '25px';
this.color = options.color || '#3498db';
this.host = null;
this.updateCSS();
}
/**
* Updates the CSS rules based on current configurations.
*/
updateCSS() {
// VertexPlugin doesn't have base CSS for .rect-region
this.baseRule = '';
this.additionalCSS = `
.rect-region::before {
content: '';
position: absolute;
width: var(--vertex-size, ${this.size});
height: var(--vertex-size, ${this.size});
background-color: var(--vertex-color, ${this.color});
box-sizing: border-box;
/* Intermediate variables */
--offset: calc(-0.5 * (var(--border-size, 2px) + var(--vertex-size)));
--adjusted-width: calc(var(--width) - var(--border-size, 2px));
--adjusted-height: calc(var(--height) - var(--border-size, 2px));
/* Positioning the first vertex */
top: var(--offset);
left: var(--offset);
/* Creating three more vertices using box-shadow, positioned at each corner */
box-shadow:
var(--adjusted-width) 0 0 0 var(--vertex-color),
var(--adjusted-width) var(--adjusted-height) 0 0 var(--vertex-color),
0 var(--adjusted-height) 0 0 var(--vertex-color);
}
`;
}
/**
* Attaches the plugin by setting global CSS variables and returning CSS rules.
* @param {HTMLElement} host - The shadow host element.
* @returns [base, additional] - An array containing 'base' and 'additional' CSS rules.
*/
attach(host) {
if (host) {
this.host = host;
}
host = this.host;
host.style.setProperty('--vertex-size', this.size);
host.style.setProperty('--vertex-color', this.color);
this.updateCSS();
return [this.baseRule, this.additionalCSS];
}
/**
* Detaches the plugin by removing global CSS variables.
* @param {HTMLElement} host - The shadow host element.
*/
detach(host) {
host.style.removeProperty('--vertex-size');
host.style.removeProperty('--vertex-color');
}
/**
* Provides the updated CSS rules for vertices.
* @returns [base, additional] - An array containing 'base' and 'additional' CSS rules.
*/
getCSS() {
return [this.baseRule, this.additionalCSS];
}
/**
* Updates global configurations and returns the updated CSS.
* @param {Object} options - Options to update.
* @returns [base, additional] - An array containing 'base' and 'additional' CSS rules.
*/
updateGlobal(options = {}) {
if (options.size) this.size = options.size;
if (options.color) this.color = options.color;
return this.attach();
}
/**
* Updates per-rectangle configurations by setting CSS variables on the rectangle.
* @param {HTMLElement} rect - The rectangle element.
* @param {Object} options - Options to update.
*/
updateRect(rect, options = {}) {
if (options.size) {
rect.style.setProperty('--vertex-size', typeof options.size === 'number' ? `${options.size}px` : options.size);
}
if (options.color) {
rect.style.setProperty('--vertex-color', options.color);
}
}
/**
* Cleans up per-rectangle configurations by removing CSS variables.
* @param {HTMLElement} rect - The rectangle element.
*/
onRectRemove(rect) {
rect.style.removeProperty('--vertex-size');
rect.style.removeProperty('--vertex-color');
}
}
// DndPlugin Implementation (As implemented above)
class DndPlugin extends PluginInterface {
constructor(options = {}) {
super();
this.listeners = new WeakMap(); // To keep track of event handlers per rectangle
this.host = null;
}
/**
* Attaches the plugin by setting up necessary event listeners.
* @param {HTMLElement} host - The shadow host element.
* @returns [base, additional] - An array containing 'base' and 'additional' CSS rules.
*/
attach(host) {
this.host = host;
// No global CSS needed for DnD
return ['', ''];
}
/**
* Detaches the plugin by cleaning up all event listeners.
* @param {HTMLElement} host - The shadow host element.
*/
detach(host) {
// Assuming we have references to all rectangles elsewhere,
// but since we don't, this method won't remove individual listeners.
// Alternatively, manage a registry of rectangles if needed.
}
/**
* Provides no additional CSS.
* @returns [base, additional] - An array containing empty CSS rules.
*/
getCSS() {
return ['', ''];
}
/**
* Called when a rectangle is created. Sets up event listeners for drag operations.
* @param {HTMLElement} rect - The rectangle element.
*/
onRectCreate(rect) {
const onMouseDown = (e) => {
if (e.button !== 0) return; // Only respond to left-click
const rectInitial = rect.getBoundingClientRect();
const containerRect = this.host.getBoundingClientRect();
const startX = e.clientX - containerRect.left;
const startY = e.clientY - containerRect.top;
const onMouseMove = (moveEvent) => {
const currentX = moveEvent.clientX - containerRect.left;
const currentY = moveEvent.clientY - containerRect.top;
const deltaX = currentX - startX;
const deltaY = currentY - startY;
this.host.dispatchEvent(new CustomEvent('dragmove', {
detail: { rect, deltaX, deltaY },
bubbles: true,
composed: true,
}));
};
const onMouseUp = () => {
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', onMouseUp);
this.host.dispatchEvent(new CustomEvent('dragend', {
detail: { rect },
bubbles: true,
composed: true,
}));
};
this.host.dispatchEvent(new CustomEvent('dragstart', {
detail: { rect, startX, startY },
bubbles: true,
composed: true,
}));
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mouseup', onMouseUp);
};
rect.addEventListener('mousedown', onMouseDown);
this.listeners.set(rect, onMouseDown);
}
/**
* Cleans up event listeners when a rectangle is removed.
* @param {HTMLElement} rect - The rectangle element.
*/
onRectRemove(rect) {
const onMouseDown = this.listeners.get(rect);
if (onMouseDown) {
rect.removeEventListener('mousedown', onMouseDown);
this.listeners.delete(rect);
}
}
/**
* Updates global configurations (not needed for DndPlugin).
* @param {Object} options - Options to update.
* @returns [base, additional] - An array containing empty CSS rules.
*/
updateGlobal(options = {}) {
// No global configurations to update
return ['', ''];
}
/**
* Updates per-rectangle configurations (not needed for DndPlugin).
* @param {HTMLElement} rect - The rectangle element.
* @param {Object} options - Options to update.
*/
updateRect(rect, options = {}) {
// No per-rectangle configurations to update
}
}
// DndMovePlugin Implementation (As implemented above)
class DndMovePlugin extends PluginInterface {
constructor(options = {}) {
super();
this.host = null;
this.draggingRect = null;
this.initialX = 0;
this.initialY = 0;
}
/**
* Attaches the plugin and sets up event listeners.
* @param {HTMLElement} host - The shadow host element.
* @returns [base, additional] - An array containing 'base' and 'additional' CSS rules.
*/
attach(host) {
this.host = host;
this.handleDragStart = this.onDragStart.bind(this);
this.handleDragMove = this.onDragMove.bind(this);
this.handleDragEnd = this.onDragEnd.bind(this);
host.addEventListener('dragstart', this.handleDragStart);
host.addEventListener('dragmove', this.handleDragMove);
host.addEventListener('dragend', this.handleDragEnd);
return ['', ''];
}
/**
* Detaches the plugin by removing event listeners.
* @param {HTMLElement} host - The shadow host element.
*/
detach(host) {
host.removeEventListener('dragstart', this.handleDragStart);
host.removeEventListener('dragmove', this.handleDragMove);
host.removeEventListener('dragend', this.handleDragEnd);
}
/**
* Provides no additional CSS.
* @returns [base, additional] - An array containing empty CSS rules.
*/
getCSS() {
return ['', ''];
}
/**
* Handles the drag start event.
* @param {CustomEvent} e - The custom dragstart event.
*/
onDragStart(e) {
this.draggingRect = e.detail.rect;
const rectStyle = window.getComputedStyle(this.draggingRect);
this.initialX = parseFloat(rectStyle.left);
this.initialY = parseFloat(rectStyle.top);
}
/**
* Handles the drag move event.
* @param {CustomEvent} e - The custom dragmove event.
*/
onDragMove(e) {
if (!this.draggingRect) return;
const { deltaX, deltaY } = e.detail;
this.draggingRect.style.left = `${this.initialX + deltaX}px`;
this.draggingRect.style.top = `${this.initialY + deltaY}px`;
}
/**
* Handles the drag end event.
* @param {CustomEvent} e - The custom dragend event.
*/
onDragEnd(e) {
this.draggingRect = null;
}
/**
* Updates global configurations (not needed for DndMovePlugin).
* @param {Object} options - Options to update.
* @returns [base, additional] - An array containing empty CSS rules.
*/
updateGlobal(options = {}) {
// No global configurations to update
return ['', ''];
}
/**
* Updates per-rectangle configurations (not needed for DndMovePlugin).
* @param {HTMLElement} rect - The rectangle element.
* @param {Object} options - Options to update.
*/
updateRect(rect, options = {}) {
// No per-rectangle configurations to update
}
}
// DndResizePlugin Implementation (As implemented above)
class DndResizePlugin extends PluginInterface {
constructor(options = {}) {
super();
this.host = null;
this.resizingRect = null;
this.startX = 0;
this.startY = 0;
this.startWidth = 0;
this.startHeight = 0;
this.resizeDir = 'bottom-right'; // Default resize direction
}
/**
* Attaches the plugin and sets up event listeners.
* @param {HTMLElement} host - The shadow host element.
* @returns [base, additional] - An array containing 'base' and 'additional' CSS rules.
*/
attach(host) {
this.host = host;
this.handleDragStart = this.onDragStart.bind(this);
this.handleDragMove = this.onDragMove.bind(this);
this.handleDragEnd = this.onDragEnd.bind(this);
host.addEventListener('dragstart', this.handleDragStart);
host.addEventListener('dragmove', this.handleDragMove);
host.addEventListener('dragend', this.handleDragEnd);
return ['', ''];
}
/**
* Detaches the plugin by removing event listeners.
* @param {HTMLElement} host - The shadow host element.
*/
detach(host) {
host.removeEventListener('dragstart', this.handleDragStart);
host.removeEventListener('dragmove', this.handleDragMove);
host.removeEventListener('dragend', this.handleDragEnd);
}
/**
* Provides no additional CSS.
* @returns [base, additional] - An array containing empty CSS rules.
*/
getCSS() {
return ['', ''];
}
/**
* Determines if the drag start position is on an edge or vertex for resizing.
* @param {HTMLElement} rect - The rectangle element.
* @param {Object} pos - The position where drag started.
* @returns {Boolean} - True if applicable for resize, else false.
*/
isApplicable(rect, pos) {
const rectBound = rect.getBoundingClientRect();
const margin = 10; // Pixels within the edge to detect resizing
const { startX, startY } = pos;
const inLeft = Math.abs(startX - rect.offsetLeft) < margin;
const inRight = Math.abs(startX - (rect.offsetLeft + rect.offsetWidth)) < margin;
const inTop = Math.abs(startY - rect.offsetTop) < margin;
const inBottom = Math.abs(startY - (rect.offsetTop + rect.offsetHeight)) < margin;
if ((inLeft || inRight) && (inTop || inBottom)) {
this.resizeDir = `${inLeft ? 'left' : 'right'}-${inTop ? 'top' : 'bottom'}`;
return true;
}
return false;
}
/**
* Handles the drag start event for resizing.
* @param {CustomEvent} e - The custom dragstart event.
*/
onDragStart(e) {
const { rect, startX, startY } = e.detail;
if (this.isApplicable(rect, { startX, startY })) {
this.resizingRect = rect;
this.startX = startX;
this.startY = startY;
const rectStyle = window.getComputedStyle(this.resizingRect);
this.startWidth = parseFloat(rectStyle.getPropertyValue('--width'));
this.startHeight = parseFloat(rectStyle.getPropertyValue('--height'));
e.preventDefault(); // Prevent move plugin from handling this drag
}
}
/**
* Handles the drag move event for resizing.
* @param {CustomEvent} e - The custom dragmove event.
*/
onDragMove(e) {
if (!this.resizingRect) return;
const { deltaX, deltaY } = e.detail;
let newWidth = this.startWidth;
let newHeight = this.startHeight;
let newLeft = parseFloat(this.resizingRect.style.left || '0');
let newTop = parseFloat(this.resizingRect.style.top || '0');
if (this.resizeDir.includes('right')) {
newWidth += deltaX;
}
if (this.resizeDir.includes('left')) {
newWidth -= deltaX;
newLeft += deltaX;
}
if (this.resizeDir.includes('bottom')) {
newHeight += deltaY;
}
if (this.resizeDir.includes('top')) {
newHeight -= deltaY;
newTop += deltaY;
}
// Minimum size constraints
newWidth = Math.max(newWidth, 50);
newHeight = Math.max(newHeight, 50);
this.resizingRect.style.setProperty('--width', `${newWidth}px`);
this.resizingRect.style.setProperty('--height', `${newHeight}px`);
this.resizingRect.style.left = `${newLeft}px`;
this.resizingRect.style.top = `${newTop}px`;
}
/**
* Handles the drag end event for resizing.
* @param {CustomEvent} e - The custom dragend event.
*/
onDragEnd(e) {
this.resizingRect = null;
}
/**
* Updates global configurations (not needed for DndResizePlugin).
* @param {Object} options - Options to update.
* @returns [base, additional] - An array containing empty CSS rules.
*/
updateGlobal(options = {}) {
// No global configurations to update
return ['', ''];
}
/**
* Updates per-rectangle configurations (not needed for DndResizePlugin).
* @param {HTMLElement} rect - The rectangle element.
* @param {Object} options - Options to update.
*/
updateRect(rect, options = {}) {
// No per-rectangle configurations to update
}
}
// Rectangle Wrapper (Updated to Notify Plugins)
class RectWrapper {
/**
* Creates a RectWrapper instance.
* @param {HTMLElement} rect - The rectangle element.
* @param {RectRegionShapeFactory} factory - Reference to the factory.
*/
constructor(rect, factory) {
this.rect = rect;
this.factory = factory;
this.pluginOptions = new Map(); // To keep track of per-plugin options for this rectangle
// Notify all plugins about the creation of this rectangle
this.factory.plugins.forEach((plugin) => {
if (typeof plugin.onRectCreate === 'function') {
plugin.onRectCreate(this.rect);
}
});
}
/**
* Removes the rectangle from the DOM and cleans up plugin-specific settings.
*/
remove() {
// Clean up plugin-specific settings
this.factory.plugins.forEach((plugin) => {
if (typeof plugin.onRectRemove === 'function') {
plugin.onRectRemove(this.rect);
}
});
// Remove the rectangle from the DOM
this.rect.remove();
}
/**
* Updates the rectangle's properties and applies plugin-specific updates.
* @param {Object} positionalOptions - New positional and size properties.
* @param {Array} pluginUpdates - Array of plugin updates in the format [[PluginClass, options], ...].
*/
update(positionalOptions = {}, pluginUpdates = []) {
const { x, y, width, height } = positionalOptions;
// Update position
if (x !== undefined) {
this.rect.style.left = typeof x === 'number' ? `${x}px` : x;
}
if (y !== undefined) {
this.rect.style.top = typeof y === 'number' ? `${y}px` : y;
}
// Update size
if (width !== undefined) {
this.rect.style.setProperty('--width', typeof width === 'number' ? `${width}px` : width);
}
if (height !== undefined) {
this.rect.style.setProperty('--height', typeof height === 'number' ? `${height}px` : height);
}
// Apply plugin-specific updates
pluginUpdates.forEach(([PluginClass, options]) => {
const plugin = this.factory.plugins.get(PluginClass);
if (plugin) {
plugin.updateRect(this.rect, options);
// Store the options for potential future use or cleanup
if (!this.pluginOptions.has(PluginClass)) {
this.pluginOptions.set(PluginClass, {});
}
const existingOptions = this.pluginOptions.get(PluginClass);
this.pluginOptions.set(PluginClass, { ...existingOptions, ...options });
} else {
console.warn(`Plugin ${PluginClass.name} not found.`);
}
});
// Note: No need to re-render global CSS for per-rectangle updates
}
}
// Rectangle Factory
class RectRegionShapeFactory {
/**
* Constructor to initialize and mount on a container with optional plugins.
* @param {HTMLElement} container - The DOM element to mount the rectangles.
* @param {Array<PluginInterface>} plugins - Array of plugin instances.
*/
constructor(container, plugins = []) {
if (!(container instanceof HTMLElement)) {
throw new Error('Container must be a valid DOM element.');
}
this.container = container;
this.plugins = new Map();
// Create a shadow root on the container
this.shadow = container.attachShadow({ mode: 'open' });
// Initialize a style element inside the shadow DOM
this.styleElement = document.createElement('style');
this.shadow.appendChild(this.styleElement);
// Initialize a container inside the shadow DOM to hold rectangles
this.rectContainer = document.createElement('div');
this.rectContainer.style.position = 'relative'; // Ensures absolute children are positioned correctly
this.shadow.appendChild(this.rectContainer);
this.baseRules = `
.rect-region {
position: absolute;
width: var(--width, 100px);
height: var(--height, 100px);
box-sizing: border-box;
cursor: move; /* Default cursor */
}
`.trim();
// Debounce renderCSS calls using a microtask queue
this.debounceTask = null;
// Register and initialize plugins
plugins.forEach(plugin => {
this.registerPlugin(plugin);
});
// Initially render all CSS
this.renderCSS();
}
/**
* Schedules renderCSS to run as a microtask.
*/
scheduleRenderCSS() {
if (!this.debounceTask) {
this.debounceTask = Promise.resolve().then(() => {
this.renderCSS();
this.debounceTask = null;
});
}
}
/**
* Registers a plugin by attaching it and storing it internally.
* @param {PluginInterface} plugin - The plugin instance.
*/
registerPlugin(plugin) {
if (this.plugins.has(plugin.constructor)) {
console.warn(`Plugin ${plugin.constructor.name} is already registered.`);
return;
}
this.plugins.set(plugin.constructor, plugin);
plugin.attach(this.shadow.host);
this.scheduleRenderCSS();
}
/**
* Unregisters a plugin by detaching it and removing its CSS.
* @param {Function} PluginClass - The plugin's class.
*/
unregisterPlugin(PluginClass) {
const plugin = this.plugins.get(PluginClass);
if (plugin) {
plugin.detach(this.shadow.host);
this.plugins.delete(PluginClass);
this.scheduleRenderCSS();
} else {
console.warn(`Plugin ${PluginClass.name} not found.`);
}
}
/**
* Updates a plugin's global configurations.
* @param {Function} PluginClass - The plugin's class.
* @param {Object} options - Options to update.
*/
updateGlobalPlugin(PluginClass, options = {}) {
const plugin = this.plugins.get(PluginClass);
if (plugin) {
// Update the plugin's global configurations
plugin.updateGlobal(options);
this.scheduleRenderCSS();
} else {
console.warn(`Plugin ${PluginClass.name} not found.`);
}
}
/**
* Aggregates CSS from all plugins and the base styles, then injects into the style element.
*/
renderCSS() {
// Initialize baseRules with the standard .rect-region styles
const baseRulesArray = [this.baseRules];
const additionalRulesArray = []; // Initialize an empty array for additional CSS rules
// Aggregate CSS from all registered plugins
this.plugins.forEach(plugin => {
const css = plugin.getCSS();
let [base, additional] = css;
base = base.trim();
additional = additional.trim();
if (base) {
baseRulesArray.push(base);
}
if (additional) {
additionalRulesArray.push(additional);
}
});
// Combine base and additional CSS rules by joining the arrays with newlines
const aggregatedCSS = `
.rect-region {
${baseRulesArray.join('\n')}
}
${additionalRulesArray.join('\n')}
`;
// Inject the aggregated CSS into the shadow DOM's style element
this.styleElement.textContent = aggregatedCSS;
}
/**
* Creates and appends a rectangle wrapped with plugins.
* @param {number} x - The left position in pixels relative to the container.
* @param {number} y - The top position in pixels relative to the container.
* @param {number} width - Width of the rectangle in pixels.
* @param {number} height - Height of the rectangle in pixels.
* @returns {RectWrapper} - The wrapper object managing the rectangle.
*/
createRect(x, y, width, height) {
// Create the rectangle div
const rect = document.createElement('div');
rect.classList.add('rect-region');
// Set position relative to the shadow container
rect.style.left = `${x}px`;
rect.style.top = `${y}px`;
// Set width and height via CSS variables
rect.style.setProperty('--width', `${width}px`);
rect.style.setProperty('--height', `${height}px`);
// Append the rectangle to the shadow DOM's container
this.rectContainer.appendChild(rect);
// Instantiate the wrapper with reference to this factory and the rectangle
const rectWrapper = new RectWrapper(rect, this);
return rectWrapper;
}
}
// Now, instantiate all plugins including the new DnD plugins
const plugins = [
new BorderPlugin({ size: '3px', color: '#2c3e50' }),
new VertexPlugin({ size: '20px', color: '#e74c3c' }),
new DndPlugin(),
new DndMovePlugin(),
new DndResizePlugin(),
];
// Get the container element
const container = document.getElementById('rectangle-container');
// Instantiate the factory with all plugins
const factory = new RectRegionShapeFactory(container, plugins);
// Create multiple rectangles with different properties
const rect1 = factory.createRect(50, 50, 200, 100);
const rect2 = factory.createRect(300, 150, 150, 150);
// Example: Unregister a plugin after 8 seconds (e.g., remove VertexPlugin)
setTimeout(() => {
factory.unregisterPlugin(VertexPlugin);
console.log('VertexPlugin has been unregistered.');
}, 8000);
// Optional: Add functionality to create rectangles dynamically
// For demonstration purposes, here's how you might add a new rectangle on click
container.addEventListener('dblclick', (e) => {
const rect = factory.createRect(e.offsetX, e.offsetY, 100, 100);
// Optionally, store the rect wrappers if you need to manage them later
});
</script>
</body>
</html>
5. Explanation of Key Components
-
Shadow DOM Usage: The RectRegionShapeFactory attaches a Shadow DOM to the container, encapsulating styles and ensuring that CSS rules from plugins don't leak into the global scope.
-
Plugin Registration and Communication: Plugins are registered with the factory, which in turn manages their attachment and detachment. Communication between plugins is handled via CustomEvents dispatched on the shadow host, allowing independent plugins like DndMovePlugin and DndResizePlugin to respond to events emitted by DndPlugin.
-
Rectangle Lifecycle Management: RectWrapper ensures that all plugins are notified when a rectangle is created or removed, allowing plugins to set up or clean up their respective configurations and event listeners.
-
Dynamic CSS Management: The factory collects CSS rules from all registered plugins and injects them into the Shadow DOM's <style> element, ensuring that all styles are applied cohesively.
-
Drag-and-Drop Functionality:
- Moving: Dragging a rectangle updates its
left and top CSS properties, effectively moving it within the container.
- Resizing: Dragging near the edges or vertices of a rectangle updates its
width, height, and potentially its left and top properties to resize accordingly.
-
Plugin Unregistration: Plugins can be unregistered at runtime, removing their styles and event listeners without affecting other plugins.
6. Testing the Implementation
To test the functionality:
- Drag to Move: Click and drag anywhere inside a rectangle to move it around.
- Drag to Resize: Click and drag near the edges or vertices of a rectangle (within 10 pixels) to resize it.
- Plugin Removal: After 8 seconds, the
VertexPlugin is unregistered, and the vertices will no longer be visible on the rectangles.
- Dynamic Rectangle Creation: Double-click inside the container to create new rectangles dynamically.
This comprehensive implementation ensures a modular, extensible, and maintainable system for managing rectangles with various plugins, including robust drag-and-drop functionality.