To reduce repetition and follow the DRY (Don't Repeat Yourself) principle, we can create a BasePlugin class that encapsulates the shared functionalities between BorderPlugin and VertexPlugin. Both plugins can then extend this base class and implement their unique behaviors. This approach not only makes the code more maintainable but also easier to extend in the future.
Here's how you can refactor the BorderPlugin and VertexPlugin classes:
1. BasePlugin Class
The BasePlugin class handles the common functionalities such as setting global contexts, attaching and detaching CSS variables, updating global settings, and updating individual rectangle elements.
// BasePlugin Implementation
class BasePlugin {
constructor(globalContext, instanceContext, options = {}) {
this.globalContext = globalContext;
this.instanceContext = instanceContext;
this.host = null;
// Initialize global context with options
this.initializeGlobalContext(options);
// Setup CSS rules specific to the plugin
this.setGlobalCSS();
}
/**
* Initializes the global context with provided options.
* To be implemented by subclasses.
*/
initializeGlobalContext(options) {
throw new Error('initializeGlobalContext() must be implemented by subclass');
}
/**
* Sets the global CSS rules.
* To be implemented by subclasses.
*/
setGlobalCSS() {
throw new Error('setGlobalCSS() must be implemented by subclass');
}
/**
* Attaches the plugin to a host element by setting CSS variables.
* @param {HTMLElement} host - The host element to attach the plugin to.
* @returns {Array<String>} - An array of CSS rules.
*/
attach(host) {
if (host) {
this.host = host;
}
const currentHost = this.host;
if (!currentHost) {
throw new Error('Host element is not set.');
}
// Set all global CSS variables
for (const [key, value] of Object.entries(this.globalContext)) {
currentHost.style.setProperty(`--${this.variablePrefix}${key}`, value);
}
return [this.baseRule, this.additionalCSS];
}
/**
* Detaches the plugin from a host element by removing CSS variables.
* @param {HTMLElement} host - The host element to detach the plugin from.
*/
detach(host) {
const currentHost = host || this.host;
if (!currentHost) return;
for (const key of Object.keys(this.globalContext)) {
currentHost.style.removeProperty(`--${this.variablePrefix}${key}`);
}
}
/**
* Retrieves the CSS rules associated with the plugin.
* @returns {Array<String>} - An array of CSS rules.
*/
getCSS() {
return [this.baseRule, this.additionalCSS];
}
/**
* Updates the global context with new options and re-attaches to the host.
* @param {Object} options - The new configuration options.
* @returns {Array<String>} - An array of updated CSS rules.
*/
updateGlobal(options = {}) {
for (const [key, value] of Object.entries(options)) {
if (key in this.globalContext) {
this.globalContext[key] = value;
}
}
return this.attach();
}
/**
* Updates CSS variables for a specific rectangle element.
* @param {HTMLElement} rectElement - The rectangle element to update.
* @param {Object} params - The parameters to update.
*/
updateRectElement(rectElement, params) {
for (const [key, value] of Object.entries(params)) {
if (key in this.globalContext) {
rectElement.style.setProperty(
`--${this.variablePrefix}${key}`,
typeof value === 'number' ? `${value}px` : value
);
// Update instance context if needed
if (this.instanceContext.has(rectElement)) {
Object.assign(this.instanceContext.get(rectElement), { [key]: value });
} else {
this.instanceContext.set(rectElement, { [key]: value });
}
}
}
}
}
Key Points:
-
Initialization: The constructor initializes global and instance contexts and sets up the CSS rules by calling setGlobalCSS().
-
Abstract Methods: initializeGlobalContext and setGlobalCSS are abstract methods that must be implemented by subclasses to handle plugin-specific initialization and CSS rule definitions.
-
CSS Variable Handling: The attach, detach, and updateRectElement methods handle setting and removing CSS variables dynamically based on the plugin's configuration.
-
Flexibility: The updateGlobal method allows dynamic updates to the plugin's global settings, automatically reflecting changes in the CSS.
2. Refactored BorderPlugin Class
The BorderPlugin extends the BasePlugin and implements the specific initialization and CSS rules for borders.
// BorderPlugin Implementation
class BorderPlugin extends BasePlugin {
constructor(globalContext, instanceContext, options = {}) {
super(globalContext, instanceContext, options);
this.variablePrefix = 'border-'; // Prefix for CSS variables
}
/**
* Initializes the global context for BorderPlugin.
* @param {Object} options - Configuration options for the border.
*/
initializeGlobalContext(options) {
this.globalContext.size = options?.size ?? '2px';
this.globalContext.color = options?.color ?? '#000';
}
/**
* Sets the CSS rules specific to borders.
*/
setGlobalCSS() {
this.baseRule = `
border: var(--${this.variablePrefix}size) solid var(--${this.variablePrefix}color);
`;
this.additionalCSS = ''; // No additional CSS for BorderPlugin
}
}
Key Points:
-
Variable Prefix: Defines a unique prefix (border-) for CSS variables to avoid naming collisions.
-
Initialization: Sets default values for size and color if not provided in the options.
-
CSS Rules: Defines the baseRule for borders and leaves additionalCSS empty as it's not needed.
3. Refactored VertexPlugin Class
Similarly, the VertexPlugin extends the BasePlugin and implements its unique configurations and CSS rules.
// VertexPlugin Implementation
class VertexPlugin extends BasePlugin {
constructor(globalContext, instanceContext, options = {}) {
super(globalContext, instanceContext, options);
this.variablePrefix = 'vertex-'; // Prefix for CSS variables
}
/**
* Initializes the global context for VertexPlugin.
* @param {Object} options - Configuration options for the vertices.
*/
initializeGlobalContext(options) {
this.globalContext.size = options?.size ?? '25px';
this.globalContext.color = options?.color ?? '#3498db';
}
/**
* Sets the CSS rules specific to vertices.
*/
setGlobalCSS() {
this.baseRule = `
--extended-size: calc(var(--border-size, 2px) + var(--${this.variablePrefix}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));
`;
this.additionalCSS = `
.rect-region::before {
content: '';
position: absolute;
width: var(--${this.variablePrefix}size);
height: var(--${this.variablePrefix}size);
background-color: var(--${this.variablePrefix}color);
box-sizing: border-box;
/* 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(--${this.variablePrefix}color),
var(--adjusted-width) var(--adjusted-height) 0 0 var(--${this.variablePrefix}color),
0 var(--adjusted-height) 0 0 var(--${this.variablePrefix}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));
}
`;
}
}
Key Points:
-
Variable Prefix: Uses vertex- as the prefix to manage CSS variables related to vertices.
-
Initialization: Sets default size and color for vertices.
-
CSS Rules: Defines complex CSS rules for positioning vertices around a rectangle, utilizing CSS variables for dynamic styling.
4. Usage Example
Here's how you can utilize the refactored plugins in your application:
// Assuming you have a host element and a rectangle element
const hostElement = document.getElementById('host');
const rectElement = document.getElementById('rectangle');
// Contexts
const globalContext = {};
const instanceContext = new Map();
// Initialize Plugins
const borderPlugin = new BorderPlugin(globalContext, instanceContext, { size: '3px', color: '#ff0000' });
const vertexPlugin = new VertexPlugin(globalContext, instanceContext, { size: '20px', color: '#00ff00' });
// Attach Plugins to the Host
const borderCSS = borderPlugin.attach(hostElement);
const vertexCSS = vertexPlugin.attach(hostElement);
// Apply CSS (this depends on how you manage CSS in your project)
// For example, inject into a <style> tag or use a CSS-in-JS solution
// Update Global Configuration
borderPlugin.updateGlobal({ size: '4px' });
// Update a Specific Rectangle Element
vertexPlugin.updateRectElement(rectElement, { size: '25px', color: '#0000ff' });
// Detach Plugins when needed
borderPlugin.detach(hostElement);
vertexPlugin.detach(hostElement);
Key Points:
-
Initialization: Create instances of BorderPlugin and VertexPlugin with desired configurations.
-
Attachment: Attach plugins to the host element to apply global CSS variables and retrieve CSS rules.
-
Dynamic Updates: Use updateGlobal to change global settings and updateRectElement to modify individual rectangle elements.
-
Detachment: Cleanly remove plugins from the host when they are no longer needed.
5. Benefits of This Refactoring
-
Maintainability: Centralizing shared logic in BasePlugin makes it easier to manage and update shared functionalities.
-
Scalability: Adding new plugins with similar patterns becomes straightforward—simply extend BasePlugin and implement the required methods.
-
Readability: Reduces code duplication, making the codebase cleaner and easier to understand.
-
Flexibility: Each plugin can still maintain its unique behavior by overriding or extending base methods as needed.
6. Potential Enhancements
-
Error Handling: Enhance error handling in the BasePlugin to manage scenarios like missing host elements or invalid configurations.
-
Plugin Registration: Implement a plugin manager that can handle multiple plugins, manage their order, and handle dependencies.
-
Testing: With a BasePlugin, writing unit tests for shared functionalities becomes more efficient.
-
Documentation: Document each class and method for better developer experience and easier onboarding.
By following this refactored structure, you ensure that your plugin system remains robust, flexible, and easy to maintain.