This repository has been archived on 2022-08-19. You can view files and clone it, but cannot push or open issues or pull requests.
hydrogen-web/src/domain/SessionPickerViewModel.js

84 lines
2.1 KiB
JavaScript
Raw Normal View History

import {SortedArray} from "../observable/index.js";
2019-10-13 00:46:48 +05:30
import EventEmitter from "../EventEmitter.js";
class SessionItemViewModel extends EventEmitter {
constructor(sessionInfo, pickerVM) {
super();
this._pickerVM = pickerVM;
this._sessionInfo = sessionInfo;
this._isDeleting = false;
this._error = null;
}
get error() {
return this._error && this._error.message;
}
async delete() {
this._isDeleting = true;
this.emit("change", "isDeleting");
try {
await this._pickerVM.delete(this.id);
} catch(err) {
this._error = err;
console.error(err);
this.emit("change", "error");
} finally {
this._isDeleting = false;
this.emit("change", "isDeleting");
}
}
get isDeleting() {
return this._isDeleting;
}
get id() {
return this._sessionInfo.id;
}
get userId() {
return this._sessionInfo.userId;
}
2019-10-13 01:48:08 +05:30
get sessionInfo() {
return this._sessionInfo;
2019-10-13 00:46:48 +05:30
}
}
export default class SessionPickerViewModel {
2019-10-13 00:46:48 +05:30
constructor({storageFactory, sessionStore, sessionCallback}) {
this._storageFactory = storageFactory;
this._sessionStore = sessionStore;
this._sessionCallback = sessionCallback;
2019-10-13 01:48:08 +05:30
this._sessions = new SortedArray((s1, s2) => (s1.sessionInfo.lastUsed || 0) - (s2.sessionInfo.lastUsed || 0));
}
async load() {
const sessions = await this._sessionStore.getAll();
2019-10-13 00:46:48 +05:30
this._sessions.setManyUnsorted(sessions.map(s => new SessionItemViewModel(s, this)));
}
pick(id) {
2019-10-13 01:48:08 +05:30
const sessionVM = this._sessions.array.find(s => s.id === id);
if (sessionVM) {
this._sessionCallback(sessionVM.sessionInfo);
}
}
2019-10-13 00:46:48 +05:30
async delete(id) {
const idx = this._sessions.array.findIndex(s => s.id === id);
await this._sessionStore.delete(id);
await this._storageFactory.delete(id);
this._sessions.remove(idx);
}
get sessions() {
return this._sessions;
}
cancel() {
this._sessionCallback();
}
}