Albums: Soul fixes (read receipt, timeline toggle, own-key kinds, edits, calmer fetch)
Some checks failed
Build pull request / Build pull request (pull_request) Has been cancelled
Some checks failed
Build pull request / Build pull request (pull_request) Has been cancelled
- A zone sends the read receipt the timeline would; the unread badge clears. - Timeline stays one tap away (and back); an event deep link opens the timeline. - Kinds come from a Map, so "constructor"/"__proto__" are not files. - Album titles follow m.replace edits. - Fetch: retry once, at most 6 relation reads in flight, refresh every 30 s, a failed refetch keeps the loaded albums. - Encrypted zone says so instead of "No albums yet". - Audio renders without the chat Attachment frame and type badge. - useIsFileZone follows alias changes. - Tests kill the surviving mutants: event type, event_id, create-type prefix. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
907e4d32a5
commit
fa9801a4d6
10 changed files with 231 additions and 38 deletions
|
|
@ -1,18 +1,36 @@
|
|||
import React, { useMemo, useState } from 'react';
|
||||
import React, { useEffect, useMemo, useState } from 'react';
|
||||
import { Box, Scroll, Text } from 'folds';
|
||||
import { Room } from 'matrix-js-sdk';
|
||||
import { Room, RoomEvent } from 'matrix-js-sdk';
|
||||
import { MediaControl } from '../../components/media';
|
||||
import { AudioContent } from '../../components/message';
|
||||
import { RenderMessageContent } from '../../components/RenderMessageContent';
|
||||
import { IAudioContent } from '../../../types/matrix/common';
|
||||
import { LINKIFY_OPTS, getReactCustomHtmlParser } from '../../plugins/react-custom-html-parser';
|
||||
import { useMatrixClient } from '../../hooks/useMatrixClient';
|
||||
import { useMediaAuthentication } from '../../hooks/useMediaAuthentication';
|
||||
import { useSetting } from '../../state/hooks/settings';
|
||||
import { settingsAtom } from '../../state/settings';
|
||||
import { markAsRead } from '../../utils/notifications';
|
||||
import { getBlobSafeMimeType } from '../../utils/mimeTypes';
|
||||
import { timeDayMonYear } from '../../utils/time';
|
||||
import { getMemberDisplayName } from '../../utils/room';
|
||||
import { Album, AlbumFile } from './buildAlbums';
|
||||
import { useAlbums } from './useAlbums';
|
||||
import * as css from './AlbumView.css';
|
||||
|
||||
/**
|
||||
* Audio goes straight to AudioContent, skipping the chat Attachment frame and file-type badge: the
|
||||
* title above it is the only label and the transport controls sit on the scene. Anything that is
|
||||
* not playable audio falls through to the stock renderer (a file download).
|
||||
*/
|
||||
const playableAudio = (content: Record<string, unknown>) => {
|
||||
const c = content as IAudioContent;
|
||||
const url = c.file?.url ?? c.url;
|
||||
const mimeType = getBlobSafeMimeType(c.info?.mimetype ?? '');
|
||||
if (!c.info || typeof url !== 'string' || !mimeType.startsWith('audio')) return undefined;
|
||||
return { info: c.info, url, mimeType, encInfo: c.file };
|
||||
};
|
||||
|
||||
type FileRowProps = { room: Room; file: AlbumFile; author: string };
|
||||
function FileRow({ room, file, author }: FileRowProps) {
|
||||
const mx = useMatrixClient();
|
||||
|
|
@ -23,32 +41,56 @@ function FileRow({ room, file, author }: FileRowProps) {
|
|||
getReactCustomHtmlParser(mx, room.roomId, { linkifyOpts: LINKIFY_OPTS, useAuthentication }),
|
||||
[mx, room.roomId, useAuthentication]
|
||||
);
|
||||
const audio = file.kind === 'audio' ? playableAudio(file.content) : undefined;
|
||||
return (
|
||||
<Box direction="Column" gap="100">
|
||||
<Text size="T300" truncate>
|
||||
{file.name}
|
||||
</Text>
|
||||
<RenderMessageContent
|
||||
displayName={author}
|
||||
msgType={file.content.msgtype as string}
|
||||
ts={file.ts}
|
||||
getContent={<T,>() => file.content as T}
|
||||
mediaAutoLoad={mediaAutoLoad}
|
||||
htmlReactParserOptions={htmlReactParserOptions}
|
||||
linkifyOpts={LINKIFY_OPTS}
|
||||
/>
|
||||
{audio ? (
|
||||
<AudioContent {...audio} renderMediaControl={(p) => <MediaControl {...p} />} />
|
||||
) : (
|
||||
<RenderMessageContent
|
||||
displayName={author}
|
||||
msgType={file.content.msgtype as string}
|
||||
ts={file.ts}
|
||||
getContent={<T,>() => file.content as T}
|
||||
mediaAutoLoad={mediaAutoLoad}
|
||||
htmlReactParserOptions={htmlReactParserOptions}
|
||||
linkifyOpts={LINKIFY_OPTS}
|
||||
/>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
const countLabel = (n: number) => `${n} ${n === 1 ? 'file' : 'files'}`;
|
||||
|
||||
export function AlbumView({ room }: { room: Room }) {
|
||||
/** The zone never mounts RoomTimeline, so it sends the read receipt the timeline would. */
|
||||
function useMarkZoneRead(room: Room) {
|
||||
const mx = useMatrixClient();
|
||||
const [hideActivity] = useSetting(settingsAtom, 'hideActivity');
|
||||
useEffect(() => {
|
||||
const mark = () => {
|
||||
markAsRead(mx, room.roomId, hideActivity).catch(() => undefined);
|
||||
};
|
||||
mark();
|
||||
room.on(RoomEvent.Timeline, mark);
|
||||
return () => {
|
||||
room.off(RoomEvent.Timeline, mark);
|
||||
};
|
||||
}, [mx, room, hideActivity]);
|
||||
}
|
||||
|
||||
type AlbumViewProps = { room: Room; onTimeline: () => void };
|
||||
export function AlbumView({ room, onTimeline }: AlbumViewProps) {
|
||||
useMarkZoneRead(room);
|
||||
const { loading, error, albums } = useAlbums(room);
|
||||
const [dateFormat] = useSetting(settingsAtom, 'dateFormatString');
|
||||
const [openId, setOpenId] = useState<string>();
|
||||
const open: Album | undefined = albums.find((a) => a.id === openId);
|
||||
const authorOf = (a: Album) => getMemberDisplayName(room, a.author) ?? a.author;
|
||||
const encrypted = room.hasEncryptionStateEvent();
|
||||
|
||||
let body: React.ReactNode;
|
||||
if (loading) body = <Text>Loading albums…</Text>;
|
||||
|
|
@ -72,7 +114,9 @@ export function AlbumView({ room }: { room: Room }) {
|
|||
</div>
|
||||
</>
|
||||
);
|
||||
} else if (albums.length === 0) body = <Text>No albums yet.</Text>;
|
||||
} else if (encrypted)
|
||||
body = <Text>This zone is encrypted, so its albums cannot be listed here.</Text>;
|
||||
else if (albums.length === 0) body = <Text>No albums yet.</Text>;
|
||||
else {
|
||||
body = albums.map((a) => (
|
||||
<button key={a.id} type="button" className={css.Row} onClick={() => setOpenId(a.id)}>
|
||||
|
|
@ -86,7 +130,12 @@ export function AlbumView({ room }: { room: Room }) {
|
|||
|
||||
return (
|
||||
<Scroll hideTrack visibility="Hover">
|
||||
<div className={css.Column}>{body}</div>
|
||||
<div className={css.Column}>
|
||||
{body}
|
||||
<button type="button" className={css.Row} onClick={onTimeline}>
|
||||
<Text size="B400">Timeline ›</Text>
|
||||
</button>
|
||||
</div>
|
||||
</Scroll>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -122,4 +122,41 @@ describe('buildAlbums', () => {
|
|||
]);
|
||||
expect(a).toMatchObject({ title: '', author: '', ts: 0, count: 1 });
|
||||
});
|
||||
|
||||
it('does not read inherited object keys as file kinds', () => {
|
||||
const a = one(root('$r', 1), [
|
||||
reply('$c', 1, 'constructor'),
|
||||
reply('$p', 2, '__proto__'),
|
||||
reply('$t', 3, 'toString'),
|
||||
]);
|
||||
expect(a.count).toBe(0);
|
||||
});
|
||||
|
||||
it('skips events that are not room messages even if their content looks like media', () => {
|
||||
const reaction = { ...reply('$x', 5, 'm.audio'), type: 'm.reaction' };
|
||||
const a = one(root('$r', 1), [reaction, reply('$ok', 6, 'm.audio')]);
|
||||
expect(a.files.map((f) => f.id)).toEqual(['$ok']);
|
||||
expect(buildAlbums([{ root: root('$g', 1, { type: 'm.reaction' }), replies: [] }])).toEqual([]);
|
||||
});
|
||||
|
||||
it('skips events without an event id', () => {
|
||||
const anon: ZoneEvent = { type: 'm.room.message', content: { msgtype: 'm.audio', body: 'a' } };
|
||||
expect(one(root('$r', 1), [anon]).count).toBe(0);
|
||||
expect(
|
||||
buildAlbums([{ root: { content: { msgtype: 'm.text', body: 'x' } }, replies: [] }])
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it('titles an edited album by its latest edit', () => {
|
||||
const edited = root('$r', 1, {
|
||||
unsigned: {
|
||||
'm.relations': {
|
||||
'm.replace': { content: { 'm.new_content': { msgtype: 'm.text', body: 'renamed' } } },
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(one(edited, []).title).toBe('renamed');
|
||||
const emptyEdit = root('$q', 1, { unsigned: { 'm.relations': { 'm.replace': {} } } });
|
||||
expect(one(emptyEdit, []).title).toBe('album $q');
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -35,12 +35,13 @@ export type Album = {
|
|||
count: number;
|
||||
};
|
||||
|
||||
const KIND_OF_MSGTYPE: Record<string, FileKind> = {
|
||||
'm.audio': 'audio',
|
||||
'm.image': 'image',
|
||||
'm.video': 'video',
|
||||
'm.file': 'file',
|
||||
};
|
||||
// A Map, not an object: msgtype is server-supplied and "constructor" must not name a kind.
|
||||
const KIND_OF_MSGTYPE = new Map<string, FileKind>([
|
||||
['m.audio', 'audio'],
|
||||
['m.image', 'image'],
|
||||
['m.video', 'video'],
|
||||
['m.file', 'file'],
|
||||
]);
|
||||
|
||||
// A redacted event keeps its id but loses its content and gains unsigned.redacted_because.
|
||||
const live = (
|
||||
|
|
@ -55,7 +56,7 @@ const asString = (v: unknown): string => (typeof v === 'string' ? v : '');
|
|||
|
||||
const toFile = (e: ZoneEvent): AlbumFile | undefined => {
|
||||
if (!live(e)) return undefined;
|
||||
const kind = KIND_OF_MSGTYPE[e.content.msgtype as string];
|
||||
const kind = KIND_OF_MSGTYPE.get(e.content.msgtype as string);
|
||||
if (!kind) return undefined;
|
||||
return {
|
||||
id: e.event_id,
|
||||
|
|
@ -66,6 +67,15 @@ const toFile = (e: ZoneEvent): AlbumFile | undefined => {
|
|||
};
|
||||
};
|
||||
|
||||
// An edited root carries its latest edit under unsigned["m.relations"]["m.replace"]; the title is
|
||||
// that edit's m.new_content.body, else the original body.
|
||||
const titleOf = (root: ZoneEvent & { content: Record<string, unknown> }): string => {
|
||||
const relations = root.unsigned?.['m.relations'] as Record<string, unknown> | undefined;
|
||||
const edit = relations?.['m.replace'] as ZoneEvent | undefined;
|
||||
const edited = (edit?.content?.['m.new_content'] as Record<string, unknown> | undefined)?.body;
|
||||
return asString(edited) || asString(root.content.body);
|
||||
};
|
||||
|
||||
const toAlbum = ({ root, replies }: AlbumInput): Album | undefined => {
|
||||
if (!live(root)) return undefined;
|
||||
const seen = new Set<string>();
|
||||
|
|
@ -79,7 +89,7 @@ const toAlbum = ({ root, replies }: AlbumInput): Album | undefined => {
|
|||
.sort((a, b) => a.ts - b.ts);
|
||||
return {
|
||||
id: root.event_id,
|
||||
title: asString(root.content.body),
|
||||
title: titleOf(root),
|
||||
author: root.sender ?? '',
|
||||
ts: root.origin_server_ts ?? 0,
|
||||
cover: files.find((f) => f.kind === 'image'),
|
||||
|
|
|
|||
|
|
@ -9,6 +9,8 @@ describe('isFileZone', () => {
|
|||
});
|
||||
it('is false for other create types and for plain rooms', () => {
|
||||
expect(isFileZone({ ...room, createType: 'm.space' }, {})).toBe(false);
|
||||
expect(isFileZone({ ...room, createType: 'org.gamecult.other' }, {})).toBe(false);
|
||||
expect(isFileZone({ ...room, createType: 'org.gamecult.file_zone.x' }, {})).toBe(false);
|
||||
expect(isFileZone(room, {})).toBe(false);
|
||||
expect(isFileZone(room, { fileZoneRooms: [] })).toBe(false);
|
||||
});
|
||||
|
|
|
|||
29
src/app/features/albums/mapLimit.test.ts
Normal file
29
src/app/features/albums/mapLimit.test.ts
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import { mapLimit } from './mapLimit';
|
||||
|
||||
describe('mapLimit', () => {
|
||||
it('keeps result order and never exceeds the limit', async () => {
|
||||
let inFlight = 0;
|
||||
let peak = 0;
|
||||
const out = await mapLimit([5, 1, 4, 2, 3, 0], 2, async (n) => {
|
||||
inFlight += 1;
|
||||
peak = Math.max(peak, inFlight);
|
||||
await new Promise((r) => {
|
||||
setTimeout(r, n);
|
||||
});
|
||||
inFlight -= 1;
|
||||
return n * 10;
|
||||
});
|
||||
expect(out).toEqual([50, 10, 40, 20, 30, 0]);
|
||||
expect(peak).toBe(2);
|
||||
});
|
||||
it('handles an empty list and rejects when a call rejects', async () => {
|
||||
expect(await mapLimit([], 3, async (n) => n)).toEqual([]);
|
||||
await expect(
|
||||
mapLimit([1, 2], 2, async (n) => {
|
||||
if (n === 2) throw new Error('boom');
|
||||
return n;
|
||||
})
|
||||
).rejects.toThrow('boom');
|
||||
});
|
||||
});
|
||||
19
src/app/features/albums/mapLimit.ts
Normal file
19
src/app/features/albums/mapLimit.ts
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
/** Like Promise.all(items.map(fn)) but with at most `limit` calls in flight; result order kept. */
|
||||
export const mapLimit = async <T, R>(
|
||||
items: T[],
|
||||
limit: number,
|
||||
fn: (item: T) => Promise<R>
|
||||
): Promise<R[]> => {
|
||||
const out = new Array<R>(items.length);
|
||||
let next = 0;
|
||||
const worker = async () => {
|
||||
while (next < items.length) {
|
||||
const i = next;
|
||||
next += 1;
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
out[i] = await fn(items[i]);
|
||||
}
|
||||
};
|
||||
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
|
||||
return out;
|
||||
};
|
||||
|
|
@ -1,15 +1,23 @@
|
|||
import { useQuery } from '@tanstack/react-query';
|
||||
import { ClientPrefix, Method, Room } from 'matrix-js-sdk';
|
||||
import { StateEvent } from '../../../types/matrix/room';
|
||||
import { useStateEvent } from '../../hooks/useStateEvent';
|
||||
import { useMatrixClient } from '../../hooks/useMatrixClient';
|
||||
import { useClientConfig } from '../../hooks/useClientConfig';
|
||||
import { Album, ZoneEvent, buildAlbums } from './buildAlbums';
|
||||
import { isFileZone } from './isFileZone';
|
||||
import { mapLimit } from './mapLimit';
|
||||
|
||||
const REPLY_FETCHES_IN_FLIGHT = 6;
|
||||
const REFRESH_MS = 30_000;
|
||||
|
||||
type Chunk = { chunk?: ZoneEvent[] };
|
||||
|
||||
/** True when the room is the file zone: by its create type, or listed in the client config. */
|
||||
export const useIsFileZone = (room: Room): boolean => {
|
||||
const config = useClientConfig();
|
||||
// Subscribes to alias changes (alt aliases live in the same event).
|
||||
useStateEvent(room, StateEvent.RoomCanonicalAlias);
|
||||
const createType = room.currentState.getStateEvents('m.room.create', '')?.getContent().type;
|
||||
return isFileZone(
|
||||
{
|
||||
|
|
@ -41,24 +49,25 @@ export const useAlbums = (room: Room): AlbumsState => {
|
|||
});
|
||||
const room_ = encodeURIComponent(roomId);
|
||||
const roots = (await get(`/rooms/${room_}/threads`, { limit: '100' })).chunk ?? [];
|
||||
const inputs = await Promise.all(
|
||||
roots.map(async (root: ZoneEvent) => ({
|
||||
root,
|
||||
replies:
|
||||
(
|
||||
await get(
|
||||
`/rooms/${room_}/relations/${encodeURIComponent(root.event_id ?? '')}/m.thread`,
|
||||
{ limit: '100', dir: 'f' }
|
||||
)
|
||||
).chunk ?? [],
|
||||
}))
|
||||
);
|
||||
const inputs = await mapLimit(roots, REPLY_FETCHES_IN_FLIGHT, async (root: ZoneEvent) => ({
|
||||
root,
|
||||
replies:
|
||||
(
|
||||
await get(
|
||||
`/rooms/${room_}/relations/${encodeURIComponent(root.event_id ?? '')}/m.thread`,
|
||||
{ limit: '100', dir: 'f' }
|
||||
)
|
||||
).chunk ?? [],
|
||||
}));
|
||||
return buildAlbums(inputs);
|
||||
},
|
||||
retry: 1,
|
||||
refetchInterval: REFRESH_MS,
|
||||
});
|
||||
return {
|
||||
loading: query.isLoading,
|
||||
error: query.error as Error | null,
|
||||
// A failed refetch keeps the albums already loaded; the error shows only when there are none.
|
||||
error: query.data ? null : (query.error as Error | null),
|
||||
albums: query.data ?? [],
|
||||
};
|
||||
};
|
||||
|
|
|
|||
13
src/app/features/albums/zoneView.test.ts
Normal file
13
src/app/features/albums/zoneView.test.ts
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import { zoneView } from './zoneView';
|
||||
|
||||
describe('zoneView', () => {
|
||||
it('opens albums by default and the timeline for an event deep link', () => {
|
||||
expect(zoneView(undefined, undefined)).toBe('albums');
|
||||
expect(zoneView(undefined, '$e')).toBe('timeline');
|
||||
});
|
||||
it('lets the user go back to albums or on to the timeline whatever the link said', () => {
|
||||
expect(zoneView('albums', '$e')).toBe('albums');
|
||||
expect(zoneView('timeline', undefined)).toBe('timeline');
|
||||
});
|
||||
});
|
||||
5
src/app/features/albums/zoneView.ts
Normal file
5
src/app/features/albums/zoneView.ts
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
export type ZoneView = 'albums' | 'timeline';
|
||||
|
||||
/** The view a file-zone room shows: the user's choice, else the timeline for an event deep link, else albums. */
|
||||
export const zoneView = (choice: ZoneView | undefined, eventId: string | undefined): ZoneView =>
|
||||
choice ?? (eventId ? 'timeline' : 'albums');
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
import React, { useCallback, useRef } from 'react';
|
||||
import React, { useCallback, useRef, useState } from 'react';
|
||||
import { Box, Text, config } from 'folds';
|
||||
import { EventType } from 'matrix-js-sdk';
|
||||
import { ReactEditor } from 'slate-react';
|
||||
|
|
@ -24,7 +24,9 @@ import { useRoomPermissions } from '../../hooks/useRoomPermissions';
|
|||
import { useRoomCreators } from '../../hooks/useRoomCreators';
|
||||
import { useRoom } from '../../hooks/useRoom';
|
||||
import { AlbumView } from '../albums/AlbumView';
|
||||
import * as albumCss from '../albums/AlbumView.css';
|
||||
import { useIsFileZone } from '../albums/useAlbums';
|
||||
import { ZoneView, zoneView } from '../albums/zoneView';
|
||||
|
||||
const FN_KEYS_REGEX = /^F\d+$/;
|
||||
const shouldFocusMessageField = (evt: KeyboardEvent): boolean => {
|
||||
|
|
@ -66,7 +68,12 @@ export function RoomView({ eventId }: { eventId?: string }) {
|
|||
const room = useRoom();
|
||||
const { roomId } = room;
|
||||
const editor = useEditor();
|
||||
const fileZone = useIsFileZone(room);
|
||||
const isZone = useIsFileZone(room);
|
||||
// A zone shows its albums; the timeline stays one tap away, and an event deep link opens it.
|
||||
const [choice, setChoice] = useState<{ roomId: string; view: ZoneView }>();
|
||||
const fileZone =
|
||||
isZone &&
|
||||
zoneView(choice && choice.roomId === roomId ? choice.view : undefined, eventId) === 'albums';
|
||||
|
||||
const mx = useMatrixClient();
|
||||
|
||||
|
|
@ -98,7 +105,11 @@ export function RoomView({ eventId }: { eventId?: string }) {
|
|||
if (fileZone) {
|
||||
return (
|
||||
<Page ref={roomViewRef}>
|
||||
<AlbumView key={roomId} room={room} />
|
||||
<AlbumView
|
||||
key={roomId}
|
||||
room={room}
|
||||
onTimeline={() => setChoice({ roomId, view: 'timeline' })}
|
||||
/>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
|
|
@ -106,6 +117,15 @@ export function RoomView({ eventId }: { eventId?: string }) {
|
|||
return (
|
||||
<Page ref={roomViewRef}>
|
||||
<Box grow="Yes" direction="Column">
|
||||
{isZone && (
|
||||
<button
|
||||
type="button"
|
||||
className={albumCss.Back}
|
||||
onClick={() => setChoice({ roomId, view: 'albums' })}
|
||||
>
|
||||
<Text size="B400">‹ Albums</Text>
|
||||
</button>
|
||||
)}
|
||||
<RoomTimeline
|
||||
key={roomId}
|
||||
room={room}
|
||||
|
|
|
|||
Loading…
Reference in a new issue