2026-06-04 10:26:08 -04:00
|
|
|
import { atom } from 'jotai';
|
2026-06-15 00:32:04 -04:00
|
|
|
import { atomWithStorage, createJSONStorage } from 'jotai/utils';
|
2026-06-04 10:26:08 -04:00
|
|
|
import { IContent } from 'matrix-js-sdk';
|
|
|
|
|
|
|
|
|
|
export type ScheduledMessage = {
|
|
|
|
|
delayId: string;
|
|
|
|
|
roomId: string;
|
|
|
|
|
content: IContent;
|
|
|
|
|
sendAt: number; // Unix timestamp ms
|
|
|
|
|
};
|
|
|
|
|
|
2026-06-15 00:32:04 -04:00
|
|
|
const STORAGE_KEY = 'cinny_scheduled_messages_v1';
|
|
|
|
|
|
|
|
|
|
// Internal atom persists as a plain Record (JSON-serializable).
|
|
|
|
|
const internalAtom = atomWithStorage<Record<string, ScheduledMessage[]>>(
|
|
|
|
|
STORAGE_KEY,
|
|
|
|
|
{},
|
|
|
|
|
createJSONStorage(() => localStorage),
|
|
|
|
|
);
|
|
|
|
|
|
2026-06-04 10:26:08 -04:00
|
|
|
/**
|
|
|
|
|
* Global atom: Map<roomId, ScheduledMessage[]>
|
|
|
|
|
* Stores all locally-tracked scheduled messages across rooms.
|
|
|
|
|
* MSC4140 has no list endpoint, so we track them ourselves.
|
2026-06-15 00:32:04 -04:00
|
|
|
* Backed by localStorage so scheduled messages survive page refreshes.
|
2026-06-04 10:26:08 -04:00
|
|
|
*/
|
2026-06-15 00:32:04 -04:00
|
|
|
export const scheduledMessagesAtom = atom(
|
|
|
|
|
(get): Map<string, ScheduledMessage[]> => new Map(Object.entries(get(internalAtom))),
|
|
|
|
|
(
|
|
|
|
|
_get,
|
|
|
|
|
set,
|
|
|
|
|
updater:
|
|
|
|
|
| Map<string, ScheduledMessage[]>
|
|
|
|
|
| ((prev: Map<string, ScheduledMessage[]>) => Map<string, ScheduledMessage[]>),
|
|
|
|
|
) => {
|
|
|
|
|
set(internalAtom, (prevObj) => {
|
|
|
|
|
const prevMap = new Map(Object.entries(prevObj));
|
|
|
|
|
const nextMap = typeof updater === 'function' ? updater(prevMap) : updater;
|
|
|
|
|
return Object.fromEntries(nextMap.entries());
|
|
|
|
|
});
|
|
|
|
|
},
|
|
|
|
|
);
|