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) => {
|
2024-05-31 19:49:46 +05:30
|
|
|
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]);
|
|
|
|
|
};
|