Skip to content

Commit

Permalink
chore: swap mitt for @rocket.chat/emitter (RocketChat#33866)
Browse files Browse the repository at this point in the history
  • Loading branch information
MartinSchoeler authored Nov 2, 2024
1 parent 971249b commit fc5bd4e
Show file tree
Hide file tree
Showing 9 changed files with 34 additions and 54 deletions.
2 changes: 1 addition & 1 deletion packages/livechat/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@
"@rocket.chat/logo": "*"
},
"dependencies": {
"@rocket.chat/emitter": "~0.31.25",
"@rocket.chat/gazzodown": "workspace:^",
"@rocket.chat/message-parser": "workspace:^",
"@rocket.chat/random": "workspace:~",
Expand All @@ -107,7 +108,6 @@
"i18next": "~23.4.9",
"markdown-it": "^14.1.0",
"mem": "^8.1.1",
"mitt": "^2.1.0",
"path-to-regexp": "^6.3.0",
"preact": "~10.24.3",
"preact-router": "^3.2.1",
Expand Down
4 changes: 2 additions & 2 deletions packages/livechat/src/helpers/canRenderMessage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ const msgTypesNotRendered = [

export const getHiddenSystemMessages = () => {
const { config, iframe } = store.state;
const configHiddenSystemMessages = config.settings.hiddenSystemMessages || [];
const localHiddenSystemMessages = iframe.hiddenSystemMessages || [];
const configHiddenSystemMessages = config?.settings.hiddenSystemMessages || [];
const localHiddenSystemMessages = iframe?.hiddenSystemMessages || [];

return [...configHiddenSystemMessages, ...localHiddenSystemMessages] as string[];
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import store from '../store';
// TODO: optimize this function
const deleteMessage = (messageId: string) => {
store.setState({
messages: store.state.messages.filter((message) => message._id !== messageId),
messages: store.state.messages?.filter((message) => message._id !== messageId),
});
};

Expand Down
6 changes: 4 additions & 2 deletions packages/livechat/src/lib/connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,14 @@ const Connection = {

async clearAlerts() {
const { alerts } = store.state;
await store.setState({ alerts: alerts.filter((alert) => ![livechatDisconnectedAlertId, livechatConnectedAlertId].includes(alert.id)) });
await store.setState({
alerts: alerts?.filter((alert) => ![livechatDisconnectedAlertId, livechatConnectedAlertId].includes(alert.id)),
});
},

async displayAlert(alert = {}) {
const { alerts } = store.state;
await store.setState({ alerts: (alerts.push(alert), alerts) });
await store.setState({ alerts: (alerts?.push(alert), alerts) });
},

async handleConnected() {
Expand Down
6 changes: 3 additions & 3 deletions packages/livechat/src/lib/triggers.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import mitt from 'mitt';
import { Emitter } from '@rocket.chat/emitter';

import { Livechat } from '../api';
import store from '../store';
Expand All @@ -24,14 +24,14 @@ class Triggers {

/** @property {boolean} _enabled */

/** @property {import('mitt').Emitter} callbacks */
/** @property {import('@rocket.chat/emitter').Emitter} callbacks */

constructor() {
if (!Triggers.instance) {
this._started = false;
this._triggers = [];
this._enabled = true;
this.callbacks = mitt();
this.callbacks = new Emitter();
Triggers.instance = this;
}

Expand Down
49 changes: 16 additions & 33 deletions packages/livechat/src/store/Store.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { Emitter, EventHandlerMap, EventType, Handler, WildcardHandler } from 'mitt';
import mitt from 'mitt';
import { Emitter } from '@rocket.chat/emitter';

import type { StoreState } from '.';

function getLocalStorage() {
try {
Expand All @@ -18,46 +19,26 @@ function getLocalStorage() {
}
const localStorage = getLocalStorage();

export default class Store<T extends Record<string, unknown>> implements Emitter {
private _state: T;

private localStorageKey: string;

private dontPersist: string[];

all: EventHandlerMap;
type StoreStateType = StoreState;

on: {
<T = any>(type: EventType, handler: Handler<T>): void;
(type: '*', handler: WildcardHandler): void;
};
export default class Store extends Emitter {
private _state: StoreStateType;

off: {
<T = any>(type: EventType, handler: Handler<T>): void;
(type: '*', handler: WildcardHandler): void;
};
private localStorageKey: string;

emit: {
<T = any>(type: EventType, event?: T): void;
(type: '*', event?: any): void;
};
private dontPersist: Array<keyof StoreStateType>;

constructor(
initialState: T,
initialState: StoreStateType,
{
localStorageKey = 'store',
dontPersist = [],
}: {
localStorageKey?: string;
dontPersist?: string[];
dontPersist?: Array<keyof StoreStateType>;
} = {},
) {
const emitter = mitt();
this.all = emitter.all;
this.on = emitter.on;
this.off = emitter.off;
this.emit = emitter.emit;

super();
this.localStorageKey = localStorageKey;
this.dontPersist = dontPersist;

Expand Down Expand Up @@ -103,28 +84,30 @@ export default class Store<T extends Record<string, unknown>> implements Emitter
localStorage.setItem(this.localStorageKey, JSON.stringify(persistable));
}

setState(partialState: Partial<T>) {
setState(partialState: Partial<StoreStateType>) {
const prevState = this._state;
this._state = { ...prevState, ...partialState };
this.persist();
this.emit('change', [this._state, prevState, partialState]);
}

unsetSinglePropInStateByName(propName: string) {
unsetSinglePropInStateByName(propName: keyof StoreStateType) {
const prevState = this._state;
delete prevState[propName];
this._state = { ...prevState };
this.persist();
this.emit('change', [this._state, prevState]);
}

setStoredState(storedState: T) {
setStoredState(storedState: StoreStateType) {
const prevState = this._state;

const nonPeristable: Record<string, unknown> = {};

for (const ignoredKey of this.dontPersist) {
nonPeristable[ignoredKey] = prevState[ignoredKey];
}

this._state = { ...storedState, ...nonPeristable };
this.emit('change', [this._state, prevState]);
}
Expand Down
2 changes: 1 addition & 1 deletion packages/livechat/src/store/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ const dontPersist = [
'incomingCallAlert',
'ongoingCall',
'parentUrl',
];
] as Array<keyof StoreState>;

export const store = new Store(initialState(), { dontPersist });

Expand Down
8 changes: 5 additions & 3 deletions packages/livechat/src/widget.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { UserStatus } from '@rocket.chat/core-typings';
import type { LivechatRoomEvents } from '@rocket.chat/ddp-client';
import mitt from 'mitt';
import { Emitter } from '@rocket.chat/emitter';

import { isDefined } from './helpers/isDefined';
import type { HooksWidgetAPI } from './lib/hooks';
Expand Down Expand Up @@ -79,7 +79,7 @@ export const VALID_CALLBACKS = [

const VALID_SYSTEM_MESSAGES = ['uj', 'ul', 'livechat-close', 'livechat-started', 'livechat_transfer_history'];

const callbacks = mitt();
const callbacks = new Emitter();

function registerCallback(eventName: string, fn: () => unknown) {
if (VALID_CALLBACKS.indexOf(eventName) === -1) {
Expand All @@ -98,7 +98,9 @@ function emitCallback(eventName: string, data?: unknown) {
}

function clearAllCallbacks() {
callbacks.all.clear();
callbacks.events().forEach((callback) => {
callbacks.off(callback, () => undefined);
});
}

// hooks
Expand Down
9 changes: 1 addition & 8 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -8979,6 +8979,7 @@ __metadata:
"@babel/preset-typescript": "npm:~7.26.0"
"@rocket.chat/core-typings": "workspace:^"
"@rocket.chat/ddp-client": "workspace:^"
"@rocket.chat/emitter": "npm:~0.31.25"
"@rocket.chat/eslint-config": "workspace:^"
"@rocket.chat/fuselage-hooks": "npm:^0.33.1"
"@rocket.chat/fuselage-tokens": "npm:^0.33.2"
Expand Down Expand Up @@ -9025,7 +9026,6 @@ __metadata:
markdown-it: "npm:^14.1.0"
mem: "npm:^8.1.1"
mini-css-extract-plugin: "npm:~1.6.2"
mitt: "npm:^2.1.0"
npm-run-all: "npm:^4.1.5"
path-to-regexp: "npm:^6.3.0"
postcss-css-variables: "npm:^0.17.0"
Expand Down Expand Up @@ -27960,13 +27960,6 @@ __metadata:
languageName: node
linkType: hard

"mitt@npm:^2.1.0":
version: 2.1.0
resolution: "mitt@npm:2.1.0"
checksum: 10/d4087f8678ef9de18af10171ed39c14fc9282532f9104b522265e4a206f81630767bce5e3ae2405e9d863d7f6a7f3095f738c33c55c06872ed25978f1c8ea9f3
languageName: node
linkType: hard

"mkdirp-classic@npm:^0.5.2, mkdirp-classic@npm:^0.5.3":
version: 0.5.3
resolution: "mkdirp-classic@npm:0.5.3"
Expand Down

0 comments on commit fc5bd4e

Please sign in to comment.