Refactor timeline (#1346)

* fix intersection & resize observer

* add binary search util

* add scroll info util

* add virtual paginator hook - WIP

* render timeline using paginator hook

* add continuous pagination to fill timeline

* add doc comments in virtual paginator hook

* add scroll to element func in virtual paginator

* extract timeline pagination login into hook

* add sliding name for timeline messages - testing

* scroll with live event

* change message rending style

* make message timestamp smaller

* remove unused imports

* add random number between util

* add compact message component

* add sanitize html types

* fix sending alias in room mention

* get room member display name util

* add get room with canonical alias util

* add sanitize html util

* render custom html with new styles

* fix linkifying link text

* add reaction component

* display message reactions in timeline

* Change mention color

* show edited message

* add event sent by function factory

* add functions to get emoji shortcode

* add component for reaction msg

* add tooltip for who has reacted

* add message layouts & placeholder

* fix reaction size

* fix dark theme colors

* add code highlight with prismjs

* add options to configure spacing in msgs

* render message reply

* fix trim reply from body regex

* fix crash when loading reply

* fix reply hover style

* decrypt event on timeline paginate

* update custom html code style

* remove console logs

* fix virtual paginator scroll to func

* fix virtual paginator scroll to types

* add stop scroll for in view item options

* fix virtual paginator out of range scroll to index

* scroll to and highlight reply on click

* fix reply hover style

* make message avatar clickable

* fix scrollTo issue in virtual paginator

* load reply from fetch

* import virtual paginator restore scroll

* load timeline for specific event

* Fix back pagination recalibration

* fix reply min height

* revert code block colors to secondary

* stop sanitizing text in code block

* add decrypt file util

* add image media component

* update folds

* fix code block font style

* add msg event type

* add scale dimension util

* strict msg layout type

* add image renderer component

* add message content fallback components

* add message matrix event renderer components

* render matrix event using hooks

* add attachment component

* add attachment content types

* handle error when rendering image in timeline

* add video component

* render video

* include blurhash in thumbnails

* generate thumbnails for image message

* fix reactToDom spoiler opts

* add hooks for HTMLMediaElement

* render audio file in timeline

* add msg image content component

* fix image content props

* add video content component

* render new image/video component in timeline

* remove console.log

* convert seconds to milliseconds in video info

* add load thumbnail prop to video content component

* add file saver types

* add file header component

* add file content component

* render file in timeline

* add media control component

* render audio message in room timeline

* remove moved components

* safely load message reply

* add media loading hook

* update media control layout

* add loading indication in audio component

* fill audio play icon when playing audio

* fix media expanding

* add image viewer - WIP

* add pan and zoom control to image viewer

* add text based file viewer

* add pdf viewer

* add error handling in pdf viewer

* add download btn to pdf viewer

* fix file button spinner fill

* fix file opens on re-render

* add range slider in audio content player

* render location in timeline

* update folds

* display membership event in timeline

* make reactions toggle

* render sticker messages in timeline

* render room name, topic, avatar change and event

* fix typos

* update render state event type style

* add  room intro in start of timeline

* add power levels context

* fix wrong param passing in RoomView

* fix sending typing notification in wrong room

Slate onChange callback was not updating with react re-renders.

* send typing status on key up

* add typing indicator component

* add typing member atom

* display typing status in member drawer

* add room view typing member component

* display typing members in room view

* remove old roomTimeline uses

* add event readers hook

* add latest event hook

* display following members in room view

* fetch event instead of event context for reply

* fix typo in virtual paginator hook

* add scroll to latest btn in timeline

* change scroll to latest chip variant

* destructure paginator object to improve perf

* restore forward dir scroll in virtual paginator

* run scroll to bottom in layout effect

* display unread message indicator in timeline

* make component for room timeline float

* add timeline divider component

* add day divider and format message time

* apply message spacing to dividers

* format date in room intro

* send read receipt on message arrive

* add event readers component

* add reply, read receipt, source delete opt

* bug fixes

* update timeline on delete & show reason

* fix empty reaction container style

* show msg selection effect on msg option open

* add report message options

* add options to send quick reactions

* add emoji board in message options

* add reaction viewer

* fix styles

* show view reaction in msg options menu

* fix spacing between two msg by same person

* add option menu in other rendered event

* handle m.room.encrypted messages

* fix italic reply text overflow cut

* handle encrypted sticker messages

* remove console log

* prevent message context menu with alt key pressed

* make mentions clickable in messages

* add options to show and hidden events in timeline

* add option to disable media autoload

* remove old emojiboard opener

* add options to use system emoji

* refresh timeline on reset

* fix stuck typing member in member drawer
This commit is contained in:
Ajay Bura 2023-10-06 13:44:06 +11:00 committed by GitHub
parent fcd7723f73
commit 3a95d0da01
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
124 changed files with 9438 additions and 258 deletions

View file

@ -20,6 +20,9 @@ module.exports = {
ecmaVersion: 'latest', ecmaVersion: 'latest',
sourceType: 'module', sourceType: 'module',
}, },
"globals": {
JSX: "readonly"
},
plugins: [ plugins: [
'react', 'react',
'@typescript-eslint' '@typescript-eslint'

648
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -33,22 +33,26 @@
"browser-encrypt-attachment": "0.3.0", "browser-encrypt-attachment": "0.3.0",
"classnames": "2.3.2", "classnames": "2.3.2",
"dateformat": "5.0.3", "dateformat": "5.0.3",
"dayjs": "1.11.10",
"emojibase": "6.1.0", "emojibase": "6.1.0",
"emojibase-data": "7.0.1", "emojibase-data": "7.0.1",
"file-saver": "2.0.5", "file-saver": "2.0.5",
"flux": "4.0.3", "flux": "4.0.3",
"focus-trap-react": "10.0.2", "focus-trap-react": "10.0.2",
"folds": "1.3.0", "folds": "1.5.0",
"formik": "2.2.9", "formik": "2.2.9",
"html-react-parser": "3.0.4", "html-react-parser": "4.2.0",
"immer": "9.0.16", "immer": "9.0.16",
"is-hotkey": "0.2.0", "is-hotkey": "0.2.0",
"jotai": "1.12.0", "jotai": "1.12.0",
"katex": "0.16.4", "katex": "0.16.4",
"linkify-html": "4.0.2", "linkify-html": "4.0.2",
"linkify-react": "4.1.1",
"linkifyjs": "4.0.2", "linkifyjs": "4.0.2",
"matrix-js-sdk": "24.1.0", "matrix-js-sdk": "24.1.0",
"millify": "6.1.0", "millify": "6.1.0",
"pdfjs-dist": "3.10.111",
"prismjs": "1.29.0",
"prop-types": "15.8.1", "prop-types": "15.8.1",
"react": "17.0.2", "react": "17.0.2",
"react-autosize-textarea": "7.1.0", "react-autosize-textarea": "7.1.0",
@ -56,8 +60,10 @@
"react-dnd": "15.1.2", "react-dnd": "15.1.2",
"react-dnd-html5-backend": "15.1.3", "react-dnd-html5-backend": "15.1.3",
"react-dom": "17.0.2", "react-dom": "17.0.2",
"react-error-boundary": "4.0.10",
"react-google-recaptcha": "2.1.0", "react-google-recaptcha": "2.1.0",
"react-modal": "3.16.1", "react-modal": "3.16.1",
"react-range": "1.8.14",
"sanitize-html": "2.8.0", "sanitize-html": "2.8.0",
"slate": "0.90.0", "slate": "0.90.0",
"slate-history": "0.93.0", "slate-history": "0.93.0",
@ -70,9 +76,12 @@
"@esbuild-plugins/node-globals-polyfill": "0.2.3", "@esbuild-plugins/node-globals-polyfill": "0.2.3",
"@rollup/plugin-inject": "5.0.3", "@rollup/plugin-inject": "5.0.3",
"@rollup/plugin-wasm": "6.1.1", "@rollup/plugin-wasm": "6.1.1",
"@types/file-saver": "2.0.5",
"@types/node": "18.11.18", "@types/node": "18.11.18",
"@types/prismjs": "1.26.0",
"@types/react": "18.0.26", "@types/react": "18.0.26",
"@types/react-dom": "18.0.9", "@types/react-dom": "18.0.9",
"@types/sanitize-html": "2.9.0",
"@types/ua-parser-js": "0.7.36", "@types/ua-parser-js": "0.7.36",
"@typescript-eslint/eslint-plugin": "5.46.1", "@typescript-eslint/eslint-plugin": "5.46.1",
"@typescript-eslint/parser": "5.46.1", "@typescript-eslint/parser": "5.46.1",

View file

@ -0,0 +1,37 @@
import { style } from '@vanilla-extract/css';
import { DefaultReset, color, config } from 'folds';
export const PdfViewer = style([
DefaultReset,
{
height: '100%',
},
]);
export const PdfViewerHeader = style([
DefaultReset,
{
paddingLeft: config.space.S200,
paddingRight: config.space.S200,
borderBottomWidth: config.borderWidth.B300,
flexShrink: 0,
gap: config.space.S200,
},
]);
export const PdfViewerFooter = style([
PdfViewerHeader,
{
borderTopWidth: config.borderWidth.B300,
borderBottomWidth: 0,
},
]);
export const PdfViewerContent = style([
DefaultReset,
{
margin: 'auto',
display: 'inline-block',
backgroundColor: color.Surface.Container,
color: color.Surface.OnContainer,
},
]);

View file

@ -0,0 +1,257 @@
/* eslint-disable no-param-reassign */
/* eslint-disable jsx-a11y/no-noninteractive-element-interactions */
import React, { FormEventHandler, useEffect, useRef, useState } from 'react';
import classNames from 'classnames';
import {
Box,
Button,
Chip,
Header,
Icon,
IconButton,
Icons,
Input,
Menu,
PopOut,
Scroll,
Spinner,
Text,
as,
config,
} from 'folds';
import FocusTrap from 'focus-trap-react';
import FileSaver from 'file-saver';
import * as css from './PdfViewer.css';
import { AsyncStatus } from '../../hooks/useAsyncCallback';
import { useZoom } from '../../hooks/useZoom';
import { createPage, usePdfDocumentLoader, usePdfJSLoader } from '../../plugins/pdfjs-dist';
export type PdfViewerProps = {
name: string;
src: string;
requestClose: () => void;
};
export const PdfViewer = as<'div', PdfViewerProps>(
({ className, name, src, requestClose, ...props }, ref) => {
const containerRef = useRef<HTMLDivElement>(null);
const scrollRef = useRef<HTMLDivElement>(null);
const { zoom, zoomIn, zoomOut, setZoom } = useZoom(0.2);
const [pdfJSState, loadPdfJS] = usePdfJSLoader();
const [docState, loadPdfDocument] = usePdfDocumentLoader(
pdfJSState.status === AsyncStatus.Success ? pdfJSState.data : undefined,
src
);
const isLoading =
pdfJSState.status === AsyncStatus.Loading || docState.status === AsyncStatus.Loading;
const isError =
pdfJSState.status === AsyncStatus.Error || docState.status === AsyncStatus.Error;
const [pageNo, setPageNo] = useState(1);
const [openJump, setOpenJump] = useState(false);
useEffect(() => {
loadPdfJS();
}, [loadPdfJS]);
useEffect(() => {
if (pdfJSState.status === AsyncStatus.Success) {
loadPdfDocument();
}
}, [pdfJSState, loadPdfDocument]);
useEffect(() => {
if (docState.status === AsyncStatus.Success) {
const doc = docState.data;
if (pageNo < 0 || pageNo > doc.numPages) return;
createPage(doc, pageNo, { scale: zoom }).then((canvas) => {
const container = containerRef.current;
if (!container) return;
container.textContent = '';
container.append(canvas);
scrollRef.current?.scrollTo({
top: 0,
});
});
}
}, [docState, pageNo, zoom]);
const handleDownload = () => {
FileSaver.saveAs(src, name);
};
const handleJumpSubmit: FormEventHandler<HTMLFormElement> = (evt) => {
evt.preventDefault();
if (docState.status !== AsyncStatus.Success) return;
const jumpInput = evt.currentTarget.jumpInput as HTMLInputElement;
if (!jumpInput) return;
const jumpTo = parseInt(jumpInput.value, 10);
setPageNo(Math.max(1, Math.min(docState.data.numPages, jumpTo)));
setOpenJump(false);
};
const handlePrevPage = () => {
setPageNo((n) => Math.max(n - 1, 1));
};
const handleNextPage = () => {
if (docState.status !== AsyncStatus.Success) return;
setPageNo((n) => Math.min(n + 1, docState.data.numPages));
};
return (
<Box className={classNames(css.PdfViewer, className)} direction="Column" {...props} ref={ref}>
<Header className={css.PdfViewerHeader} size="400">
<Box grow="Yes" alignItems="Center" gap="200">
<IconButton size="300" radii="300" onClick={requestClose}>
<Icon size="50" src={Icons.ArrowLeft} />
</IconButton>
<Text size="T300" truncate>
{name}
</Text>
</Box>
<Box shrink="No" alignItems="Center" gap="200">
<IconButton
variant={zoom < 1 ? 'Success' : 'SurfaceVariant'}
outlined={zoom < 1}
size="300"
radii="Pill"
onClick={zoomOut}
aria-label="Zoom Out"
>
<Icon size="50" src={Icons.Minus} />
</IconButton>
<Chip variant="SurfaceVariant" radii="Pill" onClick={() => setZoom(zoom === 1 ? 2 : 1)}>
<Text size="B300">{Math.round(zoom * 100)}%</Text>
</Chip>
<IconButton
variant={zoom > 1 ? 'Success' : 'SurfaceVariant'}
outlined={zoom > 1}
size="300"
radii="Pill"
onClick={zoomIn}
aria-label="Zoom In"
>
<Icon size="50" src={Icons.Plus} />
</IconButton>
<Chip
variant="Primary"
onClick={handleDownload}
radii="300"
before={<Icon size="50" src={Icons.Download} />}
>
<Text size="B300">Download</Text>
</Chip>
</Box>
</Header>
<Box direction="Column" grow="Yes" alignItems="Center" justifyContent="Center" gap="200">
{isLoading && <Spinner variant="Secondary" size="600" />}
{isError && (
<>
<Text>Failed to load PDF</Text>
<Button
variant="Critical"
fill="Soft"
size="300"
radii="300"
before={<Icon src={Icons.Warning} size="50" />}
onClick={loadPdfJS}
>
<Text size="B300">Retry</Text>
</Button>
</>
)}
{docState.status === AsyncStatus.Success && (
<Scroll
ref={scrollRef}
size="300"
direction="Both"
variant="Surface"
visibility="Hover"
>
<Box>
<div className={css.PdfViewerContent} ref={containerRef} />
</Box>
</Scroll>
)}
</Box>
{docState.status === AsyncStatus.Success && (
<Header as="footer" className={css.PdfViewerFooter} size="400">
<Chip
variant="Secondary"
radii="300"
before={<Icon size="50" src={Icons.ChevronLeft} />}
onClick={handlePrevPage}
aria-disabled={pageNo <= 1}
>
<Text size="B300">Previous</Text>
</Chip>
<Box grow="Yes" justifyContent="Center" alignItems="Center" gap="200">
<PopOut
open={openJump}
align="Center"
position="Top"
content={
<FocusTrap
focusTrapOptions={{
initialFocus: false,
onDeactivate: () => setOpenJump(false),
clickOutsideDeactivates: true,
}}
>
<Menu variant="Surface">
<Box
as="form"
onSubmit={handleJumpSubmit}
style={{ padding: config.space.S200 }}
direction="Column"
gap="200"
>
<Input
name="jumpInput"
size="300"
variant="Background"
defaultValue={pageNo}
min={1}
max={docState.data.numPages}
step={1}
outlined
type="number"
radii="300"
aria-label="Page Number"
/>
<Button type="submit" size="300" variant="Primary" radii="300">
<Text size="B300">Jump To Page</Text>
</Button>
</Box>
</Menu>
</FocusTrap>
}
>
{(anchorRef) => (
<Chip
onClick={() => setOpenJump(!openJump)}
ref={anchorRef}
variant="SurfaceVariant"
radii="300"
aria-pressed={openJump}
>
<Text size="B300">{`${pageNo}/${docState.data.numPages}`}</Text>
</Chip>
)}
</PopOut>
</Box>
<Chip
variant="Primary"
radii="300"
after={<Icon size="50" src={Icons.ChevronRight} />}
onClick={handleNextPage}
aria-disabled={pageNo >= docState.data.numPages}
>
<Text size="B300">Next</Text>
</Chip>
</Header>
)}
</Box>
);
}
);

View file

@ -0,0 +1 @@
export * from './PdfViewer';

View file

@ -54,7 +54,7 @@ export const useEditor = (): Editor => {
return editor; return editor;
}; };
export type EditorChangeHandler = ((value: Descendant[]) => void) | undefined; export type EditorChangeHandler = (value: Descendant[]) => void;
type CustomEditorProps = { type CustomEditorProps = {
top?: ReactNode; top?: ReactNode;
bottom?: ReactNode; bottom?: ReactNode;
@ -64,6 +64,7 @@ type CustomEditorProps = {
editor: Editor; editor: Editor;
placeholder?: string; placeholder?: string;
onKeyDown?: KeyboardEventHandler; onKeyDown?: KeyboardEventHandler;
onKeyUp?: KeyboardEventHandler;
onChange?: EditorChangeHandler; onChange?: EditorChangeHandler;
onPaste?: ClipboardEventHandler; onPaste?: ClipboardEventHandler;
}; };
@ -78,6 +79,7 @@ export const CustomEditor = forwardRef<HTMLDivElement, CustomEditorProps>(
editor, editor,
placeholder, placeholder,
onKeyDown, onKeyDown,
onKeyUp,
onChange, onChange,
onPaste, onPaste,
}, },
@ -141,6 +143,7 @@ export const CustomEditor = forwardRef<HTMLDivElement, CustomEditorProps>(
renderElement={renderElement} renderElement={renderElement}
renderLeaf={renderLeaf} renderLeaf={renderLeaf}
onKeyDown={handleKeydown} onKeyDown={handleKeydown}
onKeyUp={onKeyUp}
onPaste={onPaste} onPaste={onPaste}
/> />
</Scroll> </Scroll>

View file

@ -2,7 +2,7 @@ import { Scroll, Text } from 'folds';
import React from 'react'; import React from 'react';
import { RenderElementProps, RenderLeafProps, useFocused, useSelected } from 'slate-react'; import { RenderElementProps, RenderLeafProps, useFocused, useSelected } from 'slate-react';
import * as css from './Elements.css'; import * as css from '../../styles/CustomHtml.css';
import { EmoticonElement, LinkElement, MentionElement } from './slate'; import { EmoticonElement, LinkElement, MentionElement } from './slate';
import { useMatrixClient } from '../../hooks/useMatrixClient'; import { useMatrixClient } from '../../hooks/useMatrixClient';
@ -145,7 +145,13 @@ export function RenderElement({ attributes, element, children }: RenderElementPr
case BlockType.CodeBlock: case BlockType.CodeBlock:
return ( return (
<Text as="pre" className={css.CodeBlock} {...attributes}> <Text as="pre" className={css.CodeBlock} {...attributes}>
<Scroll direction="Horizontal" variant="Warning" size="300" visibility="Hover" hideTrack> <Scroll
direction="Horizontal"
variant="Secondary"
size="300"
visibility="Hover"
hideTrack
>
<div className={css.CodeBlockInternal}>{children}</div> <div className={css.CodeBlockInternal}>{children}</div>
</Scroll> </Scroll>
</Text> </Text>
@ -242,7 +248,7 @@ export function RenderLeaf({ attributes, leaf, children }: RenderLeafProps) {
); );
if (leaf.spoiler) if (leaf.spoiler)
child = ( child = (
<span className={css.Spoiler} {...attributes}> <span className={css.Spoiler()} {...attributes}>
<InlineChromiumBugfix /> <InlineChromiumBugfix />
{child} {child}
</span> </span>

View file

@ -122,8 +122,9 @@ export function RoomMentionAutocomplete({
return; return;
} }
const rId = autoCompleteRoomIds[0]; const rId = autoCompleteRoomIds[0];
const name = mx.getRoom(rId)?.name ?? rId; const r = mx.getRoom(rId);
handleAutocomplete(rId, name); const name = r?.name ?? rId;
handleAutocomplete(r?.getCanonicalAlias() ?? rId, name);
}); });
}); });
@ -147,7 +148,7 @@ export function RoomMentionAutocomplete({
onKeyDown={(evt: ReactKeyboardEvent<HTMLButtonElement>) => onKeyDown={(evt: ReactKeyboardEvent<HTMLButtonElement>) =>
onTabPress(evt, () => handleAutocomplete(rId, room.name)) onTabPress(evt, () => handleAutocomplete(rId, room.name))
} }
onClick={() => handleAutocomplete(rId, room.name)} onClick={() => handleAutocomplete(room.getCanonicalAlias() ?? rId, room.name)}
after={ after={
<Text size="T200" priority="300" truncate> <Text size="T200" priority="300" truncate>
{room.getCanonicalAlias() ?? ''} {room.getCanonicalAlias() ?? ''}

View file

@ -42,7 +42,7 @@ import { useMatrixClient } from '../../hooks/useMatrixClient';
import { useRecentEmoji } from '../../hooks/useRecentEmoji'; import { useRecentEmoji } from '../../hooks/useRecentEmoji';
import { ExtendedPackImage, ImagePack, PackUsage } from '../../plugins/custom-emoji'; import { ExtendedPackImage, ImagePack, PackUsage } from '../../plugins/custom-emoji';
import { isUserId } from '../../utils/matrix'; import { isUserId } from '../../utils/matrix';
import { editableActiveElement, inVisibleScrollArea, targetFromEvent } from '../../utils/dom'; import { editableActiveElement, isIntersectingScrollView, targetFromEvent } from '../../utils/dom';
import { useAsyncSearch, UseAsyncSearchOptions } from '../../hooks/useAsyncSearch'; import { useAsyncSearch, UseAsyncSearchOptions } from '../../hooks/useAsyncSearch';
import { useDebounce } from '../../hooks/useDebounce'; import { useDebounce } from '../../hooks/useDebounce';
import { useThrottle } from '../../hooks/useThrottle'; import { useThrottle } from '../../hooks/useThrottle';
@ -675,7 +675,7 @@ export function EmojiBoard({
const targetEl = contentScrollRef.current; const targetEl = contentScrollRef.current;
if (!targetEl) return; if (!targetEl) return;
const groupEls = [...targetEl.querySelectorAll('div[data-group-id]')] as HTMLElement[]; const groupEls = [...targetEl.querySelectorAll('div[data-group-id]')] as HTMLElement[];
const groupEl = groupEls.find((el) => inVisibleScrollArea(targetEl, el)); const groupEl = groupEls.find((el) => isIntersectingScrollView(targetEl, el));
const groupId = groupEl?.getAttribute('data-group-id') ?? undefined; const groupId = groupEl?.getAttribute('data-group-id') ?? undefined;
setActiveGroupId(groupId); setActiveGroupId(groupId);
}, [setActiveGroupId]); }, [setActiveGroupId]);

View file

@ -0,0 +1,21 @@
import { style } from '@vanilla-extract/css';
import { DefaultReset, config } from 'folds';
export const EventReaders = style([
DefaultReset,
{
height: '100%',
},
]);
export const Header = style({
paddingLeft: config.space.S400,
paddingRight: config.space.S300,
flexShrink: 0,
});
export const Content = style({
paddingLeft: config.space.S200,
paddingBottom: config.space.S400,
});

View file

@ -0,0 +1,110 @@
import React from 'react';
import classNames from 'classnames';
import {
Avatar,
AvatarFallback,
AvatarImage,
Box,
Header,
Icon,
IconButton,
Icons,
MenuItem,
Scroll,
Text,
as,
config,
} from 'folds';
import { Room, RoomMember } from 'matrix-js-sdk';
import { useRoomEventReaders } from '../../hooks/useRoomEventReaders';
import { getMemberDisplayName } from '../../utils/room';
import { getMxIdLocalPart } from '../../utils/matrix';
import * as css from './EventReaders.css';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import colorMXID from '../../../util/colorMXID';
import { openProfileViewer } from '../../../client/action/navigation';
export type EventReadersProps = {
room: Room;
eventId: string;
requestClose: () => void;
};
export const EventReaders = as<'div', EventReadersProps>(
({ className, room, eventId, requestClose, ...props }, ref) => {
const mx = useMatrixClient();
const latestEventReaders = useRoomEventReaders(room, eventId);
const followingMembers = latestEventReaders
.map((readerId) => room.getMember(readerId))
.filter((member) => member) as RoomMember[];
const getName = (member: RoomMember) =>
getMemberDisplayName(room, member.userId) ?? getMxIdLocalPart(member.userId) ?? member.userId;
return (
<Box
className={classNames(css.EventReaders, className)}
direction="Column"
{...props}
ref={ref}
>
<Header className={css.Header} variant="Surface" size="600">
<Box grow="Yes">
<Text size="H3">Seen by</Text>
</Box>
<IconButton size="300" onClick={requestClose}>
<Icon src={Icons.Cross} />
</IconButton>
</Header>
<Box grow="Yes">
<Scroll visibility="Hover" hideTrack size="300">
<Box className={css.Content} direction="Column">
{followingMembers.map((member) => {
const name = getName(member);
const avatarUrl = member.getAvatarUrl(
mx.baseUrl,
100,
100,
'crop',
undefined,
false
);
return (
<MenuItem
key={member.userId}
style={{ padding: `0 ${config.space.S200}` }}
radii="400"
onClick={() => {
requestClose();
openProfileViewer(member.userId, room.roomId);
}}
before={
<Avatar size="200">
{avatarUrl ? (
<AvatarImage src={avatarUrl} />
) : (
<AvatarFallback
style={{
background: colorMXID(member.userId),
color: 'white',
}}
>
<Text size="H6">{name[0]}</Text>
</AvatarFallback>
)}
</Avatar>
}
>
<Text size="T400" truncate>
{name}
</Text>
</MenuItem>
);
})}
</Box>
</Scroll>
</Box>
</Box>
);
}
);

View file

@ -0,0 +1 @@
export * from './EventReaders';

View file

@ -0,0 +1,40 @@
import { style } from '@vanilla-extract/css';
import { DefaultReset, color, config } from 'folds';
export const ImageViewer = style([
DefaultReset,
{
height: '100%',
},
]);
export const ImageViewerHeader = style([
DefaultReset,
{
paddingLeft: config.space.S200,
paddingRight: config.space.S200,
borderBottomWidth: config.borderWidth.B300,
flexShrink: 0,
gap: config.space.S200,
},
]);
export const ImageViewerContent = style([
DefaultReset,
{
backgroundColor: color.Background.Container,
color: color.Background.OnContainer,
overflow: 'hidden',
},
]);
export const ImageViewerImg = style([
DefaultReset,
{
objectFit: 'contain',
width: '100%',
height: '100%',
backgroundColor: color.Surface.Container,
transition: 'transform 100ms linear',
},
]);

View file

@ -0,0 +1,95 @@
/* eslint-disable jsx-a11y/no-noninteractive-element-interactions */
import React from 'react';
import FileSaver from 'file-saver';
import classNames from 'classnames';
import { Box, Chip, Header, Icon, IconButton, Icons, Text, as } from 'folds';
import * as css from './ImageViewer.css';
import { useZoom } from '../../hooks/useZoom';
import { usePan } from '../../hooks/usePan';
export type ImageViewerProps = {
alt: string;
src: string;
requestClose: () => void;
};
export const ImageViewer = as<'div', ImageViewerProps>(
({ className, alt, src, requestClose, ...props }, ref) => {
const { zoom, zoomIn, zoomOut, setZoom } = useZoom(0.2);
const { pan, cursor, onMouseDown } = usePan(zoom !== 1);
const handleDownload = () => {
FileSaver.saveAs(src, alt);
};
return (
<Box
className={classNames(css.ImageViewer, className)}
direction="Column"
{...props}
ref={ref}
>
<Header className={css.ImageViewerHeader} size="400">
<Box grow="Yes" alignItems="Center" gap="200">
<IconButton size="300" radii="300" onClick={requestClose}>
<Icon size="50" src={Icons.ArrowLeft} />
</IconButton>
<Text size="T300" truncate>
{alt}
</Text>
</Box>
<Box shrink="No" alignItems="Center" gap="200">
<IconButton
variant={zoom < 1 ? 'Success' : 'SurfaceVariant'}
outlined={zoom < 1}
size="300"
radii="Pill"
onClick={zoomOut}
aria-label="Zoom Out"
>
<Icon size="50" src={Icons.Minus} />
</IconButton>
<Chip variant="SurfaceVariant" radii="Pill" onClick={() => setZoom(zoom === 1 ? 2 : 1)}>
<Text size="B300">{Math.round(zoom * 100)}%</Text>
</Chip>
<IconButton
variant={zoom > 1 ? 'Success' : 'SurfaceVariant'}
outlined={zoom > 1}
size="300"
radii="Pill"
onClick={zoomIn}
aria-label="Zoom In"
>
<Icon size="50" src={Icons.Plus} />
</IconButton>
<Chip
variant="Primary"
onClick={handleDownload}
radii="300"
before={<Icon size="50" src={Icons.Download} />}
>
<Text size="B300">Download</Text>
</Chip>
</Box>
</Header>
<Box
grow="Yes"
className={css.ImageViewerContent}
justifyContent="Center"
alignItems="Center"
>
<img
className={css.ImageViewerImg}
style={{
cursor,
transform: `scale(${zoom}) translate(${pan.translateX}px, ${pan.translateY}px)`,
}}
src={src}
alt={alt}
onMouseDown={onMouseDown}
/>
</Box>
</Box>
);
}
);

View file

@ -0,0 +1 @@
export * from './ImageViewer';

View file

@ -0,0 +1,9 @@
import React, { ImgHTMLAttributes, forwardRef } from 'react';
import classNames from 'classnames';
import * as css from './media.css';
export const Image = forwardRef<HTMLImageElement, ImgHTMLAttributes<HTMLImageElement>>(
({ className, alt, ...props }, ref) => (
<img className={classNames(css.Image, className)} alt={alt} {...props} ref={ref} />
)
);

View file

@ -0,0 +1,27 @@
import React, { ReactNode } from 'react';
import { Box, as } from 'folds';
export type MediaControlProps = {
before?: ReactNode;
after?: ReactNode;
leftControl?: ReactNode;
rightControl?: ReactNode;
};
export const MediaControl = as<'div', MediaControlProps>(
({ before, after, leftControl, rightControl, children, ...props }, ref) => (
<Box grow="Yes" direction="Column" gap="300" {...props} ref={ref}>
{before && <Box direction="Column">{before}</Box>}
<Box alignItems="Center" gap="200">
<Box alignItems="Center" grow="Yes" gap="Inherit">
{leftControl}
</Box>
<Box justifyItems="End" alignItems="Center" gap="Inherit">
{rightControl}
</Box>
</Box>
{after && <Box direction="Column">{after}</Box>}
{children}
</Box>
)
);

View file

@ -0,0 +1,10 @@
import React, { VideoHTMLAttributes, forwardRef } from 'react';
import classNames from 'classnames';
import * as css from './media.css';
export const Video = forwardRef<HTMLVideoElement, VideoHTMLAttributes<HTMLVideoElement>>(
({ className, ...props }, ref) => (
// eslint-disable-next-line jsx-a11y/media-has-caption
<video className={classNames(css.Image, className)} {...props} ref={ref} />
)
);

View file

@ -0,0 +1,3 @@
export * from './Image';
export * from './Video';
export * from './MediaControls';

View file

@ -0,0 +1,20 @@
import { style } from '@vanilla-extract/css';
import { DefaultReset } from 'folds';
export const Image = style([
DefaultReset,
{
objectFit: 'cover',
width: '100%',
height: '100%',
},
]);
export const Video = style([
DefaultReset,
{
objectFit: 'cover',
width: '100%',
height: '100%',
},
]);

View file

@ -0,0 +1,66 @@
import { Box, Icon, Icons, Text, as, color, config } from 'folds';
import React from 'react';
const warningStyle = { color: color.Warning.Main, opacity: config.opacity.P300 };
const criticalStyle = { color: color.Critical.Main, opacity: config.opacity.P300 };
export const MessageDeletedContent = as<'div', { children?: never; reason?: string }>(
({ reason, ...props }, ref) => (
<Box as="span" alignItems="Center" gap="100" style={warningStyle} {...props} ref={ref}>
<Icon size="50" src={Icons.Delete} />
{reason ? (
<i>This message has been deleted. {reason}</i>
) : (
<i>This message has been deleted</i>
)}
</Box>
)
);
export const MessageUnsupportedContent = as<'div', { children?: never }>(({ ...props }, ref) => (
<Box as="span" alignItems="Center" gap="100" style={criticalStyle} {...props} ref={ref}>
<Icon size="50" src={Icons.Warning} />
<i>Unsupported message</i>
</Box>
));
export const MessageFailedContent = as<'div', { children?: never }>(({ ...props }, ref) => (
<Box as="span" alignItems="Center" gap="100" style={criticalStyle} {...props} ref={ref}>
<Icon size="50" src={Icons.Warning} />
<i>Failed to load message</i>
</Box>
));
export const MessageBadEncryptedContent = as<'div', { children?: never }>(({ ...props }, ref) => (
<Box as="span" alignItems="Center" gap="100" style={warningStyle} {...props} ref={ref}>
<Icon size="50" src={Icons.Lock} />
<i>Unable to decrypt message</i>
</Box>
));
export const MessageNotDecryptedContent = as<'div', { children?: never }>(({ ...props }, ref) => (
<Box as="span" alignItems="Center" gap="100" style={warningStyle} {...props} ref={ref}>
<Icon size="50" src={Icons.Lock} />
<i>This message is not decrypted yet</i>
</Box>
));
export const MessageBrokenContent = as<'div', { children?: never }>(({ ...props }, ref) => (
<Box as="span" alignItems="Center" gap="100" style={criticalStyle} {...props} ref={ref}>
<Icon size="50" src={Icons.Warning} />
<i>Broken message</i>
</Box>
));
export const MessageEmptyContent = as<'div', { children?: never }>(({ ...props }, ref) => (
<Box as="span" alignItems="Center" gap="100" style={criticalStyle} {...props} ref={ref}>
<Icon size="50" src={Icons.Warning} />
<i>Empty message</i>
</Box>
));
export const MessageEditedContent = as<'span', { children?: never }>(({ ...props }, ref) => (
<Text as="span" size="T200" priority="300" {...props} ref={ref}>
{' (edited)'}
</Text>
));

View file

@ -0,0 +1,75 @@
import { createVar, style } from '@vanilla-extract/css';
import { DefaultReset, FocusOutline, color, config, toRem } from 'folds';
const Container = createVar();
const ContainerHover = createVar();
const ContainerActive = createVar();
const ContainerLine = createVar();
const OnContainer = createVar();
export const Reaction = style([
FocusOutline,
{
vars: {
[Container]: color.SurfaceVariant.Container,
[ContainerHover]: color.SurfaceVariant.ContainerHover,
[ContainerActive]: color.SurfaceVariant.ContainerActive,
[ContainerLine]: color.SurfaceVariant.ContainerLine,
[OnContainer]: color.SurfaceVariant.OnContainer,
},
padding: `${toRem(2)} ${config.space.S200} ${toRem(2)} ${config.space.S100}`,
backgroundColor: Container,
border: `${config.borderWidth.B300} solid ${ContainerLine}`,
borderRadius: config.radii.R300,
selectors: {
'button&': {
cursor: 'pointer',
},
'&[aria-pressed=true]': {
vars: {
[Container]: color.Primary.Container,
[ContainerHover]: color.Primary.ContainerHover,
[ContainerActive]: color.Primary.ContainerActive,
[ContainerLine]: color.Primary.ContainerLine,
[OnContainer]: color.Primary.OnContainer,
},
backgroundColor: Container,
},
'&[aria-selected=true]': {
borderColor: color.Secondary.Main,
borderWidth: config.borderWidth.B400,
},
'&:hover, &:focus-visible': {
backgroundColor: ContainerHover,
},
'&:active': {
backgroundColor: ContainerActive,
},
'&[aria-disabled=true], &:disabled': {
cursor: 'not-allowed',
},
},
},
]);
export const ReactionText = style([
DefaultReset,
{
minWidth: 0,
maxWidth: toRem(150),
display: 'inline-flex',
alignItems: 'center',
lineHeight: toRem(20),
},
]);
export const ReactionImg = style([
DefaultReset,
{
height: '1em',
minWidth: 0,
maxWidth: toRem(150),
objectFit: 'contain',
},
]);

View file

@ -0,0 +1,113 @@
import React from 'react';
import { Box, Text, as } from 'folds';
import classNames from 'classnames';
import { MatrixClient, MatrixEvent, Room } from 'matrix-js-sdk';
import * as css from './Reaction.css';
import { getHexcodeForEmoji, getShortcodeFor } from '../../plugins/emoji';
import { getMemberDisplayName } from '../../utils/room';
import { eventWithShortcode, getMxIdLocalPart } from '../../utils/matrix';
export const Reaction = as<
'button',
{
mx: MatrixClient;
count: number;
reaction: string;
}
>(({ className, mx, count, reaction, ...props }, ref) => (
<Box
as="button"
className={classNames(css.Reaction, className)}
alignItems="Center"
shrink="No"
gap="200"
{...props}
ref={ref}
>
<Text className={css.ReactionText} as="span" size="T400">
{reaction.startsWith('mxc://') ? (
<img
className={css.ReactionImg}
src={mx.mxcUrlToHttp(reaction) ?? reaction}
alt={reaction}
/>
) : (
<Text as="span" size="Inherit" truncate>
{reaction}
</Text>
)}
</Text>
<Text as="span" size="T300">
{count}
</Text>
</Box>
));
type ReactionTooltipMsgProps = {
room: Room;
reaction: string;
events: MatrixEvent[];
};
export function ReactionTooltipMsg({ room, reaction, events }: ReactionTooltipMsgProps) {
const shortCodeEvt = events.find(eventWithShortcode);
const shortcode =
shortCodeEvt?.getContent().shortcode ??
getShortcodeFor(getHexcodeForEmoji(reaction)) ??
reaction;
const names = events.map(
(ev: MatrixEvent) =>
getMemberDisplayName(room, ev.getSender() ?? 'Unknown') ??
getMxIdLocalPart(ev.getSender() ?? 'Unknown') ??
'Unknown'
);
return (
<>
{names.length === 1 && <b>{names[0]}</b>}
{names.length === 2 && (
<>
<b>{names[0]}</b>
<Text as="span" size="Inherit" priority="300">
{' and '}
</Text>
<b>{names[1]}</b>
</>
)}
{names.length === 3 && (
<>
<b>{names[0]}</b>
<Text as="span" size="Inherit" priority="300">
{', '}
</Text>
<b>{names[1]}</b>
<Text as="span" size="Inherit" priority="300">
{' and '}
</Text>
<b>{names[2]}</b>
</>
)}
{names.length > 3 && (
<>
<b>{names[0]}</b>
<Text as="span" size="Inherit" priority="300">
{', '}
</Text>
<b>{names[1]}</b>
<Text as="span" size="Inherit" priority="300">
{', '}
</Text>
<b>{names[2]}</b>
<Text as="span" size="Inherit" priority="300">
{' and '}
</Text>
<b>{names.length - 3} others</b>
</>
)}
<Text as="span" size="Inherit" priority="300">
{' reacted with '}
</Text>
:<b>{shortcode}</b>:
</>
);
}

View file

@ -0,0 +1,25 @@
import { style } from '@vanilla-extract/css';
import { config, toRem } from 'folds';
export const Reply = style({
padding: `0 ${config.space.S100}`,
marginBottom: toRem(1),
cursor: 'pointer',
minWidth: 0,
maxWidth: '100%',
minHeight: config.lineHeight.T300,
});
export const ReplyContent = style({
opacity: config.opacity.P300,
selectors: {
[`${Reply}:hover &`]: {
opacity: config.opacity.P500,
},
},
});
export const ReplyContentText = style({
paddingRight: config.space.S100,
});

View file

@ -0,0 +1,100 @@
import { Box, Icon, Icons, Text, as, color, toRem } from 'folds';
import { EventTimelineSet, MatrixClient, MatrixEvent, Room } from 'matrix-js-sdk';
import { CryptoBackend } from 'matrix-js-sdk/lib/common-crypto/CryptoBackend';
import React, { useEffect, useState } from 'react';
import to from 'await-to-js';
import classNames from 'classnames';
import colorMXID from '../../../util/colorMXID';
import { getMemberDisplayName } from '../../utils/room';
import { getMxIdLocalPart, trimReplyFromBody } from '../../utils/matrix';
import { LinePlaceholder } from './placeholder';
import { randomNumberBetween } from '../../utils/common';
import * as css from './Reply.css';
import {
MessageBadEncryptedContent,
MessageDeletedContent,
MessageFailedContent,
} from './MessageContentFallback';
type ReplyProps = {
mx: MatrixClient;
room: Room;
timelineSet: EventTimelineSet;
eventId: string;
};
export const Reply = as<'div', ReplyProps>(
({ className, mx, room, timelineSet, eventId, ...props }, ref) => {
const [replyEvent, setReplyEvent] = useState<MatrixEvent | null | undefined>(
timelineSet.findEventById(eventId)
);
const { body } = replyEvent?.getContent() ?? {};
const sender = replyEvent?.getSender();
const fallbackBody = replyEvent?.isRedacted() ? (
<MessageDeletedContent />
) : (
<MessageFailedContent />
);
useEffect(() => {
let disposed = false;
const loadEvent = async () => {
const [err, evt] = await to(mx.fetchRoomEvent(room.roomId, eventId));
const mEvent = new MatrixEvent(evt);
if (disposed) return;
if (err) {
setReplyEvent(null);
return;
}
if (mEvent.isEncrypted() && mx.getCrypto()) {
await to(mEvent.attemptDecryption(mx.getCrypto() as CryptoBackend));
}
setReplyEvent(mEvent);
};
if (replyEvent === undefined) loadEvent();
return () => {
disposed = true;
};
}, [replyEvent, mx, room, eventId]);
return (
<Box
className={classNames(css.Reply, className)}
alignItems="Center"
gap="100"
{...props}
ref={ref}
>
<Box style={{ color: colorMXID(sender ?? eventId) }} alignItems="Center" shrink="No">
<Icon src={Icons.ReplyArrow} size="50" />
{sender && (
<Text size="T300" truncate>
{getMemberDisplayName(room, sender) ?? getMxIdLocalPart(sender)}
</Text>
)}
</Box>
<Box grow="Yes" className={css.ReplyContent}>
{replyEvent !== undefined ? (
<Text className={css.ReplyContentText} size="T300" truncate>
{replyEvent?.getContent().msgtype === 'm.bad.encrypted' ? (
<MessageBadEncryptedContent />
) : (
(body && trimReplyFromBody(body)) ?? fallbackBody
)}
</Text>
) : (
<LinePlaceholder
style={{
backgroundColor: color.SurfaceVariant.ContainerActive,
maxWidth: toRem(randomNumberBetween(40, 400)),
width: '100%',
}}
/>
)}
</Box>
</Box>
);
}
);

View file

@ -0,0 +1,27 @@
import React from 'react';
import { Text, as } from 'folds';
import { timeDayMonYear, timeHourMinute, today, yesterday } from '../../utils/time';
export type TimeProps = {
compact?: boolean;
ts: number;
};
export const Time = as<'span', TimeProps>(({ compact, ts, ...props }, ref) => {
let time = '';
if (compact) {
time = timeHourMinute(ts);
} else if (today(ts)) {
time = timeHourMinute(ts);
} else if (yesterday(ts)) {
time = `Yesterday ${timeHourMinute(ts)}`;
} else {
time = `${timeDayMonYear(ts)} ${timeHourMinute(ts)}`;
}
return (
<Text as="time" style={{ flexShrink: 0 }} size="T200" priority="300" {...props} ref={ref}>
{time}
</Text>
);
});

View file

@ -0,0 +1,42 @@
import { style } from '@vanilla-extract/css';
import { RecipeVariants, recipe } from '@vanilla-extract/recipes';
import { DefaultReset, color, config, toRem } from 'folds';
export const Attachment = recipe({
base: {
backgroundColor: color.SurfaceVariant.Container,
color: color.SurfaceVariant.OnContainer,
borderRadius: config.radii.R400,
overflow: 'hidden',
maxWidth: '100%',
width: toRem(400),
},
variants: {
outlined: {
true: {
boxShadow: `inset 0 0 0 ${config.borderWidth.B300} ${color.SurfaceVariant.ContainerLine}`,
},
},
},
});
export type AttachmentVariants = RecipeVariants<typeof Attachment>;
export const AttachmentHeader = style({
padding: config.space.S300,
});
export const AttachmentBox = style([
DefaultReset,
{
maxWidth: '100%',
maxHeight: toRem(600),
width: toRem(400),
overflow: 'hidden',
},
]);
export const AttachmentContent = style({
padding: config.space.S300,
paddingTop: 0,
});

View file

@ -0,0 +1,44 @@
import React from 'react';
import { Box, as } from 'folds';
import classNames from 'classnames';
import * as css from './Attachment.css';
export const Attachment = as<'div', css.AttachmentVariants>(
({ className, outlined, ...props }, ref) => (
<Box
display="InlineFlex"
direction="Column"
className={classNames(css.Attachment({ outlined }), className)}
{...props}
ref={ref}
/>
)
);
export const AttachmentHeader = as<'div'>(({ className, ...props }, ref) => (
<Box
shrink="No"
gap="200"
className={classNames(css.AttachmentHeader, className)}
{...props}
ref={ref}
/>
));
export const AttachmentBox = as<'div'>(({ className, ...props }, ref) => (
<Box
direction="Column"
className={classNames(css.AttachmentBox, className)}
{...props}
ref={ref}
/>
));
export const AttachmentContent = as<'div'>(({ className, ...props }, ref) => (
<Box
direction="Column"
className={classNames(css.AttachmentContent, className)}
{...props}
ref={ref}
/>
));

View file

@ -0,0 +1 @@
export * from './Attachment';

View file

@ -0,0 +1,7 @@
export * from './layout';
export * from './placeholder';
export * from './Reaction';
export * from './attachment';
export * from './Reply';
export * from './MessageContentFallback';
export * from './Time';

View file

@ -0,0 +1,25 @@
import React from 'react';
import { as } from 'folds';
import classNames from 'classnames';
import * as css from './layout.css';
export const MessageBase = as<'div', css.MessageBaseVariants>(
({ className, highlight, selected, collapse, autoCollapse, space, ...props }, ref) => (
<div
className={classNames(
css.MessageBase({ highlight, selected, collapse, autoCollapse, space }),
className
)}
{...props}
ref={ref}
/>
)
);
export const AvatarBase = as<'span'>(({ className, ...props }, ref) => (
<span className={classNames(css.AvatarBase, className)} {...props} ref={ref} />
));
export const Username = as<'span'>(({ as: AsUsername = 'span', className, ...props }, ref) => (
<AsUsername className={classNames(css.Username, className)} {...props} ref={ref} />
));

View file

@ -0,0 +1,18 @@
import React, { ReactNode } from 'react';
import { Box, as } from 'folds';
import * as css from './layout.css';
type BubbleLayoutProps = {
before?: ReactNode;
};
export const BubbleLayout = as<'div', BubbleLayoutProps>(({ before, children, ...props }, ref) => (
<Box gap="300" {...props} ref={ref}>
<Box className={css.BubbleBefore} shrink="No">
{before}
</Box>
<Box className={css.BubbleContent} direction="Column">
{children}
</Box>
</Box>
));

View file

@ -0,0 +1,18 @@
import React, { ReactNode } from 'react';
import { Box, as } from 'folds';
import * as css from './layout.css';
type CompactLayoutProps = {
before?: ReactNode;
};
export const CompactLayout = as<'div', CompactLayoutProps>(
({ before, children, ...props }, ref) => (
<Box gap="200" {...props} ref={ref}>
<Box className={css.CompactHeader} gap="200" shrink="No">
{before}
</Box>
{children}
</Box>
)
);

View file

@ -0,0 +1,18 @@
import React, { ReactNode } from 'react';
import { Box, as } from 'folds';
import * as css from './layout.css';
type ModernLayoutProps = {
before?: ReactNode;
};
export const ModernLayout = as<'div', ModernLayoutProps>(({ before, children, ...props }, ref) => (
<Box gap="300" {...props} ref={ref}>
<Box className={css.ModernBefore} shrink="No">
{before}
</Box>
<Box grow="Yes" direction="Column">
{children}
</Box>
</Box>
));

View file

@ -0,0 +1,4 @@
export * from './Modern';
export * from './Compact';
export * from './Bubble';
export * from './Base';

View file

@ -0,0 +1,155 @@
import { createVar, keyframes, style, styleVariants } from '@vanilla-extract/css';
import { recipe, RecipeVariants } from '@vanilla-extract/recipes';
import { DefaultReset, color, config, toRem } from 'folds';
export const StickySection = style({
position: 'sticky',
top: config.space.S100,
});
const SpacingVar = createVar();
const SpacingVariant = styleVariants({
'0': {
vars: {
[SpacingVar]: config.space.S0,
},
},
'100': {
vars: {
[SpacingVar]: config.space.S100,
},
},
'200': {
vars: {
[SpacingVar]: config.space.S200,
},
},
'300': {
vars: {
[SpacingVar]: config.space.S300,
},
},
'400': {
vars: {
[SpacingVar]: config.space.S400,
},
},
'500': {
vars: {
[SpacingVar]: config.space.S500,
},
},
});
const highlightAnime = keyframes({
'0%': {
backgroundColor: color.Primary.Container,
},
'25%': {
backgroundColor: color.Primary.ContainerActive,
},
'50%': {
backgroundColor: color.Primary.Container,
},
'75%': {
backgroundColor: color.Primary.ContainerActive,
},
'100%': {
backgroundColor: color.Primary.Container,
},
});
const HighlightVariant = styleVariants({
true: {
animation: `${highlightAnime} 2000ms ease-in-out`,
},
});
const SelectedVariant = styleVariants({
true: {
backgroundColor: color.Surface.ContainerActive,
},
});
const AutoCollapse = style({
selectors: {
[`&+&`]: {
marginTop: 0,
},
},
});
export const MessageBase = recipe({
base: [
DefaultReset,
{
marginTop: SpacingVar,
padding: `${config.space.S100} ${config.space.S200} ${config.space.S100} ${config.space.S400}`,
borderRadius: `0 ${config.radii.R400} ${config.radii.R400} 0`,
},
],
variants: {
space: SpacingVariant,
collapse: {
true: {
marginTop: 0,
},
},
autoCollapse: {
true: AutoCollapse,
},
highlight: HighlightVariant,
selected: SelectedVariant,
},
defaultVariants: {
space: '400',
},
});
export type MessageBaseVariants = RecipeVariants<typeof MessageBase>;
export const CompactHeader = style([
DefaultReset,
StickySection,
{
maxWidth: toRem(170),
width: '100%',
},
]);
export const AvatarBase = style({
paddingTop: toRem(4),
cursor: 'pointer',
transition: 'transform 200ms cubic-bezier(0, 0.8, 0.67, 0.97)',
selectors: {
'&:hover': {
transform: `translateY(${toRem(-4)})`,
},
},
});
export const ModernBefore = style({
minWidth: toRem(36),
});
export const BubbleBefore = style([ModernBefore]);
export const BubbleContent = style({
maxWidth: toRem(800),
padding: config.space.S200,
backgroundColor: color.SurfaceVariant.Container,
color: color.SurfaceVariant.OnContainer,
borderRadius: config.radii.R400,
});
export const Username = style({
cursor: 'pointer',
overflow: 'hidden',
whiteSpace: 'nowrap',
textOverflow: 'ellipsis',
selectors: {
'&:hover, &:focus-visible': {
textDecoration: 'underline',
},
},
});

View file

@ -0,0 +1,22 @@
import React from 'react';
import { as, toRem } from 'folds';
import { randomNumberBetween } from '../../../utils/common';
import { LinePlaceholder } from './LinePlaceholder';
import { CompactLayout, MessageBase } from '../layout';
export const CompactPlaceholder = as<'div'>(({ ...props }, ref) => (
<MessageBase>
<CompactLayout
{...props}
ref={ref}
before={
<>
<LinePlaceholder style={{ maxWidth: toRem(50) }} />
<LinePlaceholder style={{ maxWidth: toRem(randomNumberBetween(40, 100)) }} />
</>
}
>
<LinePlaceholder style={{ maxWidth: toRem(randomNumberBetween(120, 500)) }} />
</CompactLayout>
</MessageBase>
));

View file

@ -0,0 +1,25 @@
import React, { CSSProperties } from 'react';
import { Avatar, Box, as, color, toRem } from 'folds';
import { randomNumberBetween } from '../../../utils/common';
import { LinePlaceholder } from './LinePlaceholder';
import { MessageBase, ModernLayout } from '../layout';
const contentMargin: CSSProperties = { marginTop: toRem(3) };
const avatarBg: CSSProperties = { backgroundColor: color.SurfaceVariant.Container };
export const DefaultPlaceholder = as<'div'>(({ ...props }, ref) => (
<MessageBase>
<ModernLayout {...props} ref={ref} before={<Avatar style={avatarBg} size="300" />}>
<Box style={contentMargin} grow="Yes" direction="Column" gap="200">
<Box grow="Yes" gap="200" alignItems="Center" justifyContent="SpaceBetween">
<LinePlaceholder style={{ maxWidth: toRem(randomNumberBetween(40, 100)) }} />
<LinePlaceholder style={{ maxWidth: toRem(50) }} />
</Box>
<Box grow="Yes" gap="200" wrap="Wrap">
<LinePlaceholder style={{ maxWidth: toRem(randomNumberBetween(80, 200)) }} />
<LinePlaceholder style={{ maxWidth: toRem(randomNumberBetween(80, 200)) }} />
</Box>
</Box>
</ModernLayout>
</MessageBase>
));

View file

@ -0,0 +1,12 @@
import { style } from '@vanilla-extract/css';
import { DefaultReset, color, config, toRem } from 'folds';
export const LinePlaceholder = style([
DefaultReset,
{
width: '100%',
height: toRem(16),
borderRadius: config.radii.R300,
backgroundColor: color.SurfaceVariant.Container,
},
]);

View file

@ -0,0 +1,8 @@
import React from 'react';
import { Box, as } from 'folds';
import classNames from 'classnames';
import * as css from './LinePlaceholder.css';
export const LinePlaceholder = as<'div'>(({ className, ...props }, ref) => (
<Box className={classNames(css.LinePlaceholder, className)} shrink="No" {...props} ref={ref} />
));

View file

@ -0,0 +1,3 @@
export * from './LinePlaceholder';
export * from './CompactPlaceholder';
export * from './DefaultPlaceholder';

View file

@ -0,0 +1,114 @@
import React, { useCallback } from 'react';
import { Avatar, AvatarFallback, AvatarImage, Box, Button, Spinner, Text, as, color } from 'folds';
import { Room } from 'matrix-js-sdk';
import { openInviteUser, selectRoom } from '../../../client/action/navigation';
import { useStateEvent } from '../../hooks/useStateEvent';
import { IRoomCreateContent, Membership, StateEvent } from '../../../types/matrix/room';
import { getMemberDisplayName, getStateEvent } from '../../utils/room';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import { getMxIdLocalPart } from '../../utils/matrix';
import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback';
import { timeDayMonthYear, timeHourMinute } from '../../utils/time';
export type RoomIntroProps = {
room: Room;
};
export const RoomIntro = as<'div', RoomIntroProps>(({ room, ...props }, ref) => {
const mx = useMatrixClient();
const createEvent = getStateEvent(room, StateEvent.RoomCreate);
const avatarEvent = useStateEvent(room, StateEvent.RoomAvatar);
const nameEvent = useStateEvent(room, StateEvent.RoomName);
const topicEvent = useStateEvent(room, StateEvent.RoomTopic);
const createContent = createEvent?.getContent<IRoomCreateContent>();
const ts = createEvent?.getTs();
const creatorId = createEvent?.getSender();
const creatorName =
creatorId && (getMemberDisplayName(room, creatorId) ?? getMxIdLocalPart(creatorId));
const prevRoomId = createContent?.predecessor?.room_id;
const avatarMxc = (avatarEvent?.getContent().url as string) || undefined;
const avatarHttpUrl = avatarMxc ? mx.mxcUrlToHttp(avatarMxc) : undefined;
const name = (nameEvent?.getContent().name || room.name) as string;
const topic = (topicEvent?.getContent().topic as string) || undefined;
const [prevRoomState, joinPrevRoom] = useAsyncCallback(
useCallback(async (roomId: string) => mx.joinRoom(roomId), [mx])
);
return (
<Box direction="Column" grow="Yes" gap="500" {...props} ref={ref}>
<Box>
<Avatar size="500">
{avatarHttpUrl ? (
<AvatarImage src={avatarHttpUrl} alt={name} />
) : (
<AvatarFallback
style={{
backgroundColor: color.SurfaceVariant.Container,
color: color.SurfaceVariant.OnContainer,
}}
>
<Text size="H2">{name[0]}</Text>
</AvatarFallback>
)}
</Avatar>
</Box>
<Box direction="Column" gap="300">
<Box direction="Column" gap="100">
<Text size="H3" priority="500">
{name}
</Text>
<Text size="T400" priority="400">
{typeof topic === 'string' ? topic : 'This is the beginning of conversation.'}
</Text>
{creatorName && ts && (
<Text size="T200" priority="300">
{'Created by '}
<b>@{creatorName}</b>
{` on ${timeDayMonthYear(ts)} ${timeHourMinute(ts)}`}
</Text>
)}
</Box>
<Box gap="200" wrap="Wrap">
<Button
onClick={() => openInviteUser(room.roomId)}
variant="Secondary"
size="300"
radii="300"
>
<Text size="B300">Invite Member</Text>
</Button>
{typeof prevRoomId === 'string' &&
(mx.getRoom(prevRoomId)?.getMyMembership() === Membership.Join ? (
<Button
onClick={() => selectRoom(prevRoomId)}
variant="Success"
size="300"
fill="Soft"
radii="300"
>
<Text size="B300">Open Old Room</Text>
</Button>
) : (
<Button
onClick={() => joinPrevRoom(prevRoomId)}
variant="Secondary"
size="300"
fill="Soft"
radii="300"
disabled={prevRoomState.status === AsyncStatus.Loading}
after={
prevRoomState.status === AsyncStatus.Loading ? (
<Spinner size="50" variant="Secondary" fill="Soft" />
) : undefined
}
>
<Text size="B300">Join Old Room</Text>
</Button>
))}
</Box>
</Box>
</Box>
);
});

View file

@ -0,0 +1 @@
export * from './RoomIntro';

View file

@ -0,0 +1,37 @@
import { style } from '@vanilla-extract/css';
import { DefaultReset, color, config } from 'folds';
export const TextViewer = style([
DefaultReset,
{
height: '100%',
},
]);
export const TextViewerHeader = style([
DefaultReset,
{
paddingLeft: config.space.S200,
paddingRight: config.space.S200,
borderBottomWidth: config.borderWidth.B300,
flexShrink: 0,
gap: config.space.S200,
},
]);
export const TextViewerContent = style([
DefaultReset,
{
backgroundColor: color.Background.Container,
color: color.Background.OnContainer,
overflow: 'hidden',
},
]);
export const TextViewerPre = style([
DefaultReset,
{
padding: config.space.S600,
whiteSpace: 'pre-wrap',
},
]);

View file

@ -0,0 +1,69 @@
/* eslint-disable jsx-a11y/no-noninteractive-element-interactions */
import React, { Suspense, lazy } from 'react';
import classNames from 'classnames';
import { Box, Chip, Header, Icon, IconButton, Icons, Scroll, Text, as } from 'folds';
import { ErrorBoundary } from 'react-error-boundary';
import * as css from './TextViewer.css';
import { mimeTypeToExt } from '../../utils/mimeTypes';
import { copyToClipboard } from '../../utils/dom';
const ReactPrism = lazy(() => import('../../plugins/react-prism/ReactPrism'));
export type TextViewerProps = {
name: string;
text: string;
mimeType: string;
requestClose: () => void;
};
export const TextViewer = as<'div', TextViewerProps>(
({ className, name, text, mimeType, requestClose, ...props }, ref) => {
const handleCopy = () => {
copyToClipboard(text);
};
return (
<Box
className={classNames(css.TextViewer, className)}
direction="Column"
{...props}
ref={ref}
>
<Header className={css.TextViewerHeader} size="400">
<Box grow="Yes" alignItems="Center" gap="200">
<IconButton size="300" radii="300" onClick={requestClose}>
<Icon size="50" src={Icons.ArrowLeft} />
</IconButton>
<Text size="T300" truncate>
{name}
</Text>
</Box>
<Box shrink="No" alignItems="Center" gap="200">
<Chip variant="Primary" radii="300" onClick={handleCopy}>
<Text size="B300">Copy All</Text>
</Chip>
</Box>
</Header>
<Box
grow="Yes"
className={css.TextViewerContent}
justifyContent="Center"
alignItems="Center"
>
<Scroll hideTrack variant="Background" visibility="Hover">
<Text
as="pre"
className={classNames(css.TextViewerPre, `language-${mimeTypeToExt(mimeType)}`)}
>
<ErrorBoundary fallback={<code>{text}</code>}>
<Suspense fallback={<code>{text}</code>}>
<ReactPrism>{(codeRef) => <code ref={codeRef}>{text}</code>}</ReactPrism>
</Suspense>
</ErrorBoundary>
</Text>
</Scroll>
</Box>
</Box>
);
}
);

View file

@ -0,0 +1 @@
export * from './TextViewer';

View file

@ -0,0 +1,49 @@
import { keyframes } from '@vanilla-extract/css';
import { recipe } from '@vanilla-extract/recipes';
import { DefaultReset, toRem } from 'folds';
const TypingDotAnime = keyframes({
to: {
opacity: '0.4',
transform: 'translateY(-15%)',
},
});
export const TypingDot = recipe({
base: [
DefaultReset,
{
display: 'inline-block',
backgroundColor: 'currentColor',
borderRadius: '50%',
transform: 'translateY(15%)',
animation: `${TypingDotAnime} 0.6s infinite alternate`,
},
],
variants: {
size: {
'300': {
width: toRem(4),
height: toRem(4),
},
'400': {
width: toRem(8),
height: toRem(8),
},
},
index: {
'0': {
animationDelay: '0s',
},
'1': {
animationDelay: '0.2s',
},
'2': {
animationDelay: '0.4s',
},
},
},
defaultVariants: {
size: '400',
},
});

View file

@ -0,0 +1,21 @@
import React from 'react';
import { Box, as, toRem } from 'folds';
import * as css from './TypingIndicator.css';
export type TypingIndicatorProps = {
size?: '300' | '400';
};
export const TypingIndicator = as<'div', TypingIndicatorProps>(({ size, style, ...props }, ref) => (
<Box
as="span"
alignItems="Center"
style={{ gap: toRem(size === '300' ? 1 : 2), ...style }}
{...props}
ref={ref}
>
<span className={css.TypingDot({ size, index: '0' })} />
<span className={css.TypingDot({ size, index: '1' })} />
<span className={css.TypingDot({ size, index: '2' })} />
</Box>
));

View file

@ -0,0 +1 @@
export * from './TypingIndicator';

View file

@ -0,0 +1,6 @@
export * from './useMediaPlay';
export * from './useMediaPlayTimeCallback';
export * from './useMediaPlaybackRate';
export * from './useMediaSeek';
export * from './useMediaVolume';
export * from './useMediaLoading';

View file

@ -0,0 +1,51 @@
import { useEffect, useState } from 'react';
export type MediaLoadingData = {
loading: boolean;
error: boolean;
};
export const useMediaLoading = (
getTargetElement: () => HTMLMediaElement | null
): MediaLoadingData => {
const [loadingData, setLoadingData] = useState<MediaLoadingData>({
loading: false,
error: false,
});
useEffect(() => {
const targetEl = getTargetElement();
const handleStart = () => {
setLoadingData({
loading: true,
error: false,
});
};
const handleStop = () => {
setLoadingData({
loading: false,
error: false,
});
};
const handleError = () => {
setLoadingData({
loading: false,
error: true,
});
};
targetEl?.addEventListener('loadstart', handleStart);
targetEl?.addEventListener('loadeddata', handleStop);
targetEl?.addEventListener('stalled', handleStop);
targetEl?.addEventListener('suspend', handleStop);
targetEl?.addEventListener('error', handleError);
return () => {
targetEl?.removeEventListener('loadstart', handleStart);
targetEl?.removeEventListener('loadeddata', handleStop);
targetEl?.removeEventListener('stalled', handleStop);
targetEl?.removeEventListener('suspend', handleStop);
targetEl?.removeEventListener('error', handleError);
};
}, [getTargetElement]);
return loadingData;
};

View file

@ -0,0 +1,46 @@
import { useCallback, useEffect, useState } from 'react';
export type MediaPlayData = {
playing: boolean;
};
export type MediaPlayControl = {
setPlaying: (play: boolean) => void;
};
export const useMediaPlay = (
getTargetElement: () => HTMLMediaElement | null
): MediaPlayData & MediaPlayControl => {
const [playing, setPlay] = useState(false);
const setPlaying = useCallback(
(play: boolean) => {
const targetEl = getTargetElement();
if (!targetEl) return;
if (play) targetEl.play();
else targetEl.pause();
},
[getTargetElement]
);
useEffect(() => {
const targetEl = getTargetElement();
const handleChange = () => {
if (!targetEl) return;
setPlay(targetEl.paused === false);
};
targetEl?.addEventListener('playing', handleChange);
targetEl?.addEventListener('play', handleChange);
targetEl?.addEventListener('pause', handleChange);
return () => {
targetEl?.removeEventListener('playing', handleChange);
targetEl?.removeEventListener('play', handleChange);
targetEl?.removeEventListener('pause', handleChange);
};
}, [getTargetElement]);
return {
playing,
setPlaying,
};
};

View file

@ -0,0 +1,24 @@
import { useEffect } from 'react';
export type PlayTimeCallback = (duration: number, currentTime: number) => void;
export const useMediaPlayTimeCallback = (
getTargetElement: () => HTMLMediaElement | null,
onPlayTimeCallback: PlayTimeCallback
): void => {
useEffect(() => {
const targetEl = getTargetElement();
const handleChange = () => {
if (!targetEl) return;
onPlayTimeCallback(targetEl.duration, targetEl.currentTime);
};
targetEl?.addEventListener('timeupdate', handleChange);
targetEl?.addEventListener('loadedmetadata', handleChange);
targetEl?.addEventListener('ended', handleChange);
return () => {
targetEl?.removeEventListener('timeupdate', handleChange);
targetEl?.removeEventListener('loadedmetadata', handleChange);
targetEl?.removeEventListener('ended', handleChange);
};
}, [getTargetElement, onPlayTimeCallback]);
};

View file

@ -0,0 +1,40 @@
import { useCallback, useEffect, useState } from 'react';
export type MediaPlaybackRateData = {
playbackRate: number;
};
export type MediaPlaybackRateControl = {
setPlaybackRate: (rate: number) => void;
};
export const useMediaPlaybackRate = (
getTargetElement: () => HTMLMediaElement | null
): MediaPlaybackRateData & MediaPlaybackRateControl => {
const [rate, setRate] = useState(1.0);
const setPlaybackRate = useCallback(
(playbackRate: number) => {
const targetEl = getTargetElement();
if (!targetEl) return;
targetEl.playbackRate = playbackRate;
},
[getTargetElement]
);
useEffect(() => {
const targetEl = getTargetElement();
const handleChange = () => {
if (!targetEl) return;
setRate(targetEl.playbackRate);
};
targetEl?.addEventListener('ratechange', handleChange);
return () => {
targetEl?.removeEventListener('ratechange', handleChange);
};
}, [getTargetElement]);
return {
playbackRate: rate,
setPlaybackRate,
};
};

View file

@ -0,0 +1,51 @@
import { useCallback, useEffect, useState } from 'react';
export type MediaSeekData = {
seeking: boolean;
seekable?: TimeRanges;
};
export type MediaSeekControl = {
seek: (time: number) => void;
};
export const useMediaSeek = (
getTargetElement: () => HTMLMediaElement | null
): MediaSeekData & MediaSeekControl => {
const [seekData, setSeekData] = useState<MediaSeekData>({
seeking: false,
seekable: undefined,
});
const seek = useCallback(
(time: number) => {
const targetEl = getTargetElement();
if (!targetEl) return;
targetEl.currentTime = time;
},
[getTargetElement]
);
useEffect(() => {
const targetEl = getTargetElement();
const handleChange = () => {
if (!targetEl) return;
setSeekData({
seeking: targetEl.seeking,
seekable: targetEl.seekable,
});
};
targetEl?.addEventListener('loadedmetadata', handleChange);
targetEl?.addEventListener('seeked', handleChange);
targetEl?.addEventListener('seeking', handleChange);
return () => {
targetEl?.removeEventListener('loadedmetadata', handleChange);
targetEl?.removeEventListener('seeked', handleChange);
targetEl?.removeEventListener('seeking', handleChange);
};
}, [getTargetElement]);
return {
...seekData,
seek,
};
};

View file

@ -0,0 +1,60 @@
import { useCallback, useEffect, useState } from 'react';
export type MediaVolumeData = {
volume: number;
mute: boolean;
};
export type MediaVolumeControl = {
setMute: (mute: boolean) => void;
setVolume: (volume: number) => void;
};
export const useMediaVolume = (
getTargetElement: () => HTMLMediaElement | null
): MediaVolumeData & MediaVolumeControl => {
const [volumeData, setVolumeData] = useState<MediaVolumeData>({
volume: 1,
mute: false,
});
const setMute = useCallback(
(mute: boolean) => {
const targetEl = getTargetElement();
if (!targetEl) return;
targetEl.muted = mute;
},
[getTargetElement]
);
const setVolume = useCallback(
(volume: number) => {
const targetEl = getTargetElement();
if (!targetEl) return;
targetEl.volume = volume;
},
[getTargetElement]
);
useEffect(() => {
const targetEl = getTargetElement();
const handleChange = () => {
if (!targetEl) return;
setVolumeData({
mute: targetEl.muted,
volume: Math.max(0, Math.min(targetEl.volume, 1)),
});
};
targetEl?.addEventListener('volumechange', handleChange);
return () => {
targetEl?.removeEventListener('volumechange', handleChange);
};
}, [getTargetElement]);
return {
...volumeData,
setMute,
setVolume,
};
};

View file

@ -25,6 +25,8 @@ export const useIntersectionObserver = (
setIntersectionObserver(new IntersectionObserver(onIntersectionCallback, initOpts)); setIntersectionObserver(new IntersectionObserver(onIntersectionCallback, initOpts));
}, [onIntersectionCallback, opts]); }, [onIntersectionCallback, opts]);
useEffect(() => () => intersectionObserver?.disconnect(), [intersectionObserver]);
useEffect(() => { useEffect(() => {
const element = typeof observeElement === 'function' ? observeElement() : observeElement; const element = typeof observeElement === 'function' ? observeElement() : observeElement;
if (element) intersectionObserver?.observe(element); if (element) intersectionObserver?.observe(element);

View file

@ -0,0 +1,80 @@
import { ReactNode } from 'react';
import { MatrixEvent } from 'matrix-js-sdk';
import { MessageEvent, StateEvent } from '../../types/matrix/room';
export type EventRenderer<T extends unknown[]> = (
eventId: string,
mEvent: MatrixEvent,
...args: T
) => ReactNode;
export type EventRendererOpts<T extends unknown[]> = {
renderRoomMessage?: EventRenderer<T>;
renderRoomEncrypted?: EventRenderer<T>;
renderSticker?: EventRenderer<T>;
renderRoomMember?: EventRenderer<T>;
renderRoomName?: EventRenderer<T>;
renderRoomTopic?: EventRenderer<T>;
renderRoomAvatar?: EventRenderer<T>;
renderStateEvent?: EventRenderer<T>;
renderEvent?: EventRenderer<T>;
};
export type RenderMatrixEvent<T extends unknown[]> = (
eventId: string,
mEvent: MatrixEvent,
...args: T
) => ReactNode;
export const useMatrixEventRenderer =
<T extends unknown[]>({
renderRoomMessage,
renderRoomEncrypted,
renderSticker,
renderRoomMember,
renderRoomName,
renderRoomTopic,
renderRoomAvatar,
renderStateEvent,
renderEvent,
}: EventRendererOpts<T>): RenderMatrixEvent<T> =>
(eventId, mEvent, ...args) => {
const eventType = mEvent.getWireType();
if (eventType === MessageEvent.RoomMessage && renderRoomMessage) {
return renderRoomMessage(eventId, mEvent, ...args);
}
if (eventType === MessageEvent.RoomMessageEncrypted && renderRoomEncrypted) {
return renderRoomEncrypted(eventId, mEvent, ...args);
}
if (eventType === MessageEvent.Sticker && renderSticker) {
return renderSticker(eventId, mEvent, ...args);
}
if (eventType === StateEvent.RoomMember && renderRoomMember) {
return renderRoomMember(eventId, mEvent, ...args);
}
if (eventType === StateEvent.RoomName && renderRoomName) {
return renderRoomName(eventId, mEvent, ...args);
}
if (eventType === StateEvent.RoomTopic && renderRoomTopic) {
return renderRoomTopic(eventId, mEvent, ...args);
}
if (eventType === StateEvent.RoomAvatar && renderRoomAvatar) {
return renderRoomAvatar(eventId, mEvent, ...args);
}
if (typeof mEvent.getStateKey() === 'string' && renderStateEvent) {
return renderStateEvent(eventId, mEvent, ...args);
}
if (typeof mEvent.getStateKey() !== 'string' && renderEvent) {
return renderEvent(eventId, mEvent, ...args);
}
return null;
};

View file

@ -0,0 +1,218 @@
import React, { ReactNode } from 'react';
import { IconSrc, Icons } from 'folds';
import { MatrixEvent } from 'matrix-js-sdk';
import { IMemberContent, Membership } from '../../types/matrix/room';
import { getMxIdLocalPart } from '../utils/matrix';
export type ParsedResult = {
icon: IconSrc;
body: ReactNode;
};
export type MemberEventParser = (mEvent: MatrixEvent) => ParsedResult;
export const useMemberEventParser = (): MemberEventParser => {
const parseMemberEvent: MemberEventParser = (mEvent) => {
const content = mEvent.getContent<IMemberContent>();
const prevContent = mEvent.getPrevContent() as IMemberContent;
const senderId = mEvent.getSender();
const userId = mEvent.getStateKey();
if (!senderId || !userId)
return {
icon: Icons.User,
body: 'Broken membership event',
};
const senderName = getMxIdLocalPart(senderId);
const userName = content.displayname || getMxIdLocalPart(userId);
if (content.membership !== prevContent.membership) {
if (content.membership === Membership.Invite) {
if (prevContent.membership === Membership.Knock) {
return {
icon: Icons.ArrowGoRightPlus,
body: (
<>
<b>{senderName}</b>
{' accepted '}
<b>{userName}</b>
{`'s join request `}
{content.reason}
</>
),
};
}
return {
icon: Icons.ArrowGoRightPlus,
body: (
<>
<b>{senderName}</b>
{' invited '}
<b>{userName}</b> {content.reason}
</>
),
};
}
if (content.membership === Membership.Knock) {
return {
icon: Icons.ArrowGoRightPlus,
body: (
<>
<b>{userName}</b>
{' request to join room '}
{content.reason}
</>
),
};
}
if (content.membership === Membership.Join) {
return {
icon: Icons.ArrowGoRight,
body: (
<>
<b>{userName}</b>
{' joined the room'}
</>
),
};
}
if (content.membership === Membership.Leave) {
if (prevContent.membership === Membership.Invite) {
return {
icon: Icons.ArrowGoRightCross,
body:
senderId === userId ? (
<>
<b>{userName}</b>
{' reject the invitation '}
{content.reason}
</>
) : (
<>
<b>{senderName}</b>
{' reject '}
<b>{userName}</b>
{`'s join request `}
{content.reason}
</>
),
};
}
if (prevContent.membership === Membership.Knock) {
return {
icon: Icons.ArrowGoRightCross,
body:
senderId === userId ? (
<>
<b>{userName}</b>
{' revoked joined request '}
{content.reason}
</>
) : (
<>
<b>{senderName}</b>
{' revoked '}
<b>{userName}</b>
{`'s invite `}
{content.reason}
</>
),
};
}
if (prevContent.membership === Membership.Ban) {
return {
icon: Icons.ArrowGoLeft,
body: (
<>
<b>{senderName}</b>
{' unbanned '}
<b>{userName}</b> {content.reason}
</>
),
};
}
return {
icon: Icons.ArrowGoLeft,
body:
senderId === userId ? (
<>
<b>{userName}</b>
{' left the room '}
{content.reason}
</>
) : (
<>
<b>{senderName}</b>
{' kicked '}
<b>{userName}</b> {content.reason}
</>
),
};
}
if (content.membership === Membership.Ban) {
return {
icon: Icons.ArrowGoLeft,
body: (
<>
<b>{senderName}</b>
{' banned '}
<b>{userName}</b> {content.reason}
</>
),
};
}
}
if (content.displayname !== prevContent.displayname) {
const prevUserName = prevContent.displayname || userId;
return {
icon: Icons.Mention,
body: content.displayname ? (
<>
<b>{prevUserName}</b>
{' changed display name to '}
<b>{userName}</b>
</>
) : (
<>
<b>{prevUserName}</b>
{' removed their display name '}
</>
),
};
}
if (content.avatar_url !== prevContent.avatar_url) {
return {
icon: Icons.User,
body: content.displayname ? (
<>
<b>{userName}</b>
{' changed their avatar'}
</>
) : (
<>
<b>{userName}</b>
{' removed their avatar '}
</>
),
};
}
return {
icon: Icons.User,
body: 'Broken membership event',
};
};
return parseMemberEvent;
};

62
src/app/hooks/usePan.ts Normal file
View file

@ -0,0 +1,62 @@
import { MouseEventHandler, useEffect, useState } from 'react';
export type Pan = {
translateX: number;
translateY: number;
};
const INITIAL_PAN = {
translateX: 0,
translateY: 0,
};
export const usePan = (active: boolean) => {
const [pan, setPan] = useState<Pan>(INITIAL_PAN);
const [cursor, setCursor] = useState<'grab' | 'grabbing' | 'initial'>(
active ? 'grab' : 'initial'
);
useEffect(() => {
setCursor(active ? 'grab' : 'initial');
}, [active]);
const handleMouseMove = (evt: MouseEvent) => {
evt.preventDefault();
evt.stopPropagation();
setPan((p) => {
const { translateX, translateY } = p;
const mX = translateX + evt.movementX;
const mY = translateY + evt.movementY;
return { translateX: mX, translateY: mY };
});
};
const handleMouseUp = (evt: MouseEvent) => {
evt.preventDefault();
setCursor('grab');
document.removeEventListener('mousemove', handleMouseMove);
document.removeEventListener('mouseup', handleMouseUp);
};
const handleMouseDown: MouseEventHandler<HTMLElement> = (evt) => {
if (!active) return;
evt.preventDefault();
setCursor('grabbing');
document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('mouseup', handleMouseUp);
};
useEffect(() => {
if (!active) setPan(INITIAL_PAN);
}, [active]);
return {
pan,
cursor,
onMouseDown: handleMouseDown,
};
};

View file

@ -1,8 +1,10 @@
import { Room } from 'matrix-js-sdk'; import { Room } from 'matrix-js-sdk';
import { useCallback } from 'react'; import { createContext, useCallback, useContext } from 'react';
import { useStateEvent } from './useStateEvent'; import { useStateEvent } from './useStateEvent';
import { StateEvent } from '../../types/matrix/room'; import { StateEvent } from '../../types/matrix/room';
export type PowerLevelActions = 'invite' | 'redact' | 'kick' | 'ban' | 'historical';
enum DefaultPowerLevels { enum DefaultPowerLevels {
usersDefault = 0, usersDefault = 0,
stateDefault = 50, stateDefault = 50,
@ -29,12 +31,23 @@ interface IPowerLevels {
notifications?: Record<string, number>; notifications?: Record<string, number>;
} }
export function usePowerLevels(room: Room) { export type GetPowerLevel = (userId: string) => number;
export type CanSend = (eventType: string | undefined, powerLevel: number) => boolean;
export type CanDoAction = (action: PowerLevelActions, powerLevel: number) => boolean;
export type PowerLevelsAPI = {
getPowerLevel: GetPowerLevel;
canSendEvent: CanSend;
canSendStateEvent: CanSend;
canDoAction: CanDoAction;
};
export function usePowerLevels(room: Room): PowerLevelsAPI {
const powerLevelsEvent = useStateEvent(room, StateEvent.RoomPowerLevels); const powerLevelsEvent = useStateEvent(room, StateEvent.RoomPowerLevels);
const powerLevels: IPowerLevels = powerLevelsEvent?.getContent() ?? DefaultPowerLevels; const powerLevels: IPowerLevels = powerLevelsEvent?.getContent() ?? DefaultPowerLevels;
const getPowerLevel = useCallback( const getPowerLevel: GetPowerLevel = useCallback(
(userId: string) => { (userId) => {
const { users_default: usersDefault, users } = powerLevels; const { users_default: usersDefault, users } = powerLevels;
if (users && typeof users[userId] === 'number') { if (users && typeof users[userId] === 'number') {
return users[userId]; return users[userId];
@ -44,8 +57,8 @@ export function usePowerLevels(room: Room) {
[powerLevels] [powerLevels]
); );
const canSendEvent = useCallback( const canSendEvent: CanSend = useCallback(
(eventType: string | undefined, powerLevel: number) => { (eventType, powerLevel) => {
const { events, events_default: eventsDefault } = powerLevels; const { events, events_default: eventsDefault } = powerLevels;
if (events && eventType && typeof events[eventType] === 'number') { if (events && eventType && typeof events[eventType] === 'number') {
return powerLevel >= events[eventType]; return powerLevel >= events[eventType];
@ -55,8 +68,8 @@ export function usePowerLevels(room: Room) {
[powerLevels] [powerLevels]
); );
const canSendStateEvent = useCallback( const canSendStateEvent: CanSend = useCallback(
(eventType: string | undefined, powerLevel: number) => { (eventType, powerLevel) => {
const { events, state_default: stateDefault } = powerLevels; const { events, state_default: stateDefault } = powerLevels;
if (events && eventType && typeof events[eventType] === 'number') { if (events && eventType && typeof events[eventType] === 'number') {
return powerLevel >= events[eventType]; return powerLevel >= events[eventType];
@ -66,8 +79,8 @@ export function usePowerLevels(room: Room) {
[powerLevels] [powerLevels]
); );
const canDoAction = useCallback( const canDoAction: CanDoAction = useCallback(
(action: 'invite' | 'redact' | 'kick' | 'ban' | 'historical', powerLevel: number) => { (action, powerLevel) => {
const requiredPL = powerLevels[action]; const requiredPL = powerLevels[action];
if (typeof requiredPL === 'number') { if (typeof requiredPL === 'number') {
return powerLevel >= requiredPL; return powerLevel >= requiredPL;
@ -84,3 +97,13 @@ export function usePowerLevels(room: Room) {
canDoAction, canDoAction,
}; };
} }
export const PowerLevelsContext = createContext<PowerLevelsAPI | null>(null);
export const PowerLevelsContextProvider = PowerLevelsContext.Provider;
export const usePowerLevelsAPI = (): PowerLevelsAPI => {
const api = useContext(PowerLevelsContext);
if (!api) throw new Error('PowerLevelContext is not initialized!');
return api;
};

View file

@ -0,0 +1,25 @@
import { useEffect, useState } from 'react';
import { RelationsEvent, type Relations } from 'matrix-js-sdk/lib/models/relations';
export const useRelations = <T>(
relations: Relations,
getRelations: (relations: Relations) => T
) => {
const [data, setData] = useState(() => getRelations(relations));
useEffect(() => {
const handleUpdate = () => {
setData(getRelations(relations));
};
relations.on(RelationsEvent.Add, handleUpdate);
relations.on(RelationsEvent.Redaction, handleUpdate);
relations.on(RelationsEvent.Remove, handleUpdate);
return () => {
relations.removeListener(RelationsEvent.Add, handleUpdate);
relations.removeListener(RelationsEvent.Redaction, handleUpdate);
relations.removeListener(RelationsEvent.Remove, handleUpdate);
};
}, [relations, getRelations]);
return data;
};

View file

@ -13,6 +13,8 @@ export const useResizeObserver = (
): ResizeObserver => { ): ResizeObserver => {
const resizeObserver = useMemo(() => new ResizeObserver(onResizeCallback), [onResizeCallback]); const resizeObserver = useMemo(() => new ResizeObserver(onResizeCallback), [onResizeCallback]);
useEffect(() => () => resizeObserver?.disconnect(), [resizeObserver]);
useEffect(() => { useEffect(() => {
const element = typeof observeElement === 'function' ? observeElement() : observeElement; const element = typeof observeElement === 'function' ? observeElement() : observeElement;
if (element) resizeObserver.observe(element); if (element) resizeObserver.observe(element);

View file

@ -0,0 +1,35 @@
import { Room, RoomEvent, RoomEventHandlerMap } from 'matrix-js-sdk';
import { useEffect, useState } from 'react';
const getEventReaders = (room: Room, evtId?: string) => {
if (!evtId) return [];
const liveEvents = room.getLiveTimeline().getEvents();
const userIds: string[] = [];
for (let i = liveEvents.length - 1; i >= 0; i -= 1) {
userIds.splice(userIds.length, 0, ...room.getUsersReadUpTo(liveEvents[i]));
if (liveEvents[i].getId() === evtId) break;
}
return [...new Set(userIds)];
};
export const useRoomEventReaders = (room: Room, eventId?: string): string[] => {
const [readers, setReaders] = useState<string[]>(() => getEventReaders(room, eventId));
useEffect(() => {
setReaders(getEventReaders(room, eventId));
const handleReceipt: RoomEventHandlerMap[RoomEvent.Receipt] = (event, r) => {
if (r.roomId !== room.roomId) return;
setReaders(getEventReaders(room, eventId));
};
room.on(RoomEvent.Receipt, handleReceipt);
return () => {
room.removeListener(RoomEvent.Receipt, handleReceipt);
};
}, [room, eventId]);
return readers;
};

View file

@ -0,0 +1,29 @@
import { MatrixEvent, Room, RoomEvent, RoomEventHandlerMap } from 'matrix-js-sdk';
import { useEffect, useState } from 'react';
export const useRoomLatestEvent = (room: Room) => {
const [latestEvent, setLatestEvent] = useState<MatrixEvent>();
useEffect(() => {
const getLatestEvent = (): MatrixEvent | undefined => {
const liveEvents = room.getLiveTimeline().getEvents();
for (let i = liveEvents.length - 1; i >= 0; i -= 1) {
const evt = liveEvents[i];
if (evt) return evt;
}
return undefined;
};
const handleTimelineEvent: RoomEventHandlerMap[RoomEvent.Timeline] = () => {
setLatestEvent(getLatestEvent());
};
setLatestEvent(getLatestEvent());
room.on(RoomEvent.Timeline, handleTimelineEvent);
return () => {
room.removeListener(RoomEvent.Timeline, handleTimelineEvent);
};
}, [room]);
return latestEvent;
};

View file

@ -0,0 +1,68 @@
import { ReactNode } from 'react';
import { MatrixEvent, MsgType } from 'matrix-js-sdk';
export type MsgContentRenderer<T extends unknown[]> = (
eventId: string,
mEvent: MatrixEvent,
...args: T
) => ReactNode;
export type RoomMsgContentRendererOpts<T extends unknown[]> = {
renderText?: MsgContentRenderer<T>;
renderEmote?: MsgContentRenderer<T>;
renderNotice?: MsgContentRenderer<T>;
renderImage?: MsgContentRenderer<T>;
renderVideo?: MsgContentRenderer<T>;
renderAudio?: MsgContentRenderer<T>;
renderFile?: MsgContentRenderer<T>;
renderLocation?: MsgContentRenderer<T>;
renderBadEncrypted?: MsgContentRenderer<T>;
renderUnsupported?: MsgContentRenderer<T>;
renderBrokenFallback?: MsgContentRenderer<T>;
};
export type RenderRoomMsgContent<T extends unknown[]> = (
eventId: string,
mEvent: MatrixEvent,
...args: T
) => ReactNode;
export const useRoomMsgContentRenderer =
<T extends unknown[]>({
renderText,
renderEmote,
renderNotice,
renderImage,
renderVideo,
renderAudio,
renderFile,
renderLocation,
renderBadEncrypted,
renderUnsupported,
renderBrokenFallback,
}: RoomMsgContentRendererOpts<T>): RenderRoomMsgContent<T> =>
(eventId, mEvent, ...args) => {
const msgType = mEvent.getContent().msgtype;
let node: ReactNode = null;
if (msgType === MsgType.Text && renderText) node = renderText(eventId, mEvent, ...args);
else if (msgType === MsgType.Emote && renderEmote) node = renderEmote(eventId, mEvent, ...args);
else if (msgType === MsgType.Notice && renderNotice)
node = renderNotice(eventId, mEvent, ...args);
else if (msgType === MsgType.Image && renderImage) node = renderImage(eventId, mEvent, ...args);
else if (msgType === MsgType.Video && renderVideo) node = renderVideo(eventId, mEvent, ...args);
else if (msgType === MsgType.Audio && renderAudio) node = renderAudio(eventId, mEvent, ...args);
else if (msgType === MsgType.File && renderFile) node = renderFile(eventId, mEvent, ...args);
else if (msgType === MsgType.Location && renderLocation)
node = renderLocation(eventId, mEvent, ...args);
else if (msgType === 'm.bad.encrypted' && renderBadEncrypted)
node = renderBadEncrypted(eventId, mEvent, ...args);
else if (renderUnsupported) {
node = renderUnsupported(eventId, mEvent, ...args);
}
if (!node && renderBrokenFallback) node = renderBrokenFallback(eventId, mEvent, ...args);
return node;
};

View file

@ -0,0 +1,405 @@
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef } from 'react';
import { OnIntersectionCallback, useIntersectionObserver } from './useIntersectionObserver';
import {
canFitInScrollView,
getScrollInfo,
isInScrollView,
isIntersectingScrollView,
} from '../utils/dom';
const PAGINATOR_ANCHOR_ATTR = 'data-paginator-anchor';
export enum Direction {
Backward = 'B',
Forward = 'F',
}
export type ItemRange = {
start: number;
end: number;
};
export type ScrollToOptions = {
offset?: number;
align?: 'start' | 'center' | 'end';
behavior?: 'auto' | 'instant' | 'smooth';
stopInView?: boolean;
};
export type ScrollToElement = (element: HTMLElement, opts?: ScrollToOptions) => void;
export type ScrollToItem = (index: number, opts?: ScrollToOptions) => void;
type HandleObserveAnchor = (element: HTMLElement | null) => void;
type VirtualPaginatorOptions<TScrollElement extends HTMLElement> = {
count: number;
limit: number;
range: ItemRange;
onRangeChange: (range: ItemRange) => void;
getScrollElement: () => TScrollElement | null;
getItemElement: (index: number) => HTMLElement | undefined;
onEnd?: (back: boolean) => void;
};
type VirtualPaginator = {
getItems: () => number[];
scrollToElement: ScrollToElement;
scrollToItem: ScrollToItem;
observeBackAnchor: HandleObserveAnchor;
observeFrontAnchor: HandleObserveAnchor;
};
const generateItems = (range: ItemRange) => {
const items: number[] = [];
for (let i = range.start; i < range.end; i += 1) {
items.push(i);
}
return items;
};
const getDropIndex = (
scrollEl: HTMLElement,
range: ItemRange,
dropDirection: Direction,
getItemElement: (index: number) => HTMLElement | undefined,
pageThreshold = 1
): number | undefined => {
const fromBackward = dropDirection === Direction.Backward;
const items = fromBackward ? generateItems(range) : generateItems(range).reverse();
const { viewHeight, top, height } = getScrollInfo(scrollEl);
const { offsetTop: sOffsetTop } = scrollEl;
const bottom = top + viewHeight;
const dropEdgePx = fromBackward
? Math.max(top - viewHeight * pageThreshold, 0)
: Math.min(bottom + viewHeight * pageThreshold, height);
if (dropEdgePx === 0 || dropEdgePx === height) return undefined;
let dropIndex: number | undefined;
items.find((item) => {
const el = getItemElement(item);
if (!el) {
dropIndex = item;
return false;
}
const { clientHeight } = el;
const offsetTop = el.offsetTop - sOffsetTop;
const offsetBottom = offsetTop + clientHeight;
const isInView = fromBackward ? offsetBottom > dropEdgePx : offsetTop < dropEdgePx;
if (isInView) return true;
dropIndex = item;
return false;
});
return dropIndex;
};
type RestoreAnchorData = [number | undefined, HTMLElement | undefined];
const getRestoreAnchor = (
range: ItemRange,
getItemElement: (index: number) => HTMLElement | undefined,
direction: Direction
): RestoreAnchorData => {
let scrollAnchorEl: HTMLElement | undefined;
const scrollAnchorItem = (
direction === Direction.Backward ? generateItems(range) : generateItems(range).reverse()
).find((i) => {
const el = getItemElement(i);
if (el) {
scrollAnchorEl = el;
return true;
}
return false;
});
return [scrollAnchorItem, scrollAnchorEl];
};
const getRestoreScrollData = (scrollTop: number, restoreAnchorData: RestoreAnchorData) => {
const [anchorItem, anchorElement] = restoreAnchorData;
if (!anchorItem || !anchorElement) {
return undefined;
}
return {
scrollTop,
anchorItem,
anchorOffsetTop: anchorElement.offsetTop,
};
};
const useObserveAnchorHandle = (
intersectionObserver: ReturnType<typeof useIntersectionObserver>,
anchorType: Direction
): HandleObserveAnchor =>
useMemo<HandleObserveAnchor>(() => {
let anchor: HTMLElement | null = null;
return (element) => {
if (element === anchor) return;
if (anchor) intersectionObserver?.unobserve(anchor);
if (!element) return;
anchor = element;
element.setAttribute(PAGINATOR_ANCHOR_ATTR, anchorType);
intersectionObserver?.observe(element);
};
}, [intersectionObserver, anchorType]);
export const useVirtualPaginator = <TScrollElement extends HTMLElement>(
options: VirtualPaginatorOptions<TScrollElement>
): VirtualPaginator => {
const { count, limit, range, onRangeChange, getScrollElement, getItemElement, onEnd } = options;
const initialRenderRef = useRef(true);
const restoreScrollRef = useRef<{
scrollTop: number;
anchorOffsetTop: number;
anchorItem: number;
}>();
const scrollToItemRef = useRef<{
index: number;
opts?: ScrollToOptions;
}>();
const propRef = useRef({
range,
limit,
count,
});
if (propRef.current.count !== count) {
// Clear restoreScrollRef on count change
// As restoreScrollRef.current.anchorItem might changes
restoreScrollRef.current = undefined;
}
propRef.current = {
range,
count,
limit,
};
const getItems = useMemo(() => {
const items = generateItems(range);
return () => items;
}, [range]);
const scrollToElement = useCallback<ScrollToElement>(
(element, opts) => {
const scrollElement = getScrollElement();
if (!scrollElement) return;
if (opts?.stopInView && isInScrollView(scrollElement, element)) {
return;
}
let scrollTo = element.offsetTop;
if (opts?.align === 'center' && canFitInScrollView(scrollElement, element)) {
const scrollInfo = getScrollInfo(scrollElement);
scrollTo =
element.offsetTop -
Math.round(scrollInfo.viewHeight / 2) +
Math.round(element.clientHeight / 2);
} else if (opts?.align === 'end' && canFitInScrollView(scrollElement, element)) {
const scrollInfo = getScrollInfo(scrollElement);
scrollTo = element.offsetTop - Math.round(scrollInfo.viewHeight) + element.clientHeight;
}
scrollElement.scrollTo({
top: scrollTo - (opts?.offset ?? 0),
behavior: opts?.behavior,
});
},
[getScrollElement]
);
const scrollToItem = useCallback<ScrollToItem>(
(index, opts) => {
const { range: currentRange, limit: currentLimit, count: currentCount } = propRef.current;
if (index < 0 || index >= currentCount) return;
// index is not in range change range
// and trigger scrollToItem in layoutEffect hook
if (index < currentRange.start || index >= currentRange.end) {
onRangeChange({
start: Math.max(index - currentLimit, 0),
end: Math.min(index + currentLimit, currentCount),
});
scrollToItemRef.current = {
index,
opts,
};
return;
}
// find target or it's previous rendered element to scroll to
const targetItems = generateItems({ start: currentRange.start, end: index + 1 });
const targetItem = targetItems.reverse().find((i) => getItemElement(i) !== undefined);
const itemElement = targetItem && getItemElement(targetItem);
if (!itemElement) {
const scrollElement = getScrollElement();
scrollElement?.scrollTo({
top: opts?.offset ?? 0,
behavior: opts?.behavior,
});
return;
}
scrollToElement(itemElement, opts);
},
[getScrollElement, scrollToElement, getItemElement, onRangeChange]
);
const paginate = useCallback(
(direction: Direction) => {
const scrollEl = getScrollElement();
const { range: currentRange, limit: currentLimit, count: currentCount } = propRef.current;
let { start, end } = currentRange;
if (direction === Direction.Backward) {
restoreScrollRef.current = undefined;
if (start === 0) {
onEnd?.(true);
return;
}
if (scrollEl) {
restoreScrollRef.current = getRestoreScrollData(
scrollEl.scrollTop,
getRestoreAnchor({ start, end }, getItemElement, Direction.Backward)
);
}
if (scrollEl) {
end = getDropIndex(scrollEl, currentRange, Direction.Forward, getItemElement, 2) ?? end;
}
start = Math.max(start - currentLimit, 0);
}
if (direction === Direction.Forward) {
restoreScrollRef.current = undefined;
if (end === currentCount) {
onEnd?.(false);
return;
}
if (scrollEl) {
restoreScrollRef.current = getRestoreScrollData(
scrollEl.scrollTop,
getRestoreAnchor({ start, end }, getItemElement, Direction.Forward)
);
}
end = Math.min(end + currentLimit, currentCount);
if (scrollEl) {
start =
getDropIndex(scrollEl, currentRange, Direction.Backward, getItemElement, 2) ?? start;
}
}
onRangeChange({
start,
end,
});
},
[getScrollElement, getItemElement, onEnd, onRangeChange]
);
const handlePaginatorElIntersection: OnIntersectionCallback = useCallback(
(entries) => {
const anchorB = entries.find(
(entry) => entry.target.getAttribute(PAGINATOR_ANCHOR_ATTR) === Direction.Backward
);
if (anchorB?.isIntersecting) {
paginate(Direction.Backward);
}
const anchorF = entries.find(
(entry) => entry.target.getAttribute(PAGINATOR_ANCHOR_ATTR) === Direction.Forward
);
if (anchorF?.isIntersecting) {
paginate(Direction.Forward);
}
},
[paginate]
);
const intersectionObserver = useIntersectionObserver(
handlePaginatorElIntersection,
useMemo(
() => ({
root: getScrollElement(),
}),
[getScrollElement]
)
);
const observeBackAnchor = useObserveAnchorHandle(intersectionObserver, Direction.Backward);
const observeFrontAnchor = useObserveAnchorHandle(intersectionObserver, Direction.Forward);
// Restore scroll when local pagination.
// restoreScrollRef.current only gets set
// when paginate() changes range itself
useLayoutEffect(() => {
const scrollEl = getScrollElement();
if (!restoreScrollRef.current || !scrollEl) return;
const {
anchorOffsetTop: oldOffsetTop,
anchorItem,
scrollTop: oldScrollTop,
} = restoreScrollRef.current;
const anchorEl = getItemElement(anchorItem);
if (!anchorEl) return;
const { offsetTop } = anchorEl;
const offsetAddition = offsetTop - oldOffsetTop;
const restoreTop = oldScrollTop + offsetAddition;
scrollEl.scrollTo({
top: restoreTop,
behavior: 'instant',
});
restoreScrollRef.current = undefined;
}, [range, getScrollElement, getItemElement]);
// When scrollToItem index was not in range.
// Scroll to item after range changes.
useLayoutEffect(() => {
if (scrollToItemRef.current === undefined) return;
const { index, opts } = scrollToItemRef.current;
scrollToItem(index, {
...opts,
behavior: 'instant',
});
scrollToItemRef.current = undefined;
}, [range, scrollToItem]);
// Continue pagination to fill view height with scroll items
// check if pagination anchor are in visible view height
// and trigger pagination
useEffect(() => {
if (initialRenderRef.current) {
// Do not trigger pagination on initial render
// anchor intersection observable will trigger pagination on mount
initialRenderRef.current = false;
return;
}
const scrollElement = getScrollElement();
if (!scrollElement) return;
const backAnchor = scrollElement.querySelector(
`[${PAGINATOR_ANCHOR_ATTR}="${Direction.Backward}"]`
) as HTMLElement | null;
const frontAnchor = scrollElement.querySelector(
`[${PAGINATOR_ANCHOR_ATTR}="${Direction.Forward}"]`
) as HTMLElement | null;
if (backAnchor && isIntersectingScrollView(scrollElement, backAnchor)) {
paginate(Direction.Backward);
return;
}
if (frontAnchor && isIntersectingScrollView(scrollElement, frontAnchor)) {
paginate(Direction.Forward);
}
}, [range, getScrollElement, paginate]);
return {
getItems,
scrollToItem,
scrollToElement,
observeBackAnchor,
observeFrontAnchor,
};
};

26
src/app/hooks/useZoom.ts Normal file
View file

@ -0,0 +1,26 @@
import { useState } from 'react';
export const useZoom = (step: number, min = 0.1, max = 5) => {
const [zoom, setZoom] = useState<number>(1);
const zoomIn = () => {
setZoom((z) => {
const newZ = z + step;
return newZ > max ? z : newZ;
});
};
const zoomOut = () => {
setZoom((z) => {
const newZ = z - step;
return newZ < min ? z : newZ;
});
};
return {
zoom,
setZoom,
zoomIn,
zoomOut,
};
};

View file

@ -10,6 +10,7 @@ import {
Avatar, Avatar,
AvatarFallback, AvatarFallback,
AvatarImage, AvatarImage,
Badge,
Box, Box,
Chip, Chip,
ContainerColor, ContainerColor,
@ -33,6 +34,7 @@ import { useVirtualizer } from '@tanstack/react-virtual';
import FocusTrap from 'focus-trap-react'; import FocusTrap from 'focus-trap-react';
import millify from 'millify'; import millify from 'millify';
import classNames from 'classnames'; import classNames from 'classnames';
import { useAtomValue } from 'jotai';
import { openInviteUser, openProfileViewer } from '../../../client/action/navigation'; import { openInviteUser, openProfileViewer } from '../../../client/action/navigation';
import * as css from './MembersDrawer.css'; import * as css from './MembersDrawer.css';
@ -48,6 +50,10 @@ import { UseAsyncSearchOptions, useAsyncSearch } from '../../hooks/useAsyncSearc
import { useDebounce } from '../../hooks/useDebounce'; import { useDebounce } from '../../hooks/useDebounce';
import colorMXID from '../../../util/colorMXID'; import colorMXID from '../../../util/colorMXID';
import { usePowerLevelTags, PowerLevelTag } from '../../hooks/usePowerLevelTags'; import { usePowerLevelTags, PowerLevelTag } from '../../hooks/usePowerLevelTags';
import { roomIdToTypingMembersAtom, selectRoomTypingMembersAtom } from '../../state/typingMembers';
import { TypingIndicator } from '../../components/typing-indicator';
import { getMemberDisplayName } from '../../utils/room';
import { getMxIdLocalPart } from '../../utils/matrix';
export const MembershipFilters = { export const MembershipFilters = {
filterJoined: (m: RoomMember) => m.membership === Membership.Join, filterJoined: (m: RoomMember) => m.membership === Membership.Join,
@ -175,6 +181,10 @@ export function MembersDrawer({ room }: MembersDrawerProps) {
}); });
const [onTop, setOnTop] = useState(true); const [onTop, setOnTop] = useState(true);
const typingMembers = useAtomValue(
useMemo(() => selectRoomTypingMembersAtom(room.roomId, roomIdToTypingMembersAtom), [room])
);
const filteredMembers = useMemo( const filteredMembers = useMemo(
() => () =>
members members
@ -235,6 +245,9 @@ export function MembersDrawer({ room }: MembersDrawerProps) {
{ wait: 200 } { wait: 200 }
); );
const getName = (member: RoomMember) =>
getMemberDisplayName(room, member.userId) ?? getMxIdLocalPart(member.userId) ?? member.userId;
const handleMemberClick: MouseEventHandler<HTMLButtonElement> = (evt) => { const handleMemberClick: MouseEventHandler<HTMLButtonElement> = (evt) => {
const btn = evt.currentTarget as HTMLButtonElement; const btn = evt.currentTarget as HTMLButtonElement;
const userId = btn.getAttribute('data-user-id'); const userId = btn.getAttribute('data-user-id');
@ -470,6 +483,7 @@ export function MembersDrawer({ room }: MembersDrawerProps) {
} }
const member = tagOrMember; const member = tagOrMember;
const name = getName(member);
const avatarUrl = member.getAvatarUrl( const avatarUrl = member.getAvatarUrl(
mx.baseUrl, mx.baseUrl,
100, 100,
@ -482,7 +496,7 @@ export function MembersDrawer({ room }: MembersDrawerProps) {
return ( return (
<MenuItem <MenuItem
style={{ style={{
padding: config.space.S200, padding: `0 ${config.space.S200}`,
transform: `translateY(${vItem.start}px)`, transform: `translateY(${vItem.start}px)`,
}} }}
data-index={vItem.index} data-index={vItem.index}
@ -504,15 +518,24 @@ export function MembersDrawer({ room }: MembersDrawerProps) {
color: 'white', color: 'white',
}} }}
> >
<Text size="T200">{member.name[0]}</Text> <Text size="H6">{name[0]}</Text>
</AvatarFallback> </AvatarFallback>
)} )}
</Avatar> </Avatar>
} }
after={
typingMembers.find((tm) => tm.userId === member.userId) && (
<Badge size="300" variant="Secondary" fill="Soft" radii="Pill" outlined>
<TypingIndicator size="300" />
</Badge>
)
}
> >
<Box grow="Yes">
<Text size="T400" truncate> <Text size="T400" truncate>
{member.name} {name}
</Text> </Text>
</Box>
</MenuItem> </MenuItem>
); );
})} })}

View file

@ -1,79 +0,0 @@
import React, { useState, useEffect } from 'react';
import './Room.scss';
import { Line } from 'folds';
import initMatrix from '../../../client/initMatrix';
import cons from '../../../client/state/cons';
import RoomTimeline from '../../../client/state/RoomTimeline';
import navigation from '../../../client/state/navigation';
import { openNavigation } from '../../../client/action/navigation';
import Welcome from '../welcome/Welcome';
import RoomView from './RoomView';
import RoomSettings from './RoomSettings';
import { MembersDrawer } from './MembersDrawer';
import { ScreenSize, useScreenSize } from '../../hooks/useScreenSize';
import { useSetting } from '../../state/hooks/settings';
import { settingsAtom } from '../../state/settings';
function Room() {
const [roomInfo, setRoomInfo] = useState({
room: null,
roomTimeline: null,
eventId: null,
});
const [isDrawer] = useSetting(settingsAtom, 'isPeopleDrawer');
const [screenSize] = useScreenSize();
const mx = initMatrix.matrixClient;
useEffect(() => {
const handleRoomSelected = (rId, pRoomId, eId) => {
roomInfo.roomTimeline?.removeInternalListeners();
const r = mx.getRoom(rId);
if (r) {
setRoomInfo({
room: r,
roomTimeline: new RoomTimeline(rId),
eventId: eId ?? null,
});
} else {
// TODO: add ability to join room if roomId is invalid
setRoomInfo({
room: r,
roomTimeline: null,
eventId: null,
});
}
};
navigation.on(cons.events.navigation.ROOM_SELECTED, handleRoomSelected);
return () => {
navigation.removeListener(cons.events.navigation.ROOM_SELECTED, handleRoomSelected);
};
}, [roomInfo, mx]);
const { room, roomTimeline, eventId } = roomInfo;
if (roomTimeline === null) {
setTimeout(() => openNavigation());
return <Welcome />;
}
return (
<div className="room">
<div className="room__content">
<RoomSettings roomId={roomTimeline.roomId} />
<RoomView room={room} roomTimeline={roomTimeline} eventId={eventId} />
</div>
{screenSize === ScreenSize.Desktop && isDrawer && (
<>
<Line variant="Background" direction="Vertical" size="300" />
<MembersDrawer room={room} />
</>
)}
</div>
);
}
export default Room;

View file

@ -0,0 +1,46 @@
import React from 'react';
import './Room.scss';
import { Room } from 'matrix-js-sdk';
import { Line } from 'folds';
import RoomView from './RoomView';
import RoomSettings from './RoomSettings';
import { MembersDrawer } from './MembersDrawer';
import { ScreenSize, useScreenSize } from '../../hooks/useScreenSize';
import { useSetting } from '../../state/hooks/settings';
import { settingsAtom } from '../../state/settings';
import { PowerLevelsContextProvider, usePowerLevels } from '../../hooks/usePowerLevels';
import {
roomIdToTypingMembersAtom,
useBindRoomIdToTypingMembersAtom,
} from '../../state/typingMembers';
export type RoomBaseViewProps = {
room: Room;
eventId?: string;
};
export function RoomBaseView({ room, eventId }: RoomBaseViewProps) {
useBindRoomIdToTypingMembersAtom(room.client, roomIdToTypingMembersAtom);
const [isDrawer] = useSetting(settingsAtom, 'isPeopleDrawer');
const [screenSize] = useScreenSize();
const powerLevelAPI = usePowerLevels(room);
return (
<PowerLevelsContextProvider value={powerLevelAPI}>
<div className="room">
<div className="room__content">
<RoomSettings roomId={room.roomId} />
<RoomView room={room} eventId={eventId} />
</div>
{screenSize === ScreenSize.Desktop && isDrawer && (
<>
<Line variant="Background" direction="Vertical" size="300" />
<MembersDrawer room={room} />
</>
)}
</div>
</PowerLevelsContextProvider>
);
}

View file

@ -34,8 +34,6 @@ import to from 'await-to-js';
import { useMatrixClient } from '../../hooks/useMatrixClient'; import { useMatrixClient } from '../../hooks/useMatrixClient';
import { import {
CustomEditor, CustomEditor,
EditorChangeHandler,
useEditor,
Toolbar, Toolbar,
toMatrixCustomHTML, toMatrixCustomHTML,
toPlainText, toPlainText,
@ -102,13 +100,13 @@ import { sanitizeText } from '../../utils/sanitize';
import { useScreenSize } from '../../hooks/useScreenSize'; import { useScreenSize } from '../../hooks/useScreenSize';
interface RoomInputProps { interface RoomInputProps {
editor: Editor;
roomViewRef: RefObject<HTMLElement>; roomViewRef: RefObject<HTMLElement>;
roomId: string; roomId: string;
} }
export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>( export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
({ roomViewRef, roomId }, ref) => { ({ editor, roomViewRef, roomId }, ref) => {
const mx = useMatrixClient(); const mx = useMatrixClient();
const editor = useEditor();
const room = mx.getRoom(roomId); const room = mx.getRoom(roomId);
const [msgDraft, setMsgDraft] = useAtom(roomIdToMsgDraftAtomFamily(roomId)); const [msgDraft, setMsgDraft] = useAtom(roomIdToMsgDraftAtomFamily(roomId));
@ -226,7 +224,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
const sendPromises = uploads.map(async (upload) => { const sendPromises = uploads.map(async (upload) => {
const fileItem = selectedFiles.find((f) => f.file === upload.file); const fileItem = selectedFiles.find((f) => f.file === upload.file);
if (fileItem && fileItem.file.type.startsWith('image')) { if (fileItem && fileItem.file.type.startsWith('image')) {
const [imgError, imgContent] = await to(getImageMsgContent(fileItem, upload.mxc)); const [imgError, imgContent] = await to(getImageMsgContent(mx, fileItem, upload.mxc));
if (imgError) console.warn(imgError); if (imgError) console.warn(imgError);
if (imgContent) mx.sendMessage(roomId, imgContent); if (imgContent) mx.sendMessage(roomId, imgContent);
return; return;
@ -294,7 +292,6 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
const handleKeyDown: KeyboardEventHandler = useCallback( const handleKeyDown: KeyboardEventHandler = useCallback(
(evt) => { (evt) => {
const { selection } = editor;
if (isHotkey('enter', evt)) { if (isHotkey('enter', evt)) {
evt.preventDefault(); evt.preventDefault();
submit(); submit();
@ -303,7 +300,8 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
evt.preventDefault(); evt.preventDefault();
setReplyDraft(); setReplyDraft();
} }
if (selection && Range.isCollapsed(selection)) {
if (editor.selection && Range.isCollapsed(editor.selection)) {
if (isHotkey('arrowleft', evt)) { if (isHotkey('arrowleft', evt)) {
evt.preventDefault(); evt.preventDefault();
Transforms.move(editor, { unit: 'offset', reverse: true }); Transforms.move(editor, { unit: 'offset', reverse: true });
@ -317,20 +315,19 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
[submit, editor, setReplyDraft] [submit, editor, setReplyDraft]
); );
const handleChange: EditorChangeHandler = (value) => { const handleKeyUp: KeyboardEventHandler = useCallback(() => {
const firstChildren = editor.children[0];
if (firstChildren && Element.isElement(firstChildren)) {
const isEmpty = editor.children.length === 1 && Editor.isEmpty(editor, firstChildren);
sendTypingStatus(!isEmpty);
}
const prevWordRange = getPrevWorldRange(editor); const prevWordRange = getPrevWorldRange(editor);
const query = prevWordRange const query = prevWordRange
? getAutocompleteQuery<AutocompletePrefix>(editor, prevWordRange, AUTOCOMPLETE_PREFIXES) ? getAutocompleteQuery<AutocompletePrefix>(editor, prevWordRange, AUTOCOMPLETE_PREFIXES)
: undefined; : undefined;
setAutocompleteQuery(query); setAutocompleteQuery(query);
}, [editor, sendTypingStatus]);
const descendant = value[0];
if (descendant && Element.isElement(descendant)) {
const isEmpty = value.length === 1 && Editor.isEmpty(editor, descendant);
sendTypingStatus(!isEmpty);
}
};
const handleEmoticonSelect = (key: string, shortcode: string) => { const handleEmoticonSelect = (key: string, shortcode: string) => {
editor.insertNode(createEmoticonElement(key, shortcode)); editor.insertNode(createEmoticonElement(key, shortcode));
@ -439,7 +436,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
editor={editor} editor={editor}
placeholder="Send a message..." placeholder="Send a message..."
onKeyDown={handleKeyDown} onKeyDown={handleKeyDown}
onChange={handleChange} onKeyUp={handleKeyUp}
onPaste={handlePaste} onPaste={handlePaste}
top={ top={
replyDraft && ( replyDraft && (

View file

@ -0,0 +1,30 @@
import { RecipeVariants, recipe } from '@vanilla-extract/recipes';
import { DefaultReset, config } from 'folds';
export const TimelineFloat = recipe({
base: [
DefaultReset,
{
position: 'absolute',
left: '50%',
transform: 'translateX(-50%)',
zIndex: 1,
minWidth: 'max-content',
},
],
variants: {
position: {
Top: {
top: config.space.S400,
},
Bottom: {
bottom: config.space.S400,
},
},
},
defaultVariants: {
position: 'Top',
},
});
export type TimelineFloatVariants = RecipeVariants<typeof TimelineFloat>;

File diff suppressed because it is too large Load diff

View file

@ -4,34 +4,33 @@ import './RoomView.scss';
import { Text, config } from 'folds'; import { Text, config } from 'folds';
import { EventType } from 'matrix-js-sdk'; import { EventType } from 'matrix-js-sdk';
import EventEmitter from 'events';
import cons from '../../../client/state/cons'; import cons from '../../../client/state/cons';
import navigation from '../../../client/state/navigation'; import navigation from '../../../client/state/navigation';
import RoomViewHeader from './RoomViewHeader'; import RoomViewHeader from './RoomViewHeader';
import RoomViewContent from './RoomViewContent';
import RoomViewFloating from './RoomViewFloating';
import RoomViewCmdBar from './RoomViewCmdBar';
import { RoomInput } from './RoomInput'; import { RoomInput } from './RoomInput';
import { useStateEvent } from '../../hooks/useStateEvent'; import { useStateEvent } from '../../hooks/useStateEvent';
import { StateEvent } from '../../../types/matrix/room'; import { StateEvent } from '../../../types/matrix/room';
import { RoomTombstone } from './RoomTombstone'; import { RoomTombstone } from './RoomTombstone';
import { usePowerLevels } from '../../hooks/usePowerLevels'; import { usePowerLevelsAPI } from '../../hooks/usePowerLevels';
import { useMatrixClient } from '../../hooks/useMatrixClient'; import { useMatrixClient } from '../../hooks/useMatrixClient';
import { RoomInputPlaceholder } from './RoomInputPlaceholder'; import { RoomInputPlaceholder } from './RoomInputPlaceholder';
import { RoomTimeline } from './RoomTimeline';
import { RoomViewTyping } from './RoomViewTyping';
import { RoomViewFollowing } from './RoomViewFollowing';
import { useEditor } from '../../components/editor';
const viewEvent = new EventEmitter(); function RoomView({ room, eventId }) {
function RoomView({ room, roomTimeline, eventId }) {
const roomInputRef = useRef(null); const roomInputRef = useRef(null);
const roomViewRef = useRef(null); const roomViewRef = useRef(null);
// eslint-disable-next-line react/prop-types // eslint-disable-next-line react/prop-types
const { roomId } = roomTimeline; const { roomId } = room;
const editor = useEditor();
const mx = useMatrixClient(); const mx = useMatrixClient();
const tombstoneEvent = useStateEvent(room, StateEvent.RoomTombstone); const tombstoneEvent = useStateEvent(room, StateEvent.RoomTombstone);
const { getPowerLevel, canSendEvent } = usePowerLevels(room); const { getPowerLevel, canSendEvent } = usePowerLevelsAPI();
const myUserId = mx.getUserId(); const myUserId = mx.getUserId();
const canMessage = myUserId const canMessage = myUserId
? canSendEvent(EventType.RoomMessage, getPowerLevel(myUserId)) ? canSendEvent(EventType.RoomMessage, getPowerLevel(myUserId))
@ -61,12 +60,14 @@ function RoomView({ room, roomTimeline, eventId }) {
<RoomViewHeader roomId={roomId} /> <RoomViewHeader roomId={roomId} />
<div className="room-view__content-wrapper"> <div className="room-view__content-wrapper">
<div className="room-view__scrollable"> <div className="room-view__scrollable">
<RoomViewContent <RoomTimeline
key={roomId}
room={room}
eventId={eventId} eventId={eventId}
roomTimeline={roomTimeline}
roomInputRef={roomInputRef} roomInputRef={roomInputRef}
editor={editor}
/> />
<RoomViewFloating roomId={roomId} roomTimeline={roomTimeline} /> <RoomViewTyping room={room} />
</div> </div>
<div className="room-view__sticky"> <div className="room-view__sticky">
<div className="room-view__editor"> <div className="room-view__editor">
@ -79,7 +80,12 @@ function RoomView({ room, roomTimeline, eventId }) {
) : ( ) : (
<> <>
{canMessage && ( {canMessage && (
<RoomInput roomId={roomId} roomViewRef={roomViewRef} ref={roomInputRef} /> <RoomInput
editor={editor}
roomId={roomId}
roomViewRef={roomViewRef}
ref={roomInputRef}
/>
)} )}
{!canMessage && ( {!canMessage && (
<RoomInputPlaceholder <RoomInputPlaceholder
@ -93,7 +99,7 @@ function RoomView({ room, roomTimeline, eventId }) {
</> </>
)} )}
</div> </div>
<RoomViewCmdBar roomId={roomId} roomTimeline={roomTimeline} viewEvent={viewEvent} /> <RoomViewFollowing room={room} />
</div> </div>
</div> </div>
</div> </div>
@ -105,7 +111,6 @@ RoomView.defaultProps = {
}; };
RoomView.propTypes = { RoomView.propTypes = {
room: PropTypes.shape({}).isRequired, room: PropTypes.shape({}).isRequired,
roomTimeline: PropTypes.shape({}).isRequired,
eventId: PropTypes.string, eventId: PropTypes.string,
}; };

View file

@ -0,0 +1,31 @@
import { recipe } from '@vanilla-extract/recipes';
import { DefaultReset, color, config, toRem } from 'folds';
export const RoomViewFollowing = recipe({
base: [
DefaultReset,
{
minHeight: toRem(28),
padding: `0 ${config.space.S400}`,
width: '100%',
backgroundColor: color.Surface.Container,
color: color.Surface.OnContainer,
outline: 'none',
},
],
variants: {
clickable: {
true: {
cursor: 'pointer',
selectors: {
'&:hover, &:focus-visible': {
color: color.Primary.Main,
},
'&:active': {
color: color.Primary.Main,
},
},
},
},
},
});

View file

@ -0,0 +1,141 @@
import React, { useState } from 'react';
import {
Box,
Icon,
Icons,
Modal,
Overlay,
OverlayBackdrop,
OverlayCenter,
Text,
as,
config,
} from 'folds';
import { Room, RoomMember } from 'matrix-js-sdk';
import classNames from 'classnames';
import FocusTrap from 'focus-trap-react';
import { getMemberDisplayName } from '../../utils/room';
import { getMxIdLocalPart } from '../../utils/matrix';
import * as css from './RoomViewFollowing.css';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import { useRoomLatestEvent } from '../../hooks/useRoomLatestEvent';
import { useRoomEventReaders } from '../../hooks/useRoomEventReaders';
import { EventReaders } from '../../components/event-readers';
export type RoomViewFollowingProps = {
room: Room;
};
export const RoomViewFollowing = as<'div', RoomViewFollowingProps>(
({ className, room, ...props }, ref) => {
const mx = useMatrixClient();
const [open, setOpen] = useState(false);
const latestEvent = useRoomLatestEvent(room);
const latestEventReaders = useRoomEventReaders(room, latestEvent?.getId());
const followingMembers = latestEventReaders
.map((readerId) => room.getMember(readerId))
.filter((member) => member && member.userId !== mx.getUserId()) as RoomMember[];
const names = followingMembers.map(
(member) => getMemberDisplayName(room, member.userId) ?? getMxIdLocalPart(member.userId)
);
const eventId = latestEvent?.getId();
return (
<>
{eventId && (
<Overlay open={open} backdrop={<OverlayBackdrop />}>
<OverlayCenter>
<FocusTrap
focusTrapOptions={{
initialFocus: false,
onDeactivate: () => setOpen(false),
clickOutsideDeactivates: true,
}}
>
<Modal variant="Surface" size="300">
<EventReaders room={room} eventId={eventId} requestClose={() => setOpen(false)} />
</Modal>
</FocusTrap>
</OverlayCenter>
</Overlay>
)}
<Box
as={names.length > 0 ? 'button' : 'div'}
onClick={names.length > 0 ? () => setOpen(true) : undefined}
className={classNames(css.RoomViewFollowing({ clickable: names.length > 0 }), className)}
alignItems="Center"
justifyContent="End"
gap="200"
{...props}
ref={ref}
>
{names.length > 0 && (
<>
<Icon style={{ opacity: config.opacity.P300 }} size="100" src={Icons.CheckTwice} />
<Text size="T300" truncate>
{names.length === 1 && (
<>
<b>{names[0]}</b>
<Text as="span" size="Inherit" priority="300">
{' is following the conversation.'}
</Text>
</>
)}
{names.length === 2 && (
<>
<b>{names[0]}</b>
<Text as="span" size="Inherit" priority="300">
{' and '}
</Text>
<b>{names[1]}</b>
<Text as="span" size="Inherit" priority="300">
{' are following the conversation.'}
</Text>
</>
)}
{names.length === 3 && (
<>
<b>{names[0]}</b>
<Text as="span" size="Inherit" priority="300">
{', '}
</Text>
<b>{names[1]}</b>
<Text as="span" size="Inherit" priority="300">
{' and '}
</Text>
<b>{names[2]}</b>
<Text as="span" size="Inherit" priority="300">
{' are following the conversation.'}
</Text>
</>
)}
{names.length > 3 && (
<>
<b>{names[0]}</b>
<Text as="span" size="Inherit" priority="300">
{', '}
</Text>
<b>{names[1]}</b>
<Text as="span" size="Inherit" priority="300">
{', '}
</Text>
<b>{names[2]}</b>
<Text as="span" size="Inherit" priority="300">
{' and '}
</Text>
<b>{names.length - 3} others</b>
<Text as="span" size="Inherit" priority="300">
{' are following the conversation.'}
</Text>
</>
)}
</Text>
</>
)}
</Box>
</>
);
}
);

View file

@ -0,0 +1,24 @@
import { keyframes, style } from '@vanilla-extract/css';
import { DefaultReset, color, config } from 'folds';
const SlideUpAnime = keyframes({
from: {
transform: 'translateY(100%)',
},
to: {
transform: 'translateY(0)',
},
});
export const RoomViewTyping = style([
DefaultReset,
{
padding: `${config.space.S100} ${config.space.S500}`,
width: '100%',
backgroundColor: color.Surface.Container,
color: color.Surface.OnContainer,
position: 'absolute',
bottom: 0,
animation: `${SlideUpAnime} 100ms ease-in-out`,
},
]);

View file

@ -0,0 +1,102 @@
import React, { useMemo } from 'react';
import { Box, Text, as } from 'folds';
import { Room } from 'matrix-js-sdk';
import classNames from 'classnames';
import { useAtomValue } from 'jotai';
import { roomIdToTypingMembersAtom, selectRoomTypingMembersAtom } from '../../state/typingMembers';
import { TypingIndicator } from '../../components/typing-indicator';
import { getMemberDisplayName } from '../../utils/room';
import { getMxIdLocalPart } from '../../utils/matrix';
import * as css from './RoomViewTyping.css';
import { useMatrixClient } from '../../hooks/useMatrixClient';
export type RoomViewTypingProps = {
room: Room;
};
export const RoomViewTyping = as<'div', RoomViewTypingProps>(
({ className, room, ...props }, ref) => {
const mx = useMatrixClient();
const typingMembers = useAtomValue(
useMemo(() => selectRoomTypingMembersAtom(room.roomId, roomIdToTypingMembersAtom), [room])
);
const typingNames = typingMembers
.filter((member) => member.userId !== mx.getUserId())
.map((member) => getMemberDisplayName(room, member.userId) ?? getMxIdLocalPart(member.userId))
.reverse();
if (typingNames.length === 0) {
return null;
}
return (
<Box
className={classNames(css.RoomViewTyping, className)}
alignItems="Center"
gap="400"
{...props}
ref={ref}
>
<TypingIndicator />
<Text size="T300" truncate>
{typingNames.length === 1 && (
<>
<b>{typingNames[0]}</b>
<Text as="span" size="Inherit" priority="300">
{' is typing...'}
</Text>
</>
)}
{typingNames.length === 2 && (
<>
<b>{typingNames[0]}</b>
<Text as="span" size="Inherit" priority="300">
{' and '}
</Text>
<b>{typingNames[1]}</b>
<Text as="span" size="Inherit" priority="300">
{' are typing...'}
</Text>
</>
)}
{typingNames.length === 3 && (
<>
<b>{typingNames[0]}</b>
<Text as="span" size="Inherit" priority="300">
{', '}
</Text>
<b>{typingNames[1]}</b>
<Text as="span" size="Inherit" priority="300">
{' and '}
</Text>
<b>{typingNames[2]}</b>
<Text as="span" size="Inherit" priority="300">
{' are typing...'}
</Text>
</>
)}
{typingNames.length > 3 && (
<>
<b>{typingNames[0]}</b>
<Text as="span" size="Inherit" priority="300">
{', '}
</Text>
<b>{typingNames[1]}</b>
<Text as="span" size="Inherit" priority="300">
{', '}
</Text>
<b>{typingNames[2]}</b>
<Text as="span" size="Inherit" priority="300">
{' and '}
</Text>
<b>{typingNames.length - 3} others</b>
<Text as="span" size="Inherit" priority="300">
{' are typing...'}
</Text>
</>
)}
</Text>
</Box>
);
}
);

View file

@ -0,0 +1,192 @@
/* eslint-disable jsx-a11y/media-has-caption */
import { Badge, Chip, Icon, IconButton, Icons, ProgressBar, Spinner, Text, as, toRem } from 'folds';
import React, { useCallback, useRef, useState } from 'react';
import { EncryptedAttachmentInfo } from 'browser-encrypt-attachment';
import { Range } from 'react-range';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback';
import { getFileSrcUrl } from './util';
import { IAudioInfo } from '../../../../types/matrix/common';
import { MediaControl } from '../../../components/media';
import {
PlayTimeCallback,
useMediaLoading,
useMediaPlay,
useMediaPlayTimeCallback,
useMediaSeek,
useMediaVolume,
} from '../../../hooks/media';
import { useThrottle } from '../../../hooks/useThrottle';
import { secondsToMinutesAndSeconds } from '../../../utils/common';
const PLAY_TIME_THROTTLE_OPS = {
wait: 500,
immediate: true,
};
export type AudioContentProps = {
mimeType: string;
url: string;
info: IAudioInfo;
encInfo?: EncryptedAttachmentInfo;
};
export const AudioContent = as<'div', AudioContentProps>(
({ mimeType, url, info, encInfo, ...props }, ref) => {
const mx = useMatrixClient();
const [srcState, loadSrc] = useAsyncCallback(
useCallback(
() => getFileSrcUrl(mx.mxcUrlToHttp(url) ?? '', mimeType, encInfo),
[mx, url, mimeType, encInfo]
)
);
const audioRef = useRef<HTMLAudioElement | null>(null);
const [currentTime, setCurrentTime] = useState(0);
const [duration, setDuration] = useState(info.duration ?? 0);
const getAudioRef = useCallback(() => audioRef.current, []);
const { loading } = useMediaLoading(getAudioRef);
const { playing, setPlaying } = useMediaPlay(getAudioRef);
const { seek } = useMediaSeek(getAudioRef);
const { volume, mute, setMute, setVolume } = useMediaVolume(getAudioRef);
const handlePlayTimeCallback: PlayTimeCallback = useCallback((d, ct) => {
setDuration(d);
setCurrentTime(ct);
}, []);
useMediaPlayTimeCallback(
getAudioRef,
useThrottle(handlePlayTimeCallback, PLAY_TIME_THROTTLE_OPS)
);
const handlePlay = () => {
if (srcState.status === AsyncStatus.Success) {
setPlaying(!playing);
} else if (srcState.status !== AsyncStatus.Loading) {
loadSrc();
}
};
return (
<MediaControl
after={
<Range
step={1}
min={0}
max={duration || 1}
values={[currentTime]}
onChange={(values) => seek(values[0])}
renderTrack={(params) => (
<div {...params.props}>
{params.children}
<ProgressBar
as="div"
variant="Secondary"
size="300"
min={0}
max={duration}
value={currentTime}
radii="300"
/>
</div>
)}
renderThumb={(params) => (
<Badge
size="300"
variant="Secondary"
fill="Solid"
radii="Pill"
outlined
{...params.props}
style={{
...params.props.style,
zIndex: 0,
}}
/>
)}
/>
}
leftControl={
<>
<Chip
onClick={handlePlay}
variant="Secondary"
radii="300"
disabled={srcState.status === AsyncStatus.Loading}
before={
srcState.status === AsyncStatus.Loading || loading ? (
<Spinner variant="Secondary" size="50" />
) : (
<Icon src={playing ? Icons.Pause : Icons.Play} size="50" filled={playing} />
)
}
>
<Text size="B300">{playing ? 'Pause' : 'Play'}</Text>
</Chip>
<Text size="T200">{`${secondsToMinutesAndSeconds(
currentTime
)} / ${secondsToMinutesAndSeconds(duration)}`}</Text>
</>
}
rightControl={
<>
<IconButton
variant="SurfaceVariant"
size="300"
radii="Pill"
onClick={() => setMute(!mute)}
aria-pressed={mute}
>
<Icon src={mute ? Icons.VolumeMute : Icons.VolumeHigh} size="50" />
</IconButton>
<Range
step={0.1}
min={0}
max={1}
values={[volume]}
onChange={(values) => setVolume(values[0])}
renderTrack={(params) => (
<div {...params.props}>
{params.children}
<ProgressBar
style={{ width: toRem(48) }}
variant="Secondary"
size="300"
min={0}
max={1}
value={volume}
radii="300"
/>
</div>
)}
renderThumb={(params) => (
<Badge
size="300"
variant="Secondary"
fill="Solid"
radii="Pill"
outlined
{...params.props}
style={{
...params.props.style,
zIndex: 0,
}}
/>
)}
/>
</>
}
{...props}
ref={ref}
>
<audio controls={false} autoPlay ref={audioRef}>
{srcState.status === AsyncStatus.Success && (
<source src={srcState.data} type={mimeType} />
)}
</audio>
</MediaControl>
);
}
);

View file

@ -0,0 +1,22 @@
import { MatrixEvent, MatrixEventEvent, MatrixEventHandlerMap } from 'matrix-js-sdk';
import React, { ReactNode, useEffect, useState } from 'react';
type EncryptedContentProps = {
mEvent: MatrixEvent;
children: () => ReactNode;
};
export function EncryptedContent({ mEvent, children }: EncryptedContentProps) {
const [, setDecrypted] = useState(mEvent.isBeingDecrypted());
useEffect(() => {
const handleDecrypted: MatrixEventHandlerMap[MatrixEventEvent.Decrypted] = () =>
setDecrypted(true);
mEvent.on(MatrixEventEvent.Decrypted, handleDecrypted);
return () => {
mEvent.removeListener(MatrixEventEvent.Decrypted, handleDecrypted);
};
}, [mEvent]);
return <>{children()}</>;
}

View file

@ -0,0 +1,37 @@
import { Box, Icon, IconSrc } from 'folds';
import React, { ReactNode } from 'react';
import { CompactLayout, ModernLayout } from '../../../components/message';
export type EventContentProps = {
messageLayout: number;
time: ReactNode;
iconSrc: IconSrc;
content: ReactNode;
};
export function EventContent({ messageLayout, time, iconSrc, content }: EventContentProps) {
const beforeJSX = (
<Box gap="300" justifyContent="SpaceBetween" alignItems="Center" grow="Yes">
{messageLayout === 1 && time}
<Box
grow={messageLayout === 1 ? undefined : 'Yes'}
alignItems="Center"
justifyContent="Center"
>
<Icon style={{ opacity: 0.6 }} size="50" src={iconSrc} />
</Box>
</Box>
);
const msgContentJSX = (
<Box justifyContent="SpaceBetween" alignItems="Baseline" gap="200">
{content}
{messageLayout !== 1 && time}
</Box>
);
return messageLayout === 1 ? (
<CompactLayout before={beforeJSX}>{msgContentJSX}</CompactLayout>
) : (
<ModernLayout before={beforeJSX}>{msgContentJSX}</ModernLayout>
);
}

View file

@ -0,0 +1,250 @@
import React, { useCallback, useState } from 'react';
import {
Box,
Button,
Icon,
Icons,
Modal,
Overlay,
OverlayBackdrop,
OverlayCenter,
Spinner,
Text,
Tooltip,
TooltipProvider,
as,
} from 'folds';
import FileSaver from 'file-saver';
import { EncryptedAttachmentInfo } from 'browser-encrypt-attachment';
import FocusTrap from 'focus-trap-react';
import { IFileInfo } from '../../../../types/matrix/common';
import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { getFileSrcUrl, getSrcFile } from './util';
import { bytesToSize } from '../../../utils/common';
import { TextViewer } from '../../../components/text-viewer';
import { READABLE_TEXT_MIME_TYPES } from '../../../utils/mimeTypes';
import { PdfViewer } from '../../../components/Pdf-viewer';
export type FileContentProps = {
body: string;
mimeType: string;
url: string;
info: IFileInfo;
encInfo?: EncryptedAttachmentInfo;
};
const renderErrorButton = (retry: () => void, text: string) => (
<TooltipProvider
tooltip={
<Tooltip variant="Critical">
<Text>Failed to load file!</Text>
</Tooltip>
}
position="Top"
align="Center"
>
{(triggerRef) => (
<Button
ref={triggerRef}
size="400"
variant="Critical"
fill="Soft"
outlined
radii="300"
onClick={retry}
before={<Icon size="100" src={Icons.Warning} filled />}
>
<Text size="B400" truncate>
{text}
</Text>
</Button>
)}
</TooltipProvider>
);
function ReadTextFile({ body, mimeType, url, encInfo }: Omit<FileContentProps, 'info'>) {
const mx = useMatrixClient();
const [textViewer, setTextViewer] = useState(false);
const loadSrc = useCallback(
() => getFileSrcUrl(mx.mxcUrlToHttp(url) ?? '', mimeType, encInfo),
[mx, url, mimeType, encInfo]
);
const [textState, loadText] = useAsyncCallback(
useCallback(async () => {
const src = await loadSrc();
const blob = await getSrcFile(src);
const text = blob.text();
setTextViewer(true);
return text;
}, [loadSrc])
);
return (
<>
{textState.status === AsyncStatus.Success && (
<Overlay open={textViewer} backdrop={<OverlayBackdrop />}>
<OverlayCenter>
<FocusTrap
focusTrapOptions={{
initialFocus: false,
onDeactivate: () => setTextViewer(false),
clickOutsideDeactivates: true,
}}
>
<Modal size="500">
<TextViewer
name={body}
text={textState.data}
mimeType={mimeType}
requestClose={() => setTextViewer(false)}
/>
</Modal>
</FocusTrap>
</OverlayCenter>
</Overlay>
)}
{textState.status === AsyncStatus.Error ? (
renderErrorButton(loadText, 'Open File')
) : (
<Button
variant="Secondary"
fill="Solid"
radii="300"
size="400"
onClick={() =>
textState.status === AsyncStatus.Success ? setTextViewer(true) : loadText()
}
disabled={textState.status === AsyncStatus.Loading}
before={
textState.status === AsyncStatus.Loading ? (
<Spinner fill="Solid" size="100" variant="Secondary" />
) : (
<Icon size="100" src={Icons.ArrowRight} filled />
)
}
>
<Text size="B400" truncate>
Open File
</Text>
</Button>
)}
</>
);
}
function ReadPdfFile({ body, mimeType, url, encInfo }: Omit<FileContentProps, 'info'>) {
const mx = useMatrixClient();
const [pdfViewer, setPdfViewer] = useState(false);
const [pdfState, loadPdf] = useAsyncCallback(
useCallback(async () => {
const httpUrl = await getFileSrcUrl(mx.mxcUrlToHttp(url) ?? '', mimeType, encInfo);
setPdfViewer(true);
return httpUrl;
}, [mx, url, mimeType, encInfo])
);
return (
<>
{pdfState.status === AsyncStatus.Success && (
<Overlay open={pdfViewer} backdrop={<OverlayBackdrop />}>
<OverlayCenter>
<FocusTrap
focusTrapOptions={{
initialFocus: false,
onDeactivate: () => setPdfViewer(false),
clickOutsideDeactivates: true,
}}
>
<Modal size="500">
<PdfViewer
name={body}
src={pdfState.data}
requestClose={() => setPdfViewer(false)}
/>
</Modal>
</FocusTrap>
</OverlayCenter>
</Overlay>
)}
{pdfState.status === AsyncStatus.Error ? (
renderErrorButton(loadPdf, 'Open PDF')
) : (
<Button
variant="Secondary"
fill="Solid"
radii="300"
size="400"
onClick={() => (pdfState.status === AsyncStatus.Success ? setPdfViewer(true) : loadPdf())}
disabled={pdfState.status === AsyncStatus.Loading}
before={
pdfState.status === AsyncStatus.Loading ? (
<Spinner fill="Solid" size="100" variant="Secondary" />
) : (
<Icon size="100" src={Icons.ArrowRight} filled />
)
}
>
<Text size="B400" truncate>
Open PDF
</Text>
</Button>
)}
</>
);
}
function DownloadFile({ body, mimeType, url, info, encInfo }: FileContentProps) {
const mx = useMatrixClient();
const [downloadState, download] = useAsyncCallback(
useCallback(async () => {
const httpUrl = await getFileSrcUrl(mx.mxcUrlToHttp(url) ?? '', mimeType, encInfo);
FileSaver.saveAs(httpUrl, body);
return httpUrl;
}, [mx, url, mimeType, encInfo, body])
);
return downloadState.status === AsyncStatus.Error ? (
renderErrorButton(download, `Retry Download (${bytesToSize(info.size ?? 0)})`)
) : (
<Button
variant="Secondary"
fill="Soft"
radii="300"
size="400"
onClick={() =>
downloadState.status === AsyncStatus.Success
? FileSaver.saveAs(downloadState.data, body)
: download()
}
disabled={downloadState.status === AsyncStatus.Loading}
before={
downloadState.status === AsyncStatus.Loading ? (
<Spinner fill="Soft" size="100" variant="Secondary" />
) : (
<Icon size="100" src={Icons.Download} filled />
)
}
>
<Text size="B400" truncate>{`Download (${bytesToSize(info.size ?? 0)})`}</Text>
</Button>
);
}
export const FileContent = as<'div', FileContentProps>(
({ body, mimeType, url, info, encInfo, ...props }, ref) => (
<Box direction="Column" gap="300" {...props} ref={ref}>
{READABLE_TEXT_MIME_TYPES.includes(mimeType) && (
<ReadTextFile body={body} mimeType={mimeType} url={url} encInfo={encInfo} />
)}
{mimeType === 'application/pdf' && (
<ReadPdfFile body={body} mimeType={mimeType} url={url} encInfo={encInfo} />
)}
<DownloadFile body={body} mimeType={mimeType} url={url} info={info} encInfo={encInfo} />
</Box>
)
);

View file

@ -0,0 +1,22 @@
import { Badge, Box, Text, as, toRem } from 'folds';
import React from 'react';
import { mimeTypeToExt } from '../../../utils/mimeTypes';
const badgeStyles = { maxWidth: toRem(100) };
export type FileHeaderProps = {
body: string;
mimeType: string;
};
export const FileHeader = as<'div', FileHeaderProps>(({ body, mimeType, ...props }, ref) => (
<Box alignItems="Center" gap="200" grow="Yes" {...props} ref={ref}>
<Badge style={badgeStyles} variant="Secondary" radii="Pill">
<Text size="O400" truncate>
{mimeTypeToExt(mimeType)}
</Text>
</Badge>
<Text size="T300" truncate>
{body}
</Text>
</Box>
));

View file

@ -0,0 +1,170 @@
import React, { useCallback, useEffect, useState } from 'react';
import {
Badge,
Box,
Button,
Icon,
Icons,
Modal,
Overlay,
OverlayBackdrop,
OverlayCenter,
Spinner,
Text,
Tooltip,
TooltipProvider,
as,
} from 'folds';
import classNames from 'classnames';
import { BlurhashCanvas } from 'react-blurhash';
import FocusTrap from 'focus-trap-react';
import { EncryptedAttachmentInfo } from 'browser-encrypt-attachment';
import { IImageInfo, MATRIX_BLUR_HASH_PROPERTY_NAME } from '../../../../types/matrix/common';
import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { getFileSrcUrl } from './util';
import { Image } from '../../../components/media';
import * as css from './styles.css';
import { bytesToSize } from '../../../utils/common';
import { ImageViewer } from '../../../components/image-viewer';
export type ImageContentProps = {
body: string;
mimeType: string;
url: string;
info: IImageInfo;
encInfo?: EncryptedAttachmentInfo;
autoPlay?: boolean;
};
export const ImageContent = as<'div', ImageContentProps>(
({ className, body, mimeType, url, info, encInfo, autoPlay, ...props }, ref) => {
const mx = useMatrixClient();
const blurHash = info[MATRIX_BLUR_HASH_PROPERTY_NAME];
const [load, setLoad] = useState(false);
const [error, setError] = useState(false);
const [viewer, setViewer] = useState(false);
const [srcState, loadSrc] = useAsyncCallback(
useCallback(
() => getFileSrcUrl(mx.mxcUrlToHttp(url) ?? '', mimeType, encInfo),
[mx, url, mimeType, encInfo]
)
);
const handleLoad = () => {
setLoad(true);
};
const handleError = () => {
setLoad(false);
setError(true);
};
const handleRetry = () => {
setError(false);
loadSrc();
};
useEffect(() => {
if (autoPlay) loadSrc();
}, [autoPlay, loadSrc]);
return (
<Box className={classNames(css.RelativeBase, className)} {...props} ref={ref}>
{srcState.status === AsyncStatus.Success && (
<Overlay open={viewer} backdrop={<OverlayBackdrop />}>
<OverlayCenter>
<FocusTrap
focusTrapOptions={{
initialFocus: false,
onDeactivate: () => setViewer(false),
clickOutsideDeactivates: true,
}}
>
<Modal size="500">
<ImageViewer
src={srcState.data}
alt={body}
requestClose={() => setViewer(false)}
/>
</Modal>
</FocusTrap>
</OverlayCenter>
</Overlay>
)}
{typeof blurHash === 'string' && !load && (
<BlurhashCanvas style={{ width: '100%', height: '100%' }} hash={blurHash} punch={1} />
)}
{!autoPlay && srcState.status === AsyncStatus.Idle && (
<Box className={css.AbsoluteContainer} alignItems="Center" justifyContent="Center">
<Button
variant="Secondary"
fill="Solid"
radii="300"
size="300"
onClick={loadSrc}
before={<Icon size="Inherit" src={Icons.Photo} filled />}
>
<Text size="B300">View</Text>
</Button>
</Box>
)}
{srcState.status === AsyncStatus.Success && (
<Box className={css.AbsoluteContainer}>
<Image
alt={body}
title={body}
src={srcState.data}
loading="lazy"
onLoad={handleLoad}
onError={handleError}
onClick={() => setViewer(true)}
tabIndex={0}
/>
</Box>
)}
{(srcState.status === AsyncStatus.Loading || srcState.status === AsyncStatus.Success) &&
!load && (
<Box className={css.AbsoluteContainer} alignItems="Center" justifyContent="Center">
<Spinner variant="Secondary" />
</Box>
)}
{(error || srcState.status === AsyncStatus.Error) && (
<Box className={css.AbsoluteContainer} alignItems="Center" justifyContent="Center">
<TooltipProvider
tooltip={
<Tooltip variant="Critical">
<Text>Failed to load image!</Text>
</Tooltip>
}
position="Top"
align="Center"
>
{(triggerRef) => (
<Button
ref={triggerRef}
size="300"
variant="Critical"
fill="Soft"
outlined
radii="300"
onClick={handleRetry}
before={<Icon size="Inherit" src={Icons.Warning} filled />}
>
<Text size="B300">Retry</Text>
</Button>
)}
</TooltipProvider>
</Box>
)}
{!load && typeof info.size === 'number' && (
<Box className={css.AbsoluteFooter} justifyContent="End" alignContent="Center" gap="200">
<Badge variant="Secondary" fill="Soft">
<Text size="L400">{bytesToSize(info.size)}</Text>
</Badge>
</Box>
)}
</Box>
);
}
);

View file

@ -0,0 +1,993 @@
import {
Avatar,
AvatarFallback,
AvatarImage,
Box,
Button,
Dialog,
Header,
Icon,
IconButton,
Icons,
Input,
Line,
Menu,
MenuItem,
Modal,
Overlay,
OverlayBackdrop,
OverlayCenter,
PopOut,
Spinner,
Text,
as,
color,
config,
} from 'folds';
import React, {
FormEventHandler,
MouseEventHandler,
ReactNode,
useCallback,
useState,
} from 'react';
import FocusTrap from 'focus-trap-react';
import { MatrixEvent, Room } from 'matrix-js-sdk';
import { Relations } from 'matrix-js-sdk/lib/models/relations';
import classNames from 'classnames';
import {
AvatarBase,
BubbleLayout,
CompactLayout,
MessageBase,
ModernLayout,
Time,
Username,
} from '../../../components/message';
import colorMXID from '../../../../util/colorMXID';
import { getMemberAvatarMxc, getMemberDisplayName } from '../../../utils/room';
import { getMxIdLocalPart } from '../../../utils/matrix';
import { MessageLayout, MessageSpacing } from '../../../state/settings';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { useRecentEmoji } from '../../../hooks/useRecentEmoji';
import * as css from './styles.css';
import { EventReaders } from '../../../components/event-readers';
import { TextViewer } from '../../../components/text-viewer';
import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback';
import { EmojiBoard } from '../../../components/emoji-board';
import { ReactionViewer } from '../reaction-viewer';
export type ReactionHandler = (keyOrMxc: string, shortcode: string) => void;
type MessageQuickReactionsProps = {
onReaction: ReactionHandler;
};
export const MessageQuickReactions = as<'div', MessageQuickReactionsProps>(
({ onReaction, ...props }, ref) => {
const mx = useMatrixClient();
const recentEmojis = useRecentEmoji(mx, 4);
if (recentEmojis.length === 0) return <span />;
return (
<>
<Box
style={{ padding: config.space.S200 }}
alignItems="Center"
justifyContent="Center"
gap="200"
{...props}
ref={ref}
>
{recentEmojis.map((emoji) => (
<IconButton
key={emoji.unicode}
className={css.MessageQuickReaction}
size="300"
variant="SurfaceVariant"
radii="Pill"
title={emoji.shortcode}
aria-label={emoji.shortcode}
onClick={() => onReaction(emoji.unicode, emoji.shortcode)}
>
<Text size="T500">{emoji.unicode}</Text>
</IconButton>
))}
</Box>
<Line size="300" />
</>
);
}
);
export const MessageAllReactionItem = as<
'button',
{
room: Room;
relations: Relations;
onClose?: () => void;
}
>(({ room, relations, onClose, ...props }, ref) => {
const [open, setOpen] = useState(false);
const handleClose = () => {
setOpen(false);
onClose?.();
};
return (
<>
<Overlay
onContextMenu={(evt: any) => {
evt.stopPropagation();
}}
open={open}
backdrop={<OverlayBackdrop />}
>
<OverlayCenter>
<FocusTrap
focusTrapOptions={{
initialFocus: false,
returnFocusOnDeactivate: false,
onDeactivate: () => handleClose(),
clickOutsideDeactivates: true,
}}
>
<Modal variant="Surface" size="300">
<ReactionViewer
room={room}
relations={relations}
requestClose={() => setOpen(false)}
/>
</Modal>
</FocusTrap>
</OverlayCenter>
</Overlay>
<MenuItem
size="300"
after={<Icon size="100" src={Icons.Smile} />}
radii="300"
onClick={() => setOpen(true)}
{...props}
ref={ref}
aria-pressed={open}
>
<Text className={css.MessageMenuItemText} as="span" size="T300" truncate>
View Reactions
</Text>
</MenuItem>
</>
);
});
export const MessageReadReceiptItem = as<
'button',
{
room: Room;
eventId: string;
onClose?: () => void;
}
>(({ room, eventId, onClose, ...props }, ref) => {
const [open, setOpen] = useState(false);
const handleClose = () => {
setOpen(false);
onClose?.();
};
return (
<>
<Overlay open={open} backdrop={<OverlayBackdrop />}>
<OverlayCenter>
<FocusTrap
focusTrapOptions={{
initialFocus: false,
onDeactivate: handleClose,
clickOutsideDeactivates: true,
}}
>
<Modal variant="Surface" size="300">
<EventReaders room={room} eventId={eventId} requestClose={handleClose} />
</Modal>
</FocusTrap>
</OverlayCenter>
</Overlay>
<MenuItem
size="300"
after={<Icon size="100" src={Icons.CheckTwice} />}
radii="300"
onClick={() => setOpen(true)}
{...props}
ref={ref}
aria-pressed={open}
>
<Text className={css.MessageMenuItemText} as="span" size="T300" truncate>
Read Receipts
</Text>
</MenuItem>
</>
);
});
export const MessageSourceCodeItem = as<
'button',
{
mEvent: MatrixEvent;
onClose?: () => void;
}
>(({ mEvent, onClose, ...props }, ref) => {
const [open, setOpen] = useState(false);
const text = JSON.stringify(
mEvent.isEncrypted()
? {
[`<== DECRYPTED_EVENT ==>`]: mEvent.getEffectiveEvent(),
[`<== ORIGINAL_EVENT ==>`]: mEvent.event,
}
: mEvent.event,
null,
2
);
const handleClose = () => {
setOpen(false);
onClose?.();
};
return (
<>
<Overlay open={open} backdrop={<OverlayBackdrop />}>
<OverlayCenter>
<FocusTrap
focusTrapOptions={{
initialFocus: false,
onDeactivate: handleClose,
clickOutsideDeactivates: true,
}}
>
<Modal variant="Surface" size="500">
<TextViewer
name="Source Code"
mimeType="application/json"
text={text}
requestClose={handleClose}
/>
</Modal>
</FocusTrap>
</OverlayCenter>
</Overlay>
<MenuItem
size="300"
after={<Icon size="100" src={Icons.BlockCode} />}
radii="300"
onClick={() => setOpen(true)}
{...props}
ref={ref}
aria-pressed={open}
>
<Text className={css.MessageMenuItemText} as="span" size="T300" truncate>
View Source
</Text>
</MenuItem>
</>
);
});
export const MessageDeleteItem = as<
'button',
{
room: Room;
mEvent: MatrixEvent;
onClose?: () => void;
}
>(({ room, mEvent, onClose, ...props }, ref) => {
const mx = useMatrixClient();
const [open, setOpen] = useState(false);
const [deleteState, deleteMessage] = useAsyncCallback(
useCallback(
(eventId: string, reason?: string) =>
mx.redactEvent(room.roomId, eventId, undefined, reason ? { reason } : undefined),
[mx, room]
)
);
const handleSubmit: FormEventHandler<HTMLFormElement> = (evt) => {
evt.preventDefault();
const eventId = mEvent.getId();
if (
!eventId ||
deleteState.status === AsyncStatus.Loading ||
deleteState.status === AsyncStatus.Success
)
return;
const target = evt.target as HTMLFormElement | undefined;
const reasonInput = target?.reasonInput as HTMLInputElement | undefined;
const reason = reasonInput && reasonInput.value.trim();
deleteMessage(eventId, reason);
};
const handleClose = () => {
setOpen(false);
onClose?.();
};
return (
<>
<Overlay open={open} backdrop={<OverlayBackdrop />}>
<OverlayCenter>
<FocusTrap
focusTrapOptions={{
initialFocus: false,
onDeactivate: handleClose,
clickOutsideDeactivates: true,
}}
>
<Dialog variant="Surface">
<Header
style={{
padding: `0 ${config.space.S200} 0 ${config.space.S400}`,
borderBottomWidth: config.borderWidth.B300,
}}
variant="Surface"
size="500"
>
<Box grow="Yes">
<Text size="H4">Delete Message</Text>
</Box>
<IconButton size="300" onClick={handleClose} radii="300">
<Icon src={Icons.Cross} />
</IconButton>
</Header>
<Box
as="form"
onSubmit={handleSubmit}
style={{ padding: config.space.S400 }}
direction="Column"
gap="400"
>
<Text priority="400">
This action is irreversible! Are you sure that you want to delete this message?
</Text>
<Box direction="Column" gap="100">
<Text size="L400">
Reason{' '}
<Text as="span" size="T200">
(optional)
</Text>
</Text>
<Input name="reasonInput" variant="Background" />
{deleteState.status === AsyncStatus.Error && (
<Text style={{ color: color.Critical.Main }} size="T300">
Failed to delete message! Please try again.
</Text>
)}
</Box>
<Button
type="submit"
variant="Critical"
before={
deleteState.status === AsyncStatus.Loading ? (
<Spinner fill="Soft" variant="Critical" size="200" />
) : undefined
}
aria-disabled={deleteState.status === AsyncStatus.Loading}
>
<Text size="B400">
{deleteState.status === AsyncStatus.Loading ? 'Deleting...' : 'Delete'}
</Text>
</Button>
</Box>
</Dialog>
</FocusTrap>
</OverlayCenter>
</Overlay>
<Button
variant="Critical"
fill="None"
size="300"
after={<Icon size="100" src={Icons.Delete} />}
radii="300"
onClick={() => setOpen(true)}
aria-pressed={open}
{...props}
ref={ref}
>
<Text className={css.MessageMenuItemText} as="span" size="T300" truncate>
Delete
</Text>
</Button>
</>
);
});
export const MessageReportItem = as<
'button',
{
room: Room;
mEvent: MatrixEvent;
onClose?: () => void;
}
>(({ room, mEvent, onClose, ...props }, ref) => {
const mx = useMatrixClient();
const [open, setOpen] = useState(false);
const [reportState, reportMessage] = useAsyncCallback(
useCallback(
(eventId: string, score: number, reason: string) =>
mx.reportEvent(room.roomId, eventId, score, reason),
[mx, room]
)
);
const handleSubmit: FormEventHandler<HTMLFormElement> = (evt) => {
evt.preventDefault();
const eventId = mEvent.getId();
if (
!eventId ||
reportState.status === AsyncStatus.Loading ||
reportState.status === AsyncStatus.Success
)
return;
const target = evt.target as HTMLFormElement | undefined;
const reasonInput = target?.reasonInput as HTMLInputElement | undefined;
const reason = reasonInput && reasonInput.value.trim();
if (reasonInput) reasonInput.value = '';
reportMessage(eventId, reason ? -100 : -50, reason || 'No reason provided');
};
const handleClose = () => {
setOpen(false);
onClose?.();
};
return (
<>
<Overlay open={open} backdrop={<OverlayBackdrop />}>
<OverlayCenter>
<FocusTrap
focusTrapOptions={{
initialFocus: false,
onDeactivate: handleClose,
clickOutsideDeactivates: true,
}}
>
<Dialog variant="Surface">
<Header
style={{
padding: `0 ${config.space.S200} 0 ${config.space.S400}`,
borderBottomWidth: config.borderWidth.B300,
}}
variant="Surface"
size="500"
>
<Box grow="Yes">
<Text size="H4">Report Message</Text>
</Box>
<IconButton size="300" onClick={handleClose} radii="300">
<Icon src={Icons.Cross} />
</IconButton>
</Header>
<Box
as="form"
onSubmit={handleSubmit}
style={{ padding: config.space.S400 }}
direction="Column"
gap="400"
>
<Text priority="400">
Report this message to server, which may then notify the appropriate people to
take action.
</Text>
<Box direction="Column" gap="100">
<Text size="L400">Reason</Text>
<Input name="reasonInput" variant="Background" required />
{reportState.status === AsyncStatus.Error && (
<Text style={{ color: color.Critical.Main }} size="T300">
Failed to report message! Please try again.
</Text>
)}
{reportState.status === AsyncStatus.Success && (
<Text style={{ color: color.Success.Main }} size="T300">
Message has been reported to server.
</Text>
)}
</Box>
<Button
type="submit"
variant="Critical"
before={
reportState.status === AsyncStatus.Loading ? (
<Spinner fill="Soft" variant="Critical" size="200" />
) : undefined
}
aria-disabled={
reportState.status === AsyncStatus.Loading ||
reportState.status === AsyncStatus.Success
}
>
<Text size="B400">
{reportState.status === AsyncStatus.Loading ? 'Reporting...' : 'Report'}
</Text>
</Button>
</Box>
</Dialog>
</FocusTrap>
</OverlayCenter>
</Overlay>
<Button
variant="Critical"
fill="None"
size="300"
after={<Icon size="100" src={Icons.Warning} />}
radii="300"
onClick={() => setOpen(true)}
aria-pressed={open}
{...props}
ref={ref}
>
<Text className={css.MessageMenuItemText} as="span" size="T300" truncate>
Report
</Text>
</Button>
</>
);
});
export type MessageProps = {
room: Room;
mEvent: MatrixEvent;
collapse: boolean;
highlight: boolean;
canDelete?: boolean;
canSendReaction?: boolean;
imagePackRooms?: Room[];
relations?: Relations;
messageLayout: MessageLayout;
messageSpacing: MessageSpacing;
onUserClick: MouseEventHandler<HTMLButtonElement>;
onUsernameClick: MouseEventHandler<HTMLButtonElement>;
onReplyClick: MouseEventHandler<HTMLButtonElement>;
onReactionToggle: (targetEventId: string, key: string, shortcode?: string) => void;
reply?: ReactNode;
reactions?: ReactNode;
};
export const Message = as<'div', MessageProps>(
(
{
className,
room,
mEvent,
collapse,
highlight,
canDelete,
canSendReaction,
imagePackRooms,
relations,
messageLayout,
messageSpacing,
onUserClick,
onUsernameClick,
onReplyClick,
onReactionToggle,
reply,
reactions,
children,
...props
},
ref
) => {
const mx = useMatrixClient();
const senderId = mEvent.getSender() ?? '';
const [hover, setHover] = useState(false);
const [menu, setMenu] = useState(false);
const [emojiBoard, setEmojiBoard] = useState(false);
const senderDisplayName =
getMemberDisplayName(room, senderId) ?? getMxIdLocalPart(senderId) ?? senderId;
const senderAvatarMxc = getMemberAvatarMxc(room, senderId);
const headerJSX = !collapse && (
<Box
gap="300"
direction={messageLayout === 1 ? 'RowReverse' : 'Row'}
justifyContent="SpaceBetween"
alignItems="Baseline"
grow="Yes"
>
<Username
as="button"
style={{ color: colorMXID(senderId) }}
data-user-id={senderId}
onContextMenu={onUserClick}
onClick={onUsernameClick}
>
<Text as="span" size={messageLayout === 2 ? 'T300' : 'T400'} truncate>
<b>{senderDisplayName}</b>
</Text>
</Username>
<Box shrink="No" gap="100">
{messageLayout !== 1 && hover && (
<>
<Text as="span" size="T200" priority="300">
{senderId}
</Text>
<Text as="span" size="T200" priority="300">
|
</Text>
</>
)}
<Time ts={mEvent.getTs()} compact={messageLayout === 1} />
</Box>
</Box>
);
const avatarJSX = !collapse && messageLayout !== 1 && (
<AvatarBase>
<Avatar as="button" size="300" data-user-id={senderId} onClick={onUserClick}>
{senderAvatarMxc ? (
<AvatarImage
src={mx.mxcUrlToHttp(senderAvatarMxc, 48, 48, 'crop') ?? senderAvatarMxc}
/>
) : (
<AvatarFallback
style={{
background: colorMXID(senderId),
color: 'white',
}}
>
<Text size="H4">{senderDisplayName[0]}</Text>
</AvatarFallback>
)}
</Avatar>
</AvatarBase>
);
const msgContentJSX = (
<Box direction="Column" alignSelf="Start" style={{ maxWidth: '100%' }}>
{reply}
{children}
{reactions}
</Box>
);
const showOptions = () => setHover(true);
const hideOptions = () => setHover(false);
const handleContextMenu: MouseEventHandler<HTMLDivElement> = (evt) => {
if (evt.altKey) return;
const tag = (evt.target as any).tagName;
if (typeof tag === 'string' && tag.toLowerCase() === 'a') return;
evt.preventDefault();
setMenu(true);
};
const closeMenu = () => {
setMenu(false);
};
return (
<MessageBase
className={classNames(css.MessageBase, className)}
tabIndex={0}
space={messageSpacing}
collapse={collapse}
highlight={highlight}
selected={menu || emojiBoard}
{...props}
onMouseEnter={showOptions}
onMouseLeave={hideOptions}
ref={ref}
>
{(hover || menu || emojiBoard) && (
<div className={css.MessageOptionsBase}>
<Menu className={css.MessageOptionsBar} variant="SurfaceVariant">
<Box gap="100">
{canSendReaction && (
<PopOut
alignOffset={-65}
position="Bottom"
align="End"
open={emojiBoard}
content={
<EmojiBoard
imagePackRooms={imagePackRooms ?? []}
returnFocusOnDeactivate={false}
onEmojiSelect={(key) => {
onReactionToggle(mEvent.getId()!, key);
setEmojiBoard(false);
}}
onCustomEmojiSelect={(mxc, shortcode) => {
onReactionToggle(mEvent.getId()!, mxc, shortcode);
setEmojiBoard(false);
}}
requestClose={() => {
setEmojiBoard(false);
}}
/>
}
>
{(anchorRef) => (
<IconButton
ref={anchorRef}
onClick={() => setEmojiBoard(true)}
variant="SurfaceVariant"
size="300"
radii="300"
aria-pressed={emojiBoard}
>
<Icon src={Icons.SmilePlus} size="100" />
</IconButton>
)}
</PopOut>
)}
<IconButton
onClick={onReplyClick}
data-event-id={mEvent.getId()}
variant="SurfaceVariant"
size="300"
radii="300"
>
<Icon src={Icons.ReplyArrow} size="100" />
</IconButton>
<PopOut
open={menu}
alignOffset={-5}
position="Bottom"
align="End"
content={
<FocusTrap
focusTrapOptions={{
initialFocus: false,
onDeactivate: () => setMenu(false),
clickOutsideDeactivates: true,
isKeyForward: (evt: KeyboardEvent) => evt.key === 'ArrowDown',
isKeyBackward: (evt: KeyboardEvent) => evt.key === 'ArrowUp',
}}
>
<Menu {...props} ref={ref}>
{canSendReaction && (
<MessageQuickReactions
onReaction={(key, shortcode) => {
onReactionToggle(mEvent.getId()!, key, shortcode);
closeMenu();
}}
/>
)}
<Box direction="Column" gap="100" className={css.MessageMenuGroup}>
{canSendReaction && (
<MenuItem
size="300"
after={<Icon size="100" src={Icons.SmilePlus} />}
radii="300"
onClick={() => {
closeMenu();
// open it with timeout because closeMenu
// FocusTrap will return focus from emojiBoard
setTimeout(() => setEmojiBoard(true), 100);
}}
>
<Text
className={css.MessageMenuItemText}
as="span"
size="T300"
truncate
>
Add Reaction
</Text>
</MenuItem>
)}
{relations && (
<MessageAllReactionItem
room={room}
relations={relations}
onClose={closeMenu}
/>
)}
<MenuItem
size="300"
after={<Icon size="100" src={Icons.ReplyArrow} />}
radii="300"
data-event-id={mEvent.getId()}
onClick={(evt: any) => {
onReplyClick(evt);
closeMenu();
}}
>
<Text
className={css.MessageMenuItemText}
as="span"
size="T300"
truncate
>
Reply
</Text>
</MenuItem>
<MessageReadReceiptItem
room={room}
eventId={mEvent.getId() ?? ''}
onClose={closeMenu}
/>
<MessageSourceCodeItem mEvent={mEvent} onClose={closeMenu} />
</Box>
{((!mEvent.isRedacted() && canDelete) ||
mEvent.getSender() !== mx.getUserId()) && (
<>
<Line size="300" />
<Box direction="Column" gap="100" className={css.MessageMenuGroup}>
{!mEvent.isRedacted() && canDelete && (
<MessageDeleteItem
room={room}
mEvent={mEvent}
onClose={closeMenu}
/>
)}
{mEvent.getSender() !== mx.getUserId() && (
<MessageReportItem
room={room}
mEvent={mEvent}
onClose={closeMenu}
/>
)}
</Box>
</>
)}
</Menu>
</FocusTrap>
}
>
{(targetRef) => (
<IconButton
ref={targetRef}
variant="SurfaceVariant"
size="300"
radii="300"
onClick={() => setMenu((v) => !v)}
aria-pressed={menu}
>
<Icon src={Icons.VerticalDots} size="100" />
</IconButton>
)}
</PopOut>
</Box>
</Menu>
</div>
)}
{messageLayout === 1 && (
<CompactLayout before={headerJSX} onContextMenu={handleContextMenu}>
{msgContentJSX}
</CompactLayout>
)}
{messageLayout === 2 && (
<BubbleLayout before={avatarJSX} onContextMenu={handleContextMenu}>
{headerJSX}
{msgContentJSX}
</BubbleLayout>
)}
{messageLayout !== 1 && messageLayout !== 2 && (
<ModernLayout before={avatarJSX} onContextMenu={handleContextMenu}>
{headerJSX}
{msgContentJSX}
</ModernLayout>
)}
</MessageBase>
);
}
);
export type EventProps = {
room: Room;
mEvent: MatrixEvent;
highlight: boolean;
canDelete?: boolean;
messageSpacing: MessageSpacing;
};
export const Event = as<'div', EventProps>(
({ className, room, mEvent, highlight, canDelete, messageSpacing, children, ...props }, ref) => {
const mx = useMatrixClient();
const [hover, setHover] = useState(false);
const [menu, setMenu] = useState(false);
const stateEvent = typeof mEvent.getStateKey() === 'string';
const showOptions = () => setHover(true);
const hideOptions = () => setHover(false);
const handleContextMenu: MouseEventHandler<HTMLDivElement> = (evt) => {
if (evt.altKey) return;
const tag = (evt.target as any).tagName;
if (typeof tag === 'string' && tag.toLowerCase() === 'a') return;
evt.preventDefault();
setMenu(true);
};
const closeMenu = () => {
setMenu(false);
};
return (
<MessageBase
className={classNames(css.MessageBase, className)}
tabIndex={0}
space={messageSpacing}
autoCollapse
highlight={highlight}
selected={menu}
{...props}
onMouseEnter={showOptions}
onMouseLeave={hideOptions}
ref={ref}
>
{(hover || menu) && (
<div className={css.MessageOptionsBase}>
<Menu className={css.MessageOptionsBar} variant="SurfaceVariant">
<Box gap="100">
<PopOut
open={menu}
alignOffset={-5}
position="Bottom"
align="End"
content={
<FocusTrap
focusTrapOptions={{
initialFocus: false,
onDeactivate: () => setMenu(false),
clickOutsideDeactivates: true,
isKeyForward: (evt: KeyboardEvent) => evt.key === 'ArrowDown',
isKeyBackward: (evt: KeyboardEvent) => evt.key === 'ArrowUp',
}}
>
<Menu {...props} ref={ref}>
<Box direction="Column" gap="100" className={css.MessageMenuGroup}>
<MessageReadReceiptItem
room={room}
eventId={mEvent.getId() ?? ''}
onClose={closeMenu}
/>
<MessageSourceCodeItem mEvent={mEvent} onClose={closeMenu} />
</Box>
{((!mEvent.isRedacted() && canDelete && !stateEvent) ||
(mEvent.getSender() !== mx.getUserId() && !stateEvent)) && (
<>
<Line size="300" />
<Box direction="Column" gap="100" className={css.MessageMenuGroup}>
{!mEvent.isRedacted() && canDelete && (
<MessageDeleteItem
room={room}
mEvent={mEvent}
onClose={closeMenu}
/>
)}
{mEvent.getSender() !== mx.getUserId() && (
<MessageReportItem
room={room}
mEvent={mEvent}
onClose={closeMenu}
/>
)}
</Box>
</>
)}
</Menu>
</FocusTrap>
}
>
{(targetRef) => (
<IconButton
ref={targetRef}
variant="SurfaceVariant"
size="300"
radii="300"
onClick={() => setMenu((v) => !v)}
aria-pressed={menu}
>
<Icon src={Icons.VerticalDots} size="100" />
</IconButton>
)}
</PopOut>
</Box>
</Menu>
</div>
)}
<div onContextMenu={handleContextMenu}>{children}</div>
</MessageBase>
);
}
);

View file

@ -0,0 +1,133 @@
import React, { MouseEventHandler, useCallback, useState } from 'react';
import {
Box,
Modal,
Overlay,
OverlayBackdrop,
OverlayCenter,
Text,
Tooltip,
TooltipProvider,
as,
toRem,
} from 'folds';
import classNames from 'classnames';
import { EventTimelineSet, EventType, RelationType, Room } from 'matrix-js-sdk';
import { type Relations } from 'matrix-js-sdk/lib/models/relations';
import FocusTrap from 'focus-trap-react';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { factoryEventSentBy } from '../../../utils/matrix';
import { Reaction, ReactionTooltipMsg } from '../../../components/message';
import { useRelations } from '../../../hooks/useRelations';
import * as css from './styles.css';
import { ReactionViewer } from '../reaction-viewer';
export const getEventReactions = (timelineSet: EventTimelineSet, eventId: string) =>
timelineSet.relations.getChildEventsForEvent(
eventId,
RelationType.Annotation,
EventType.Reaction
);
export type ReactionsProps = {
room: Room;
mEventId: string;
canSendReaction?: boolean;
relations: Relations;
onReactionToggle: (targetEventId: string, key: string, shortcode?: string) => void;
};
export const Reactions = as<'div', ReactionsProps>(
({ className, room, relations, mEventId, canSendReaction, onReactionToggle, ...props }, ref) => {
const mx = useMatrixClient();
const [viewer, setViewer] = useState<boolean | string>(false);
const myUserId = mx.getUserId();
const reactions = useRelations(
relations,
useCallback((rel) => [...(rel.getSortedAnnotationsByKey() ?? [])], [])
);
const handleViewReaction: MouseEventHandler<HTMLButtonElement> = (evt) => {
evt.stopPropagation();
evt.preventDefault();
const key = evt.currentTarget.getAttribute('data-reaction-key');
console.log(key);
if (!key) setViewer(true);
else setViewer(key);
};
return (
<Box
className={classNames(css.ReactionsContainer, className)}
gap="200"
wrap="Wrap"
{...props}
ref={ref}
>
{reactions.map(([key, events]) => {
const rEvents = Array.from(events);
if (rEvents.length === 0) return null;
const myREvent = myUserId ? rEvents.find(factoryEventSentBy(myUserId)) : undefined;
const isPressed = !!myREvent?.getRelation();
return (
<TooltipProvider
key={key}
position="Top"
tooltip={
<Tooltip style={{ maxWidth: toRem(200) }}>
<Text size="T300">
<ReactionTooltipMsg room={room} reaction={key} events={rEvents} />
</Text>
</Tooltip>
}
>
{(targetRef) => (
<Reaction
ref={targetRef}
data-reaction-key={key}
aria-pressed={isPressed}
key={key}
mx={mx}
reaction={key}
count={events.size}
onClick={canSendReaction ? () => onReactionToggle(mEventId, key) : undefined}
onContextMenu={handleViewReaction}
aria-disabled={!canSendReaction}
/>
)}
</TooltipProvider>
);
})}
{reactions.length > 0 && (
<Overlay
onContextMenu={(evt: any) => {
evt.stopPropagation();
}}
open={!!viewer}
backdrop={<OverlayBackdrop />}
>
<OverlayCenter>
<FocusTrap
focusTrapOptions={{
initialFocus: false,
returnFocusOnDeactivate: false,
onDeactivate: () => setViewer(false),
clickOutsideDeactivates: true,
}}
>
<Modal variant="Surface" size="300">
<ReactionViewer
room={room}
initialKey={typeof viewer === 'string' ? viewer : undefined}
relations={relations}
requestClose={() => setViewer(false)}
/>
</Modal>
</FocusTrap>
</OverlayCenter>
</Overlay>
)}
</Box>
);
}
);

View file

@ -0,0 +1,41 @@
import React from 'react';
import { as, toRem } from 'folds';
import { MatrixEvent } from 'matrix-js-sdk';
import { AttachmentBox, MessageBrokenContent } from '../../../components/message';
import { ImageContent } from './ImageContent';
import { scaleYDimension } from '../../../utils/common';
import { IImageContent } from '../../../../types/matrix/common';
type StickerContentProps = {
mEvent: MatrixEvent;
autoPlay: boolean;
};
export const StickerContent = as<'div', StickerContentProps>(({ mEvent, autoPlay, ...props }, ref) => {
const content = mEvent.getContent<IImageContent>();
const imgInfo = content?.info;
const mxcUrl = content.file?.url ?? content.url;
if (!imgInfo || typeof imgInfo.mimetype !== 'string' || typeof mxcUrl !== 'string') {
return <MessageBrokenContent />;
}
const height = scaleYDimension(imgInfo.w || 152, 152, imgInfo.h || 152);
return (
<AttachmentBox
style={{
height: toRem(height < 48 ? 48 : height),
width: toRem(152),
}}
{...props}
ref={ref}
>
<ImageContent
autoPlay={autoPlay}
body={content.body || 'Image'}
info={imgInfo}
mimeType={imgInfo.mimetype}
url={mxcUrl}
encInfo={content.file}
/>
</AttachmentBox>
);
});

View file

@ -0,0 +1,176 @@
import React, { useCallback, useEffect, useState } from 'react';
import {
Badge,
Box,
Button,
Icon,
Icons,
Spinner,
Text,
Tooltip,
TooltipProvider,
as,
} from 'folds';
import classNames from 'classnames';
import { BlurhashCanvas } from 'react-blurhash';
import { EncryptedAttachmentInfo } from 'browser-encrypt-attachment';
import {
IThumbnailContent,
IVideoInfo,
MATRIX_BLUR_HASH_PROPERTY_NAME,
} from '../../../../types/matrix/common';
import * as css from './styles.css';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback';
import { getFileSrcUrl } from './util';
import { Image, Video } from '../../../components/media';
import { bytesToSize } from '../../../../util/common';
import { millisecondsToMinutesAndSeconds } from '../../../utils/common';
export type VideoContentProps = {
body: string;
mimeType: string;
url: string;
info: IVideoInfo & IThumbnailContent;
encInfo?: EncryptedAttachmentInfo;
autoPlay?: boolean;
loadThumbnail?: boolean;
};
export const VideoContent = as<'div', VideoContentProps>(
({ className, body, mimeType, url, info, encInfo, autoPlay, loadThumbnail, ...props }, ref) => {
const mx = useMatrixClient();
const blurHash = info.thumbnail_info?.[MATRIX_BLUR_HASH_PROPERTY_NAME];
const [load, setLoad] = useState(false);
const [error, setError] = useState(false);
const [srcState, loadSrc] = useAsyncCallback(
useCallback(
() => getFileSrcUrl(mx.mxcUrlToHttp(url) ?? '', mimeType, encInfo),
[mx, url, mimeType, encInfo]
)
);
const [thumbSrcState, loadThumbSrc] = useAsyncCallback(
useCallback(() => {
const thumbInfo = info.thumbnail_info;
const thumbMxcUrl = info.thumbnail_file?.url ?? info.thumbnail_url;
if (typeof thumbMxcUrl !== 'string' || typeof thumbInfo?.mimetype !== 'string') {
throw new Error('Failed to load thumbnail');
}
return getFileSrcUrl(
mx.mxcUrlToHttp(thumbMxcUrl) ?? '',
thumbInfo.mimetype,
info.thumbnail_file
);
}, [mx, info])
);
const handleLoad = () => {
setLoad(true);
};
const handleError = () => {
setLoad(false);
setError(true);
};
const handleRetry = () => {
setError(false);
loadSrc();
};
useEffect(() => {
if (autoPlay) loadSrc();
}, [autoPlay, loadSrc]);
useEffect(() => {
if (loadThumbnail) loadThumbSrc();
}, [loadThumbnail, loadThumbSrc]);
return (
<Box className={classNames(css.RelativeBase, className)} {...props} ref={ref}>
{typeof blurHash === 'string' && !load && (
<BlurhashCanvas style={{ width: '100%', height: '100%' }} hash={blurHash} punch={1} />
)}
{thumbSrcState.status === AsyncStatus.Success && !load && (
<Box className={css.AbsoluteContainer} alignItems="Center" justifyContent="Center">
<Image alt={body} title={body} src={thumbSrcState.data} loading="lazy" />
</Box>
)}
{!autoPlay && srcState.status === AsyncStatus.Idle && (
<Box className={css.AbsoluteContainer} alignItems="Center" justifyContent="Center">
<Button
variant="Secondary"
fill="Solid"
radii="300"
size="300"
onClick={loadSrc}
before={<Icon size="Inherit" src={Icons.Play} filled />}
>
<Text size="B300">Watch</Text>
</Button>
</Box>
)}
{srcState.status === AsyncStatus.Success && (
<Box className={css.AbsoluteContainer}>
<Video
title={body}
src={srcState.data}
onLoadedMetadata={handleLoad}
onError={handleError}
autoPlay
controls
/>
</Box>
)}
{(srcState.status === AsyncStatus.Loading || srcState.status === AsyncStatus.Success) &&
!load && (
<Box className={css.AbsoluteContainer} alignItems="Center" justifyContent="Center">
<Spinner variant="Secondary" />
</Box>
)}
{(error || srcState.status === AsyncStatus.Error) && (
<Box className={css.AbsoluteContainer} alignItems="Center" justifyContent="Center">
<TooltipProvider
tooltip={
<Tooltip variant="Critical">
<Text>Failed to load video!</Text>
</Tooltip>
}
position="Top"
align="Center"
>
{(triggerRef) => (
<Button
ref={triggerRef}
size="300"
variant="Critical"
fill="Soft"
outlined
radii="300"
onClick={handleRetry}
before={<Icon size="Inherit" src={Icons.Warning} filled />}
>
<Text size="B300">Retry</Text>
</Button>
)}
</TooltipProvider>
</Box>
)}
{!load && typeof info.size === 'number' && (
<Box
className={css.AbsoluteFooter}
justifyContent="SpaceBetween"
alignContent="Center"
gap="200"
>
<Badge variant="Secondary" fill="Soft">
<Text size="L400">{millisecondsToMinutesAndSeconds(info.duration ?? 0)}</Text>
</Badge>
<Badge variant="Secondary" fill="Soft">
<Text size="L400">{bytesToSize(info.size)}</Text>
</Badge>
</Box>
)}
</Box>
);
}
);

View file

@ -0,0 +1,45 @@
import React from 'react';
import { MatrixEvent } from 'matrix-js-sdk';
import { IFileContent } from '../../../../types/matrix/common';
import {
Attachment,
AttachmentBox,
AttachmentContent,
AttachmentHeader,
} from '../../../components/message';
import { FileHeader } from './FileHeader';
import { FileContent } from './FileContent';
import { FALLBACK_MIMETYPE } from '../../../utils/mimeTypes';
export const fileRenderer = (mEventId: string, mEvent: MatrixEvent) => {
const content = mEvent.getContent<IFileContent>();
const fileInfo = content?.info;
const mxcUrl = content.file?.url ?? content.url;
if (typeof mxcUrl !== 'string') {
return null;
}
return (
<Attachment>
<AttachmentHeader>
<FileHeader
body={content.body ?? 'Unnamed File'}
mimeType={fileInfo?.mimetype ?? FALLBACK_MIMETYPE}
/>
</AttachmentHeader>
<AttachmentBox>
<AttachmentContent>
<FileContent
body={content.body ?? 'File'}
info={fileInfo ?? {}}
mimeType={fileInfo?.mimetype ?? FALLBACK_MIMETYPE}
url={mxcUrl}
encInfo={content.file}
/>
</AttachmentContent>
</AttachmentBox>
</Attachment>
);
};

View file

@ -0,0 +1,10 @@
export * from './ImageContent';
export * from './VideoContent';
export * from './FileHeader';
export * from './fileRenderer';
export * from './AudioContent';
export * from './Reactions';
export * from './EventContent';
export * from './Message';
export * from './EncryptedContent';
export * from './StickerContent';

View file

@ -0,0 +1,72 @@
import { style } from '@vanilla-extract/css';
import { DefaultReset, config, toRem } from 'folds';
export const RelativeBase = style([
DefaultReset,
{
position: 'relative',
width: '100%',
height: '100%',
},
]);
export const AbsoluteContainer = style([
DefaultReset,
{
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: '100%',
},
]);
export const AbsoluteFooter = style([
DefaultReset,
{
position: 'absolute',
bottom: config.space.S100,
left: config.space.S100,
right: config.space.S100,
},
]);
export const MessageBase = style({
position: 'relative',
});
export const MessageOptionsBase = style([
DefaultReset,
{
position: 'absolute',
top: toRem(-30),
right: 0,
zIndex: 1,
},
]);
export const MessageOptionsBar = style([
DefaultReset,
{
padding: config.space.S100,
},
]);
export const MessageQuickReaction = style({
minWidth: toRem(32),
});
export const MessageMenuGroup = style({
padding: config.space.S100,
});
export const MessageMenuItemText = style({
flexGrow: 1,
});
export const ReactionsContainer = style({
selectors: {
'&:empty': {
display: 'none',
},
},
});

View file

@ -0,0 +1,23 @@
import { EncryptedAttachmentInfo } from 'browser-encrypt-attachment';
import { decryptFile } from '../../../utils/matrix';
export const getFileSrcUrl = async (
httpUrl: string,
mimeType: string,
encInfo?: EncryptedAttachmentInfo
): Promise<string> => {
if (encInfo) {
if (typeof httpUrl !== 'string') throw new Error('Malformed event');
const encRes = await fetch(httpUrl, { method: 'GET' });
const encData = await encRes.arrayBuffer();
const decryptedBlob = await decryptFile(encData, mimeType, encInfo);
return URL.createObjectURL(decryptedBlob);
}
return httpUrl;
};
export const getSrcFile = async (src: string): Promise<Blob> => {
const res = await fetch(src, { method: 'GET' });
const blob = await res.blob();
return blob;
};

View file

@ -1,6 +1,6 @@
import { IContent, MatrixClient, MsgType } from 'matrix-js-sdk'; import { IContent, MatrixClient, MsgType } from 'matrix-js-sdk';
import to from 'await-to-js'; import to from 'await-to-js';
import { IThumbnailContent } from '../../../types/matrix/common'; import { IThumbnailContent, MATRIX_BLUR_HASH_PROPERTY_NAME } from '../../../types/matrix/common';
import { import {
getImageFileUrl, getImageFileUrl,
getThumbnail, getThumbnail,
@ -11,7 +11,7 @@ import {
} from '../../utils/dom'; } from '../../utils/dom';
import { encryptFile, getImageInfo, getThumbnailContent, getVideoInfo } from '../../utils/matrix'; import { encryptFile, getImageInfo, getThumbnailContent, getVideoInfo } from '../../utils/matrix';
import { TUploadItem } from '../../state/roomInputDrafts'; import { TUploadItem } from '../../state/roomInputDrafts';
import { MATRIX_BLUR_HASH_PROPERTY_NAME, encodeBlurHash } from '../../utils/blurHash'; import { encodeBlurHash } from '../../utils/blurHash';
const generateThumbnailContent = async ( const generateThumbnailContent = async (
mx: MatrixClient, mx: MatrixClient,
@ -38,7 +38,11 @@ const generateThumbnailContent = async (
return thumbnailContent; return thumbnailContent;
}; };
export const getImageMsgContent = async (item: TUploadItem, mxc: string): Promise<IContent> => { export const getImageMsgContent = async (
mx: MatrixClient,
item: TUploadItem,
mxc: string
): Promise<IContent> => {
const { file, originalFile, encInfo } = item; const { file, originalFile, encInfo } = item;
const [imgError, imgEl] = await to(loadImageElement(getImageFileUrl(originalFile))); const [imgError, imgEl] = await to(loadImageElement(getImageFileUrl(originalFile)));
if (imgError) console.warn(imgError); if (imgError) console.warn(imgError);
@ -48,9 +52,24 @@ export const getImageMsgContent = async (item: TUploadItem, mxc: string): Promis
body: file.name, body: file.name,
}; };
if (imgEl) { if (imgEl) {
const blurHash = encodeBlurHash(imgEl);
const [thumbError, thumbContent] = await to(
generateThumbnailContent(
mx,
imgEl,
getThumbnailDimensions(imgEl.width, imgEl.height),
!!encInfo
)
);
if (thumbContent && thumbContent.thumbnail_info) {
thumbContent.thumbnail_info[MATRIX_BLUR_HASH_PROPERTY_NAME] = blurHash;
}
if (thumbError) console.warn(thumbError);
content.info = { content.info = {
...getImageInfo(imgEl, file), ...getImageInfo(imgEl, file),
[MATRIX_BLUR_HASH_PROPERTY_NAME]: encodeBlurHash(imgEl), [MATRIX_BLUR_HASH_PROPERTY_NAME]: blurHash,
...thumbContent,
}; };
} }
if (encInfo) { if (encInfo) {
@ -87,6 +106,9 @@ export const getVideoMsgContent = async (
!!encInfo !!encInfo
) )
); );
if (thumbContent && thumbContent.thumbnail_info) {
thumbContent.thumbnail_info[MATRIX_BLUR_HASH_PROPERTY_NAME] = encodeBlurHash(videoEl);
}
if (thumbError) console.warn(thumbError); if (thumbError) console.warn(thumbError);
content.info = { content.info = {
...getVideoInfo(videoEl, file), ...getVideoInfo(videoEl, file),

View file

@ -0,0 +1,31 @@
import { style } from '@vanilla-extract/css';
import { DefaultReset, color, config } from 'folds';
export const ReactionViewer = style([
DefaultReset,
{
height: '100%',
},
]);
export const Sidebar = style({
backgroundColor: color.Background.Container,
color: color.Background.OnContainer,
});
export const SidebarContent = style({
padding: config.space.S200,
paddingRight: 0,
});
export const Header = style({
paddingLeft: config.space.S400,
paddingRight: config.space.S300,
flexShrink: 0,
gap: config.space.S200,
});
export const Content = style({
paddingLeft: config.space.S200,
paddingBottom: config.space.S400,
});

View file

@ -0,0 +1,155 @@
import React, { useCallback, useState } from 'react';
import classNames from 'classnames';
import {
Avatar,
AvatarFallback,
AvatarImage,
Box,
Header,
Icon,
IconButton,
Icons,
Line,
MenuItem,
Scroll,
Text,
as,
config,
} from 'folds';
import { MatrixEvent, Room, RoomMember } from 'matrix-js-sdk';
import { Relations } from 'matrix-js-sdk/lib/models/relations';
import { getMemberDisplayName } from '../../../utils/room';
import { eventWithShortcode, getMxIdLocalPart } from '../../../utils/matrix';
import * as css from './ReactionViewer.css';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
import colorMXID from '../../../../util/colorMXID';
import { openProfileViewer } from '../../../../client/action/navigation';
import { useRelations } from '../../../hooks/useRelations';
import { Reaction } from '../../../components/message';
import { getHexcodeForEmoji, getShortcodeFor } from '../../../plugins/emoji';
export type ReactionViewerProps = {
room: Room;
initialKey?: string;
relations: Relations;
requestClose: () => void;
};
export const ReactionViewer = as<'div', ReactionViewerProps>(
({ className, room, initialKey, relations, requestClose, ...props }, ref) => {
const mx = useMatrixClient();
const reactions = useRelations(
relations,
useCallback((rel) => [...(rel.getSortedAnnotationsByKey() ?? [])], [])
);
const [selectedKey, setSelectedKey] = useState<string>(initialKey ?? reactions[0][0]);
const getName = (member: RoomMember) =>
getMemberDisplayName(room, member.userId) ?? getMxIdLocalPart(member.userId) ?? member.userId;
const getReactionsForKey = (key: string): MatrixEvent[] => {
const reactSet = reactions.find(([k]) => k === key)?.[1];
if (!reactSet) return [];
return Array.from(reactSet);
};
const selectedReactions = getReactionsForKey(selectedKey);
const selectedShortcode =
selectedReactions.find(eventWithShortcode)?.getContent().shortcode ??
getShortcodeFor(getHexcodeForEmoji(selectedKey)) ??
selectedKey;
return (
<Box
className={classNames(css.ReactionViewer, className)}
direction="Row"
{...props}
ref={ref}
>
<Box shrink="No" className={css.Sidebar}>
<Scroll visibility="Hover" hideTrack size="300">
<Box className={css.SidebarContent} direction="Column" gap="200">
{reactions.map(([key, evts]) => (
<Reaction
key={key}
mx={mx}
reaction={key}
count={evts.size}
aria-selected={key === selectedKey}
onClick={() => setSelectedKey(key)}
/>
))}
</Box>
</Scroll>
</Box>
<Line variant="Surface" direction="Vertical" size="300" />
<Box grow="Yes" direction="Column">
<Header className={css.Header} variant="Surface" size="600">
<Box grow="Yes">
<Text size="H3" truncate>{`Reacted with :${selectedShortcode}:`}</Text>
</Box>
<IconButton size="300" onClick={requestClose}>
<Icon src={Icons.Cross} />
</IconButton>
</Header>
<Box grow="Yes">
<Scroll visibility="Hover" hideTrack size="300">
<Box className={css.Content} direction="Column">
{selectedReactions.map((mEvent) => {
const senderId = mEvent.getSender();
if (!senderId) return null;
const member = room.getMember(senderId);
if (!member) return null;
const name = getName(member);
const avatarUrl = member.getAvatarUrl(
mx.baseUrl,
100,
100,
'crop',
undefined,
false
);
return (
<MenuItem
key={member.userId}
style={{ padding: `0 ${config.space.S200}` }}
radii="400"
onClick={() => {
requestClose();
openProfileViewer(member.userId, room.roomId);
}}
before={
<Avatar size="200">
{avatarUrl ? (
<AvatarImage src={avatarUrl} />
) : (
<AvatarFallback
style={{
background: colorMXID(member.userId),
color: 'white',
}}
>
<Text size="H6">{name[0]}</Text>
</AvatarFallback>
)}
</Avatar>
}
>
<Box grow="Yes">
<Text size="T400" truncate>
{name}
</Text>
</Box>
</MenuItem>
);
})}
</Box>
</Scroll>
</Box>
</Box>
</Box>
);
}
);

View file

@ -0,0 +1 @@
export * from './ReactionViewer';

View file

@ -6,7 +6,7 @@ import cons from '../../../client/state/cons';
import settings from '../../../client/state/settings'; import settings from '../../../client/state/settings';
import navigation from '../../../client/state/navigation'; import navigation from '../../../client/state/navigation';
import { import {
toggleSystemTheme, toggleMarkdown, toggleMembershipEvents, toggleNickAvatarEvents, toggleSystemTheme, toggleMarkdown,
toggleNotifications, toggleNotificationSounds, toggleNotifications, toggleNotificationSounds,
} from '../../../client/action/settings'; } from '../../../client/action/settings';
import { usePermission } from '../../hooks/usePermission'; import { usePermission } from '../../hooks/usePermission';
@ -43,10 +43,21 @@ import CrossIC from '../../../../public/res/ic/outlined/cross.svg';
import CinnySVG from '../../../../public/res/svg/cinny.svg'; import CinnySVG from '../../../../public/res/svg/cinny.svg';
import { confirmDialog } from '../../molecules/confirm-dialog/ConfirmDialog'; import { confirmDialog } from '../../molecules/confirm-dialog/ConfirmDialog';
import { useSetting } from '../../state/hooks/settings';
import { settingsAtom } from '../../state/settings';
function AppearanceSection() { function AppearanceSection() {
const [, updateState] = useState({}); const [, updateState] = useState({});
const [messageLayout, setMessageLayout] = useSetting(settingsAtom, 'messageLayout');
const [messageSpacing, setMessageSpacing] = useSetting(settingsAtom, 'messageSpacing');
const [useSystemEmoji, setUseSystemEmoji] = useSetting(settingsAtom, 'useSystemEmoji');
const [hideMembershipEvents, setHideMembershipEvents] = useSetting(settingsAtom, 'hideMembershipEvents');
const [hideNickAvatarEvents, setHideNickAvatarEvents] = useSetting(settingsAtom, 'hideNickAvatarEvents');
const [mediaAutoLoad, setMediaAutoLoad] = useSetting(settingsAtom, 'mediaAutoLoad');
const [showHiddenEvents, setShowHiddenEvents] = useSetting(settingsAtom, 'showHiddenEvents');
const spacings = ['0', '100', '200', '300', '400', '500']
return ( return (
<div className="settings-appearance"> <div className="settings-appearance">
<div className="settings-appearance__card"> <div className="settings-appearance__card">
@ -80,9 +91,52 @@ function AppearanceSection() {
/> />
)} )}
/> />
<SettingTile
title="Use System Emoji"
options={(
<Toggle
isActive={useSystemEmoji}
onToggle={() => setUseSystemEmoji(!useSystemEmoji)}
/>
)}
content={<Text variant="b3">Use system emoji instead of Twitter emojis.</Text>}
/>
</div> </div>
<div className="settings-appearance__card"> <div className="settings-appearance__card">
<MenuHeader>Room messages</MenuHeader> <MenuHeader>Room messages</MenuHeader>
<SettingTile
title="Message Layout"
content={
<SegmentedControls
selected={messageLayout}
segments={[
{ text: 'Modern' },
{ text: 'Compact' },
{ text: 'Bubble' },
]}
onSelect={(index) => setMessageLayout(index)}
/>
}
/>
<SettingTile
title="Message Spacing"
content={
<SegmentedControls
selected={spacings.findIndex((s) => s === messageSpacing)}
segments={[
{ text: 'No' },
{ text: 'XXS' },
{ text: 'XS' },
{ text: 'S' },
{ text: 'M' },
{ text: 'L' },
]}
onSelect={(index) => {
setMessageSpacing(spacings[index])
}}
/>
}
/>
<SettingTile <SettingTile
title="Markdown formatting" title="Markdown formatting"
options={( options={(
@ -97,8 +151,8 @@ function AppearanceSection() {
title="Hide membership events" title="Hide membership events"
options={( options={(
<Toggle <Toggle
isActive={settings.hideMembershipEvents} isActive={hideMembershipEvents}
onToggle={() => { toggleMembershipEvents(); updateState({}); }} onToggle={() => setHideMembershipEvents(!hideMembershipEvents)}
/> />
)} )}
content={<Text variant="b3">Hide membership change messages from room timeline. (Join, Leave, Invite, Kick and Ban)</Text>} content={<Text variant="b3">Hide membership change messages from room timeline. (Join, Leave, Invite, Kick and Ban)</Text>}
@ -107,12 +161,32 @@ function AppearanceSection() {
title="Hide nick/avatar events" title="Hide nick/avatar events"
options={( options={(
<Toggle <Toggle
isActive={settings.hideNickAvatarEvents} isActive={hideNickAvatarEvents}
onToggle={() => { toggleNickAvatarEvents(); updateState({}); }} onToggle={() => setHideNickAvatarEvents(!hideNickAvatarEvents)}
/> />
)} )}
content={<Text variant="b3">Hide nick and avatar change messages from room timeline.</Text>} content={<Text variant="b3">Hide nick and avatar change messages from room timeline.</Text>}
/> />
<SettingTile
title="Disable media auto load"
options={(
<Toggle
isActive={!mediaAutoLoad}
onToggle={() => setMediaAutoLoad(!mediaAutoLoad)}
/>
)}
content={<Text variant="b3">Prevent images and videos from auto loading to save bandwidth.</Text>}
/>
<SettingTile
title="Show hidden events"
options={(
<Toggle
isActive={showHiddenEvents}
onToggle={() => setShowHiddenEvents(!showHiddenEvents)}
/>
)}
content={<Text variant="b3">Show hidden state and message events.</Text>}
/>
</div> </div>
</div> </div>
); );

View file

@ -1,4 +1,4 @@
import { CompactEmoji } from 'emojibase'; import { CompactEmoji, fromUnicodeToHexcode } from 'emojibase';
import emojisData from 'emojibase-data/en/compact.json'; import emojisData from 'emojibase-data/en/compact.json';
import joypixels from 'emojibase-data/en/shortcodes/joypixels.json'; import joypixels from 'emojibase-data/en/shortcodes/joypixels.json';
import emojibase from 'emojibase-data/en/shortcodes/emojibase.json'; import emojibase from 'emojibase-data/en/shortcodes/emojibase.json';
@ -24,6 +24,16 @@ export type IEmojiGroup = {
emojis: IEmoji[]; emojis: IEmoji[];
}; };
export const getShortcodesFor = (hexcode: string): string[] | string | undefined =>
joypixels[hexcode] || emojibase[hexcode];
export const getShortcodeFor = (hexcode: string): string | undefined => {
const shortcode = joypixels[hexcode] || emojibase[hexcode];
return Array.isArray(shortcode) ? shortcode[0] : shortcode;
};
export const getHexcodeForEmoji = fromUnicodeToHexcode;
export const emojiGroups: IEmojiGroup[] = [ export const emojiGroups: IEmojiGroup[] = [
{ {
id: EmojiGroupId.People, id: EmojiGroupId.People,
@ -86,7 +96,7 @@ function getGroupIndex(emoji: IEmoji): number | undefined {
} }
emojisData.forEach((emoji) => { emojisData.forEach((emoji) => {
const myShortCodes = joypixels[emoji.hexcode] || emojibase[emoji.hexcode]; const myShortCodes = getShortcodesFor(emoji.hexcode);
if (!myShortCodes) return; if (!myShortCodes) return;
if (Array.isArray(myShortCodes) && myShortCodes.length === 0) return; if (Array.isArray(myShortCodes) && myShortCodes.length === 0) return;

Some files were not shown because too many files have changed in this diff Show more