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' }]]);
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;
}
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];
return rectContext[name].value;
}
}
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);
`,
});