To encapsulate the styles and structure of each rectangle more effectively and prevent CSS leakage, you can utilize the Shadow DOM. This approach ensures that each rectangle's styles are scoped locally, providing better modularity and maintainability.
Below is the modified version of your RectRegionShapeFactory class that leverages the Shadow DOM for each rectangle instance:
class RectRegionShapeFactory {
/**
* Constructor to initialize default options.
* @param {Object} defaultOptions - Default customization options.
*/
constructor(defaultOptions = {}) {
// Merge user-provided default options with inherent defaults
this.defaultOptions = {
vertexSize: '25px', // Size of the corner squares
vertexColor: '#3498db', // Color of the corner squares
borderColor: '#000', // Color of the rectangle border
borderWidth: '2px', // Width of the rectangle border
...defaultOptions
};
}
/**
* Creates a <style> element containing the necessary CSS.
* @param {Object} options - Customization options for CSS variables.
* @returns {HTMLStyleElement} - The created style element.
*/
createStyleElement(options) {
const style = document.createElement('style');
style.textContent = `
:host {
/* CSS Variables */
--vertex-size: ${options.vertexSize};
--vertex-color: ${options.vertexColor};
--border-width: ${options.borderWidth};
--border-color: ${options.borderColor};
position: absolute; /* Fixed on page, not affecting document flow */
width: var(--width);
height: var(--height);
border: var(--border-width) solid var(--border-color);
box-sizing: border-box;
}
:host::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-width) + var(--vertex-size)) );
--adjusted-width: calc(var(--width) - var(--border-width));
--adjusted-height: calc(var(--height) - var(--border-width));
/* Center the first dot at (0,0) by shifting it by half its size */
top: var(--offset);
left: var(--offset);
/* Creating three more squares using box-shadow, centered 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);
}
`;
return style;
}
/**
* Creates a rectangle element with centered corner dots using Shadow DOM.
* @param {number} x - The left position in pixels.
* @param {number} y - The top position in pixels.
* @param {number} width - Width of the rectangle in pixels.
* @param {number} height - Height of the rectangle in pixels.
* @param {Object} options - Customization options.
* @returns {HTMLElement} - The created rectangle element with Shadow DOM.
*/
createRect(x, y, width, height, options = {}) {
// Merge options with default options
const finalOptions = { ...this.defaultOptions, ...options };
// Create the host element for Shadow DOM
const rectHost = document.createElement('div');
// Attach Shadow DOM to the host element
const shadow = rectHost.attachShadow({ mode: 'open' });
// Create and append the style element to Shadow DOM
const style = this.createStyleElement(finalOptions);
shadow.appendChild(style);
// Optionally, you can add additional elements inside the shadow root if needed
// For this scenario, styles and pseudo-elements are sufficient
// Set position of the host element
rectHost.style.left = `${x}px`;
rectHost.style.top = `${y}px`;
// Set width and height via CSS variables
rectHost.style.setProperty('--width', `${width}px`);
rectHost.style.setProperty('--height', `${height}px`);
return rectHost;
}
/**
* Updates a rectangle's properties.
* @param {HTMLElement} rect - The rectangle element to update.
* @param {Object} options - Properties to update.
*/
updateRect(rect, options = {}) {
if (!(rect instanceof HTMLElement)) {
console.error('The first argument to updateRect must be a DOM element.');
return;
}
const shadow = rect.shadowRoot;
if (!shadow) {
console.error('The provided element does not have a Shadow DOM.');
return;
}
// Destructure possible options
const {
x,
y,
width,
height,
vertexSize,
vertexColor,
borderColor,
borderWidth
} = options;
// Update position if provided
if (x !== undefined) {
rect.style.left = typeof x === 'number' ? `${x}px` : x;
}
if (y !== undefined) {
rect.style.top = typeof y === 'number' ? `${y}px` : y;
}
// Update size if provided
if (width !== undefined) {
rect.style.setProperty('--width', typeof width === 'number' ? `${width}px` : width);
}
if (height !== undefined) {
rect.style.setProperty('--height', typeof height === 'number' ? `${height}px` : height);
}
// Update customization options if provided
if (vertexSize !== undefined) {
rect.style.setProperty('--vertex-size', vertexSize);
}
if (vertexColor !== undefined) {
rect.style.setProperty('--vertex-color', vertexColor);
}
if (borderColor !== undefined) {
rect.style.setProperty('--border-color', borderColor);
}
if (borderWidth !== undefined) {
rect.style.setProperty('--border-width', borderWidth);
}
}
}
// Instantiate the factory with optional default options
const factory = new RectRegionShapeFactory({
vertexSize: '20px',
vertexColor: '#e74c3c',
borderColor: '#2c3e50',
borderWidth: '3px'
});
// Reference to the container where rectangles will be added
const container = document.getElementById('rectangle-container');
// Create multiple rectangles with different properties
const rect1 = factory.createRect(50, 50, 200, 100, {
vertexSize: '12px',
vertexColor: '#1abc9c',
borderColor: '#16a085',
borderWidth: '2px'
});
const rect2 = factory.createRect(300, 150, 250, 150, {
vertexSize: '24px',
vertexColor: '#f1c40f',
borderColor: '#f39c12',
borderWidth: '4px'
});
const rect3 = factory.createRect(600, 80, 180, 120); // Uses default options
// Append rectangles to the container
container.appendChild(rect1);
container.appendChild(rect2);
container.appendChild(rect3);
HTML Structure
Ensure you have a container element in your HTML where the rectangles will be appended. For example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Shadow DOM Rectangles</title>
<style>
/* Optional: Style the container */
#rectangle-container {
position: relative; /* Ensure that absolutely positioned rectangles are relative to this container */
width: 100%;
height: 100vh;
background-color: #f0f0f0;
}
</style>
</head>
<body>
<div id="rectangle-container"></div>
<!-- Include your script here -->
<script src="path-to-your-script.js"></script>
</body>
</html>
Explanation of Changes
-
Shadow DOM Integration:
- Each rectangle (
rectHost) now has its own Shadow DOM (shadow) where styles are encapsulated.
- The styles previously injected into the global document head are now scoped within the Shadow DOM, preventing any unintended CSS conflicts.
-
Style Encapsulation:
- The
createStyleElement method generates a <style> element containing CSS that targets the :host pseudo-class. This ensures that the styles apply to the shadow host (rectHost) and its pseudo-elements without affecting other elements on the page.
-
CSS Variables:
- CSS variables are still used to allow dynamic customization of each rectangle's appearance. These variables are set directly on the
rectHost element using style.setProperty.
-
Removal of Global CSS Injection:
- The static CSS injection mechanism (
isCSSInjected and injectCSS methods) has been removed because each Shadow DOM instance now manages its own styles.
-
Update Mechanism:
- The
updateRect method has been adjusted to modify CSS variables on the rectHost element, which in turn updates the styles within the Shadow DOM.
-
Container Positioning:
- The container (
#rectangle-container) is styled with position: relative to ensure that absolutely positioned rectangles are positioned relative to this container.
Benefits of Using Shadow DOM
-
Style Encapsulation: Styles defined within a Shadow DOM are scoped to that particular shadow tree. This prevents styles from leaking out or being affected by global styles.
-
Reuse and Modularity: Components with Shadow DOM can be easily reused without worrying about CSS conflicts, enhancing modularity.
-
Maintainability: Managing styles becomes more straightforward as each component maintains its own styles independent of the rest of the document.
Final Notes
-
Performance Consideration: While using Shadow DOM provides better encapsulation, creating numerous shadow roots can have performance implications. If you plan to create a large number of rectangles, consider optimizing by sharing styles using techniques like constructing a single <template> that can be cloned across multiple shadow roots.
-
Browser Support: Shadow DOM is widely supported in modern browsers. However, always ensure compatibility if you need to support older browsers.
By integrating Shadow DOM into your RectRegionShapeFactory, you've enhanced the modularity and encapsulation of your rectangle components, making your codebase cleaner and more maintainable.