refactor and optimize the code for speed and DRY.
"""
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.');
}
}
Updates the CSS rules based on current configurations.
*/
updateCSS() {
this.baseRule = border: var(--border-size, ${this.size}) solid var(--border-color, ${this.color}); ;
code
// BorderPlugin doesn't have additional CSS rules
code
this.additionalCSS = '';
}
/**
Attaches the plugin by setting global CSS variables and returning CSS rules.
@param {HTMLElement} host - The shadow host element.
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');
}
}
// 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
}
/**
Removes the rectangle from the DOM and cleans up plugin-specific settings.
*/
remove() {
// Clean up plugin-specific settings
this.factory.plugins.forEach((plugin, PluginClass) => {
plugin.onRectRemove(this.rect);
});
code
// Remove the rectangle from the DOM
code
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;
code
// Update position
code
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} plugins - Array of plugin instances.
*/
constructor(container, plugins = []) {
if (!(container instanceof HTMLElement)) {
throw new Error('Container must be a valid DOM element.');
}
code
this.container = container;
code
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 = `
position: absolute;
width: var(--width, 100px);
height: var(--height, 100px);
box-sizing: border-box;
`.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];
code
const additionalRulesArray = []; // Initialize an empty array for additional CSS rules
code
// Aggregate CSS from all registered plugins
this.plugins.forEach(plugin => {
const css = plugin.getCSS();
let [base, additional] = css;
base = base.trim().replace(/\}$/, '');
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');
code
// Set position relative to the shadow container
code
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;
// Create a new rectangle to see updated global settings
const rect4 = factory.createRect(100, 300, 150, 150);
const rect5 = factory.createRect(400, 350, 200, 100);
}, 6000);
// Example: Unregister a plugin after 8 seconds (e.g., remove VertexPlugin)
"""
Here's the refactored and optimized version of your code. The primary enhancements include:
Abstracting Common Plugin Functionality: Introduced a BasePlugin class to handle shared logic between plugins, reducing redundancy.
Utility Methods for CSS Variable Management: Added helper methods to set and remove CSS variables efficiently.
Streamlined RectWrapper and RectRegionShapeFactory: Simplified these classes to make them more maintainable and performant.
Enhanced CSS Aggregation: Optimized how CSS rules from plugins are aggregated and injected.
Below is the complete refactored code:
javascript
// PluginInterface Definition
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 {[string, string]} - 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 {[string, string]} - 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.');
}
/**
* Retrieves the current CSS rules.
* @returns {[string, string]} - An array containing 'base' and 'additional' CSS rules.
*/
getCSS() {
throw new Error('getCSS method must be implemented by the plugin.');
}
}
// BasePlugin Implementation to Abstract Common Functionality
class BasePlugin extends PluginInterface {
/**
* Initializes the plugin with default options and CSS variables.
* @param {Object} options - Initial configuration options.
* @param {Object} cssVariables - Mapping of CSS variable names to their default values.
*/
constructor(options = {}, cssVariables = {}) {
super();
this.cssVariables = { ...cssVariables, ...options };
this.host = null;
this.updateCSS();
}
/**
* Updates the CSS rules based on current configurations.
* Should be implemented by derived classes.
*/
updateCSS() {
throw new Error('updateCSS must be implemented by the plugin.');
}
/**
* Sets CSS variables on the host element.
* @param {HTMLElement} host - The shadow host element.
*/
setCSSVariables(host) {
Object.entries(this.cssVariables).forEach(([key, value]) => {
host.style.setProperty(`--${key}`, value);
});
}
/**
* Removes CSS variables from the host element.
* @param {HTMLElement} host - The shadow host element.
*/
removeCSSVariables(host) {
Object.keys(this.cssVariables).forEach(key => {
host.style.removeProperty(`--${key}`);
});
}
/**
* Attaches the plugin by setting CSS variables and updating CSS rules.
* @param {HTMLElement} host - The shadow host element.
* @returns {[string, string]} - An array containing 'base' and 'additional' CSS rules.
*/
attach(host) {
this.host = host;
this.setCSSVariables(host);
this.updateCSS();
return [this.baseRule, this.additionalCSS];
}
/**
* Detaches the plugin by removing CSS variables.
* @param {HTMLElement} host - The shadow host element.
*/
detach(host) {
this.removeCSSVariables(host);
}
/**
* Updates global configurations and CSS variables.
* @param {Object} options - New configuration options.
* @returns {[string, string]} - Updated 'base' and 'additional' CSS rules.
*/
updateGlobal(options = {}) {
this.cssVariables = { ...this.cssVariables, ...options };
this.setCSSVariables(this.host);
this.updateCSS();
return this.getCSS();
}
/**
* Updates per-rectangle CSS variables.
* @param {HTMLElement} rect - The rectangle element.
* @param {Object} options - Options to update.
*/
updateRect(rect, options = {}) {
Object.entries(options).forEach(([key, value]) => {
rect.style.setProperty(`--${key}`, typeof value === 'number' ? `${value}px` : value);
});
}
/**
* Cleans up per-rectangle CSS variables.
* @param {HTMLElement} rect - The rectangle element.
*/
onRectRemove(rect) {
Object.keys(this.cssVariables).forEach(key => {
rect.style.removeProperty(`--${key}`);
});
}
}
// BorderPlugin Implementation
class BorderPlugin extends BasePlugin {
/**
* Initializes the BorderPlugin with default or provided options.
* @param {Object} options - Configuration options for border size and color.
*/
constructor(options = {}) {
const cssVariables = {
'border-size': options.size || '2px',
'border-color': options.color || '#000'
};
super(options, cssVariables);
}
/**
* Updates the CSS rules for the border.
*/
updateCSS() {
this.baseRule = `
border: var(--border-size) solid var(--border-color);
`;
this.additionalCSS = '';
}
}
// VertexPlugin Implementation
class VertexPlugin extends BasePlugin {
/**
* Initializes the VertexPlugin with default or provided options.
* @param {Object} options - Configuration options for vertex size and color.
*/
constructor(options = {}) {
const cssVariables = {
'vertex-size': options.size || '25px',
'vertex-color': options.color || '#3498db'
};
super(options, cssVariables);
}
/**
* Updates the CSS rules for the vertices.
*/
updateCSS() {
this.baseRule = '';
this.additionalCSS = `
.rect-region::before {
content: '';
position: absolute;
width: var(--vertex-size);
height: var(--vertex-size);
background-color: var(--vertex-color);
box-sizing: border-box;
/* Intermediate variables */
--offset: calc(-0.5 * (var(--border-size) + var(--vertex-size)));
--adjusted-width: calc(var(--width) - var(--border-size));
--adjusted-height: calc(var(--height) - var(--border-size));
/* 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);
}
`;
}
}
// 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();
}
/**
* Removes the rectangle from the DOM and cleans up plugin-specific settings.
*/
remove() {
// Clean up plugin-specific settings
this.factory.plugins.forEach(plugin => {
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
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 = `
position: absolute;
width: var(--width, 100px);
height: var(--height, 100px);
box-sizing: border-box;
`.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 = [];
// Aggregate CSS from all registered plugins
this.plugins.forEach(plugin => {
const [base, additional] = plugin.getCSS();
if (base) {
baseRulesArray.push(base.trim());
}
if (additional) {
additionalRulesArray.push(additional.trim());
}
});
// 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
return new RectWrapper(rect, this);
}
}
// Usage Example
// Instantiate plugins
const plugins = [
new BorderPlugin({ size: '3px', color: '#2c3e50' }),
new VertexPlugin({ size: '20px', color: '#e74c3c' })
];
// Get the container element
const container = document.getElementById('rectangle-container');
// Instantiate the factory with 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, 250, 150);
const rect3 = factory.createRect(600, 80, 180, 120); // Uses plugin defaults
// Example: Update rect1 after 2 seconds
setTimeout(() => {
rect1.update(
{ x: 60, y: 60, width: 220, height: 120 },
[
[BorderPlugin, { size: '4px', color: '#8e44ad' }],
[VertexPlugin, { size: '25px', color: '#2980b9' }]
]
);
}, 2000);
// Example: Remove rect2 after 4 seconds
setTimeout(() => {
rect2.remove();
}, 4000);
// Example: Update global plugin settings after 6 seconds
setTimeout(() => {
factory.updateGlobalPlugin(BorderPlugin, { size: '5px', color: 'red' });
factory.updateGlobalPlugin(VertexPlugin, { size: '30px', color: '#f1c40f' });
// Create new rectangles to see updated global settings
factory.createRect(100, 300, 150, 150);
factory.createRect(400, 350, 200, 100);
}, 6000);
// Example: Unregister a plugin after 8 seconds (e.g., remove VertexPlugin)
setTimeout(() => {
factory.unregisterPlugin(VertexPlugin);
}, 8000);
Key Refactoring Highlights:
BasePlugin Class:
Purpose: Centralizes shared logic for setting and removing CSS variables, attaching/detaching plugins, and updating global configurations.
Advantages:
Reduces duplication across plugin implementations.
Simplifies maintenance and future plugin additions.
BorderPlugin and VertexPlugin Enhancements:
Both now extend BasePlugin, inheriting common functionalities.
BorderPlugin: Focuses solely on border-related CSS variables and rules.
VertexPlugin: Manages vertex-related CSS, including pseudo-elements and box-shadow for additional vertices.
RectWrapper Optimization:
Streamlined the way plugin-specific updates are handled.
Ensures that each rectangle can manage its own state concerning different plugins without redundant code.
RectRegionShapeFactory Improvements:
Enhanced CSS aggregation by trimming CSS strings and ensuring no unnecessary whitespace or characters affect the final styles.
Maintains a Map for plugins, allowing efficient retrieval and management.
Utilizes microtasks (Promise.resolve().then(...)) for debouncing renderCSS calls, ensuring that multiple rapid updates don't trigger excessive re-rendering.
Usage Example Adjustments:
Added comments to clarify the purpose of each operation.
Included an example of unregistering a plugin to demonstrate dynamic plugin management.
Benefits of the Refactored Code:
DRY Compliance: By abstracting common functionalities into BasePlugin, the code adheres to the DRY (Don't Repeat Yourself) principle, making it more efficient and easier to manage.
Performance Optimization: Efficient management of CSS variables and optimized CSS aggregation reduces unnecessary recalculations and DOM manipulations, enhancing performance, especially when dealing with numerous rectangles and plugins.
Scalability: The architecture now easily accommodates additional plugins with minimal boilerplate, facilitating future expansions or modifications.
Maintainability: Clear separation of concerns and centralized logic simplify debugging and feature enhancements.
Feel free to integrate this refactored code into your project. It should provide better performance and easier maintenance while maintaining all the existing functionalities.