DP16: add typed get/setAccountData helpers, remove ~19 any-casts

Add centralized typed helpers in src/app/utils/accountData.ts:
- getAccountData<T>(mx, eventType): T | undefined (returns content)
- setAccountData<T>(mx, eventType, content): Promise<void>

These wrap the single `as any` cast needed because matrix-js-sdk's typed
overloads reject the fork's custom account-data event names. Every call site
now stays fully typed on its content shape.

Route all account-data reads/writes that previously used
`(mx as any).getAccountData/setAccountData` or `mx.getAccountData(... as any)`
through the helpers (or, where a MatrixEvent is needed, through the existing
utils/room.ts getAccountData whose param is widened to accept string keys).
No behavior change: same event types, same content shapes.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-07-07 23:14:35 -04:00
parent e545706c3b
commit b1ee3ada98
16 changed files with 69 additions and 46 deletions
+2 -1
View File
@@ -41,6 +41,7 @@ import { StateEvent } from '../../../types/matrix/room';
import { CanDropCallback, useDnDMonitor } from './DnD'; import { CanDropCallback, useDnDMonitor } from './DnD';
import { ASCIILexicalTable, orderKeys } from '../../utils/ASCIILexicalTable'; import { ASCIILexicalTable, orderKeys } from '../../utils/ASCIILexicalTable';
import { getStateEvent } from '../../utils/room'; import { getStateEvent } from '../../utils/room';
import { setAccountData } from '../../utils/accountData';
import { useClosedLobbyCategoriesAtom } from '../../state/hooks/closedLobbyCategories'; import { useClosedLobbyCategoriesAtom } from '../../state/hooks/closedLobbyCategories';
import { import {
makeCinnySpacesContent, makeCinnySpacesContent,
@@ -427,7 +428,7 @@ export function Lobby() {
newItems.push(rId); newItems.push(rId);
} }
const newSpacesContent = makeCinnySpacesContent(mx, newItems); const newSpacesContent = makeCinnySpacesContent(mx, newItems);
mx.setAccountData(AccountDataEvent.CinnySpaces as any, newSpacesContent as any); setAccountData(mx, AccountDataEvent.CinnySpaces, newSpacesContent);
}, },
[mx, sidebarItems, sidebarSpaces], [mx, sidebarItems, sidebarSpaces],
); );
+4 -6
View File
@@ -34,6 +34,7 @@ import { NavItem, NavItemContent, NavItemOptions, NavLink } from '../../componen
import { UnreadBadge, UnreadBadgeCenter } from '../../components/unread-badge'; import { UnreadBadge, UnreadBadgeCenter } from '../../components/unread-badge';
import { RoomAvatar, RoomIcon } from '../../components/room-avatar'; import { RoomAvatar, RoomIcon } from '../../components/room-avatar';
import { getDirectRoomAvatarUrl, getRoomAvatarUrl, getStateEvent } from '../../utils/room'; import { getDirectRoomAvatarUrl, getRoomAvatarUrl, getStateEvent } from '../../utils/room';
import { setAccountData } from '../../utils/accountData';
import { nameInitials } from '../../utils/common'; import { nameInitials } from '../../utils/common';
import { useMatrixClient } from '../../hooks/useMatrixClient'; import { useMatrixClient } from '../../hooks/useMatrixClient';
import { useRoomUnread } from '../../state/hooks/unread'; import { useRoomUnread } from '../../state/hooks/unread';
@@ -127,11 +128,9 @@ function RenameRoomDialog({ room, onClose }: RenameRoomDialogProps) {
const existing = getLocalRoomNamesContent(mx); const existing = getLocalRoomNamesContent(mx);
if (newName === '') { if (newName === '') {
const { [room.roomId]: _removed, ...rest } = existing.rooms; const { [room.roomId]: _removed, ...rest } = existing.rooms;
// eslint-disable-next-line @typescript-eslint/no-explicit-any setAccountData(mx, LOCAL_ROOM_NAMES_KEY, { rooms: rest });
(mx as any).setAccountData(LOCAL_ROOM_NAMES_KEY, { rooms: rest });
} else { } else {
// eslint-disable-next-line @typescript-eslint/no-explicit-any setAccountData(mx, LOCAL_ROOM_NAMES_KEY, {
(mx as any).setAccountData(LOCAL_ROOM_NAMES_KEY, {
rooms: { ...existing.rooms, [room.roomId]: newName }, rooms: { ...existing.rooms, [room.roomId]: newName },
}); });
} }
@@ -141,8 +140,7 @@ function RenameRoomDialog({ room, onClose }: RenameRoomDialogProps) {
const handleClear = useCallback(() => { const handleClear = useCallback(() => {
const existing = getLocalRoomNamesContent(mx); const existing = getLocalRoomNamesContent(mx);
const { [room.roomId]: _removed, ...rest } = existing.rooms; const { [room.roomId]: _removed, ...rest } = existing.rooms;
// eslint-disable-next-line @typescript-eslint/no-explicit-any setAccountData(mx, LOCAL_ROOM_NAMES_KEY, { rooms: rest });
(mx as any).setAccountData(LOCAL_ROOM_NAMES_KEY, { rooms: rest });
onClose(); onClose();
}, [mx, room.roomId, onClose]); }, [mx, room.roomId, onClose]);
@@ -35,6 +35,7 @@ import { SequenceCard } from '../../../components/sequence-card';
import { SequenceCardStyle } from '../styles.css'; import { SequenceCardStyle } from '../styles.css';
import { SettingTile } from '../../../components/setting-tile'; import { SettingTile } from '../../../components/setting-tile';
import { useMatrixClient } from '../../../hooks/useMatrixClient'; import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { getAccountData, setAccountData } from '../../../utils/accountData';
import { presenceStateFromSetting } from '../../../hooks/usePresenceUpdater'; import { presenceStateFromSetting } from '../../../hooks/usePresenceUpdater';
import { useSetting } from '../../../state/hooks/settings'; import { useSetting } from '../../../state/hooks/settings';
import { settingsAtom } from '../../../state/settings'; import { settingsAtom } from '../../../state/settings';
@@ -725,9 +726,7 @@ function ProfileTimezone() {
const [savedTimezone, setSavedTimezone] = useState<string>(''); const [savedTimezone, setSavedTimezone] = useState<string>('');
useEffect(() => { useEffect(() => {
const cached = mx const cached = getAccountData<{ timezone: string }>(mx, 'im.lotus.timezone');
.getAccountData('im.lotus.timezone' as any)
?.getContent<{ timezone: string }>();
if (cached?.timezone) { if (cached?.timezone) {
setTimezone(cached.timezone); setTimezone(cached.timezone);
setSavedTimezone(cached.timezone); setSavedTimezone(cached.timezone);
@@ -754,7 +753,7 @@ function ProfileTimezone() {
Promise.all([ Promise.all([
// Self-fallback: account data is readable by useExtendedProfile for the // Self-fallback: account data is readable by useExtendedProfile for the
// own user even on servers without extended-profile (m.tz) support. // own user even on servers without extended-profile (m.tz) support.
(mx as any).setAccountData('im.lotus.timezone', { timezone: value }), setAccountData(mx, 'im.lotus.timezone', { timezone: value }),
// Mirror the pronouns write path so OTHER users can read the timezone // Mirror the pronouns write path so OTHER users can read the timezone
// via the m.tz profile field. Best-effort: standard Synapse rejects // via the m.tz profile field. Best-effort: standard Synapse rejects
// unknown profile fields, so a failure here must not fail the save. // unknown profile fields, so a failure here must not fail the save.
@@ -12,6 +12,7 @@ import {
AccountDataSubmitCallback, AccountDataSubmitCallback,
} from '../../../components/AccountDataEditor'; } from '../../../components/AccountDataEditor';
import { copyToClipboard } from '../../../utils/dom'; import { copyToClipboard } from '../../../utils/dom';
import { getAccountData, setAccountData } from '../../../utils/accountData';
import { AccountData } from './AccountData'; import { AccountData } from './AccountData';
import { CryptoDiagnostics } from '../developer/CryptoDiagnostics'; import { CryptoDiagnostics } from '../developer/CryptoDiagnostics';
@@ -26,7 +27,7 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) {
const submitAccountData: AccountDataSubmitCallback = useCallback( const submitAccountData: AccountDataSubmitCallback = useCallback(
async (type, content) => { async (type, content) => {
await (mx as any).setAccountData(type, content); await setAccountData(mx, type, content);
}, },
[mx], [mx],
); );
@@ -36,7 +37,7 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) {
<AccountDataEditor <AccountDataEditor
type={accountDataType ?? undefined} type={accountDataType ?? undefined}
content={ content={
accountDataType ? (mx as any).getAccountData(accountDataType)?.getContent() : undefined accountDataType ? getAccountData<object>(mx, accountDataType) : undefined
} }
submitChange={submitAccountData} submitChange={submitAccountData}
requestClose={() => setAccountDataType(undefined)} requestClose={() => setAccountDataType(undefined)}
@@ -1,4 +1,4 @@
import { MatrixEvent, Room } from 'matrix-js-sdk'; import { Room } from 'matrix-js-sdk';
import React, { MouseEventHandler, useCallback, useEffect, useMemo, useState } from 'react'; import React, { MouseEventHandler, useCallback, useEffect, useMemo, useState } from 'react';
import { import {
Box, Box,
@@ -41,6 +41,7 @@ import {
import { LineClamp2 } from '../../../styles/Text.css'; import { LineClamp2 } from '../../../styles/Text.css';
import { allRoomsAtom } from '../../../state/room-list/roomList'; import { allRoomsAtom } from '../../../state/room-list/roomList';
import { AccountDataEvent } from '../../../../types/matrix/accountData'; import { AccountDataEvent } from '../../../../types/matrix/accountData';
import { getAccountData, setAccountData } from '../../../utils/accountData';
import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback'; import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback';
import { stopPropagation } from '../../../utils/keyboard'; import { stopPropagation } from '../../../utils/keyboard';
@@ -303,9 +304,7 @@ export function GlobalPacks({ onViewPack }: GlobalPacksProps) {
const [applyState, applyChanges] = useAsyncCallback( const [applyState, applyChanges] = useAsyncCallback(
useCallback(async () => { useCallback(async () => {
const content = const content =
( getAccountData<EmoteRoomsContent>(mx, AccountDataEvent.PoniesEmoteRooms) ?? {};
(mx as any).getAccountData(AccountDataEvent.PoniesEmoteRooms) as MatrixEvent | undefined
)?.getContent<EmoteRoomsContent>() ?? {};
const updatedContent: EmoteRoomsContent = JSON.parse(JSON.stringify(content)); const updatedContent: EmoteRoomsContent = JSON.parse(JSON.stringify(content));
selectedPacks.forEach((addr) => { selectedPacks.forEach((addr) => {
@@ -322,7 +321,7 @@ export function GlobalPacks({ onViewPack }: GlobalPacksProps) {
} }
}); });
await (mx as any).setAccountData(AccountDataEvent.PoniesEmoteRooms, updatedContent); await setAccountData(mx, AccountDataEvent.PoniesEmoteRooms, updatedContent);
}, [mx, selectedPacks, removedPacks]), }, [mx, selectedPacks, removedPacks]),
); );
+3 -2
View File
@@ -2,11 +2,12 @@ import { MatrixEvent } from 'matrix-js-sdk';
import { useState, useCallback } from 'react'; import { useState, useCallback } from 'react';
import { useMatrixClient } from './useMatrixClient'; import { useMatrixClient } from './useMatrixClient';
import { useAccountDataCallback } from './useAccountDataCallback'; import { useAccountDataCallback } from './useAccountDataCallback';
import { getAccountData } from '../utils/room';
export function useAccountData(eventType: string): MatrixEvent | undefined { export function useAccountData(eventType: string): MatrixEvent | undefined {
const mx = useMatrixClient(); const mx = useMatrixClient();
const [event, setEvent] = useState<MatrixEvent | undefined>( const [event, setEvent] = useState<MatrixEvent | undefined>(() =>
() => (mx as any).getAccountData(eventType) as MatrixEvent | undefined, getAccountData(mx, eventType),
); );
useAccountDataCallback( useAccountDataCallback(
+3 -5
View File
@@ -1,6 +1,7 @@
import { useCallback, useEffect, useState } from 'react'; import { useCallback, useEffect, useState } from 'react';
import { ClientEvent, ClientEventHandlerMap, MatrixClient } from 'matrix-js-sdk'; import { ClientEvent, ClientEventHandlerMap, MatrixClient } from 'matrix-js-sdk';
import { useMatrixClient } from './useMatrixClient'; import { useMatrixClient } from './useMatrixClient';
import { getAccountData, setAccountData } from '../utils/accountData';
export type Bookmark = { export type Bookmark = {
roomId: string; roomId: string;
@@ -18,10 +19,7 @@ type BookmarksContent = {
}; };
function readBookmarks(mx: MatrixClient): Bookmark[] { function readBookmarks(mx: MatrixClient): Bookmark[] {
return ( return getAccountData<BookmarksContent>(mx, BOOKMARKS_KEY)?.bookmarks ?? [];
(mx.getAccountData(BOOKMARKS_KEY as any)?.getContent() as BookmarksContent | undefined)
?.bookmarks ?? []
);
} }
// Module-scoped serialization state. // Module-scoped serialization state.
@@ -85,7 +83,7 @@ function enqueueBookmarkWrite(
const next = compute(state.latest); const next = compute(state.latest);
state.latest = next; state.latest = next;
state.listeners.forEach((listener) => listener(next)); state.listeners.forEach((listener) => listener(next));
await (mx as any).setAccountData(BOOKMARKS_KEY, { bookmarks: next }); await setAccountData(mx, BOOKMARKS_KEY, { bookmarks: next });
}); });
// Keep the chain alive even if one write rejects, but propagate the // Keep the chain alive even if one write rejects, but propagate the
// rejection to this caller so it can react (e.g. retry). // rejection to this caller so it can react (e.g. retry).
+3 -5
View File
@@ -1,6 +1,7 @@
import { useCallback, useEffect, useState } from 'react'; import { useCallback, useEffect, useState } from 'react';
import { ClientEvent, ClientEventHandlerMap, MatrixClient } from 'matrix-js-sdk'; import { ClientEvent, ClientEventHandlerMap, MatrixClient } from 'matrix-js-sdk';
import { useMatrixClient } from './useMatrixClient'; import { useMatrixClient } from './useMatrixClient';
import { getAccountData, setAccountData } from '../utils/accountData';
export type Reminder = { export type Reminder = {
roomId: string; roomId: string;
@@ -16,10 +17,7 @@ type RemindersContent = {
}; };
function readReminders(mx: MatrixClient): Reminder[] { function readReminders(mx: MatrixClient): Reminder[] {
return ( return getAccountData<RemindersContent>(mx, REMINDERS_KEY)?.reminders ?? [];
(mx.getAccountData(REMINDERS_KEY as any)?.getContent() as RemindersContent | undefined)
?.reminders ?? []
);
} }
// Module-scoped serialization state. // Module-scoped serialization state.
@@ -83,7 +81,7 @@ function enqueueReminderWrite(
const next = compute(state.latest); const next = compute(state.latest);
state.latest = next; state.latest = next;
state.listeners.forEach((listener) => listener(next)); state.listeners.forEach((listener) => listener(next));
await (mx as any).setAccountData(REMINDERS_KEY, { reminders: next }); await setAccountData(mx, REMINDERS_KEY, { reminders: next });
}); });
// Keep the chain alive even if one write rejects, but propagate the // Keep the chain alive even if one write rejects, but propagate the
// rejection to this caller so it can react (e.g. retry). // rejection to this caller so it can react (e.g. retry).
+2 -3
View File
@@ -4,6 +4,7 @@ import { ClientEvent, MatrixEvent, Room, RoomEvent, RoomEventHandlerMap } from '
import { StateEvent } from '../../types/matrix/room'; import { StateEvent } from '../../types/matrix/room';
import { useStateEvent } from './useStateEvent'; import { useStateEvent } from './useStateEvent';
import { useMatrixClient } from './useMatrixClient'; import { useMatrixClient } from './useMatrixClient';
import { getAccountData } from '../utils/accountData';
export const useRoomAvatar = (room: Room, dm?: boolean): string | undefined => { export const useRoomAvatar = (room: Room, dm?: boolean): string | undefined => {
const avatarEvent = useStateEvent(room, StateEvent.RoomAvatar); const avatarEvent = useStateEvent(room, StateEvent.RoomAvatar);
@@ -42,9 +43,7 @@ export type LocalRoomNamesContent = { rooms: Record<string, string> };
export function getLocalRoomNamesContent( export function getLocalRoomNamesContent(
mx: ReturnType<typeof useMatrixClient>, mx: ReturnType<typeof useMatrixClient>,
): LocalRoomNamesContent { ): LocalRoomNamesContent {
// Use any-cast because LOCAL_ROOM_NAMES_KEY is not in matrix-js-sdk AccountDataEvents const raw: unknown = getAccountData<unknown>(mx, LOCAL_ROOM_NAMES_KEY);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const raw: unknown = (mx as any).getAccountData(LOCAL_ROOM_NAMES_KEY)?.getContent();
if ( if (
raw && raw &&
typeof raw === 'object' && typeof raw === 'object' &&
+3 -4
View File
@@ -12,6 +12,7 @@ import {
} from '../utils/threadNotifications'; } from '../utils/threadNotifications';
import { useMatrixClient } from './useMatrixClient'; import { useMatrixClient } from './useMatrixClient';
import { AsyncState, useAsyncCallback } from './useAsyncCallback'; import { AsyncState, useAsyncCallback } from './useAsyncCallback';
import { getAccountData, setAccountData } from '../utils/accountData';
/** Read the current notification mode for a thread from the bound atom. */ /** Read the current notification mode for a thread from the bound atom. */
export function useThreadNotificationMode( export function useThreadNotificationMode(
@@ -23,9 +24,7 @@ export function useThreadNotificationMode(
} }
const readContent = (mx: MatrixClient): ThreadNotificationsContent => const readContent = (mx: MatrixClient): ThreadNotificationsContent =>
((mx as any).getAccountData(AccountDataEvent.LotusThreadNotifications)?.getContent() as getAccountData<ThreadNotificationsContent>(mx, AccountDataEvent.LotusThreadNotifications) ?? {};
| ThreadNotificationsContent
| undefined) ?? {};
const getJoinedRoomIds = (mx: MatrixClient): Set<string> => { const getJoinedRoomIds = (mx: MatrixClient): Set<string> => {
const joined = new Set<string>(); const joined = new Set<string>();
@@ -74,7 +73,7 @@ const writeThreadNotificationMode = async (
// ALWAYS prune before persisting to keep account data bounded. // ALWAYS prune before persisting to keep account data bounded.
const finalContent = pruneThreadNotifications(next, getJoinedRoomIds(mx), now); const finalContent = pruneThreadNotifications(next, getJoinedRoomIds(mx), now);
await (mx as any).setAccountData(AccountDataEvent.LotusThreadNotifications, finalContent); await setAccountData(mx, AccountDataEvent.LotusThreadNotifications, finalContent);
}; };
export function useSetThreadNotificationMode( export function useSetThreadNotificationMode(
+3 -2
View File
@@ -1,6 +1,7 @@
import { useCallback, useEffect, useState } from 'react'; import { useCallback, useEffect, useState } from 'react';
import { ClientEvent, ClientEventHandlerMap, MatrixClient } from 'matrix-js-sdk'; import { ClientEvent, ClientEventHandlerMap, MatrixClient } from 'matrix-js-sdk';
import { useMatrixClient } from './useMatrixClient'; import { useMatrixClient } from './useMatrixClient';
import { getAccountData, setAccountData } from '../utils/accountData';
const NOTES_KEY = 'io.lotus.user_notes'; const NOTES_KEY = 'io.lotus.user_notes';
export const USER_NOTE_MAX_LENGTH = 500; export const USER_NOTE_MAX_LENGTH = 500;
@@ -8,7 +9,7 @@ export const USER_NOTE_MAX_LENGTH = 500;
type UserNotesContent = Record<string, string>; type UserNotesContent = Record<string, string>;
function readNotes(mx: MatrixClient): UserNotesContent { function readNotes(mx: MatrixClient): UserNotesContent {
return (mx.getAccountData(NOTES_KEY as any)?.getContent() as UserNotesContent | undefined) ?? {}; return getAccountData<UserNotesContent>(mx, NOTES_KEY) ?? {};
} }
// Module-scoped serialization state. // Module-scoped serialization state.
@@ -72,7 +73,7 @@ function enqueueNotesWrite(
const next = compute(state.latest); const next = compute(state.latest);
state.latest = next; state.latest = next;
state.listeners.forEach((listener) => listener(next)); state.listeners.forEach((listener) => listener(next));
await (mx as any).setAccountData(NOTES_KEY, next); await setAccountData(mx, NOTES_KEY, next);
}); });
// Keep the chain alive even if one write rejects, but propagate the // Keep the chain alive even if one write rejects, but propagate the
// rejection to this caller so it can react (e.g. retry). // rejection to this caller so it can react (e.g. retry).
+3 -2
View File
@@ -74,6 +74,7 @@ import {
useSidebarItems, useSidebarItems,
} from '../../../hooks/useSidebarItems'; } from '../../../hooks/useSidebarItems';
import { AccountDataEvent } from '../../../../types/matrix/accountData'; import { AccountDataEvent } from '../../../../types/matrix/accountData';
import { setAccountData } from '../../../utils/accountData';
import { ScreenSize, useScreenSizeContext } from '../../../hooks/useScreenSize'; import { ScreenSize, useScreenSizeContext } from '../../../hooks/useScreenSize';
import { useNavToActivePathAtom } from '../../../state/hooks/navToActivePath'; import { useNavToActivePathAtom } from '../../../state/hooks/navToActivePath';
import { useOpenedSidebarFolderAtom } from '../../../state/hooks/openedSidebarFolder'; import { useOpenedSidebarFolderAtom } from '../../../state/hooks/openedSidebarFolder';
@@ -752,7 +753,7 @@ export function SpaceTabs({ scrollRef }: SpaceTabsProps) {
const newSpacesContent = makeCinnySpacesContent(mx, newItems); const newSpacesContent = makeCinnySpacesContent(mx, newItems);
localEchoSidebarItem(parseSidebar(mx, orphanSpaces, newSpacesContent)); localEchoSidebarItem(parseSidebar(mx, orphanSpaces, newSpacesContent));
(mx as any).setAccountData(AccountDataEvent.CinnySpaces, newSpacesContent); setAccountData(mx, AccountDataEvent.CinnySpaces, newSpacesContent);
}, },
[mx, sidebarItems, setOpenedFolder, localEchoSidebarItem, orphanSpaces], [mx, sidebarItems, setOpenedFolder, localEchoSidebarItem, orphanSpaces],
), ),
@@ -798,7 +799,7 @@ export function SpaceTabs({ scrollRef }: SpaceTabsProps) {
const newSpacesContent = makeCinnySpacesContent(mx, newItems); const newSpacesContent = makeCinnySpacesContent(mx, newItems);
localEchoSidebarItem(parseSidebar(mx, orphanSpaces, newSpacesContent)); localEchoSidebarItem(parseSidebar(mx, orphanSpaces, newSpacesContent));
(mx as any).setAccountData(AccountDataEvent.CinnySpaces, newSpacesContent); setAccountData(mx, AccountDataEvent.CinnySpaces, newSpacesContent);
}, },
[mx, sidebarItems, orphanSpaces, localEchoSidebarItem], [mx, sidebarItems, orphanSpaces, localEchoSidebarItem],
); );
+2 -1
View File
@@ -1,5 +1,6 @@
import { MatrixClient } from 'matrix-js-sdk'; import { MatrixClient } from 'matrix-js-sdk';
import { getAccountData } from '../utils/room'; import { getAccountData } from '../utils/room';
import { setAccountData } from '../utils/accountData';
import { IEmoji, emojis } from './emoji'; import { IEmoji, emojis } from './emoji';
import { AccountDataEvent } from '../../types/matrix/accountData'; import { AccountDataEvent } from '../../types/matrix/accountData';
@@ -39,7 +40,7 @@ export function addRecentEmoji(mx: MatrixClient, unicode: string) {
entry[1] += 1; entry[1] += 1;
} }
recentEmoji.unshift(entry); recentEmoji.unshift(entry);
(mx as any).setAccountData(AccountDataEvent.ElementRecentEmoji, { setAccountData(mx, AccountDataEvent.ElementRecentEmoji, {
recent_emoji: recentEmoji.slice(0, 100), recent_emoji: recentEmoji.slice(0, 100),
}); });
} }
+2 -3
View File
@@ -3,15 +3,14 @@ import { ClientEvent, MatrixClient, MatrixEvent } from 'matrix-js-sdk';
import { useEffect } from 'react'; import { useEffect } from 'react';
import { AccountDataEvent } from '../../types/matrix/accountData'; import { AccountDataEvent } from '../../types/matrix/accountData';
import { ThreadNotificationsContent } from '../utils/threadNotifications'; import { ThreadNotificationsContent } from '../utils/threadNotifications';
import { getAccountData } from '../utils/accountData';
// Holds the parsed `io.lotus.thread_notifications` account data. Seeded and // Holds the parsed `io.lotus.thread_notifications` account data. Seeded and
// kept in sync by `useBindThreadNotificationsAtom`. // kept in sync by `useBindThreadNotificationsAtom`.
export const threadNotificationsAtom = atom<ThreadNotificationsContent>({}); export const threadNotificationsAtom = atom<ThreadNotificationsContent>({});
const readContent = (mx: MatrixClient): ThreadNotificationsContent => const readContent = (mx: MatrixClient): ThreadNotificationsContent =>
((mx as any).getAccountData(AccountDataEvent.LotusThreadNotifications)?.getContent() as getAccountData<ThreadNotificationsContent>(mx, AccountDataEvent.LotusThreadNotifications) ?? {};
| ThreadNotificationsContent
| undefined) ?? {};
export const useBindThreadNotificationsAtom = ( export const useBindThreadNotificationsAtom = (
mx: MatrixClient, mx: MatrixClient,
+28
View File
@@ -0,0 +1,28 @@
import { MatrixClient, MatrixEvent } from 'matrix-js-sdk';
import { AccountDataEvent } from '../../types/matrix/accountData';
// Typed global account-data read/write helpers.
//
// matrix-js-sdk's `getAccountData`/`setAccountData` overloads only accept the
// SDK's built-in AccountDataEvents union and reject the fork's custom event
// names (the `io.lotus.*` / `in.cinny.*` values in the AccountDataEvent enum, as
// well as a few dynamic keys used by developer tools). We centralize the single
// `as any` cast here so every call site stays fully typed on its content shape.
export function getAccountData<T>(
mx: MatrixClient,
eventType: AccountDataEvent | string,
): T | undefined {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const event = (mx as any).getAccountData(eventType) as MatrixEvent | undefined;
return event?.getContent() as T | undefined;
}
export function setAccountData<T>(
mx: MatrixClient,
eventType: AccountDataEvent | string,
content: T,
): Promise<void> {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return (mx as any).setAccountData(eventType, content);
}
+1 -1
View File
@@ -45,7 +45,7 @@ export const getStateEvents = (room: Room, eventType: StateEvent): MatrixEvent[]
export const getAccountData = ( export const getAccountData = (
mx: MatrixClient, mx: MatrixClient,
eventType: AccountDataEvent, eventType: AccountDataEvent | string,
): MatrixEvent | undefined => mx.getAccountData(eventType as any); ): MatrixEvent | undefined => mx.getAccountData(eventType as any);
export const getMDirects = (mDirectEvent: MatrixEvent): Set<string> => { export const getMDirects = (mDirectEvent: MatrixEvent): Set<string> => {