Files
cinny/src/app/state/mDirectList.ts
T

47 lines
1.3 KiB
TypeScript
Raw Normal View History

2024-01-21 23:50:56 +11:00
import { atom, useSetAtom } from 'jotai';
2023-06-12 21:15:23 +10:00
import { ClientEvent, MatrixClient, MatrixEvent } from 'matrix-js-sdk';
import { useEffect } from 'react';
import { AccountDataEvent } from '../../types/matrix/accountData';
import { getAccountData, getMDirects } from '../utils/room';
export type MDirectAction = {
type: 'INITIALIZE' | 'UPDATE';
rooms: Set<string>;
};
const baseMDirectAtom = atom(new Set<string>());
2024-01-21 23:50:56 +11:00
export const mDirectAtom = atom<Set<string>, [MDirectAction], undefined>(
2023-06-12 21:15:23 +10:00
(get) => get(baseMDirectAtom),
(get, set, action) => {
set(baseMDirectAtom, action.rooms);
}
);
2024-01-21 23:50:56 +11:00
export const useBindMDirectAtom = (mx: MatrixClient, mDirect: typeof mDirectAtom) => {
2023-06-12 21:15:23 +10:00
const setMDirect = useSetAtom(mDirect);
useEffect(() => {
const mDirectEvent = getAccountData(mx, AccountDataEvent.Direct);
if (mDirectEvent) {
setMDirect({
type: 'INITIALIZE',
rooms: getMDirects(mDirectEvent),
});
}
const handleAccountData = (event: MatrixEvent) => {
if (event.getType() === AccountDataEvent.Direct) {
setMDirect({
type: 'UPDATE',
rooms: getMDirects(event),
});
}
2023-06-12 21:15:23 +10:00
};
mx.on(ClientEvent.AccountData, handleAccountData);
return () => {
mx.removeListener(ClientEvent.AccountData, handleAccountData);
};
}, [mx, setMDirect]);
};