robosats/frontend/src/models/Slot.model.ts

70 lines
2.1 KiB
TypeScript
Raw Normal View History

2023-12-15 15:17:46 +00:00
import { sha256 } from 'js-sha256';
2023-11-21 17:36:59 +00:00
import { Robot, type Order } from '.';
2023-12-15 15:17:46 +00:00
import { robohash } from '../components/RobotAvatar/RobohashGenerator';
import { generate_roboname } from 'robo-identities-wasm';
2023-11-21 17:36:59 +00:00
class Slot {
constructor(token: string) {
this.token = token;
2023-12-15 15:17:46 +00:00
this.hashId = sha256(sha256(this.token));
this.nickname = generate_roboname(this.hashId);
// trigger RoboHash avatar generation in webworker and store in RoboHash class cache.
robohash.generate(this.hashId, 'small');
robohash.generate(this.hashId, 'large');
2023-11-21 17:36:59 +00:00
this.robots = {};
this.order = null;
2023-12-15 15:17:46 +00:00
2023-11-21 17:36:59 +00:00
this.activeShortAlias = null;
this.lastShortAlias = null;
this.copiedToken = false;
}
token: string | null;
2023-12-15 15:17:46 +00:00
hashId: string | null;
nickname: string | null;
2023-12-02 19:50:07 +00:00
robots: Record<string, Robot>;
2023-11-21 17:36:59 +00:00
order: Order | null;
activeShortAlias: string | null;
lastShortAlias: string | null;
copiedToken: boolean;
setCopiedToken = (copied: boolean): void => {
this.copiedToken = copied;
};
getRobot = (shortAlias?: string): Robot | null => {
2023-12-02 19:50:07 +00:00
if (shortAlias != null) {
2023-11-21 17:36:59 +00:00
return this.robots[shortAlias];
2023-12-02 19:50:07 +00:00
} else if (this.activeShortAlias !== null && this.robots[this.activeShortAlias] != null) {
2023-11-21 17:36:59 +00:00
return this.robots[this.activeShortAlias];
2023-12-02 19:50:07 +00:00
} else if (this.lastShortAlias !== null && this.robots[this.lastShortAlias] != null) {
2023-11-21 17:36:59 +00:00
return this.robots[this.lastShortAlias];
} else if (Object.values(this.robots).length > 0) {
return Object.values(this.robots)[0];
}
return null;
};
upsertRobot = (shortAlias: string, attributes: Record<any, any>): Robot | null => {
if (this.robots[shortAlias] === undefined) this.robots[shortAlias] = new Robot();
this.robots[shortAlias].update(attributes);
if (attributes.lastOrderId !== undefined && attributes.lastOrderId != null) {
this.lastShortAlias = shortAlias;
if (this.activeShortAlias === shortAlias) {
this.activeShortAlias = null;
}
}
if (attributes.activeOrderId !== undefined && attributes.activeOrderId != null) {
this.activeShortAlias = attributes.shortAlias;
}
return this.robots[shortAlias];
};
}
export default Slot;