Implement ToolManager.ts
This commit is contained in:
@@ -0,0 +1,76 @@
|
|||||||
|
import { YjsDocument } from '../crdt/YjsDocument';
|
||||||
|
import { Tool } from './Tool';
|
||||||
|
|
||||||
|
interface ToolConstructor {
|
||||||
|
new (yjsDoc: YjsDocument): Tool;
|
||||||
|
}
|
||||||
|
|
||||||
|
class ToolManager {
|
||||||
|
private yjsDoc: YjsDocument;
|
||||||
|
private activeTool: Tool | null = null;
|
||||||
|
private tools: Map<string, ToolConstructor> = new Map();
|
||||||
|
private canvas: HTMLElement;
|
||||||
|
|
||||||
|
constructor(yjsDoc: YjsDocument, canvas: HTMLElement) {
|
||||||
|
this.yjsDoc = yjsDoc;
|
||||||
|
this.canvas = canvas;
|
||||||
|
this.setupEventListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
registerTool(name: string, toolConstructor: ToolConstructor): void {
|
||||||
|
this.tools.set(name, toolConstructor);
|
||||||
|
}
|
||||||
|
|
||||||
|
activateTool(toolName: string): void {
|
||||||
|
// Reset current tool if exists
|
||||||
|
if (this.activeTool) {
|
||||||
|
this.activeTool.reset();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create and activate new tool
|
||||||
|
const ToolClass = this.tools.get(toolName);
|
||||||
|
if (ToolClass) {
|
||||||
|
this.activeTool = new ToolClass(this.yjsDoc);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
deactivateTool(): void {
|
||||||
|
if (this.activeTool) {
|
||||||
|
this.activeTool.reset();
|
||||||
|
this.activeTool = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private setupEventListeners(): void {
|
||||||
|
this.canvas.addEventListener('mousedown', this.handleMouseDown.bind(this));
|
||||||
|
this.canvas.addEventListener('mousemove', this.handleMouseMove.bind(this));
|
||||||
|
this.canvas.addEventListener('mouseup', this.handleMouseUp.bind(this));
|
||||||
|
document.addEventListener('keyup', this.handleKeyUp.bind(this));
|
||||||
|
}
|
||||||
|
|
||||||
|
private handleMouseDown(event: MouseEvent): void {
|
||||||
|
if (this.activeTool) {
|
||||||
|
this.activeTool.onMouseDown(event);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private handleMouseMove(event: MouseEvent): void {
|
||||||
|
if (this.activeTool) {
|
||||||
|
this.activeTool.onMouseMove(event);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private handleMouseUp(event: MouseEvent): void {
|
||||||
|
if (this.activeTool) {
|
||||||
|
this.activeTool.onMouseUp(event);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private handleKeyUp(event: KeyboardEvent): void {
|
||||||
|
if (this.activeTool) {
|
||||||
|
this.activeTool.onKeyUp(event);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export { ToolManager };
|
||||||
Reference in New Issue
Block a user