analyze what can be improved in the code for better performance (not about error handling, adding comments, etc) while keeping the same functionality.
"""
class Unit {
  constructor(value, type = null) {
    this.type = type;
    this.suffix = typeof type === 'string' ? type : null;
    this.assign(value);
  }

  assign(value) {
    if (value === this.value || value === this.css) {
      return;
    }
    if (this.type === null) {
      this.css = this.value = value;
      return;
    }
    
    const type = typeof value;
    let parsedValue;

    if (type === 'number') {
      parsedValue = value;
    } else if (type === 'string') {
      parsedValue = parseFloat(value);
      if (isNaN(parsedValue)) {
        throw new Error(`Invalid value: ${value}`);
      }
    } else {
      throw new Error(`Invalid type for assignment: Expected number or string, received ${type}.`);
    }
  
    this.value = parsedValue;
    this.css = this.suffix ? `${parsedValue}${this.suffix}` : parsedValue.toString();
  }

  clone() {
    const cloned = Object.create(Unit.prototype);
    Object.assign(cloned, this);
    return cloned;
  }

  static px(value) {
    return new Unit(value, 'px');
  }

  static number(value) {
    return new Unit(value, Number);
  }

  static identity(value) {
    return new Unit(value);
  }
}


class ParameterPlugin {
  params = {};
  paramPrefix = '';
  cssVariableMap = null;
  host = null;

  initialize(globalContext, instanceContext, params = {}) {
    this.globalContext = globalContext;
    this.instanceContext = instanceContext;
    if (!this.cssVariableMap) {
      this.cssVariableMap = this.createCSSVariableMap();
    }
    this.css = [this.baseRules, this.additionalCSS];
    Object.assign(globalContext, this.params);  // setup units
    Object.assign(globalContext, params); // user params adhere to units
  }

  createCSSVariableMap() {
    const map = {};
    const {paramPrefix, params} = this;
    
    for (const key in params) {
        map[key] = paramPrefix ? `--${paramPrefix}-${key}` : `--${key}`;
    }
    return map;
  }

  getCSS() {
    return this.css;
  }

  attach(host) {
    this.host = host || this.host;
    this.setGlobalCSS();
  }

  detach() {
    this.unsetGlobalCSS();
    this.host = null;
  }

  updateGlobal(params = {}) {
      Object.assign(this.globalContext, params);
      this.setGlobalCSS();
  }

  updateRectElement(rectElement, params) {
      const {instanceContext, cssVariableMap} = this;
      const rectContext = instanceContext.get(rectElement);
      for (const key in params) {
          const cssVar = cssVariableMap[key];
          if (cssVar) {
            rectContext[key] = params[key];
            rectElement.style.setProperty(cssVar, rectContext[key].css);
          }
      }
  }

  setGlobalCSS() {
      if (!this.host) return;
      const { globalContext, cssVariableMap, host } = this;
  
      for (const key in globalContext) {
          const cssVar = cssVariableMap[key];
          if (cssVar) {
              host.style.setProperty(cssVar, globalContext[key].css);
          }
      }
  }

  unsetGlobalCSS() {
      if (!this.host) return;
      const { globalContext, cssVariableMap, host } = this;
      for (const key in globalContext) {
          const cssVar = cssVariableMap[key];
          if (cssVar) {
              host.style.removeProperty(cssVar);
          }
      }
  }

  static createPluginClass(config) {
    return class extends ParameterPlugin {
      constructor(...args) {
        super();
        Object.assign(this, config);
        this.initialize(...args);
      }
    };
  }
}

const BasePlugin = ParameterPlugin.createPluginClass({
  params: {
    width: Unit.px(20),
    height: Unit.px(20),
    x: Unit.px(0),
    y: Unit.px(0),
    opacity: Unit.number(1),
  },
  baseRules: `
    width: var(--width);
    height: var(--height);
    left: var(--x);
    top: var(--y);
    opacity: var(--opacity);
  `,
});

const BorderPlugin = ParameterPlugin.createPluginClass({
  params: {
      size: Unit.px(2),
      color: '#000',
  },
  paramPrefix: 'border',
  baseRules: 'border: var(--border-size) solid var(--border-color);',
});

const VertexPlugin = ParameterPlugin.createPluginClass({
  params: {
    size: Unit.px(24),
    color: '#3498db',
  },
  paramPrefix: 'vertex',
  baseRules: `
    --extended-size: calc(var(--border-size, 2px) + var(--vertex-size));
    --offset: calc(-0.5 * var(--extended-size));
    --adjusted-width: calc(var(--width) - var(--border-size, 2px));
    --adjusted-height: calc(var(--height) - var(--border-size, 2px));
    `,
    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 */

      /* 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);
    }
    .rect-region::after {
      content: '';
      position: absolute;
      top: var(--offset);
      left: var(--offset);
      width: calc(100% + var(--extended-size));
      height: calc(100% + var(--extended-size));
    }
  `
});

const FillPlugin = ParameterPlugin.createPluginClass({
  params: {
    color: '#ffffff'
  },
  paramPrefix: 'fill',
  baseRules: `background-color: var(--fill-color);`
})

const DndPlugin = (() => {
  // ------------------------
  // Action Type Constants
  // ------------------------
  const RESIZE_NW = 0;  // Resize from the North-West corner
  const RESIZE_NE = 1;  // Resize from the North-East corner
  const RESIZE_SW = 2;  // Resize from the South-West corner
  const RESIZE_SE = 3;  // Resize from the South-East corner
  const RESIZE_N = 4;   // Resize from the North edge
  const RESIZE_S = 5;   // Resize from the South edge
  const RESIZE_W = 6;   // Resize from the West edge
  const RESIZE_E = 7;   // Resize from the East edge
  const MOVE = 8;       // Move the rectangle
  const NULL = 9;       // No action

  // ------------------------
  // Action Lookup Table
  // ------------------------
  // This table maps cursor positions to specific actions based on X and Y indices.
  // Both X and Y indices range from 0 to 6, corresponding to seven distinct regions.
  // Row: Y, Col: X
  const ACTION_TABLE = [
    [RESIZE_NW, RESIZE_NW,  RESIZE_NW,  NULL,     RESIZE_NE,  RESIZE_NE, RESIZE_NE], // Y=0
    [RESIZE_NW, RESIZE_NW,  RESIZE_NW,  RESIZE_N, RESIZE_NE,  RESIZE_NE, RESIZE_NE], // Y=1
    [RESIZE_NW, RESIZE_NW,  RESIZE_NW,  MOVE,     RESIZE_NE,  RESIZE_NE, RESIZE_NE], // Y=2
    [NULL,      RESIZE_W,   MOVE,       MOVE,     MOVE,       RESIZE_E,  NULL     ], // Y=3
    [RESIZE_SW, RESIZE_SW,  RESIZE_SW,  MOVE,     RESIZE_SE,  RESIZE_SE, RESIZE_SE], // Y=4
    [RESIZE_SW, RESIZE_SW,  RESIZE_SW,  RESIZE_S, RESIZE_SE,  RESIZE_SE, RESIZE_SE], // Y=5
    [RESIZE_SW, RESIZE_SW,  RESIZE_SW,  NULL,     RESIZE_SE,  RESIZE_SE, RESIZE_SE], // Y=6
  ];


  // ------------------------
  // Change Tables
  // ------------------------
  // Determines how the width/height/x/y changes based on the action.
  // -1: Decrease, 0: No change, 1: Increase/Change
  //                           NW  NE   SW  SE  N  S   W   E
  const WIDTH_CHANGE_TABLE  = [-1,  1, -1,  1,  0, 0, -1,  1];
  const HEIGHT_CHANGE_TABLE = [-1, -1,  1,  1, -1, 1,  0,  0];
  const X_CHANGE_TABLE      = [ 1,  0,  1,  0,  0, 0,  1,  0];
  const Y_CHANGE_TABLE      = [ 1,  1,  0,  0,  1, 0,  0,  0];


  // ------------------------
  // DndPlugin Class Definition
  // ------------------------
  return class DndPlugin {
    /**
     * Constructor initializes the plugin's state and binds event handlers.
     */
    constructor() {
      // Current rectangle being interacted with
      this.currentRect = null;

      // Current action being performed (e.g., MOVE, RESIZE_NW)
      this.currentAction = NULL;

      // Host element to which the plugin is attached
      this.host = null;

      // Starting mouse coordinates when interaction begins
      this.initialMouseX = 0;
      this.initialMouseY = 0;

      // Initial state of the rectangle before interaction
      this.initialRectState = null;

      // Bound event handlers for mouse move and mouse up events
      this.mouseMoveHandler = this.onMouseMove.bind(this);
      this.mouseUpHandler = this.onMouseUp.bind(this);

      // WeakMap to store event listeners associated with each element
      this.listeners = new WeakMap();

      // Flags and storage for requestAnimationFrame optimization
      this.isAnimating = false;  // Indicates if an animation frame is already scheduled

      // Minimum size constraints to prevent the rectangle from becoming too small
      this.MIN_WIDTH = 50;  // Minimum width in pixels
      this.MIN_HEIGHT = 50; // Minimum height in pixels
    }

    /**
     * Attaches the plugin to a host element.
     * @param {HTMLElement} host - The host element.
     * @returns {null} Always returns null.
     */
    attach(host) {
      if (host) {
        this.host = host;
      }
      return null;
    }

    /**
     * Called when a rectangle is created. Sets up the mousedown event listener.
     * @param {Object} rect - The rectangle object.
     * @param {HTMLElement} element - The DOM element representing the rectangle.
     */
    onRectCreate(rect, element) {
      // Bind the onMouseDown handler with the current rectangle
      const callback = this.onMouseDown.bind(this, rect);

      // Store the callback in the listeners WeakMap
      this.listeners.set(element, callback);

      // Add the mousedown event listener to the rectangle element
      element.addEventListener('mousedown', callback);
    }

    /**
     * Called when a rectangle is removed. Cleans up the mousedown event listener.
     * @param {Object} rect - The rectangle object.
     * @param {HTMLElement} element - The DOM element representing the rectangle.
     */
    onRectRemove(rect, element) {
      const callback = this.listeners.get(element);
      if (callback) {
        // Remove the previously added mousedown event listener
        element.removeEventListener('mousedown', callback);

        // Remove the callback from the listeners WeakMap
        this.listeners.delete(element);
      }
    }

    onMouseDown(rect, e) {
      const rectElement = e.target;
      if (!rectElement) return;
      const width = rect.getParam('width');
      const height = rect.getParam('height');
      const x = rect.getParam('x');
      const y = rect.getParam('y');
      const borderSize = rect.getParam('size', BorderPlugin) || 6;
      const vertexSize = rect.getParam('size', VertexPlugin) || 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;

      const minY = minX;
      const maxY = halfVertexPlusBorder + yOffset;

      // Check if cursorOffsetX and cursorOffsetY are outside the boundaries
      if (cursorOffsetX < minX || cursorOffsetX > maxX || cursorOffsetY < minY || cursorOffsetY > maxY) {
        return;
      }

      // Sorted array excluding the first and last elements
      const xSorted = [
        // segment 0: minX to x[0]
        0,
        borderSize,
        halfVertexPlusBorder,
        -halfVertexMinusBorder + xOffset,
        width - borderSize,
        width
        // segment 6: x[5] to maxX
      ];

      const ySorted = [
        // segment 0: minY to y[0]
        0,
        borderSize,
        halfVertexPlusBorder,
        -halfVertexMinusBorder + yOffset,
        height - borderSize,
        height
        // segment 6: y[5] to maxY
      ];

      let xi = 0;
      let yi = 0;

      // Find the segment index for cursorOffsetX
      for (; xi < 6 && cursorOffsetX >= xSorted[xi]; xi++) { }

      // Find the segment index for cursorOffsetY
      for (; yi < 6 && cursorOffsetY >= ySorted[yi]; yi++) { }

      // Lookup the action based on the position of cursor in particular [y, x] segment
      this.currentAction = ACTION_TABLE[yi][xi];

      // If the action is NULL, no operation should be performed
      if (this.currentAction === NULL) {
        return;
      }

      // Store starting mouse coordinates
      this.initialMouseX = e.clientX;
      this.initialMouseY = e.clientY;

      // Store the current rectangle and its initial state
      this.currentRect = rect;
      this.initialRectState = { x, y, width, height };

      // Prevent default browser behavior (e.g., text selection)
      e.preventDefault();

      // Add global event listeners for mousemove and mouseup
      document.addEventListener('mousemove', this.mouseMoveHandler);
      document.addEventListener('mouseup', this.mouseUpHandler);
    }

    onMouseMove(e) {
      if (!this.currentRect || this.isAnimating) return;
      this.isAnimating = true;

      const dx = e.clientX - this.initialMouseX;
      const dy = e.clientY - this.initialMouseY;

      if (this.currentAction === MOVE) {
        this.moveRect(this.currentRect, this.initialRectState, dx, dy);
      } else {
        this.resizeRect(this.currentRect, this.initialRectState, dx, dy);
      }
    }

    moveRect(rect, initialRectState, dx, dy) {
      let {x, y} = initialRectState;
      x += dx;
      y += dy;

      requestAnimationFrame(() => {
        rect.update({x, y});
        // Reset the animation flag
        this.isAnimating = false;
      });
    }

    resizeRect(rect, initialRectState, dx, dy) {
      const action = this.currentAction;

      const {x: initialX, y: initialY, width: initialWidth, height: initialHeight} = initialRectState;

      const width = Math.max(initialWidth + WIDTH_CHANGE_TABLE[action] * dx, this.MIN_WIDTH);
      const height = Math.max(initialHeight + HEIGHT_CHANGE_TABLE[action] * dy, this.MIN_HEIGHT);

      const x = initialX + X_CHANGE_TABLE[action] * (initialWidth - width);
      const y = initialY + Y_CHANGE_TABLE[action] * (initialHeight - height);

      requestAnimationFrame(() => {
        this.updateRect(rect, initialRectState, { x, y, width, height });
        // Reset the animation flag and latestRect storage
        this.isAnimating = false;
      });
    }


    /**
     * Updates the rectangle's properties based on the new state.
     * @param {Object} newRect - The new state of the rectangle.
     */
    updateRect(rect, initialRectState, newRect) {
      const updates = {};

      // Compare each property and collect updates that have changed
      for (const key in newRect) {
        if (newRect[key] !== initialRectState[key]) {
          updates[key] = newRect[key];
        }
      }

      rect.update(updates);
    }

    /**
     * Handles the mouseup event. Cleans up event listeners and resets state.
     */
    onMouseUp() {
      // Remove global event listeners for mousemove and mouseup
      document.removeEventListener('mousemove', this.mouseMoveHandler);
      document.removeEventListener('mouseup', this.mouseUpHandler);

      // Reset the current rectangle and currentAction
      this.currentRect = null;
      this.currentAction = NULL;

      // Reset animation flags and storage
      this.isAnimating = false;
    }
  }
})();

// Rectangle Wrapper
class Rect {
  /**
   * Creates a Rect instance.
   * @param {HTMLElement} rect - The rectangle element.
   * @param {RectRegionShapeFactory} factory - Reference to the factory.
   */
  constructor(rectElement, factory) {
    this.rectElement = rectElement;
    this.factory = factory;
    this.factory.plugins.forEach((plugin, pluginClass) => {
      plugin.onRectCreate?.(this, this.rectElement);
    });
  }


  /**
   * Removes the rectangle from the DOM and cleans up plugin-specific settings.
   */
  remove() {
    if (!this.rectElement) {
      return;
    }
    // Clean up plugin-specific settings
    this.factory.plugins.forEach((plugin, pluginClass) => {
      plugin.onRectRemove?.(this, this.rectElement);
    });

    // Remove the rectangle from the DOM
    this.rectElement.remove();
    this.rectElement = null;
    this.factory._onRectRemove(this);
  }

  update(params, pluginClass = BasePlugin) {
    const plugin = this.factory.plugins.get(pluginClass);
    if (plugin) {
      plugin.updateRectElement?.(this.rectElement, params);
    } else {
      console.warn(`Plugin ${pluginClass.name} not found.`);
    }
  }

  updateMany(pluginClassParamPairs = []) {
    for (let i = 0; i < pluginClassParamPairs.length; i++) {
      const [pluginClass, params]  = pluginClassParamPairs[i];
      this.update(params, pluginClass);
    }
  }

  getParam(name, pluginClass = BasePlugin) {
    const [_, instanceContext] = this.factory.getPluginContext(pluginClass);
    const rectContext = instanceContext.get(this.rectElement);
    const unit = rectContext[name];
    debugger;
    return rectContext[name].value;
  }
}

class DefaultMap extends WeakMap {
  constructor(defaultValueFactory, iterable) {
    super(iterable);
    this.defaultValueFactory = defaultValueFactory;
  }

  get(key) {
    if (!this.has(key)) {
      this.set(key, this.defaultValueFactory());
    }
    return super.get(key);
  }
}

const UnitContext = (parentContext) => 
  new Proxy({}, {
    set(target, prop, val) {
      const currentValue = target[prop];
      if (val instanceof Unit) {
        target[prop] = val;
      } else if (currentValue instanceof Unit) {
        currentValue.assign(val);
      } else if (parentContext && prop in parentContext) {
        // Clone and assign value from parentContext if it exists
        const clonedUnit = parentContext[prop].clone();
        clonedUnit.assign(val);
        target[prop] = clonedUnit;
      } else {
        target[prop] = Unit.identity(val);
      }
      return true;  // Indicate the operation was successful
    },
    get(target, prop) {
      return prop in target ? target[prop] : parentContext[prop];
    }
  });

// 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|PluginInterface>} plugins - Array of plugin instances.
   */
  constructor(container) {
    if (!(container instanceof HTMLElement)) {
      throw new Error('Container must be a valid DOM element.');
    }

    this.container = container;
    this.plugins = new Map();
    this.pluginContexts = 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.rects = new Set();
    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;
      box-sizing: border-box;
  `.trim();

    // Debounce renderCSS calls using a microtask queue
    this.debounceTask = null;

    // Initially render all CSS
    this.renderCSS();
    this.registerPlugin(BasePlugin);
  }

  /**
   * 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|PluginInterface} plugin - The plugin instance.
   */
  registerPlugin(pluginClass, params = null) {
    if (this.plugins.has(pluginClass)) {
      console.warn(`Plugin ${pluginClass.name} is already registered.`);
      return;
    }
    const globalContext = UnitContext();
    const instanceContext = new DefaultMap(() => (UnitContext(globalContext)));
    const plugin = new pluginClass(globalContext, instanceContext, params);
    this.plugins.set(pluginClass, plugin);
    this.pluginContexts.set(pluginClass, [globalContext, instanceContext]);
    plugin.attach?.(this.shadow.host);
    this.scheduleRenderCSS();
  }

  unregisterPlugin(pluginClass) {
    const plugin = this.plugins.get(pluginClass);
    if (plugin) {
      plugin.detach?.(this.shadow.host);
      this.plugins.delete(pluginClass);
      this.pluginContexts.delete(pluginClass);
      this.scheduleRenderCSS();
    } else {
      console.warn(`Plugin ${pluginClass.name} not found.`);
    }
  }

  updateGlobalPlugin(pluginClass, params = {}) {
    const plugin = this.plugins.get(pluginClass);
    if (plugin) {
      // Update the plugin's global configurations
      plugin.updateGlobal?.(params);
      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?.();
      if (css) {
        let [base, additional] = css;
        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 {Rect} - The wrapper object managing the rectangle.
   */
  createRect(pluginClassParamPairs) {
    // Create the rectangle div
    const rectElement = document.createElement('div');
    rectElement.classList.add('rect-region');
    // Append the rectangle to the shadow DOM's container
    this.rectContainer.appendChild(rectElement);

    // Instantiate the wrapper with reference to this factory and the rectangle
    const rect = new Rect(rectElement, this);
    this.rects.add(rect);

    rect.updateMany(pluginClassParamPairs);
    return rect;
  }

  _onRectRemove(rect) {
    this.rects.remove(rect);
  }

  getPluginContext(pluginClass) {
    return this.pluginContexts.get(pluginClass);
  }

  getAll() {
    return Array.from(this.rects);
  }
}

// Get the container element
const container = document.getElementById('rectangle-container');

// Instantiate the factory with plugins
const factory = new RectRegionShapeFactory(container);
factory.registerPlugin(BorderPlugin, {size: '3px', color: '#2c3e50'});
factory.registerPlugin(VertexPlugin, {size: '20px', color: '#e74c3c'});
factory.registerPlugin(FillPlugin, {color: '#2ecc71'});
factory.registerPlugin(DndPlugin);

// Create multiple rectangles with different properties
const rect1 = factory.createRect([[BasePlugin, {
  x: 50, y:50, width: 200, height: 100
}]]);
const rect2 = factory.createRect([[BasePlugin, {
  x: 300, y:150, width: 250, height: 150
}]]);
const rect3 = factory.createRect([[BasePlugin, {
  x: 600, y:80, width: 180, height: 120, opacity: '0.5'
}], [BorderPlugin, { size: '6px' }]]);


"""