Untitled conversation
- Usercode
- Assistant
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
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
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');
}
}
class FillPlugin extends PluginInterface {
/**
* Constructs a FillPlugin instance with given options.
* @param {Object} options - Configuration options.
* @param {string} options.color - The fill color (e.g., '#ff0000').
*/
constructor(options = {}) {
super();
this.color = options.color || '#ffffff'; // Default fill color is white
this.host = null;
this.updateCSS();
}
/**
* Updates the CSS rules based on current configurations.
*/
updateCSS() {
this.baseRule = `
background-color: var(--fill-color, ${this.color});
`;
// FillPlugin 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('--fill-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('--fill-color');
}
/**
* Provides the updated CSS rules for fill color.
* @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.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.color) {
rect.style.setProperty('--fill-color', options.color);
}
}
/**
* Cleans up per-rectangle configurations by removing CSS variables.
* @param {HTMLElement} rect - The rectangle element.
*/
onRectRemove(rect) {
rect.style.removeProperty('--fill-color');
}
}
class TransparencyPlugin extends PluginInterface {
/**
* Constructs a TransparencyPlugin instance with given options.
* @param {Object} options - Configuration options.
* @param {number|string} options.opacity - The opacity value (e.g., 0.5 or '50%').
*/
constructor(options = {}) {
super();
this.opacity = options.opacity !== undefined ? options.opacity : 1; // Default opacity is 1 (fully opaque)
this.host = null;
this.updateCSS();
}
/**
* Updates the CSS rules based on current configurations.
*/
updateCSS() {
this.baseRule = `
opacity: var(--rect-opacity, ${this.opacity});
`;
// TransparencyPlugin 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('--rect-opacity', this.opacity);
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('--rect-opacity');
}
/**
* Provides the updated CSS rules for opacity.
* @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.opacity !== undefined) this.opacity = options.opacity;
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.opacity !== undefined) {
rect.style.setProperty('--rect-opacity', options.opacity);
}
}
/**
* Cleans up per-rectangle configurations by removing CSS variables.
* @param {HTMLElement} rect - The rectangle element.
*/
onRectRemove(rect) {
rect.style.removeProperty('--rect-opacity');
}
}
// 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);
});
// 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 = `
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 = []; // 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;
}
}
// Usage Example
// Instantiate plugins
const plugins = [
new BorderPlugin({ size: '3px', color: '#2c3e50' }),
new VertexPlugin({ size: '20px', color: '#e74c3c' }),
new FillPlugin({ color: '#2ecc71' }), // New FillPlugin
new TransparencyPlugin({ opacity: 0.8 }) // New TransparencyPlugin
];
// 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
// 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' }],
[FillPlugin, { color: '#16a085' }],
[TransparencyPlugin, { opacity: 0.85 }]
]
);
}, 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' });
factory.updateGlobalPlugin(FillPlugin, { color: '#34495e' });
factory.updateGlobalPlugin(TransparencyPlugin, { opacity: 0.5 });
// 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);
rect3.update(
{ x: 600, y: 80, width: 180, height: 120 },
[
[FillPlugin, { color: '#8e44ad' }],
[TransparencyPlugin, { opacity: 0.1 }]
]
);
}, 6000);
// Example: Unregister a plugin after 8 seconds (e.g., remove VertexPlugin)
extend the code with drag and drop with these plugins: """ class DndPlugin extends PluginInterface { onRectCreate(rect) { // set up listeners }
onRectRemove(rect) { // remove listeners } }
// resize when dragging edges or vertices class DndMovePlugin extends PluginInterface { constructor(...) { // states, since we dnd on 1 rect at a time we dont need separate instances }
isApplicable(rect, pos) { // maybe use a better method name // determine if start drag position is valid for this plugin return bool; }
onDragStart(rect, pos) {
} onDragMove(rect, pos) {
} onDragEnd(rect, pos) {
} }
// resize when dragging edges or vertices class DndResizePlugin extends PluginInterface { constructor(...) { // states, since we dnd on 1 rect at a time we dont need separate instances }
isApplicable(rect, pos) { // maybe use a better method name // determine if start drag position is valid for this plugin return bool; }
onDragStart(rect, pos) {
} onDragMove(rect, pos) {
} onDragEnd(rect, pos) {
} } """
To extend your existing rectangle region shape factory with drag-and-drop (DnD) capabilities, we'll implement three new plugins:
These plugins will integrate seamlessly with your existing plugin architecture, leveraging the PluginInterface and interacting with the RectWrapper and RectRegionShapeFactory. Below is a comprehensive implementation, including the new plugins, their integration, and usage examples.
The DndPlugin serves as a container for movement and resizing functionalities. It initializes and coordinates the DndMovePlugin and DndResizePlugin.
// DndPlugin Implementation
class DndPlugin extends PluginInterface {
/**
* Constructs a DndPlugin instance and initializes move and resize plugins.
* @param {Object} options - Configuration options.
*/
constructor(options = {}) {
super();
this.movePlugin = new DndMovePlugin(options.move || {});
this.resizePlugin = new DndResizePlugin(options.resize || {});
}
/**
* Attaches both move and resize plugins.
* @param {HTMLElement} host - The shadow host element.
* @returns [base, additional] - Combined CSS rules from both plugins.
*/
attach(host) {
const [moveBase, moveAdditional] = this.movePlugin.attach(host);
const [resizeBase, resizeAdditional] = this.resizePlugin.attach(host);
return [
moveBase + '\n' + resizeBase,
moveAdditional + '\n' + resizeAdditional,
];
}
/**
* Detaches both move and resize plugins.
* @param {HTMLElement} host - The shadow host element.
*/
detach(host) {
this.movePlugin.detach(host);
this.resizePlugin.detach(host);
}
/**
* Updates global configurations for both move and resize plugins.
* @param {Object} options - Options to update.
* @returns [base, additional] - Combined updated CSS rules.
*/
updateGlobal(options = {}) {
const [moveBase, moveAdditional] = this.movePlugin.updateGlobal(options.move || {});
const [resizeBase, resizeAdditional] = this.resizePlugin.updateGlobal(options.resize || {});
return [
moveBase + '\n' + resizeBase,
moveAdditional + '\n' + resizeAdditional,
];
}
/**
* Updates per-rectangle configurations for both move and resize plugins.
* @param {HTMLElement} rect - The rectangle element.
* @param {Object} options - Options to update.
*/
updateRect(rect, options = {}) {
if (options.move) {
this.movePlugin.updateRect(rect, options.move);
}
if (options.resize) {
this.resizePlugin.updateRect(rect, options.resize);
}
}
/**
* Cleans up per-rectangle configurations by detaching plugins.
* @param {HTMLElement} rect - The rectangle element.
*/
onRectRemove(rect) {
this.movePlugin.onRectRemove(rect);
this.resizePlugin.onRectRemove(rect);
}
/**
* No specific CSS rules for DndPlugin itself.
* @returns [base, additional] - Empty arrays.
*/
getCSS() {
return ['', ''];
}
}
The DndMovePlugin enables users to drag and move rectangles around the container.
The DndResizePlugin allows users to resize rectangles by dragging their edges or vertices.
To incorporate the new DnD functionality, follow these integration steps:
DndPlugin, optionally passing configuration options.DndPlugin instance to the factory's plugin list.// Instantiate plugins including DnD plugins
const dndPlugin = new DndPlugin({
move: {}, // You can pass move-specific options here
resize: { handleSize: 12, handleColor: '#e67e22' } // Example resize handle configurations
});
const plugins = [
new BorderPlugin({ size: '3px', color: '#2c3e50' }),
new VertexPlugin({ size: '20px', color: '#e74c3c' }),
new FillPlugin({ color: '#2ecc71' }), // Existing FillPlugin
new TransparencyPlugin({ opacity: 0.8 }), // Existing TransparencyPlugin
dndPlugin // Newly added DnDPlugin
];
// Get the container element
const container = document.getElementById('rectangle-container');
// Instantiate the factory with all plugins
const factory = new RectRegionShapeFactory(container, plugins);
Here's an updated usage example that demonstrates creating multiple rectangles with drag-and-drop capabilities. It also showcases dynamic updates, such as moving and resizing rectangles.
// Usage Example
// 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' }],
[FillPlugin, { color: '#16a085' }],
[TransparencyPlugin, { opacity: 0.85 }]
]
);
}, 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' });
factory.updateGlobalPlugin(FillPlugin, { color: '#34495e' });
factory.updateGlobalPlugin(TransparencyPlugin, { opacity: 0.5 });
// Create new rectangles to see updated global settings
const rect4 = factory.createRect(100, 300, 150, 150);
const rect5 = factory.createRect(400, 350, 200, 100);
rect3.update(
{ x: 600, y: 80, width: 180, height: 120 },
[
[FillPlugin, { color: '#8e44ad' }],
[TransparencyPlugin, { opacity: 0.1 }]
]
);
}, 6000);
If you wish to unregister a plugin (e.g., remove the DndPlugin), you can do so as follows:
setTimeout(() => {
factory.unregisterPlugin(DndPlugin);
}, 8000);
After unregistering the DndPlugin, rectangles will no longer be draggable or resizable.
Below is the complete updated code incorporating the DnD functionalities alongside your existing setup.
Plugins Registration: The RectRegionShapeFactory initializes and registers all plugins, including the new DndPlugin, which in turn manages the DndMovePlugin and DndResizePlugin.
Creating Rectangles: When a rectangle is created via factory.createRect, it is appended to the shadow DOM and wrapped with the necessary plugin functionalities.
Drag and Drop:
n, ne, e, se, s, sw, w, nw) enables resizing the rectangle in the respective direction.Dynamic Updates: The usage example demonstrates how rectangles can be updated, removed, and how global plugin configurations can be altered at runtime, affecting all existing and future rectangles.
Plugin Unregistration: Removing the DndPlugin disables all drag-and-drop functionalities, effectively making the rectangles static.
You can customize the behavior and appearance of the drag-and-drop functionalities by passing configuration options when instantiating the plugins. For example:
DndMovePlugin: Currently, it doesn't accept specific options, but you can extend it to include aspects like drag thresholds or snapping behavior.
DndResizePlugin: You can customize the size and color of the resize handles:
const dndPlugin = new DndPlugin({
move: {}, // Pass move-specific options if any
resize: { handleSize: 16, handleColor: '#e74c3c' } // Customized resize handle configurations
});
Z-Index Management: Ensure that plugins like DndResizePlugin manage z-index appropriately to keep resize handles above other elements.
Performance: For a large number of rectangles, consider optimizing event listeners to prevent performance bottlenecks.
Accessibility: Implement keyboard controls and ARIA attributes to make the drag-and-drop functionality accessible to all users.
Touch Support: Extend event handling to include touch events for mobile device compatibility.
By following this implementation, your rectangle region shape factory is now enhanced with robust drag-and-drop capabilities, allowing for interactive and dynamic manipulation of rectangles within the container. Feel free to further customize and extend the plugins to suit your specific requirements.
Not yet included in a published release.
// DndMovePlugin Implementation
class DndMovePlugin extends PluginInterface {
constructor(options = {}) {
super();
this.host = null;
this.dragging = false;
this.currentRect = null;
this.startX = 0;
this.startY = 0;
this.offsetX = 0;
this.offsetY = 0;
this.handleMouseDown = this.handleMouseDown.bind(this);
this.handleMouseMove = this.handleMouseMove.bind(this);
this.handleMouseUp = this.handleMouseUp.bind(this);
}
/**
* Attaches the move plugin by setting up event listeners.
* @param {HTMLElement} host - The shadow host element.
* @returns [base, additional] - Empty CSS as move doesn't require specific styling.
*/
attach(host) {
this.host = host;
// No additional CSS required for moving
return ['', ''];
}
/**
* Detaches the move plugin by removing event listeners.
* @param {HTMLElement} host - The shadow host element.
*/
detach(host) {
// Remove global event listeners in case they are still attached
host.removeEventListener('mousemove', this.handleMouseMove);
host.removeEventListener('mouseup', this.handleMouseUp);
}
/**
* Updates global configurations if needed.
* @param {Object} options - Options to update.
* @returns [base, additional] - Empty CSS.
*/
updateGlobal(options = {}) {
// Currently, no global options to handle
return ['', ''];
}
/**
* Updates per-rectangle configurations if needed.
* @param {HTMLElement} rect - The rectangle element.
* @param {Object} options - Options to update.
*/
updateRect(rect, options = {}) {
// Currently, no per-rectangle options to handle
// Ensure the rectangle is draggable
rect.style.cursor = 'move';
rect.addEventListener('mousedown', this.handleMouseDown);
}
/**
* Cleans up per-rectangle configurations by removing event listeners.
* @param {HTMLElement} rect - The rectangle element.
*/
onRectRemove(rect) {
rect.removeEventListener('mousedown', this.handleMouseDown);
}
/**
* No specific CSS rules for moving.
* @returns [base, additional] - Empty arrays.
*/
getCSS() {
return ['', ''];
}
/**
* Determines if the drag should initiate moving.
* @param {HTMLElement} rect - The rectangle being interacted with.
* @param {number} x - X-coordinate of the mouse event.
* @param {number} y - Y-coordinate of the mouse event.
* @returns {boolean} - Whether moving is applicable.
*/
isApplicable(rect, x, y) {
// For moving, clicking anywhere inside the rect that's not on resize handles
// Assuming resize handles have higher specificity, so no overlap
return true;
}
/**
* Handles the mousedown event to initiate dragging.
* @param {MouseEvent} e - The mouse event.
*/
handleMouseDown(e) {
// Identify the rectangle element
const rect = e.currentTarget;
if (!this.isApplicable(rect, e.clientX, e.clientY)) return;
this.dragging = true;
this.currentRect = rect;
this.startX = e.clientX;
this.startY = e.clientY;
// Get the current position
const computedStyle = window.getComputedStyle(rect);
const left = parseFloat(computedStyle.left) || 0;
const top = parseFloat(computedStyle.top) || 0;
this.offsetX = this.startX - left;
this.offsetY = this.startY - top;
// Attach global listeners
this.host.ownerDocument.addEventListener('mousemove', this.handleMouseMove);
this.host.ownerDocument.addEventListener('mouseup', this.handleMouseUp);
// Prevent text selection
e.preventDefault();
}
/**
* Handles the mousemove event to update the rectangle's position.
* @param {MouseEvent} e - The mouse event.
*/
handleMouseMove(e) {
if (!this.dragging || !this.currentRect) return;
const newX = e.clientX - this.offsetX;
const newY = e.clientY - this.offsetY;
// Update the rectangle's position
this.currentRect.style.left = `${newX}px`;
this.currentRect.style.top = `${newY}px`;
}
/**
* Handles the mouseup event to finalize dragging.
* @param {MouseEvent} e - The mouse event.
*/
handleMouseUp(e) {
if (!this.dragging) return;
this.dragging = false;
this.currentRect = null;
// Remove global listeners
this.host.ownerDocument.removeEventListener('mousemove', this.handleMouseMove);
this.host.ownerDocument.removeEventListener('mouseup', this.handleMouseUp);
}
}
// DndResizePlugin Implementation
class DndResizePlugin extends PluginInterface {
constructor(options = {}) {
super();
this.host = null;
this.dragging = false;
this.currentRect = null;
this.resizeDirection = null;
this.startX = 0;
this.startY = 0;
this.startWidth = 0;
this.startHeight = 0;
this.startLeft = 0;
this.startTop = 0;
this.handleMouseDown = this.handleMouseDown.bind(this);
this.handleMouseMove = this.handleMouseMove.bind(this);
this.handleMouseUp = this.handleMouseUp.bind(this);
// Define resize handles' size
this.handleSize = options.handleSize || 10;
this.handleColor = options.handleColor || '#2980b9';
}
/**
* Attaches the resize plugin by setting up resize handles and event listeners.
* @param {HTMLElement} host - The shadow host element.
* @returns [base, additional] - CSS styling for resize handles.
*/
attach(host) {
this.host = host;
// Define CSS for resize handles
const base = `
.resize-handle {
position: absolute;
width: ${this.handleSize}px;
height: ${this.handleSize}px;
background-color: ${this.handleColor};
z-index: 10;
}
.resize-handle.n { top: -${this.handleSize / 2}px; left: 50%; cursor: n-resize; transform: translateX(-50%); }
.resize-handle.s { bottom: -${this.handleSize / 2}px; left: 50%; cursor: s-resize; transform: translateX(-50%); }
.resize-handle.e { right: -${this.handleSize / 2}px; top: 50%; cursor: e-resize; transform: translateY(-50%); }
.resize-handle.w { left: -${this.handleSize / 2}px; top: 50%; cursor: w-resize; transform: translateY(-50%); }
.resize-handle.ne { top: -${this.handleSize / 2}px; right: -${this.handleSize / 2}px; cursor: ne-resize; }
.resize-handle.nw { top: -${this.handleSize / 2}px; left: -${this.handleSize / 2}px; cursor: nw-resize; }
.resize-handle.se { bottom: -${this.handleSize / 2}px; right: -${this.handleSize / 2}px; cursor: se-resize; }
.resize-handle.sw { bottom: -${this.handleSize / 2}px; left: -${this.handleSize / 2}px; cursor: sw-resize; }
`;
const additional = ''; // No additional CSS needed
return [base, additional];
}
/**
* Detaches the resize plugin by removing resize handles and event listeners.
* @param {HTMLElement} host - The shadow host element.
*/
detach(host) {
// No global event listeners to remove
}
/**
* Updates global configurations if needed.
* @param {Object} options - Options to update.
* @returns [base, additional] - Updated CSS for resize handles.
*/
updateGlobal(options = {}) {
if (options.handleSize) {
this.handleSize = options.handleSize;
}
if (options.handleColor) {
this.handleColor = options.handleColor;
}
// Re-attach to update CSS
if (this.host) {
return this.attach(this.host);
}
return ['', ''];
}
/**
* Updates per-rectangle configurations by adding resize handles.
* @param {HTMLElement} rect - The rectangle element.
* @param {Object} options - Options to update.
*/
updateRect(rect, options = {}) {
// Add resize handles to the rectangle
const directions = ['n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw'];
directions.forEach(dir => {
const handle = document.createElement('div');
handle.classList.add('resize-handle', dir);
handle.dataset.direction = dir;
rect.appendChild(handle);
handle.addEventListener('mousedown', (e) => this.handleMouseDown(e, dir));
});
}
/**
* Cleans up per-rectangle configurations by removing resize handles and event listeners.
* @param {HTMLElement} rect - The rectangle element.
*/
onRectRemove(rect) {
const handles = rect.querySelectorAll('.resize-handle');
handles.forEach(handle => {
handle.removeEventListener('mousedown', this.handleMouseDown);
handle.remove();
});
}
/**
* No specific base CSS rules.
* @returns [base, additional] - Empty arrays.
*/
getCSS() {
return ['', ''];
}
/**
* Determines if the drag should initiate resizing based on the handle.
* @param {HTMLElement} rect - The rectangle being interacted with.
* @param {string} direction - The direction of the resize handle.
* @returns {boolean} - Whether resizing is applicable.
*/
isApplicable(rect, direction) {
// Currently, always applicable if a resize handle is used
return ['n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw'].includes(direction);
}
/**
* Handles the mousedown event on a resize handle to initiate resizing.
* @param {MouseEvent} e - The mouse event.
* @param {string} direction - The direction of the resize handle.
*/
handleMouseDown(e, direction) {
e.stopPropagation(); // Prevent triggering move
const rect = e.currentTarget.parentElement;
if (!this.isApplicable(rect, direction)) return;
this.dragging = true;
this.currentRect = rect;
this.resizeDirection = direction;
this.startX = e.clientX;
this.startY = e.clientY;
const computedStyle = window.getComputedStyle(rect);
this.startWidth = parseFloat(computedStyle.getPropertyValue('width'));
this.startHeight = parseFloat(computedStyle.getPropertyValue('height'));
this.startLeft = parseFloat(computedStyle.left);
this.startTop = parseFloat(computedStyle.top);
// Attach global listeners
this.host.ownerDocument.addEventListener('mousemove', this.handleMouseMove);
this.host.ownerDocument.addEventListener('mouseup', this.handleMouseUp);
// Prevent text selection
e.preventDefault();
}
/**
* Handles the mousemove event to update the rectangle's size.
* @param {MouseEvent} e - The mouse event.
*/
handleMouseMove(e) {
if (!this.dragging || !this.currentRect) return;
const dx = e.clientX - this.startX;
const dy = e.clientY - this.startY;
let newWidth = this.startWidth;
let newHeight = this.startHeight;
let newLeft = this.startLeft;
let newTop = this.startTop;
switch (this.resizeDirection) {
case 'n':
newHeight = this.startHeight - dy;
newTop = this.startTop + dy;
break;
case 's':
newHeight = this.startHeight + dy;
break;
case 'e':
newWidth = this.startWidth + dx;
break;
case 'w':
newWidth = this.startWidth - dx;
newLeft = this.startLeft + dx;
break;
case 'ne':
newWidth = this.startWidth + dx;
newHeight = this.startHeight - dy;
newTop = this.startTop + dy;
break;
case 'nw':
newWidth = this.startWidth - dx;
newHeight = this.startHeight - dy;
newLeft = this.startLeft + dx;
newTop = this.startTop + dy;
break;
case 'se':
newWidth = this.startWidth + dx;
newHeight = this.startHeight + dy;
break;
case 'sw':
newWidth = this.startWidth - dx;
newHeight = this.startHeight + dy;
newLeft = this.startLeft + dx;
break;
default:
break;
}
// Enforce minimum size
newWidth = Math.max(newWidth, 20);
newHeight = Math.max(newHeight, 20);
// Update styles
this.currentRect.style.width = `${newWidth}px`;
this.currentRect.style.height = `${newHeight}px`;
this.currentRect.style.left = `${newLeft}px`;
this.currentRect.style.top = `${newTop}px`;
}
/**
* Handles the mouseup event to finalize resizing.
* @param {MouseEvent} e - The mouse event.
*/
handleMouseUp(e) {
if (!this.dragging) return;
this.dragging = false;
this.currentRect = null;
this.resizeDirection = null;
// Remove global listeners
this.host.ownerDocument.removeEventListener('mousemove', this.handleMouseMove);
this.host.ownerDocument.removeEventListener('mouseup', this.handleMouseUp);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Rectangle Region Shape Factory with DnD</title>
<style>
/* Basic styles for the container */
#rectangle-container {
position: relative;
width: 1000px;
height: 600px;
border: 1px solid #ccc;
margin: 20px auto;
background-color: #f9f9f9;
}
</style>
</head>
<body>
<div id="rectangle-container"></div>
<script>
// PluginInterface and existing plugins (BorderPlugin, VertexPlugin, FillPlugin, TransparencyPlugin)
// ... [Include all your existing PluginInterface and other plugin classes here] ...
// Insert the existing PluginInterface, BorderPlugin, VertexPlugin, FillPlugin, and TransparencyPlugin classes here
// For brevity, they are assumed to be already defined as per your initial code
// DndPlugin Implementation
class DndPlugin extends PluginInterface {
/**
* Constructs a DndPlugin instance and initializes move and resize plugins.
* @param {Object} options - Configuration options.
*/
constructor(options = {}) {
super();
this.movePlugin = new DndMovePlugin(options.move || {});
this.resizePlugin = new DndResizePlugin(options.resize || {});
}
/**
* Attaches both move and resize plugins.
* @param {HTMLElement} host - The shadow host element.
* @returns [base, additional] - Combined CSS rules from both plugins.
*/
attach(host) {
const [moveBase, moveAdditional] = this.movePlugin.attach(host);
const [resizeBase, resizeAdditional] = this.resizePlugin.attach(host);
return [
moveBase + '\n' + resizeBase,
moveAdditional + '\n' + resizeAdditional,
];
}
/**
* Detaches both move and resize plugins.
* @param {HTMLElement} host - The shadow host element.
*/
detach(host) {
this.movePlugin.detach(host);
this.resizePlugin.detach(host);
}
/**
* Updates global configurations for both move and resize plugins.
* @param {Object} options - Options to update.
* @returns [base, additional] - Combined updated CSS rules.
*/
updateGlobal(options = {}) {
const [moveBase, moveAdditional] = this.movePlugin.updateGlobal(options.move || {});
const [resizeBase, resizeAdditional] = this.resizePlugin.updateGlobal(options.resize || {});
return [
moveBase + '\n' + resizeBase,
moveAdditional + '\n' + resizeAdditional,
];
}
/**
* Updates per-rectangle configurations for both move and resize plugins.
* @param {HTMLElement} rect - The rectangle element.
* @param {Object} options - Options to update.
*/
updateRect(rect, options = {}) {
if (options.move) {
this.movePlugin.updateRect(rect, options.move);
}
if (options.resize) {
this.resizePlugin.updateRect(rect, options.resize);
}
}
/**
* Cleans up per-rectangle configurations by detaching plugins.
* @param {HTMLElement} rect - The rectangle element.
*/
onRectRemove(rect) {
this.movePlugin.onRectRemove(rect);
this.resizePlugin.onRectRemove(rect);
}
/**
* No specific CSS rules for DndPlugin itself.
* @returns [base, additional] - Empty arrays.
*/
getCSS() {
return ['', ''];
}
}
// DndMovePlugin Implementation
class DndMovePlugin extends PluginInterface {
constructor(options = {}) {
super();
this.host = null;
this.dragging = false;
this.currentRect = null;
this.startX = 0;
this.startY = 0;
this.offsetX = 0;
this.offsetY = 0;
this.handleMouseDown = this.handleMouseDown.bind(this);
this.handleMouseMove = this.handleMouseMove.bind(this);
this.handleMouseUp = this.handleMouseUp.bind(this);
}
/**
* Attaches the move plugin by setting up event listeners.
* @param {HTMLElement} host - The shadow host element.
* @returns [base, additional] - Empty CSS as move doesn't require specific styling.
*/
attach(host) {
this.host = host;
// No additional CSS required for moving
return ['', ''];
}
/**
* Detaches the move plugin by removing event listeners.
* @param {HTMLElement} host - The shadow host element.
*/
detach(host) {
// Remove global event listeners in case they are still attached
host.removeEventListener('mousemove', this.handleMouseMove);
host.removeEventListener('mouseup', this.handleMouseUp);
}
/**
* Updates global configurations if needed.
* @param {Object} options - Options to update.
* @returns [base, additional] - Empty CSS.
*/
updateGlobal(options = {}) {
// Currently, no global options to handle
return ['', ''];
}
/**
* Updates per-rectangle configurations if needed.
* @param {HTMLElement} rect - The rectangle element.
* @param {Object} options - Options to update.
*/
updateRect(rect, options = {}) {
// Currently, no per-rectangle options to handle
// Ensure the rectangle is draggable
rect.style.cursor = 'move';
rect.addEventListener('mousedown', this.handleMouseDown);
}
/**
* Cleans up per-rectangle configurations by removing event listeners.
* @param {HTMLElement} rect - The rectangle element.
*/
onRectRemove(rect) {
rect.removeEventListener('mousedown', this.handleMouseDown);
}
/**
* No specific CSS rules for moving.
* @returns [base, additional] - Empty arrays.
*/
getCSS() {
return ['', ''];
}
/**
* Determines if the drag should initiate moving.
* @param {HTMLElement} rect - The rectangle being interacted with.
* @param {number} x - X-coordinate of the mouse event.
* @param {number} y - Y-coordinate of the mouse event.
* @returns {boolean} - Whether moving is applicable.
*/
isApplicable(rect, x, y) {
// For moving, clicking anywhere inside the rect that's not on resize handles
// Assuming resize handles have higher specificity, so no overlap
return true;
}
/**
* Handles the mousedown event to initiate dragging.
* @param {MouseEvent} e - The mouse event.
*/
handleMouseDown(e) {
// Identify the rectangle element
const rect = e.currentTarget;
if (!this.isApplicable(rect, e.clientX, e.clientY)) return;
this.dragging = true;
this.currentRect = rect;
this.startX = e.clientX;
this.startY = e.clientY;
// Get the current position
const computedStyle = window.getComputedStyle(rect);
const left = parseFloat(computedStyle.left) || 0;
const top = parseFloat(computedStyle.top) || 0;
this.offsetX = this.startX - left;
this.offsetY = this.startY - top;
// Attach global listeners
this.host.ownerDocument.addEventListener('mousemove', this.handleMouseMove);
this.host.ownerDocument.addEventListener('mouseup', this.handleMouseUp);
// Prevent text selection
e.preventDefault();
}
/**
* Handles the mousemove event to update the rectangle's position.
* @param {MouseEvent} e - The mouse event.
*/
handleMouseMove(e) {
if (!this.dragging || !this.currentRect) return;
const newX = e.clientX - this.offsetX;
const newY = e.clientY - this.offsetY;
// Update the rectangle's position
this.currentRect.style.left = `${newX}px`;
this.currentRect.style.top = `${newY}px`;
}
/**
* Handles the mouseup event to finalize dragging.
* @param {MouseEvent} e - The mouse event.
*/
handleMouseUp(e) {
if (!this.dragging) return;
this.dragging = false;
this.currentRect = null;
// Remove global listeners
this.host.ownerDocument.removeEventListener('mousemove', this.handleMouseMove);
this.host.ownerDocument.removeEventListener('mouseup', this.handleMouseUp);
}
}
// DndResizePlugin Implementation
class DndResizePlugin extends PluginInterface {
constructor(options = {}) {
super();
this.host = null;
this.dragging = false;
this.currentRect = null;
this.resizeDirection = null;
this.startX = 0;
this.startY = 0;
this.startWidth = 0;
this.startHeight = 0;
this.startLeft = 0;
this.startTop = 0;
this.handleMouseDown = this.handleMouseDown.bind(this);
this.handleMouseMove = this.handleMouseMove.bind(this);
this.handleMouseUp = this.handleMouseUp.bind(this);
// Define resize handles' size
this.handleSize = options.handleSize || 10;
this.handleColor = options.handleColor || '#2980b9';
}
/**
* Attaches the resize plugin by setting up resize handles and event listeners.
* @param {HTMLElement} host - The shadow host element.
* @returns [base, additional] - CSS styling for resize handles.
*/
attach(host) {
this.host = host;
// Define CSS for resize handles
const base = `
.resize-handle {
position: absolute;
width: ${this.handleSize}px;
height: ${this.handleSize}px;
background-color: ${this.handleColor};
z-index: 10;
}
.resize-handle.n { top: -${this.handleSize / 2}px; left: 50%; cursor: n-resize; transform: translateX(-50%); }
.resize-handle.s { bottom: -${this.handleSize / 2}px; left: 50%; cursor: s-resize; transform: translateX(-50%); }
.resize-handle.e { right: -${this.handleSize / 2}px; top: 50%; cursor: e-resize; transform: translateY(-50%); }
.resize-handle.w { left: -${this.handleSize / 2}px; top: 50%; cursor: w-resize; transform: translateY(-50%); }
.resize-handle.ne { top: -${this.handleSize / 2}px; right: -${this.handleSize / 2}px; cursor: ne-resize; }
.resize-handle.nw { top: -${this.handleSize / 2}px; left: -${this.handleSize / 2}px; cursor: nw-resize; }
.resize-handle.se { bottom: -${this.handleSize / 2}px; right: -${this.handleSize / 2}px; cursor: se-resize; }
.resize-handle.sw { bottom: -${this.handleSize / 2}px; left: -${this.handleSize / 2}px; cursor: sw-resize; }
`;
const additional = ''; // No additional CSS needed
return [base, additional];
}
/**
* Detaches the resize plugin by removing resize handles and event listeners.
* @param {HTMLElement} host - The shadow host element.
*/
detach(host) {
// No global event listeners to remove
}
/**
* Updates global configurations if needed.
* @param {Object} options - Options to update.
* @returns [base, additional] - Updated CSS for resize handles.
*/
updateGlobal(options = {}) {
if (options.handleSize) {
this.handleSize = options.handleSize;
}
if (options.handleColor) {
this.handleColor = options.handleColor;
}
// Re-attach to update CSS
if (this.host) {
return this.attach(this.host);
}
return ['', ''];
}
/**
* Updates per-rectangle configurations by adding resize handles.
* @param {HTMLElement} rect - The rectangle element.
* @param {Object} options - Options to update.
*/
updateRect(rect, options = {}) {
// Add resize handles to the rectangle
const directions = ['n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw'];
directions.forEach(dir => {
const handle = document.createElement('div');
handle.classList.add('resize-handle', dir);
handle.dataset.direction = dir;
rect.appendChild(handle);
handle.addEventListener('mousedown', (e) => this.handleMouseDown(e, dir));
});
}
/**
* Cleans up per-rectangle configurations by removing resize handles and event listeners.
* @param {HTMLElement} rect - The rectangle element.
*/
onRectRemove(rect) {
const handles = rect.querySelectorAll('.resize-handle');
handles.forEach(handle => {
handle.removeEventListener('mousedown', this.handleMouseDown);
handle.remove();
});
}
/**
* No specific base CSS rules.
* @returns [base, additional] - Empty arrays.
*/
getCSS() {
return ['', ''];
}
/**
* Determines if the drag should initiate resizing based on the handle.
* @param {HTMLElement} rect - The rectangle being interacted with.
* @param {string} direction - The direction of the resize handle.
* @returns {boolean} - Whether resizing is applicable.
*/
isApplicable(rect, direction) {
// Currently, always applicable if a resize handle is used
return ['n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw'].includes(direction);
}
/**
* Handles the mousedown event on a resize handle to initiate resizing.
* @param {MouseEvent} e - The mouse event.
* @param {string} direction - The direction of the resize handle.
*/
handleMouseDown(e, direction) {
e.stopPropagation(); // Prevent triggering move
const rect = e.currentTarget.parentElement;
if (!this.isApplicable(rect, direction)) return;
this.dragging = true;
this.currentRect = rect;
this.resizeDirection = direction;
this.startX = e.clientX;
this.startY = e.clientY;
const computedStyle = window.getComputedStyle(rect);
this.startWidth = parseFloat(computedStyle.getPropertyValue('width'));
this.startHeight = parseFloat(computedStyle.getPropertyValue('height'));
this.startLeft = parseFloat(computedStyle.left);
this.startTop = parseFloat(computedStyle.top);
// Attach global listeners
this.host.ownerDocument.addEventListener('mousemove', this.handleMouseMove);
this.host.ownerDocument.addEventListener('mouseup', this.handleMouseUp);
// Prevent text selection
e.preventDefault();
}
/**
* Handles the mousemove event to update the rectangle's size.
* @param {MouseEvent} e - The mouse event.
*/
handleMouseMove(e) {
if (!this.dragging || !this.currentRect) return;
const dx = e.clientX - this.startX;
const dy = e.clientY - this.startY;
let newWidth = this.startWidth;
let newHeight = this.startHeight;
let newLeft = this.startLeft;
let newTop = this.startTop;
switch (this.resizeDirection) {
case 'n':
newHeight = this.startHeight - dy;
newTop = this.startTop + dy;
break;
case 's':
newHeight = this.startHeight + dy;
break;
case 'e':
newWidth = this.startWidth + dx;
break;
case 'w':
newWidth = this.startWidth - dx;
newLeft = this.startLeft + dx;
break;
case 'ne':
newWidth = this.startWidth + dx;
newHeight = this.startHeight - dy;
newTop = this.startTop + dy;
break;
case 'nw':
newWidth = this.startWidth - dx;
newHeight = this.startHeight - dy;
newLeft = this.startLeft + dx;
newTop = this.startTop + dy;
break;
case 'se':
newWidth = this.startWidth + dx;
newHeight = this.startHeight + dy;
break;
case 'sw':
newWidth = this.startWidth - dx;
newHeight = this.startHeight + dy;
newLeft = this.startLeft + dx;
break;
default:
break;
}
// Enforce minimum size
newWidth = Math.max(newWidth, 20);
newHeight = Math.max(newHeight, 20);
// Update styles
this.currentRect.style.width = `${newWidth}px`;
this.currentRect.style.height = `${newHeight}px`;
this.currentRect.style.left = `${newLeft}px`;
this.currentRect.style.top = `${newTop}px`;
}
/**
* Handles the mouseup event to finalize resizing.
* @param {MouseEvent} e - The mouse event.
*/
handleMouseUp(e) {
if (!this.dragging) return;
this.dragging = false;
this.currentRect = null;
this.resizeDirection = null;
// Remove global listeners
this.host.ownerDocument.removeEventListener('mousemove', this.handleMouseMove);
this.host.ownerDocument.removeEventListener('mouseup', this.handleMouseUp);
}
}
// 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);
});
// 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);
this.rect.style.width = `${width}px`;
}
if (height !== undefined) {
this.rect.style.setProperty('--height', typeof height === 'number' ? `${height}px` : height);
this.rect.style.height = `${height}px`;
}
// 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 = `
position: absolute;
width: var(--width, 100px);
height: var(--height, 100px);
box-sizing: border-box;
/* Ensure rectangles are positioned correctly */
transition: all 0.2s ease;
`.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`);
rect.style.width = `${width}px`;
rect.style.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;
}
}
// Instantiate DnDPlugin
const dndPlugin = new DndPlugin({
move: {}, // Pass move-specific options if any
resize: { handleSize: 12, handleColor: '#e67e22' } // Example resize handle configurations
});
// Instantiate other plugins
const plugins = [
new BorderPlugin({ size: '3px', color: '#2c3e50' }),
new VertexPlugin({ size: '20px', color: '#e74c3c' }),
new FillPlugin({ color: '#2ecc71' }), // Existing FillPlugin
new TransparencyPlugin({ opacity: 0.8 }), // Existing TransparencyPlugin
dndPlugin // Newly added DnDPlugin
];
// Get the container element
const container = document.getElementById('rectangle-container');
// Instantiate the factory with all plugins
const factory = new RectRegionShapeFactory(container, plugins);
// Usage Example
// 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' }],
[FillPlugin, { color: '#16a085' }],
[TransparencyPlugin, { opacity: 0.85 }]
]
);
}, 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' });
factory.updateGlobalPlugin(FillPlugin, { color: '#34495e' });
factory.updateGlobalPlugin(TransparencyPlugin, { opacity: 0.5 });
// Create new rectangles to see updated global settings
const rect4 = factory.createRect(100, 300, 150, 150);
const rect5 = factory.createRect(400, 350, 200, 100);
rect3.update(
{ x: 600, y: 80, width: 180, height: 120 },
[
[FillPlugin, { color: '#8e44ad' }],
[TransparencyPlugin, { opacity: 0.1 }]
]
);
}, 6000);
// Example: Unregister the DndPlugin after 8 seconds
setTimeout(() => {
factory.unregisterPlugin(DndPlugin);
console.log('DndPlugin has been unregistered. Drag and drop is now disabled.');
}, 8000);
</script>
</body>
</html>