homemanager-fe/src/modules/house-planner/tools.ts

468 lines
12 KiB
TypeScript

import type { HousePlannerCanvas } from './canvas';
import { HousePlannerCanvasHistory } from './history';
import {
History,
ICanvasToolBase,
Layer,
LayerObject,
Line,
ToolEvent,
Vec2,
} from './interfaces';
import { LineTool } from './tools/line';
import { MoveTool } from './tools/move';
import { vec2Distance, vec2Snap, vec2Sub } from './utils';
export class HousePlannerCanvasTools {
public selectedLayer?: Layer;
public selectedObjects: LayerObject[] = [];
public mousePosition: Vec2 = [0, 0];
public mouseClickPosition: Vec2 = [0, 0];
public mousePositionSnapped: Vec2 = [0, 0];
public gridSnap = true;
public gridSnapScale = 8;
public tool?: ICanvasToolBase<unknown>;
public tools: Record<string, ICanvasToolBase<unknown>> = {
['move']: new MoveTool(this),
['line']: new LineTool(this),
};
public history = new HousePlannerCanvasHistory();
public lastStrokeWidth = 16;
public lastColor = '#000000';
public holdShift = false;
public selectError = 16;
private dragging = false;
private pinching = false;
private lastPinchLength = 0;
private moved = false;
private clickedOn: LayerObject | null = null;
constructor(public manager: HousePlannerCanvas) {}
get canvas() {
return this.manager.canvas;
}
get ctx() {
return this.manager.ctx;
}
isSelected(object: LayerObject) {
return this.selectedObjects.indexOf(object) > -1;
}
selectLayer(layer: Layer) {
if (this.selectedLayer) {
this.selectedLayer.active = false;
for (const item of this.selectedLayer.contents) {
item.selected = false;
}
this.selectedObjects.length = 0;
}
this.selectedLayer = layer;
this.selectedLayer.active = true;
this.canvas.dispatchEvent(
new CustomEvent('hpc:layerchange', {
detail: this.selectedObjects,
})
);
this.canvas.dispatchEvent(
new CustomEvent('hpc:update', {
detail: {
event: 'layerchange',
},
})
);
}
selectObject(object?: LayerObject | null, add = false) {
if (!object) {
if (!add) {
this.selectedObjects.forEach((object) => {
object.selected = false;
});
this.selectedObjects.length = 0;
this.tool?.selectionChanged(this.selectedObjects);
}
this.manager.draw();
this.selectedEvent();
return;
}
if (this.selectedObjects.includes(object)) {
// Unselect in multi-select
if (add) {
const foundAt = this.selectedObjects.indexOf(object);
object.selected = false;
this.selectedObjects.splice(foundAt, 1);
this.tool?.selectionChanged(this.selectedObjects);
this.manager.draw();
this.selectedEvent();
}
return;
}
// Select in multi-select
if (add) {
object.selected = true;
this.selectedObjects.push(object);
this.tool?.selectionChanged(this.selectedObjects);
this.manager.draw();
this.selectedEvent();
return;
}
this.selectedObjects.forEach((obj) => {
obj.selected = false;
});
object.selected = true;
this.selectedObjects = [object];
this.tool?.selectionChanged(this.selectedObjects);
this.manager.draw();
this.selectedEvent();
}
setInitialSelection() {
if (!this.selectedLayer) return;
this.selectedObjects = this.selectedLayer.contents.filter(
(object) => object.selected
);
}
getMousedObject() {
if (!this.selectedLayer?.visible) return null;
const [x, y] = this.mousePosition;
for (const object of this.selectedLayer.contents) {
if ((object as Line).segments) {
const moused = this.manager.isOnLine(
object as Line,
x,
y,
this.selectError
);
if (moused) return object;
}
// TODO: other kinds of objects
}
return null;
}
getMousedLineSegment(line: Line) {
if (!this.selectedLayer?.visible) return null;
const [x, y] = this.mousePosition;
let lastSegment = null;
for (const segment of line.segments) {
const lastPoint = lastSegment ? lastSegment.end : (segment.start as Vec2);
if (
this.manager.isOnSegment(
line,
segment,
lastPoint,
x,
y,
this.selectError
)
) {
return segment;
}
lastSegment = segment;
}
return null;
}
drawHighlights() {
for (const object of this.selectedObjects) {
const line = object as Line;
if (line.segments) {
const path = this.manager.makeLinePath(line);
this.manager.setupLine(line, this.selectError, '#00ddff55');
this.ctx.stroke(path);
}
// TODO: other kinds of objects
}
this.tool?.drawHighlights();
}
drawControls() {
this.tool?.drawControls();
}
cleanUp() {}
setTool(tool?: string, subTool?: string) {
if (!tool) {
this.tool?.deactivate();
this.setTool('move');
return;
}
if (this.tool?.name === tool) {
if (!subTool) return;
this.tool.setSubTool(subTool);
this.canvas.dispatchEvent(
new CustomEvent<ToolEvent>('hpc:tool', {
detail: { primary: this.tool.name, secondary: this.tool.subTool },
})
);
this.manager.draw();
return;
}
const findTool = this.tools[tool];
if (!findTool) return;
if (this.tool) this.tool.deactivate();
this.tool = findTool;
this.tool.activate();
if (subTool) {
this.tool.setSubTool(subTool);
}
this.canvas.dispatchEvent(
new CustomEvent<ToolEvent>('hpc:tool', {
detail: { primary: this.tool.name, secondary: this.tool.subTool },
})
);
this.manager.draw();
}
get activeTool() {
return this.tool?.name;
}
onMouseMove(e: MouseEvent) {
this.dragEvent(e.clientX, e.clientY);
}
onMouseDown(e: MouseEvent) {
this.mousePosition = [e.clientX, e.clientY];
this.mouseClickPosition = [...this.mousePosition];
this.mousePositionSnapped = this.gridSnap
? vec2Snap(this.mousePosition, this.gridSnapScale)
: this.mousePosition;
this.dragging = true;
this.moved = false;
this.pointerDown();
}
onMouseUp(e: MouseEvent) {
this.dragging = false;
this.pointerUp();
}
onTouchMove(ev: TouchEvent) {
ev.preventDefault();
if (ev.touches.length === 2 && this.pinching) {
const pinchLength = Math.hypot(
ev.touches[0].pageX - ev.touches[1].pageX,
ev.touches[0].pageY - ev.touches[1].pageY
);
// TODO: zoom
// if (this.lastPinchLength) {
// const delta = pinchLength / this.lastPinchLength;
// const scaleX = (ev.touches[0].clientX - this._posx) / this._zoom;
// const scaleY = (ev.touches[0].clientY - this._posy) / this._zoom;
// delta > 0 ? (this._zoom *= delta) : (this._zoom /= delta);
// this._zoom = clamp(this._zoom, 1, 100);
// this._posx = ev.touches[0].clientX - scaleX * this._zoom;
// this._posy = ev.touches[0].clientY - scaleY * this._zoom;
// }
// this.lastPinchLength = pinchLength;
}
this.dragEvent(ev.touches[0].clientX, ev.touches[0].clientY);
}
onTouchStart(e: TouchEvent) {
e.preventDefault();
const touch = e.touches[0] || e.changedTouches[0];
this.mousePosition = [touch.pageX, touch.pageY];
this.mouseClickPosition = [...this.mousePosition];
this.mousePositionSnapped = this.gridSnap
? vec2Snap(this.mousePosition, this.gridSnapScale)
: this.mousePosition;
this.dragging = true;
this.moved = false;
if (e.touches.length === 2) {
this.pinching = true;
}
this.pointerDown();
}
onTouchEnd(e: TouchEvent) {
this.pinching = false;
this.lastPinchLength = 0;
if (!e.touches?.length) {
this.dragging = false;
}
this.pointerUp();
}
onMouseWheel(e: WheelEvent) {
// TODO: zoom
// ev.preventDefault();
// this._mousex = ev.clientX;
// this._mousey = ev.clientY;
// const scaleX = (ev.clientX - this._posx) / this._zoom;
// const scaleY = (ev.clientY - this._posy) / this._zoom;
// ev.deltaY < 0 ? (this._zoom *= 1.2) : (this._zoom /= 1.2);
// this._zoom = clamp(this._zoom, this._minZoom, this._maxZoom);
// this._posx = ev.clientX - scaleX * this._zoom;
// this._posy = ev.clientY - scaleY * this._zoom;
// const realSize = this._zoom * this._size;
// this._posx = clamp(this._posx, this._cursorx - realSize, this._cursorx);
// this._posy = clamp(this._posy, this._cursory - realSize, this._cursory);
}
onPointerLeave() {
this.dragging = false;
}
onKeyDown(e: KeyboardEvent) {
if (e.key === 'z' && e.ctrlKey) {
this.history.undo();
this.manager.draw();
this.canvas.dispatchEvent(
new CustomEvent('hpc:undo', {
detail: 'keyboard',
})
);
this.canvas.dispatchEvent(
new CustomEvent('hpc:update', {
detail: {
event: 'undo',
},
})
);
}
if (e.key === 'y' && e.ctrlKey) {
this.history.redo();
this.manager.draw();
this.canvas.dispatchEvent(
new CustomEvent('hpc:redo', {
detail: 'keyboard',
})
);
this.canvas.dispatchEvent(
new CustomEvent('hpc:update', {
detail: { event: 'redo' },
})
);
}
if (e.key === 'Shift') {
this.holdShift = true;
}
}
onKeyUp(e: KeyboardEvent) {
if (e.key === 'Enter') {
}
if (e.key === 'Escape') {
this.tool?.escapePress(e);
if (this.selectedObjects.length === 0 && this.tool?.isToolCancelable()) {
this.setTool();
}
this.selectObject(null);
}
if (e.key === 'Shift') {
this.holdShift = false;
}
if (e.key === 'l') {
this.setTool('line');
}
if (e.key === 'Delete' || e.key === 'x') {
this.deleteSelection();
}
}
deleteSelection() {
if (!this.selectedObjects.length || !this.selectedLayer) return;
this.history.appendToHistory([
{
object: this.selectedLayer,
property: 'contents',
value: [...this.selectedLayer.contents],
} as History<typeof this.selectedLayer>,
]);
this.selectedLayer.contents = this.selectedLayer.contents.filter(
(item) => this.selectedObjects.indexOf(item) === -1
);
this.selectedObjects.length = 0;
this.tool?.selectionDeleted();
this.tool?.selectionChanged([]);
this.manager.draw();
this.canvas.dispatchEvent(
new CustomEvent('hpc:update', {
detail: { event: 'delete' },
})
);
}
private pointerDown() {
this.clickedOn = this.getMousedObject();
this.tool?.mouseDown(this.clickedOn || undefined);
}
private pointerUp() {
// FIXME: possibly there's a better approach, but right now some clicks do not register
if (
this.moved &&
vec2Distance(this.mouseClickPosition, this.mousePosition) < 0.25
) {
this.moved = false;
}
this.tool?.mouseUp(this.moved);
this.clickedOn = null;
}
private dragEvent(x: number, y: number) {
this.moved = true;
const currentPos = this.gridSnap
? vec2Snap(this.mousePosition, this.gridSnapScale)
: this.mousePosition;
const rect = this.manager.canvas.getBoundingClientRect();
this.mousePosition = [x - rect.left, y - rect.top];
this.mousePositionSnapped = this.gridSnap
? vec2Snap(this.mousePosition, this.gridSnapScale)
: this.mousePosition;
let offset = vec2Sub(currentPos, this.mousePositionSnapped);
this.tool?.mouseMoved(
this.mousePositionSnapped,
offset,
this.mousePosition
);
}
private selectedEvent() {
this.canvas.dispatchEvent(
new CustomEvent('hpc:selectionchange', {
detail: this.selectedObjects,
})
);
}
}