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