I have a problem: "When a mouse down, create a rectangle, resize it when move and complete when a mouse up". I tried to use rxjs, but it is not really good solution:
import { scan, mergeMap, takeUntil, fromEvent } from 'rxjs';
const mouseDown$ = fromEvent(document, 'mousedown');
const mouseUp$ = fromEvent(document, 'mouseup');
const mouseMove$ = fromEvent(document, 'mousemove');
function createNode() {
const node = document.createElement('DIV');
node.setAttribute('style', 'position: absolute; border: 1px solid red;');
document.body.appendChild(node);
return node;
}
mouseDown$
.pipe(
mergeMap(() => {
return mouseMove$.pipe(
takeUntil(mouseUp$),
scan((node, e: MouseEvent) => {
if (!node) {
let x = null;
x = createNode();
x.style.top = `${e.clientY}px`;
x.style.left = `${e.clientX}px`;
return x;
} else {
node.style.bottom = `${e.clientY}px`;
node.style.right = `${e.clientX}px`;
}
return node;
}, null)
);
})
)
.subscribe(() => {});
The problem is the side-effects is added to the method "scan" Do you have much better solution for this problem?