Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/frontend/chat/register.ts
5743 views
1
/*
2
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
3
* License: MS-RSL – see LICENSE.md for details
4
*/
5
6
import { alert_message } from "@cocalc/frontend/alerts";
7
import { redux, redux_name } from "@cocalc/frontend/app-framework";
8
import { webapp_client } from "@cocalc/frontend/webapp-client";
9
import { path_split, startswith } from "@cocalc/util/misc";
10
import { ChatActions } from "./actions";
11
import { ChatStore } from "./store";
12
13
// it is fine to call this more than once.
14
export function initChat(project_id: string, path: string): ChatActions {
15
const name = redux_name(project_id, path);
16
if (redux.getActions(name) != null) {
17
return redux.getActions(name); // already initialized
18
}
19
20
const actions = redux.createActions(name, ChatActions);
21
const store = redux.createStore(name, ChatStore);
22
actions.setState({ project_id, path });
23
24
if (startswith(path_split(path).tail, ".")) {
25
// Sidechat being opened -- ensure chat isn't marked as deleted:
26
redux.getProjectActions(project_id)?.setNotDeleted(path);
27
}
28
29
const syncdb = webapp_client.sync_client.sync_db({
30
project_id,
31
path,
32
primary_keys: ["date", "sender_id", "event"],
33
// used only for drafts, since store lots of versions as user types:
34
string_cols: ["input"],
35
});
36
37
syncdb.once("error", (err) => {
38
const mesg = `Error using '${path}' -- ${err}`;
39
console.warn(mesg);
40
alert_message({ type: "error", message: mesg });
41
});
42
43
syncdb.once("ready", () => {
44
actions.set_syncdb(syncdb, store);
45
actions.init_from_syncdb();
46
syncdb.on("change", actions.syncdbChange);
47
redux.getProjectActions(project_id)?.log_opened_time(path);
48
});
49
50
return actions;
51
}
52
53
export function remove(path: string, redux, project_id: string): string {
54
const name = redux_name(project_id, path);
55
const actions = redux.getActions(name);
56
actions?.syncdb?.close();
57
const store = redux.getStore(name);
58
if (store == null) {
59
return name;
60
}
61
delete store.state;
62
// It is *critical* to first unmount the store, then the actions,
63
// or there will be a huge memory leak.
64
redux.removeStore(name);
65
redux.removeActions(name);
66
return name;
67
}
68
69