diff --git a/src/app/features/albums/AlbumView.css.ts b/src/app/features/albums/AlbumView.css.ts new file mode 100644 index 00000000..c4f4fc79 --- /dev/null +++ b/src/app/features/albums/AlbumView.css.ts @@ -0,0 +1,51 @@ +import { style } from '@vanilla-extract/css'; +import { color, config, toRem } from 'folds'; +import { MOBILE_BREAKPOINT } from '../../hooks/useScreenSize'; + +const WIDE = `screen and (min-width: ${MOBILE_BREAKPOINT + 1}px)`; + +/** One column, bare ink on the scene. */ +export const Column = style({ + maxWidth: toRem(720), + width: '100%', + margin: '0 auto', + padding: config.space.S400, + display: 'flex', + flexDirection: 'column', + gap: config.space.S200, +}); + +/** A tappable text row: no border, no fill, at least 44 px tall. */ +export const Row = style({ + all: 'unset', + boxSizing: 'border-box', + cursor: 'pointer', + minHeight: 44, + display: 'flex', + flexDirection: 'column', + justifyContent: 'center', + gap: toRem(2), + color: color.Background.OnContainer, + ':focus-visible': { textDecoration: 'underline' }, +}); + +export const Back = style([Row, { minHeight: 44 }]); + +export const Files = style({ + display: 'flex', + flexDirection: 'column', + gap: config.space.S400, +}); + +/** Images may tile into a grid on wide screens only. */ +export const FilesWide = style({ + '@media': { + [WIDE]: { + display: 'grid', + gridTemplateColumns: 'repeat(auto-fill, minmax(220px, 1fr))', + alignItems: 'start', + }, + }, +}); + +export const Dim = style({ opacity: config.opacity.P300 }); diff --git a/src/app/features/albums/AlbumView.tsx b/src/app/features/albums/AlbumView.tsx new file mode 100644 index 00000000..c8961f0d --- /dev/null +++ b/src/app/features/albums/AlbumView.tsx @@ -0,0 +1,92 @@ +import React, { useMemo, useState } from 'react'; +import { Box, Scroll, Text } from 'folds'; +import { Room } from 'matrix-js-sdk'; +import { RenderMessageContent } from '../../components/RenderMessageContent'; +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 { timeDayMonYear } from '../../utils/time'; +import { getMemberDisplayName } from '../../utils/room'; +import { Album, AlbumFile } from './buildAlbums'; +import { useAlbums } from './useAlbums'; +import * as css from './AlbumView.css'; + +type FileRowProps = { room: Room; file: AlbumFile; author: string }; +function FileRow({ room, file, author }: FileRowProps) { + const mx = useMatrixClient(); + const useAuthentication = useMediaAuthentication(); + const [mediaAutoLoad] = useSetting(settingsAtom, 'mediaAutoLoad'); + const htmlReactParserOptions = useMemo( + () => + getReactCustomHtmlParser(mx, room.roomId, { linkifyOpts: LINKIFY_OPTS, useAuthentication }), + [mx, room.roomId, useAuthentication] + ); + return ( + + + {file.name} + + () => file.content as T} + mediaAutoLoad={mediaAutoLoad} + htmlReactParserOptions={htmlReactParserOptions} + linkifyOpts={LINKIFY_OPTS} + /> + + ); +} + +const countLabel = (n: number) => `${n} ${n === 1 ? 'file' : 'files'}`; + +export function AlbumView({ room }: { room: Room }) { + const { loading, error, albums } = useAlbums(room); + const [dateFormat] = useSetting(settingsAtom, 'dateFormatString'); + const [openId, setOpenId] = useState(); + const open: Album | undefined = albums.find((a) => a.id === openId); + const authorOf = (a: Album) => getMemberDisplayName(room, a.author) ?? a.author; + + let body: React.ReactNode; + if (loading) body = Loading albums…; + else if (error) body = Could not load albums: {error.message}; + else if (open) { + const images = open.files.length > 0 && open.files.every((f) => f.kind === 'image'); + body = ( + <> + + {open.title} + + {authorOf(open)} · {countLabel(open.count)} · {timeDayMonYear(open.ts, dateFormat)} + + {open.count === 0 && This album has no files.} +
+ {open.files.map((f) => ( + + ))} +
+ + ); + } else if (albums.length === 0) body = No albums yet.; + else { + body = albums.map((a) => ( + + )); + } + + return ( + +
{body}
+
+ ); +} diff --git a/src/app/features/albums/useAlbums.ts b/src/app/features/albums/useAlbums.ts new file mode 100644 index 00000000..e883c838 --- /dev/null +++ b/src/app/features/albums/useAlbums.ts @@ -0,0 +1,64 @@ +import { useQuery } from '@tanstack/react-query'; +import { ClientPrefix, Method, Room } from 'matrix-js-sdk'; +import { useMatrixClient } from '../../hooks/useMatrixClient'; +import { useClientConfig } from '../../hooks/useClientConfig'; +import { Album, ZoneEvent, buildAlbums } from './buildAlbums'; +import { isFileZone } from './isFileZone'; + +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(); + const createType = room.currentState.getStateEvents('m.room.create', '')?.getContent().type; + return isFileZone( + { + roomId: room.roomId, + aliases: [room.getCanonicalAlias(), ...room.getAltAliases()].filter((a): a is string => !!a), + createType, + }, + config + ); +}; + +export type AlbumsState = { loading: boolean; error: Error | null; albums: Album[] }; + +/** + * Slice 1 reads ONE page of each endpoint (threads: 100 roots; replies per root: 100). A zone with + * more albums or files than that is truncated; pagination is a later slice. Reads are made with + * the logged-in client, so the room must be unencrypted: encrypted events carry no msgtype and + * are skipped. + */ +export const useAlbums = (room: Room): AlbumsState => { + const mx = useMatrixClient(); + const { roomId } = room; + const query = useQuery({ + queryKey: ['albums', roomId], + queryFn: async (): Promise => { + const get = (path: string, params: Record) => + mx.http.authedRequest(Method.Get, path, params, undefined, { + prefix: ClientPrefix.V1, + }); + 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 ?? [], + })) + ); + return buildAlbums(inputs); + }, + }); + return { + loading: query.isLoading, + error: query.error as Error | null, + albums: query.data ?? [], + }; +}; diff --git a/src/app/features/room/RoomView.tsx b/src/app/features/room/RoomView.tsx index 3fbd81fa..4ead415d 100644 --- a/src/app/features/room/RoomView.tsx +++ b/src/app/features/room/RoomView.tsx @@ -23,6 +23,8 @@ import { useSetting } from '../../state/hooks/settings'; import { useRoomPermissions } from '../../hooks/useRoomPermissions'; import { useRoomCreators } from '../../hooks/useRoomCreators'; import { useRoom } from '../../hooks/useRoom'; +import { AlbumView } from '../albums/AlbumView'; +import { useIsFileZone } from '../albums/useAlbums'; const FN_KEYS_REGEX = /^F\d+$/; const shouldFocusMessageField = (evt: KeyboardEvent): boolean => { @@ -64,6 +66,7 @@ export function RoomView({ eventId }: { eventId?: string }) { const room = useRoom(); const { roomId } = room; const editor = useEditor(); + const fileZone = useIsFileZone(room); const mx = useMatrixClient(); @@ -78,7 +81,7 @@ export function RoomView({ eventId }: { eventId?: string }) { window, useCallback( (evt) => { - if (editableActiveElement()) return; + if (fileZone || editableActiveElement()) return; const portalContainer = document.getElementById('portalContainer'); if (portalContainer && portalContainer.children.length > 0) { return; @@ -87,10 +90,19 @@ export function RoomView({ eventId }: { eventId?: string }) { ReactEditor.focus(editor); } }, - [editor] + [editor, fileZone] ) ); + // The file zone is its own view: no timeline, no composer. + if (fileZone) { + return ( + + + + ); + } + return (