2021-12-10 12:53:41 +00:00
|
|
|
import { action, computed, makeAutoObservable, ObservableMap } from "mobx";
|
|
|
|
|
2021-12-11 16:24:23 +00:00
|
|
|
import { mapToRecord } from "../../lib/conversion";
|
|
|
|
|
2021-12-11 14:36:26 +00:00
|
|
|
import Persistent from "../interfaces/Persistent";
|
2021-12-11 16:24:23 +00:00
|
|
|
import Store from "../interfaces/Store";
|
2021-12-10 12:53:41 +00:00
|
|
|
|
|
|
|
interface Data {
|
|
|
|
drafts: Record<string, string>;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Handles storing draft (currently being written) messages.
|
|
|
|
*/
|
2021-12-11 16:24:23 +00:00
|
|
|
export default class Draft implements Store, Persistent<Data> {
|
2021-12-10 12:53:41 +00:00
|
|
|
private drafts: ObservableMap<string, string>;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Construct new Draft store.
|
|
|
|
*/
|
|
|
|
constructor() {
|
|
|
|
this.drafts = new ObservableMap();
|
|
|
|
makeAutoObservable(this);
|
|
|
|
}
|
|
|
|
|
2021-12-11 16:24:23 +00:00
|
|
|
get id() {
|
|
|
|
return "draft";
|
|
|
|
}
|
|
|
|
|
2021-12-10 12:53:41 +00:00
|
|
|
toJSON() {
|
|
|
|
return {
|
2021-12-11 16:24:23 +00:00
|
|
|
drafts: mapToRecord(this.drafts),
|
2021-12-10 12:53:41 +00:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
@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();
|
|
|
|
}
|
|
|
|
}
|