Files
interactor/interactor.js
2025-11-06 14:09:13 -07:00

53 lines
1.3 KiB
JavaScript

import { Stream } from './stream.js';
export class Interactor {
_actions = new Stream();
_reactions = new Stream();
_latestReaction;
constructor(initialReaction = new Reaction()) {
this._latestReactions = {};
this._actions.listen((action) => this._interaction(action));
this._react(initialReaction);
}
act(action) {
if (!(action instanceof Action)) throw 'invalid action';
this._actions.add(action);
}
observe(reactionHandler, provideLatestReaction = true) {
if (provideLatestReaction) reactionHandler(this._latestReaction);
let listener = (reaction) => {
if (!(reaction instanceof Reaction)) throw 'invalid reaction';
reactionHandler(reaction);
};
this._reactions.listen(listener);
return listener;
}
ignore(listener) {
this._reactions.ignore(listener);
}
_interaction(action) {}
_react(reaction) {
if (!(reaction instanceof Reaction)) throw 'invalid reaction';
let latest = this._latestReactions[reaction.constructor.name];
if (!reaction.equals(latest)) {
this._latestReaction = reaction;
this._latestReactions[reaction.constructor.name] = reaction;
this._reactions.add(reaction);
}
}
}
export class Action {}
export class Reaction {
equals(reaction) {
return false;
}
}