feat(mobx): add drafts and state context

This commit is contained in:
Paul Makles
2021-12-10 12:53:41 +00:00
parent 66bfc658c3
commit 5a41c25e3c
10 changed files with 285 additions and 14 deletions

80
src/mobx/stores/Draft.ts Normal file
View File

@@ -0,0 +1,80 @@
import { action, computed, makeAutoObservable, ObservableMap } from "mobx";
import Persistent from "../Persistent";
interface Data {
drafts: Record<string, string>;
}
/**
* Handles storing draft (currently being written) messages.
*/
export default class Draft implements Persistent<Data> {
private drafts: ObservableMap<string, string>;
/**
* Construct new Draft store.
*/
constructor() {
this.drafts = new ObservableMap();
makeAutoObservable(this);
}
// eslint-disable-next-line require-jsdoc
toJSON() {
return {
drafts: this.drafts,
};
}
// eslint-disable-next-line require-jsdoc
@action hydrate(data: Data) {
Object.keys(data.drafts).forEach((key) =>
this.drafts.set(key, data.drafts[key]),
);
}
/**
* Get draft for a channel.
* @param channel Channel ID
*/
@computed get(channel: string) {
return this.drafts.get(channel);
}
/**
* Check whether a channel has a draft.
* @param channel Channel ID
*/
@computed has(channel: string) {
return this.drafts.has(channel) && this.drafts.get(channel)!.length > 0;
}
/**
* Set draft for a channel.
* @param channel Channel ID
* @param content Draft content
*/
@action set(channel: string, content?: string) {
if (typeof content === "undefined") {
return this.clear(channel);
}
this.drafts.set(channel, content);
}
/**
* Clear draft from a channel.
* @param channel Channel ID
*/
@action clear(channel: string) {
this.drafts.delete(channel);
}
/**
* Reset and clear all drafts.
*/
@action reset() {
this.drafts.clear();
}
}