fix(types): align account-data and message edit payload typing

Adopt matrix event-map augmentation and Element-style typed boundaries for account data, and build message edit content with explicit replacement event types. Also make read receipt and fully_read marker sends independent with explicit failure handling.
This commit is contained in:
hazre committed 2026-02-14 17:24:46 +01:00
1 parent 71425f8644
commit 346a32c7d0
10 files changed
+117 -49

No files matched your search

+1 -1
View File
@@ -14,7 +14,7 @@
"check:eslint": "eslint src/*", "check:eslint": "eslint src/*",
"check:prettier": "prettier --check .", "check:prettier": "prettier --check .",
"fix:prettier": "prettier --write .", "fix:prettier": "prettier --write .",
"typecheck": "tsc --noEmit" "typecheck": "tsc"
}, },
"keywords": [], "keywords": [],
"author": "Ajay Bura", "author": "Ajay Bura",
+31 -23
View File
@@ -26,27 +26,30 @@ import { useTextAreaCodeEditor } from '../hooks/useTextAreaCodeEditor';
const EDITOR_INTENT_SPACE_COUNT = 2; const EDITOR_INTENT_SPACE_COUNT = 2;
export type AccountDataSubmitCallback = (type: string, content: object) => Promise<void>; export type AccountDataSubmitCallback<T extends string = string> = (
type: T,
content: object
) => Promise<void>;
type AccountDataInfo = { type AccountDataInfo<T extends string = string> = {
type: string; type: T;
content: object; content: object;
}; };
type AccountDataEditProps = { type AccountDataEditProps<T extends string = string> = {
type: string; type: T | '';
defaultContent: string; defaultContent: string;
submitChange: AccountDataSubmitCallback; submitChange: AccountDataSubmitCallback<T>;
onCancel: () => void; onCancel: () => void;
onSave: (info: AccountDataInfo) => void; onSave: (info: AccountDataInfo<T>) => void;
}; };
function AccountDataEdit({ function AccountDataEdit<T extends string = string>({
type, type,
defaultContent, defaultContent,
submitChange, submitChange,
onCancel, onCancel,
onSave, onSave,
}: AccountDataEditProps) { }: AccountDataEditProps<T>) {
const alive = useAlive(); const alive = useAlive();
const textAreaRef = useRef<HTMLTextAreaElement>(null); const textAreaRef = useRef<HTMLTextAreaElement>(null);
@@ -57,7 +60,7 @@ function AccountDataEdit({
EDITOR_INTENT_SPACE_COUNT EDITOR_INTENT_SPACE_COUNT
); );
const [submitState, submit] = useAsyncCallback<void, MatrixError, [string, object]>(submitChange); const [submitState, submit] = useAsyncCallback<void, MatrixError, [T, object]>(submitChange);
const submitting = submitState.status === AsyncStatus.Loading; const submitting = submitState.status === AsyncStatus.Loading;
const handleSubmit: FormEventHandler<HTMLFormElement> = (evt) => { const handleSubmit: FormEventHandler<HTMLFormElement> = (evt) => {
@@ -89,10 +92,11 @@ function AccountDataEdit({
return; return;
} }
submit(typeStr, parsedContent).then(() => { const eventType = typeStr as T;
submit(eventType, parsedContent).then(() => {
if (alive()) { if (alive()) {
onSave({ onSave({
type: typeStr, type: eventType,
content: parsedContent, content: parsedContent,
}); });
} }
@@ -192,12 +196,16 @@ function AccountDataEdit({
); );
} }
type AccountDataViewProps = { type AccountDataViewProps<T extends string = string> = {
type: string; type: T;
defaultContent: string; defaultContent: string;
onEdit: () => void; onEdit: () => void;
}; };
function AccountDataView({ type, defaultContent, onEdit }: AccountDataViewProps) { function AccountDataView<T extends string = string>({
type,
defaultContent,
onEdit,
}: AccountDataViewProps<T>) {
return ( return (
<Box <Box
direction="Column" direction="Column"
@@ -241,21 +249,21 @@ function AccountDataView({ type, defaultContent, onEdit }: AccountDataViewProps)
); );
} }
export type AccountDataEditorProps = { export type AccountDataEditorProps<T extends string = string> = {
type?: string; type?: T;
content?: object; content?: object;
submitChange: AccountDataSubmitCallback; submitChange: AccountDataSubmitCallback<T>;
requestClose: () => void; requestClose: () => void;
}; };
export function AccountDataEditor({ export function AccountDataEditor<T extends string = string>({
type, type,
content, content,
submitChange, submitChange,
requestClose, requestClose,
}: AccountDataEditorProps) { }: AccountDataEditorProps<T>) {
const [data, setData] = useState<AccountDataInfo>({ const [data, setData] = useState<AccountDataInfo<T>>({
type: type ?? '', type: (type ?? '') as T,
content: content ?? {}, content: content ?? {},
}); });
@@ -269,7 +277,7 @@ export function AccountDataEditor({
setEdit(false); setEdit(false);
}, [type, requestClose]); }, [type, requestClose]);
const handleSave = useCallback((info: AccountDataInfo) => { const handleSave = useCallback((info: AccountDataInfo<T>) => {
setData(info); setData(info);
setEdit(false); setEdit(false);
}, []); }, []);
@@ -21,7 +21,16 @@ import {
} from 'folds'; } from 'folds';
import { Editor, Transforms } from 'slate'; import { Editor, Transforms } from 'slate';
import { ReactEditor } from 'slate-react'; import { ReactEditor } from 'slate-react';
import { IContent, IMentions, MatrixEvent, RelationType, Room } from '$types/matrix-sdk'; import {
IContent,
IMentions,
MatrixEvent,
ReplacementEvent,
RelationType,
Room,
RoomMessageEventContent,
RoomMessageTextEventContent,
} from '$types/matrix-sdk';
import { isKeyHotkey } from 'is-hotkey'; import { isKeyHotkey } from 'is-hotkey';
import { import {
AUTOCOMPLETE_PREFIXES, AUTOCOMPLETE_PREFIXES,
@@ -80,7 +89,8 @@ export const MessageEditor = as<'div', MessageEditorProps>(
string | undefined, string | undefined,
IMentions | undefined IMentions | undefined
] => { ] => {
const evtId = mEvent.getId()!; const evtId = mEvent.getId();
if (!evtId) return [undefined, undefined, undefined];
const evtTimeline = room.getTimelineForEvent(evtId); const evtTimeline = room.getTimelineForEvent(evtId);
const editedEvent = const editedEvent =
evtTimeline && getEditedEvent(evtId, mEvent, evtTimeline.getTimelineSet()); evtTimeline && getEditedEvent(evtId, mEvent, evtTimeline.getTimelineSet());
@@ -111,6 +121,9 @@ export const MessageEditor = as<'div', MessageEditorProps>(
const [prevBody, prevCustomHtml, prevMentions] = getPrevBodyAndFormattedBody(); const [prevBody, prevCustomHtml, prevMentions] = getPrevBodyAndFormattedBody();
if (plainText === '') return undefined; if (plainText === '') return undefined;
const eventId = mEvent.getId();
if (!eventId) return undefined;
if (prevBody) { if (prevBody) {
if (prevCustomHtml && trimReplyFromFormattedBody(prevCustomHtml) === customHtml) { if (prevCustomHtml && trimReplyFromFormattedBody(prevCustomHtml) === customHtml) {
return undefined; return undefined;
@@ -124,11 +137,20 @@ export const MessageEditor = as<'div', MessageEditorProps>(
} }
} }
const newContent: IContent = { const msgtype = mEvent.getContent().msgtype as RoomMessageTextEventContent['msgtype'];
msgtype: mEvent.getContent().msgtype,
const newContent: RoomMessageTextEventContent = {
msgtype,
body: plainText, body: plainText,
}; };
const contentBody: RoomMessageTextEventContent &
Omit<ReplacementEvent<RoomMessageEventContent>, 'm.relates_to'> = {
msgtype,
body: `* ${plainText}`,
'm.new_content': newContent,
};
const mentionData = getMentions(mx, roomId, editor); const mentionData = getMentions(mx, roomId, editor);
prevMentions?.user_ids?.forEach((prevMentionId) => { prevMentions?.user_ids?.forEach((prevMentionId) => {
@@ -137,18 +159,19 @@ export const MessageEditor = as<'div', MessageEditorProps>(
const mMentions = getMentionContent(Array.from(mentionData.users), mentionData.room); const mMentions = getMentionContent(Array.from(mentionData.users), mentionData.room);
newContent['m.mentions'] = mMentions; newContent['m.mentions'] = mMentions;
contentBody['m.mentions'] = mMentions;
if (!customHtmlEqualsPlainText(customHtml, plainText)) { if (!customHtmlEqualsPlainText(customHtml, plainText)) {
newContent.format = 'org.matrix.custom.html'; newContent.format = 'org.matrix.custom.html';
newContent.formatted_body = customHtml; newContent.formatted_body = customHtml;
contentBody.format = 'org.matrix.custom.html';
contentBody.formatted_body = `* ${customHtml}`;
} }
const content: IContent = { const content: RoomMessageEventContent = {
...newContent, ...contentBody,
body: `* ${plainText}`,
'm.new_content': newContent,
'm.relates_to': { 'm.relates_to': {
event_id: mEvent.getId(), event_id: eventId,
rel_type: RelationType.Replace, rel_type: RelationType.Replace,
}, },
}; };
@@ -1,5 +1,6 @@
import React, { useCallback, useState } from 'react'; import React, { useCallback, useState } from 'react';
import { Box, Text, Icon, Icons, Button, MenuItem } from 'folds'; import { Box, Text, Icon, Icons, Button, MenuItem } from 'folds';
import { AccountDataEvents } from '$types/matrix-sdk';
import { SequenceCard } from '../../../components/sequence-card'; 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';
@@ -10,18 +11,22 @@ import { CutoutCard } from '../../../components/cutout-card';
type AccountDataProps = { type AccountDataProps = {
expand: boolean; expand: boolean;
onExpandToggle: (expand: boolean) => void; onExpandToggle: (expand: boolean) => void;
onSelect: (type: string | null) => void; onSelect: (type: Extract<keyof AccountDataEvents, string> | null) => void;
}; };
export function AccountData({ expand, onExpandToggle, onSelect }: AccountDataProps) { export function AccountData({ expand, onExpandToggle, onSelect }: AccountDataProps) {
const mx = useMatrixClient(); const mx = useMatrixClient();
const [accountDataTypes, setAccountDataKeys] = useState(() => const [accountDataTypes, setAccountDataKeys] = useState<
Array.from(mx.store.accountData.keys()) Array<Extract<keyof AccountDataEvents, string>>
>(
() => Array.from(mx.store.accountData.keys()) as Array<Extract<keyof AccountDataEvents, string>>
); );
useAccountDataCallback( useAccountDataCallback(
mx, mx,
useCallback(() => { useCallback(() => {
setAccountDataKeys(Array.from(mx.store.accountData.keys())); setAccountDataKeys(
Array.from(mx.store.accountData.keys()) as Array<Extract<keyof AccountDataEvents, string>>
);
}, [mx]) }, [mx])
); );
@@ -7,6 +7,7 @@ import { SettingTile } from '../../../components/setting-tile';
import { useSetting } from '../../../state/hooks/settings'; import { useSetting } from '../../../state/hooks/settings';
import { settingsAtom } from '../../../state/settings'; import { settingsAtom } from '../../../state/settings';
import { useMatrixClient } from '../../../hooks/useMatrixClient'; import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { AccountDataEvents } from '$types/matrix-sdk';
import { import {
AccountDataEditor, AccountDataEditor,
AccountDataSubmitCallback, AccountDataSubmitCallback,
@@ -14,6 +15,8 @@ import {
import { copyToClipboard } from '../../../utils/dom'; import { copyToClipboard } from '../../../utils/dom';
import { AccountData } from './AccountData'; import { AccountData } from './AccountData';
type AccountDataEventType = Extract<keyof AccountDataEvents, string>;
type DeveloperToolsProps = { type DeveloperToolsProps = {
requestClose: () => void; requestClose: () => void;
}; };
@@ -21,9 +24,9 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) {
const mx = useMatrixClient(); const mx = useMatrixClient();
const [developerTools, setDeveloperTools] = useSetting(settingsAtom, 'developerTools'); const [developerTools, setDeveloperTools] = useSetting(settingsAtom, 'developerTools');
const [expand, setExpend] = useState(false); const [expand, setExpend] = useState(false);
const [accountDataType, setAccountDataType] = useState<string | null>(); const [accountDataType, setAccountDataType] = useState<AccountDataEventType | null>();
const submitAccountData: AccountDataSubmitCallback = useCallback( const submitAccountData: AccountDataSubmitCallback<AccountDataEventType> = useCallback(
async (type, content) => { async (type, content) => {
await mx.setAccountData(type, content); await mx.setAccountData(type, content);
}, },
+2 -1
View File
@@ -1,10 +1,11 @@
import { useState, useCallback } from 'react'; import { useState, useCallback } from 'react';
import { AccountDataEvents } from '$types/matrix-sdk';
import { useMatrixClient } from './useMatrixClient'; import { useMatrixClient } from './useMatrixClient';
import { useAccountDataCallback } from './useAccountDataCallback'; import { useAccountDataCallback } from './useAccountDataCallback';
export function useAccountData(eventType: string) { export function useAccountData(eventType: string) {
const mx = useMatrixClient(); const mx = useMatrixClient();
const [event, setEvent] = useState(() => mx.getAccountData(eventType)); const [event, setEvent] = useState(() => mx.getAccountData(eventType as keyof AccountDataEvents));
useAccountDataCallback( useAccountDataCallback(
mx, mx,
+15 -8
View File
@@ -22,12 +22,19 @@ export async function markAsRead(mx: MatrixClient, roomId: string, privateReceip
const latestEventId = latestEvent.getId(); const latestEventId = latestEvent.getId();
if (!latestEventId) return; if (!latestEventId) return;
// Set both the read receipt AND the fully_read marker // Match Element Web behavior: send receipt and fully_read marker separately.
// The fully_read marker is what persists your read position across sessions // Keep them independent so a failure in one does not block the other.
await mx.setRoomReadMarkers( const receiptType = privateReceipt ? ReceiptType.ReadPrivate : undefined;
roomId,
latestEventId, // m.fully_read marker const [receiptResult, markerResult] = await Promise.allSettled([
latestEvent, // m.read receipt event mx.sendReadReceipt(latestEvent, receiptType),
privateReceipt ? { receiptType: ReceiptType.ReadPrivate } : undefined mx.setRoomReadMarkers(roomId, latestEventId),
); ]);
if (receiptResult.status === 'rejected') {
console.error('Failed to send read receipt', receiptResult.reason);
}
if (markerResult.status === 'rejected') {
console.error('Failed to send fully_read marker', markerResult.reason);
}
} }
+18
View File
@@ -0,0 +1,18 @@
import type { PackContent } from '../app/plugins/custom-emoji/types';
import type { EmoteRoomsContent } from '../app/plugins/custom-emoji/types';
import type { IRecentEmojiContent } from '../app/plugins/recent-emoji';
import type { InCinnySpacesContent } from '../app/hooks/useSidebarItems';
declare module 'matrix-js-sdk/lib/@types/event' {
interface StateEvents {
'im.ponies.room_emotes': PackContent;
'in.cinny.room.power_level_tags': Record<string, unknown>;
}
interface AccountDataEvents {
'in.cinny.spaces': InCinnySpacesContent;
'io.element.recent_emoji': IRecentEmojiContent;
'im.ponies.user_emotes': PackContent;
'im.ponies.emote_rooms': EmoteRoomsContent;
}
}
+1
View File
@@ -31,6 +31,7 @@ export * from 'matrix-js-sdk/lib/crypto-api/index';
export * from 'matrix-js-sdk/lib/@types/common'; export * from 'matrix-js-sdk/lib/@types/common';
export * from 'matrix-js-sdk/lib/@types/uia'; export * from 'matrix-js-sdk/lib/@types/uia';
export * from 'matrix-js-sdk/lib/@types/event'; export * from 'matrix-js-sdk/lib/@types/event';
export * from 'matrix-js-sdk/lib/@types/events';
export * from 'matrix-js-sdk/lib/@types/PushRules'; export * from 'matrix-js-sdk/lib/@types/PushRules';
export * from 'matrix-js-sdk/lib/@types/partials'; export * from 'matrix-js-sdk/lib/@types/partials';
export * from 'matrix-js-sdk/lib/@types/requests'; export * from 'matrix-js-sdk/lib/@types/requests';
+3 -1
View File
@@ -11,7 +11,9 @@
"paths": { "paths": {
"$types/*": ["src/types/*"] "$types/*": ["src/types/*"]
}, },
"moduleResolution": "Node", "moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"noEmit": true,
"resolveJsonModule": true, "resolveJsonModule": true,
"outDir": "dist", "outDir": "dist",
"skipLibCheck": true, "skipLibCheck": true,