javascript / expert
Snippet
Polymorphic State Machine Controllers Attached to Svelte Node Actions
Using object-oriented state inheritance within Svelte DOM actions encapsulates event handler branching logic into polymorphic classes, replacing monolithic switch statements.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
export class BaseActionState {constructor(node) { this.node = node; }handlePointerDown(e) { return this; }handlePointerMove(e) { return this; }destroy() {}}export class IdleState extends BaseActionState {handlePointerDown(e) {this.node.style.borderColor = '#0055ff';return new DraggingState(this.node);}}export class DraggingState extends BaseActionState {handlePointerMove(e) {this.node.style.transform = `translate(${e.clientX}px, ${e.clientY}px)`;return this;}}export function statefulAction(node) {let current = new IdleState(node);const onDown = (e) => { current = current.handlePointerDown(e) || current; };const onMove = (e) => { current = current.handlePointerMove(e) || current; };node.addEventListener('pointerdown', onDown);window.addEventListener('pointermove', onMove);return {destroy() {current.destroy();node.removeEventListener('pointerdown', onDown);window.removeEventListener('pointermove', onMove);}};}
svelte
Breakdown
1
export class BaseActionState {
Abstract base class defining state interface signatures for node interaction handlers.
2
return new DraggingState(this.node);
Executes state transition by yielding a new state instance to replace active controller state.
3
current = current.handlePointerDown(e) || current;
Delegates event handling polymorphically to current state object and updates state reference.