Compare commits

...

15 Commits

Author SHA1 Message Date
Krishan
d70ca86d7c Release v4.4.0 (#2225) 2025-02-23 22:27:50 +11:00
nexy7574
8d95758ed7 Remove fallback replies & implement intentional mentions (#2138)
* Remove reply fallbacks & add m.mentions

(WIP) the typing on line 301 and 303 needs fixing but apart from that this is mint

* Less jank typing

* Mention the reply author in m.mentions

* Improve typing

* Fix typing in m.mentions finder

* Correctly iterate through editor children, properly handle @room, ...

..., don't mention the reply author when the reply author is ourself, don't add own user IDs when mentioning intentionally

* Formatting

* Add intentional mentions to edited messages

* refactor reusable code and fix todo

* parse mentions from all nodes

---------

Co-authored-by: Ajay Bura <32841439+ajbura@users.noreply.github.com>
2025-02-23 22:08:08 +11:00
Ginger
dd4c1a94e6 Add support for spoilers on images (MSC4193) (#2212)
* Add support for MSC4193: Spoilers on Media

* Clarify variable names and wording

* Restore list atom

* Improve spoilered image UX with autoload off

* Use `aria-pressed` to indicate attachment spoiler state

* Improve spoiler button tooltip wording, keep reveal button from conflicting with load errors
2025-02-22 14:25:13 +05:30
Ajay Bura
7c6ab366af Fix unknown rooms in space lobby (#2224)
* add hook to fetch one level of space hierarchy

* add enable param to level hierarchy hook

* improve HierarchyItem types

* fix type errors in lobby

* load space hierarachy per level

* fix menu item visibility

* fix unknown spaces over federation

* show inaccessible rooms only to admins

* fix unknown room renders loading content twice

* fix unknown room visible to normal user if space all room are unknown

* show no rooms card if space does not have any room
2025-02-22 19:24:33 +11:00
Lain Iwakura
f121cc0a24 fix space/tab inconsistency (#2180) 2025-02-21 19:22:48 +11:00
Ajay Bura
7456c152b7 Escape markdown sequences (#2208)
* escape inline markdown character

* fix typo

* improve document around custom markdown plugin and add escape sequence utils

* recover inline escape sequences on edit

* remove escape sequences from plain text body

* use `s` for strike-through instead of del

* escape block markdown sequences

* fix remove escape sequence was not removing all slashes from plain text

* recover block sequences on edit
2025-02-21 19:19:24 +11:00
Ajay Bura
b63868bbb5 scroll to bottom in unfocused window but stop sending read receipt (#2214)
* scroll to bottom in unfocused window but stop sending read receipt

* send read-receipt when new message are in view after regaining focus
2025-02-21 19:18:02 +11:00
Ajay Bura
59e8d66255 Add email notification toggle (#2223)
* refactor system notification to dedicated file

* add hook for email notification status

* add toogle for email notifications in settings
2025-02-21 19:15:47 +11:00
Ajay Bura
1b200eb676 Improve search result counts (#2221)
* remove limit from emoji autocomplete

* remove search limit from user mention

* remove limit from room mention autocomplete

* increase user search limit to 1000

* better search string selection for emoticons
2025-02-21 19:14:38 +11:00
Ajay Bura
3ada21a1df fix autocomplete menu flickering issue (#2220) 2025-02-20 18:32:44 +11:00
Ajay Bura
9fe67da98b sanitize string before used in regex to prevent crash (#2219) 2025-02-20 18:30:54 +11:00
Ajay Bura
d8d4bce287 add button to select all room pack as global pack (#2218) 2025-02-19 22:13:29 +11:00
Ajay Bura
b3979b31c7 fix room activity indicator appearing on self typing (#2217) 2025-02-19 22:08:58 +11:00
Ajay Bura
2e0c7c4406 Fix link visible inside spoiler (#2215)
* hide links in spoiler

* prevent link click inside spoiler
2025-02-19 22:07:33 +11:00
Ajay Bura
f73dc05e25 add order algorithm in search result 2025-02-19 11:23:32 +05:30
60 changed files with 2142 additions and 1080 deletions

View File

@@ -1,35 +1,35 @@
server { server {
listen 80; listen 80;
listen [::]:80; listen [::]:80;
server_name cinny.domain.tld; server_name cinny.domain.tld;
location / { location / {
return 301 https://$host$request_uri; return 301 https://$host$request_uri;
} }
location /.well-known/acme-challenge/ { location /.well-known/acme-challenge/ {
alias /var/lib/letsencrypt/.well-known/acme-challenge/; alias /var/lib/letsencrypt/.well-known/acme-challenge/;
} }
} }
server { server {
listen 443 ssl http2; listen 443 ssl http2;
listen [::]:443 ssl; listen [::]:443 ssl;
server_name cinny.domain.tld; server_name cinny.domain.tld;
location / { location / {
root /opt/cinny/dist/; root /opt/cinny/dist/;
rewrite ^/config.json$ /config.json break; rewrite ^/config.json$ /config.json break;
rewrite ^/manifest.json$ /manifest.json break; rewrite ^/manifest.json$ /manifest.json break;
rewrite ^.*/olm.wasm$ /olm.wasm break; rewrite ^.*/olm.wasm$ /olm.wasm break;
rewrite ^/sw.js$ /sw.js break; rewrite ^/sw.js$ /sw.js break;
rewrite ^/pdf.worker.min.js$ /pdf.worker.min.js break; rewrite ^/pdf.worker.min.js$ /pdf.worker.min.js break;
rewrite ^/public/(.*)$ /public/$1 break; rewrite ^/public/(.*)$ /public/$1 break;
rewrite ^/assets/(.*)$ /assets/$1 break; rewrite ^/assets/(.*)$ /assets/$1 break;
rewrite ^(.+)$ /index.html break; rewrite ^(.+)$ /index.html break;
} }
} }

4
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{ {
"name": "cinny", "name": "cinny",
"version": "4.3.2", "version": "4.4.0",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "cinny", "name": "cinny",
"version": "4.3.2", "version": "4.4.0",
"license": "AGPL-3.0-only", "license": "AGPL-3.0-only",
"dependencies": { "dependencies": {
"@atlaskit/pragmatic-drag-and-drop": "1.1.6", "@atlaskit/pragmatic-drag-and-drop": "1.1.6",

View File

@@ -1,6 +1,6 @@
{ {
"name": "cinny", "name": "cinny",
"version": "4.3.2", "version": "4.4.0",
"description": "Yet another matrix client", "description": "Yet another matrix client",
"main": "index.js", "main": "index.js",
"type": "module", "type": "module",

View File

@@ -5,6 +5,7 @@ import { Header, Menu, Scroll, config } from 'folds';
import * as css from './AutocompleteMenu.css'; import * as css from './AutocompleteMenu.css';
import { preventScrollWithArrowKey, stopPropagation } from '../../../utils/keyboard'; import { preventScrollWithArrowKey, stopPropagation } from '../../../utils/keyboard';
import { useAlive } from '../../../hooks/useAlive';
type AutocompleteMenuProps = { type AutocompleteMenuProps = {
requestClose: () => void; requestClose: () => void;
@@ -12,13 +13,22 @@ type AutocompleteMenuProps = {
children: ReactNode; children: ReactNode;
}; };
export function AutocompleteMenu({ headerContent, requestClose, children }: AutocompleteMenuProps) { export function AutocompleteMenu({ headerContent, requestClose, children }: AutocompleteMenuProps) {
const alive = useAlive();
const handleDeactivate = () => {
if (alive()) {
// The component is unmounted so we will not call for `requestClose`
requestClose();
}
};
return ( return (
<div className={css.AutocompleteMenuBase}> <div className={css.AutocompleteMenuBase}>
<div className={css.AutocompleteMenuContainer}> <div className={css.AutocompleteMenuContainer}>
<FocusTrap <FocusTrap
focusTrapOptions={{ focusTrapOptions={{
initialFocus: false, initialFocus: false,
onDeactivate: () => requestClose(), onPostDeactivate: handleDeactivate,
returnFocusOnDeactivate: false, returnFocusOnDeactivate: false,
clickOutsideDeactivates: true, clickOutsideDeactivates: true,
allowOutsideClick: true, allowOutsideClick: true,

View File

@@ -6,11 +6,7 @@ import { Room } from 'matrix-js-sdk';
import { AutocompleteQuery } from './autocompleteQuery'; import { AutocompleteQuery } from './autocompleteQuery';
import { AutocompleteMenu } from './AutocompleteMenu'; import { AutocompleteMenu } from './AutocompleteMenu';
import { useMatrixClient } from '../../../hooks/useMatrixClient'; import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { import { UseAsyncSearchOptions, useAsyncSearch } from '../../../hooks/useAsyncSearch';
SearchItemStrGetter,
UseAsyncSearchOptions,
useAsyncSearch,
} from '../../../hooks/useAsyncSearch';
import { onTabPress } from '../../../utils/keyboard'; import { onTabPress } from '../../../utils/keyboard';
import { createEmoticonElement, moveCursor, replaceWithElement } from '../utils'; import { createEmoticonElement, moveCursor, replaceWithElement } from '../utils';
import { useRecentEmoji } from '../../../hooks/useRecentEmoji'; import { useRecentEmoji } from '../../../hooks/useRecentEmoji';
@@ -20,6 +16,7 @@ import { useKeyDown } from '../../../hooks/useKeyDown';
import { mxcUrlToHttp } from '../../../utils/matrix'; import { mxcUrlToHttp } from '../../../utils/matrix';
import { useMediaAuthentication } from '../../../hooks/useMediaAuthentication'; import { useMediaAuthentication } from '../../../hooks/useMediaAuthentication';
import { ImageUsage, PackImageReader } from '../../../plugins/custom-emoji'; import { ImageUsage, PackImageReader } from '../../../plugins/custom-emoji';
import { getEmoticonSearchStr } from '../../../plugins/utils';
type EmoticonCompleteHandler = (key: string, shortcode: string) => void; type EmoticonCompleteHandler = (key: string, shortcode: string) => void;
@@ -33,16 +30,11 @@ type EmoticonAutocompleteProps = {
}; };
const SEARCH_OPTIONS: UseAsyncSearchOptions = { const SEARCH_OPTIONS: UseAsyncSearchOptions = {
limit: 20,
matchOptions: { matchOptions: {
contain: true, contain: true,
}, },
}; };
const getEmoticonStr: SearchItemStrGetter<EmoticonSearchItem> = (emoticon) => [
`:${emoticon.shortcode}:`,
];
export function EmoticonAutocomplete({ export function EmoticonAutocomplete({
imagePackRooms, imagePackRooms,
editor, editor,
@@ -63,10 +55,12 @@ export function EmoticonAutocomplete({
); );
}, [imagePacks]); }, [imagePacks]);
const [result, search, resetSearch] = useAsyncSearch(searchList, getEmoticonStr, SEARCH_OPTIONS); const [result, search, resetSearch] = useAsyncSearch(
const autoCompleteEmoticon = (result ? result.items : recentEmoji).sort((a, b) => searchList,
a.shortcode.localeCompare(b.shortcode) getEmoticonSearchStr,
SEARCH_OPTIONS
); );
const autoCompleteEmoticon = result ? result.items.slice(0, 20) : recentEmoji;
useEffect(() => { useEffect(() => {
if (query.text) search(query.text); if (query.text) search(query.text);

View File

@@ -65,7 +65,6 @@ type RoomMentionAutocompleteProps = {
}; };
const SEARCH_OPTIONS: UseAsyncSearchOptions = { const SEARCH_OPTIONS: UseAsyncSearchOptions = {
limit: 20,
matchOptions: { matchOptions: {
contain: true, contain: true,
}, },
@@ -97,7 +96,7 @@ export function RoomMentionAutocomplete({
SEARCH_OPTIONS SEARCH_OPTIONS
); );
const autoCompleteRoomIds = result ? result.items : allRooms.slice(0, 20); const autoCompleteRoomIds = result ? result.items.slice(0, 20) : allRooms.slice(0, 20);
useEffect(() => { useEffect(() => {
if (query.text) search(query.text); if (query.text) search(query.text);

View File

@@ -74,7 +74,7 @@ const withAllowedMembership = (member: RoomMember): boolean =>
member.membership === Membership.Knock; member.membership === Membership.Knock;
const SEARCH_OPTIONS: UseAsyncSearchOptions = { const SEARCH_OPTIONS: UseAsyncSearchOptions = {
limit: 20, limit: 1000,
matchOptions: { matchOptions: {
contain: true, contain: true,
}, },
@@ -97,7 +97,7 @@ export function UserMentionAutocomplete({
const members = useRoomMembers(mx, roomId); const members = useRoomMembers(mx, roomId);
const [result, search, resetSearch] = useAsyncSearch(members, getRoomMemberStr, SEARCH_OPTIONS); const [result, search, resetSearch] = useAsyncSearch(members, getRoomMemberStr, SEARCH_OPTIONS);
const autoCompleteMembers = (result ? result.items : members.slice(0, 20)).filter( const autoCompleteMembers = (result ? result.items.slice(0, 20) : members.slice(0, 20)).filter(
withAllowedMembership withAllowedMembership
); );

View File

@@ -26,48 +26,75 @@ import {
testMatrixTo, testMatrixTo,
} from '../../plugins/matrix-to'; } from '../../plugins/matrix-to';
import { tryDecodeURIComponent } from '../../utils/dom'; import { tryDecodeURIComponent } from '../../utils/dom';
import {
escapeMarkdownInlineSequences,
escapeMarkdownBlockSequences,
} from '../../plugins/markdown';
const markNodeToType: Record<string, MarkType> = { type ProcessTextCallback = (text: string) => string;
b: MarkType.Bold,
strong: MarkType.Bold,
i: MarkType.Italic,
em: MarkType.Italic,
u: MarkType.Underline,
s: MarkType.StrikeThrough,
del: MarkType.StrikeThrough,
code: MarkType.Code,
span: MarkType.Spoiler,
};
const elementToTextMark = (node: Element): MarkType | undefined => { const getText = (node: ChildNode): string => {
const markType = markNodeToType[node.name];
if (!markType) return undefined;
if (markType === MarkType.Spoiler && node.attribs['data-mx-spoiler'] === undefined) {
return undefined;
}
if (
markType === MarkType.Code &&
node.parent &&
'name' in node.parent &&
node.parent.name === 'pre'
) {
return undefined;
}
return markType;
};
const parseNodeText = (node: ChildNode): string => {
if (isText(node)) { if (isText(node)) {
return node.data; return node.data;
} }
if (isTag(node)) { if (isTag(node)) {
return node.children.map((child) => parseNodeText(child)).join(''); return node.children.map((child) => getText(child)).join('');
} }
return ''; return '';
}; };
const elementToInlineNode = (node: Element): MentionElement | EmoticonElement | undefined => { const getInlineNodeMarkType = (node: Element): MarkType | undefined => {
if (node.name === 'b' || node.name === 'strong') {
return MarkType.Bold;
}
if (node.name === 'i' || node.name === 'em') {
return MarkType.Italic;
}
if (node.name === 'u') {
return MarkType.Underline;
}
if (node.name === 's' || node.name === 'del') {
return MarkType.StrikeThrough;
}
if (node.name === 'code') {
if (node.parent && 'name' in node.parent && node.parent.name === 'pre') {
return undefined; // Don't apply `Code` mark inside a <pre> tag
}
return MarkType.Code;
}
if (node.name === 'span' && node.attribs['data-mx-spoiler'] !== undefined) {
return MarkType.Spoiler;
}
return undefined;
};
const getInlineMarkElement = (
markType: MarkType,
node: Element,
getChild: (child: ChildNode) => InlineElement[]
): InlineElement[] => {
const children = node.children.flatMap(getChild);
const mdSequence = node.attribs['data-md'];
if (mdSequence !== undefined) {
children.unshift({ text: mdSequence });
children.push({ text: mdSequence });
return children;
}
children.forEach((child) => {
if (Text.isText(child)) {
child[markType] = true;
}
});
return children;
};
const getInlineNonMarkElement = (node: Element): MentionElement | EmoticonElement | undefined => {
if (node.name === 'img' && node.attribs['data-mx-emoticon'] !== undefined) { if (node.name === 'img' && node.attribs['data-mx-emoticon'] !== undefined) {
const { src, alt } = node.attribs; const { src, alt } = node.attribs;
if (!src) return undefined; if (!src) return undefined;
@@ -79,13 +106,13 @@ const elementToInlineNode = (node: Element): MentionElement | EmoticonElement |
if (testMatrixTo(href)) { if (testMatrixTo(href)) {
const userMention = parseMatrixToUser(href); const userMention = parseMatrixToUser(href);
if (userMention) { if (userMention) {
return createMentionElement(userMention, parseNodeText(node) || userMention, false); return createMentionElement(userMention, getText(node) || userMention, false);
} }
const roomMention = parseMatrixToRoom(href); const roomMention = parseMatrixToRoom(href);
if (roomMention) { if (roomMention) {
return createMentionElement( return createMentionElement(
roomMention.roomIdOrAlias, roomMention.roomIdOrAlias,
parseNodeText(node) || roomMention.roomIdOrAlias, getText(node) || roomMention.roomIdOrAlias,
false, false,
undefined, undefined,
roomMention.viaServers roomMention.viaServers
@@ -95,7 +122,7 @@ const elementToInlineNode = (node: Element): MentionElement | EmoticonElement |
if (eventMention) { if (eventMention) {
return createMentionElement( return createMentionElement(
eventMention.roomIdOrAlias, eventMention.roomIdOrAlias,
parseNodeText(node) || eventMention.roomIdOrAlias, getText(node) || eventMention.roomIdOrAlias,
false, false,
eventMention.eventId, eventMention.eventId,
eventMention.viaServers eventMention.viaServers
@@ -106,44 +133,40 @@ const elementToInlineNode = (node: Element): MentionElement | EmoticonElement |
return undefined; return undefined;
}; };
const parseInlineNodes = (node: ChildNode): InlineElement[] => { const getInlineElement = (node: ChildNode, processText: ProcessTextCallback): InlineElement[] => {
if (isText(node)) { if (isText(node)) {
return [{ text: node.data }]; return [{ text: processText(node.data) }];
} }
if (isTag(node)) { if (isTag(node)) {
const markType = elementToTextMark(node); const markType = getInlineNodeMarkType(node);
if (markType) { if (markType) {
const children = node.children.flatMap(parseInlineNodes); return getInlineMarkElement(markType, node, (child) => {
if (node.attribs['data-md'] !== undefined) { if (markType === MarkType.Code) return [{ text: getText(child) }];
children.unshift({ text: node.attribs['data-md'] }); return getInlineElement(child, processText);
children.push({ text: node.attribs['data-md'] }); });
} else {
children.forEach((child) => {
if (Text.isText(child)) {
child[markType] = true;
}
});
}
return children;
} }
const inlineNode = elementToInlineNode(node); const inlineNode = getInlineNonMarkElement(node);
if (inlineNode) return [inlineNode]; if (inlineNode) return [inlineNode];
if (node.name === 'a') { if (node.name === 'a') {
const children = node.childNodes.flatMap(parseInlineNodes); const children = node.childNodes.flatMap((child) => getInlineElement(child, processText));
children.unshift({ text: '[' }); children.unshift({ text: '[' });
children.push({ text: `](${node.attribs.href})` }); children.push({ text: `](${node.attribs.href})` });
return children; return children;
} }
return node.childNodes.flatMap(parseInlineNodes); return node.childNodes.flatMap((child) => getInlineElement(child, processText));
} }
return []; return [];
}; };
const parseBlockquoteNode = (node: Element): BlockQuoteElement[] | ParagraphElement[] => { const parseBlockquoteNode = (
node: Element,
processText: ProcessTextCallback
): BlockQuoteElement[] | ParagraphElement[] => {
const quoteLines: Array<InlineElement[]> = []; const quoteLines: Array<InlineElement[]> = [];
let lineHolder: InlineElement[] = []; let lineHolder: InlineElement[] = [];
@@ -156,7 +179,7 @@ const parseBlockquoteNode = (node: Element): BlockQuoteElement[] | ParagraphElem
node.children.forEach((child) => { node.children.forEach((child) => {
if (isText(child)) { if (isText(child)) {
lineHolder.push({ text: child.data }); lineHolder.push({ text: processText(child.data) });
return; return;
} }
if (isTag(child)) { if (isTag(child)) {
@@ -168,19 +191,20 @@ const parseBlockquoteNode = (node: Element): BlockQuoteElement[] | ParagraphElem
if (child.name === 'p') { if (child.name === 'p') {
appendLine(); appendLine();
quoteLines.push(child.children.flatMap((c) => parseInlineNodes(c))); quoteLines.push(child.children.flatMap((c) => getInlineElement(c, processText)));
return; return;
} }
parseInlineNodes(child).forEach((inlineNode) => lineHolder.push(inlineNode)); lineHolder.push(...getInlineElement(child, processText));
} }
}); });
appendLine(); appendLine();
if (node.attribs['data-md'] !== undefined) { const mdSequence = node.attribs['data-md'];
if (mdSequence !== undefined) {
return quoteLines.map((lineChildren) => ({ return quoteLines.map((lineChildren) => ({
type: BlockType.Paragraph, type: BlockType.Paragraph,
children: [{ text: `${node.attribs['data-md']} ` }, ...lineChildren], children: [{ text: `${mdSequence} ` }, ...lineChildren],
})); }));
} }
@@ -195,22 +219,19 @@ const parseBlockquoteNode = (node: Element): BlockQuoteElement[] | ParagraphElem
]; ];
}; };
const parseCodeBlockNode = (node: Element): CodeBlockElement[] | ParagraphElement[] => { const parseCodeBlockNode = (node: Element): CodeBlockElement[] | ParagraphElement[] => {
const codeLines = parseNodeText(node).trim().split('\n'); const codeLines = getText(node).trim().split('\n');
if (node.attribs['data-md'] !== undefined) { const mdSequence = node.attribs['data-md'];
const pLines = codeLines.map<ParagraphElement>((lineText) => ({ if (mdSequence !== undefined) {
const pLines = codeLines.map<ParagraphElement>((text) => ({
type: BlockType.Paragraph, type: BlockType.Paragraph,
children: [ children: [{ text }],
{
text: lineText,
},
],
})); }));
const childCode = node.children[0]; const childCode = node.children[0];
const className = const className =
isTag(childCode) && childCode.tagName === 'code' ? childCode.attribs.class ?? '' : ''; isTag(childCode) && childCode.tagName === 'code' ? childCode.attribs.class ?? '' : '';
const prefix = { text: `${node.attribs['data-md']}${className.replace('language-', '')}` }; const prefix = { text: `${mdSequence}${className.replace('language-', '')}` };
const suffix = { text: node.attribs['data-md'] }; const suffix = { text: mdSequence };
return [ return [
{ type: BlockType.Paragraph, children: [prefix] }, { type: BlockType.Paragraph, children: [prefix] },
...pLines, ...pLines,
@@ -221,19 +242,16 @@ const parseCodeBlockNode = (node: Element): CodeBlockElement[] | ParagraphElemen
return [ return [
{ {
type: BlockType.CodeBlock, type: BlockType.CodeBlock,
children: codeLines.map<CodeLineElement>((lineTxt) => ({ children: codeLines.map<CodeLineElement>((text) => ({
type: BlockType.CodeLine, type: BlockType.CodeLine,
children: [ children: [{ text }],
{
text: lineTxt,
},
],
})), })),
}, },
]; ];
}; };
const parseListNode = ( const parseListNode = (
node: Element node: Element,
processText: ProcessTextCallback
): OrderedListElement[] | UnorderedListElement[] | ParagraphElement[] => { ): OrderedListElement[] | UnorderedListElement[] | ParagraphElement[] => {
const listLines: Array<InlineElement[]> = []; const listLines: Array<InlineElement[]> = [];
let lineHolder: InlineElement[] = []; let lineHolder: InlineElement[] = [];
@@ -247,7 +265,7 @@ const parseListNode = (
node.children.forEach((child) => { node.children.forEach((child) => {
if (isText(child)) { if (isText(child)) {
lineHolder.push({ text: child.data }); lineHolder.push({ text: processText(child.data) });
return; return;
} }
if (isTag(child)) { if (isTag(child)) {
@@ -259,17 +277,18 @@ const parseListNode = (
if (child.name === 'li') { if (child.name === 'li') {
appendLine(); appendLine();
listLines.push(child.children.flatMap((c) => parseInlineNodes(c))); listLines.push(child.children.flatMap((c) => getInlineElement(c, processText)));
return; return;
} }
parseInlineNodes(child).forEach((inlineNode) => lineHolder.push(inlineNode)); lineHolder.push(...getInlineElement(child, processText));
} }
}); });
appendLine(); appendLine();
if (node.attribs['data-md'] !== undefined) { const mdSequence = node.attribs['data-md'];
const prefix = node.attribs['data-md'] || '-'; if (mdSequence !== undefined) {
const prefix = mdSequence || '-';
const [starOrHyphen] = prefix.match(/^\*|-$/) ?? []; const [starOrHyphen] = prefix.match(/^\*|-$/) ?? [];
return listLines.map((lineChildren) => ({ return listLines.map((lineChildren) => ({
type: BlockType.Paragraph, type: BlockType.Paragraph,
@@ -302,17 +321,21 @@ const parseListNode = (
}, },
]; ];
}; };
const parseHeadingNode = (node: Element): HeadingElement | ParagraphElement => { const parseHeadingNode = (
const children = node.children.flatMap((child) => parseInlineNodes(child)); node: Element,
processText: ProcessTextCallback
): HeadingElement | ParagraphElement => {
const children = node.children.flatMap((child) => getInlineElement(child, processText));
const headingMatch = node.name.match(/^h([123456])$/); const headingMatch = node.name.match(/^h([123456])$/);
const [, g1AsLevel] = headingMatch ?? ['h3', '3']; const [, g1AsLevel] = headingMatch ?? ['h3', '3'];
const level = parseInt(g1AsLevel, 10); const level = parseInt(g1AsLevel, 10);
if (node.attribs['data-md'] !== undefined) { const mdSequence = node.attribs['data-md'];
if (mdSequence !== undefined) {
return { return {
type: BlockType.Paragraph, type: BlockType.Paragraph,
children: [{ text: `${node.attribs['data-md']} ` }, ...children], children: [{ text: `${mdSequence} ` }, ...children],
}; };
} }
@@ -323,7 +346,11 @@ const parseHeadingNode = (node: Element): HeadingElement | ParagraphElement => {
}; };
}; };
export const domToEditorInput = (domNodes: ChildNode[]): Descendant[] => { export const domToEditorInput = (
domNodes: ChildNode[],
processText: ProcessTextCallback,
processLineStartText: ProcessTextCallback
): Descendant[] => {
const children: Descendant[] = []; const children: Descendant[] = [];
let lineHolder: InlineElement[] = []; let lineHolder: InlineElement[] = [];
@@ -340,7 +367,14 @@ export const domToEditorInput = (domNodes: ChildNode[]): Descendant[] => {
domNodes.forEach((node) => { domNodes.forEach((node) => {
if (isText(node)) { if (isText(node)) {
lineHolder.push({ text: node.data }); if (lineHolder.length === 0) {
// we are inserting first part of line
// it may contain block markdown starting data
// that we may need to escape.
lineHolder.push({ text: processLineStartText(node.data) });
return;
}
lineHolder.push({ text: processText(node.data) });
return; return;
} }
if (isTag(node)) { if (isTag(node)) {
@@ -354,14 +388,14 @@ export const domToEditorInput = (domNodes: ChildNode[]): Descendant[] => {
appendLine(); appendLine();
children.push({ children.push({
type: BlockType.Paragraph, type: BlockType.Paragraph,
children: node.children.flatMap((child) => parseInlineNodes(child)), children: node.children.flatMap((child) => getInlineElement(child, processText)),
}); });
return; return;
} }
if (node.name === 'blockquote') { if (node.name === 'blockquote') {
appendLine(); appendLine();
children.push(...parseBlockquoteNode(node)); children.push(...parseBlockquoteNode(node, processText));
return; return;
} }
if (node.name === 'pre') { if (node.name === 'pre') {
@@ -371,17 +405,17 @@ export const domToEditorInput = (domNodes: ChildNode[]): Descendant[] => {
} }
if (node.name === 'ol' || node.name === 'ul') { if (node.name === 'ol' || node.name === 'ul') {
appendLine(); appendLine();
children.push(...parseListNode(node)); children.push(...parseListNode(node, processText));
return; return;
} }
if (node.name.match(/^h[123456]$/)) { if (node.name.match(/^h[123456]$/)) {
appendLine(); appendLine();
children.push(parseHeadingNode(node)); children.push(parseHeadingNode(node, processText));
return; return;
} }
parseInlineNodes(node).forEach((inlineNode) => lineHolder.push(inlineNode)); lineHolder.push(...getInlineElement(node, processText));
} }
}); });
appendLine(); appendLine();
@@ -389,21 +423,31 @@ export const domToEditorInput = (domNodes: ChildNode[]): Descendant[] => {
return children; return children;
}; };
export const htmlToEditorInput = (unsafeHtml: string): Descendant[] => { export const htmlToEditorInput = (unsafeHtml: string, markdown?: boolean): Descendant[] => {
const sanitizedHtml = sanitizeCustomHtml(unsafeHtml); const sanitizedHtml = sanitizeCustomHtml(unsafeHtml);
const processText = (partText: string) => {
if (!markdown) return partText;
return escapeMarkdownInlineSequences(partText);
};
const domNodes = parse(sanitizedHtml); const domNodes = parse(sanitizedHtml);
const editorNodes = domToEditorInput(domNodes); const editorNodes = domToEditorInput(domNodes, processText, (lineStartText: string) => {
if (!markdown) return lineStartText;
return escapeMarkdownBlockSequences(lineStartText, processText);
});
return editorNodes; return editorNodes;
}; };
export const plainToEditorInput = (text: string): Descendant[] => { export const plainToEditorInput = (text: string, markdown?: boolean): Descendant[] => {
const editorNodes: Descendant[] = text.split('\n').map((lineText) => { const editorNodes: Descendant[] = text.split('\n').map((lineText) => {
const paragraphNode: ParagraphElement = { const paragraphNode: ParagraphElement = {
type: BlockType.Paragraph, type: BlockType.Paragraph,
children: [ children: [
{ {
text: lineText, text: markdown
? escapeMarkdownBlockSequences(lineText, escapeMarkdownInlineSequences)
: lineText,
}, },
], ],
}; };

View File

@@ -1,10 +1,17 @@
import { Descendant, Text } from 'slate'; import { Descendant, Editor, Text } from 'slate';
import { MatrixClient } from 'matrix-js-sdk';
import { sanitizeText } from '../../utils/sanitize'; import { sanitizeText } from '../../utils/sanitize';
import { BlockType } from './types'; import { BlockType } from './types';
import { CustomElement } from './slate'; import { CustomElement } from './slate';
import { parseBlockMD, parseInlineMD } from '../../plugins/markdown'; import {
parseBlockMD,
parseInlineMD,
unescapeMarkdownBlockSequences,
unescapeMarkdownInlineSequences,
} from '../../plugins/markdown';
import { findAndReplace } from '../../utils/findAndReplace'; import { findAndReplace } from '../../utils/findAndReplace';
import { sanitizeForRegex } from '../../utils/regex';
import { getCanonicalAliasOrRoomId, isUserId } from '../../utils/matrix';
export type OutputOptions = { export type OutputOptions = {
allowTextFormatting?: boolean; allowTextFormatting?: boolean;
@@ -18,7 +25,7 @@ const textToCustomHtml = (node: Text, opts: OutputOptions): string => {
if (node.bold) string = `<strong>${string}</strong>`; if (node.bold) string = `<strong>${string}</strong>`;
if (node.italic) string = `<i>${string}</i>`; if (node.italic) string = `<i>${string}</i>`;
if (node.underline) string = `<u>${string}</u>`; if (node.underline) string = `<u>${string}</u>`;
if (node.strikeThrough) string = `<del>${string}</del>`; if (node.strikeThrough) string = `<s>${string}</s>`;
if (node.code) string = `<code>${string}</code>`; if (node.code) string = `<code>${string}</code>`;
if (node.spoiler) string = `<span data-mx-spoiler>${string}</span>`; if (node.spoiler) string = `<span data-mx-spoiler>${string}</span>`;
} }
@@ -101,7 +108,8 @@ export const toMatrixCustomHTML = (
allowBlockMarkdown: false, allowBlockMarkdown: false,
}) })
.replace(/<br\/>$/, '\n') .replace(/<br\/>$/, '\n')
.replace(/^&gt;/, '>'); .replace(/^(\\*)&gt;/, '$1>');
markdownLines += line; markdownLines += line;
if (index === targetNodes.length - 1) { if (index === targetNodes.length - 1) {
return parseBlockMD(markdownLines, ignoreHTMLParseInlineMD); return parseBlockMD(markdownLines, ignoreHTMLParseInlineMD);
@@ -156,11 +164,14 @@ const elementToPlainText = (node: CustomElement, children: string): string => {
} }
}; };
export const toPlainText = (node: Descendant | Descendant[]): string => { export const toPlainText = (node: Descendant | Descendant[], isMarkdown: boolean): string => {
if (Array.isArray(node)) return node.map((n) => toPlainText(n)).join(''); if (Array.isArray(node)) return node.map((n) => toPlainText(n, isMarkdown)).join('');
if (Text.isText(node)) return node.text; if (Text.isText(node))
return isMarkdown
? unescapeMarkdownBlockSequences(node.text, unescapeMarkdownInlineSequences)
: node.text;
const children = node.children.map((n) => toPlainText(n)).join(''); const children = node.children.map((n) => toPlainText(n, isMarkdown)).join('');
return elementToPlainText(node, children); return elementToPlainText(node, children);
}; };
@@ -179,9 +190,42 @@ export const customHtmlEqualsPlainText = (customHtml: string, plain: string): bo
export const trimCustomHtml = (customHtml: string) => customHtml.replace(/<br\/>$/g, '').trim(); export const trimCustomHtml = (customHtml: string) => customHtml.replace(/<br\/>$/g, '').trim();
export const trimCommand = (cmdName: string, str: string) => { export const trimCommand = (cmdName: string, str: string) => {
const cmdRegX = new RegExp(`^(\\s+)?(\\/${cmdName})([^\\S\n]+)?`); const cmdRegX = new RegExp(`^(\\s+)?(\\/${sanitizeForRegex(cmdName)})([^\\S\n]+)?`);
const match = str.match(cmdRegX); const match = str.match(cmdRegX);
if (!match) return str; if (!match) return str;
return str.slice(match[0].length); return str.slice(match[0].length);
}; };
export type MentionsData = {
room: boolean;
users: Set<string>;
};
export const getMentions = (mx: MatrixClient, roomId: string, editor: Editor): MentionsData => {
const mentionData: MentionsData = {
room: false,
users: new Set(),
};
const parseMentions = (node: Descendant): void => {
if (Text.isText(node)) return;
if (node.type === BlockType.CodeBlock) return;
if (node.type === BlockType.Mention) {
if (node.id === getCanonicalAliasOrRoomId(mx, roomId)) {
mentionData.room = true;
}
if (isUserId(node.id) && node.id !== mx.getUserId()) {
mentionData.users.add(node.id);
}
return;
}
node.children.forEach(parseMentions);
};
editor.children.forEach(parseMentions);
return mentionData;
};

View File

@@ -50,6 +50,7 @@ import { addRecentEmoji } from '../../plugins/recent-emoji';
import { mobileOrTablet } from '../../utils/user-agent'; import { mobileOrTablet } from '../../utils/user-agent';
import { useMediaAuthentication } from '../../hooks/useMediaAuthentication'; import { useMediaAuthentication } from '../../hooks/useMediaAuthentication';
import { ImagePack, ImageUsage, PackImageReader } from '../../plugins/custom-emoji'; import { ImagePack, ImageUsage, PackImageReader } from '../../plugins/custom-emoji';
import { getEmoticonSearchStr } from '../../plugins/utils';
const RECENT_GROUP_ID = 'recent_group'; const RECENT_GROUP_ID = 'recent_group';
const SEARCH_GROUP_ID = 'search_group'; const SEARCH_GROUP_ID = 'search_group';
@@ -471,36 +472,34 @@ export function SearchEmojiGroup({
return ( return (
<EmojiGroup key={id} id={id} label={label}> <EmojiGroup key={id} id={id} label={label}>
{tab === EmojiBoardTab.Emoji {tab === EmojiBoardTab.Emoji
? searchResult ? searchResult.map((emoji) =>
.sort((a, b) => a.shortcode.localeCompare(b.shortcode)) 'unicode' in emoji ? (
.map((emoji) => <EmojiItem
'unicode' in emoji ? ( key={emoji.unicode}
<EmojiItem label={emoji.label}
key={emoji.unicode} type={EmojiType.Emoji}
label={emoji.label} data={emoji.unicode}
type={EmojiType.Emoji} shortcode={emoji.shortcode}
data={emoji.unicode} >
shortcode={emoji.shortcode} {emoji.unicode}
> </EmojiItem>
{emoji.unicode} ) : (
</EmojiItem> <EmojiItem
) : ( key={emoji.shortcode}
<EmojiItem label={emoji.body || emoji.shortcode}
key={emoji.shortcode} type={EmojiType.CustomEmoji}
label={emoji.body || emoji.shortcode} data={emoji.url}
type={EmojiType.CustomEmoji} shortcode={emoji.shortcode}
data={emoji.url} >
shortcode={emoji.shortcode} <img
> loading="lazy"
<img className={css.CustomEmojiImg}
loading="lazy" alt={emoji.body || emoji.shortcode}
className={css.CustomEmojiImg} src={mxcUrlToHttp(mx, emoji.url, useAuthentication) ?? emoji.url}
alt={emoji.body || emoji.shortcode} />
src={mxcUrlToHttp(mx, emoji.url, useAuthentication) ?? emoji.url} </EmojiItem>
/>
</EmojiItem>
)
) )
)
: searchResult.map((emoji) => : searchResult.map((emoji) =>
'unicode' in emoji ? null : ( 'unicode' in emoji ? null : (
<StickerItem <StickerItem
@@ -638,15 +637,8 @@ export const NativeEmojiGroups = memo(
) )
); );
const getSearchListItemStr = (item: PackImageReader | IEmoji) => {
const shortcode = `:${item.shortcode}:`;
if ('body' in item) {
return [shortcode, item.body ?? ''];
}
return shortcode;
};
const SEARCH_OPTIONS: UseAsyncSearchOptions = { const SEARCH_OPTIONS: UseAsyncSearchOptions = {
limit: 26, limit: 1000,
matchOptions: { matchOptions: {
contain: true, contain: true,
}, },
@@ -698,10 +690,12 @@ export function EmojiBoard({
const [result, search, resetSearch] = useAsyncSearch( const [result, search, resetSearch] = useAsyncSearch(
searchList, searchList,
getSearchListItemStr, getEmoticonSearchStr,
SEARCH_OPTIONS SEARCH_OPTIONS
); );
const searchedItems = result?.items.slice(0, 100);
const handleOnChange: ChangeEventHandler<HTMLInputElement> = useDebounce( const handleOnChange: ChangeEventHandler<HTMLInputElement> = useDebounce(
useCallback( useCallback(
(evt) => { (evt) => {
@@ -922,13 +916,13 @@ export function EmojiBoard({
direction="Column" direction="Column"
gap="200" gap="200"
> >
{result && ( {searchedItems && (
<SearchEmojiGroup <SearchEmojiGroup
mx={mx} mx={mx}
tab={tab} tab={tab}
id={SEARCH_GROUP_ID} id={SEARCH_GROUP_ID}
label={result.items.length ? 'Search Results' : 'No Results found'} label={searchedItems.length ? 'Search Results' : 'No Results found'}
emojis={result.items} emojis={searchedItems}
useAuthentication={useAuthentication} useAuthentication={useAuthentication}
/> />
)} )}

View File

@@ -22,6 +22,8 @@ import {
IThumbnailContent, IThumbnailContent,
IVideoContent, IVideoContent,
IVideoInfo, IVideoInfo,
MATRIX_SPOILER_PROPERTY_NAME,
MATRIX_SPOILER_REASON_PROPERTY_NAME,
} from '../../../types/matrix/common'; } from '../../../types/matrix/common';
import { FALLBACK_MIMETYPE, getBlobSafeMimeType } from '../../utils/mimeTypes'; import { FALLBACK_MIMETYPE, getBlobSafeMimeType } from '../../utils/mimeTypes';
import { parseGeoUri, scaleYDimension } from '../../utils/common'; import { parseGeoUri, scaleYDimension } from '../../utils/common';
@@ -177,6 +179,8 @@ type RenderImageContentProps = {
mimeType?: string; mimeType?: string;
url: string; url: string;
encInfo?: IEncryptedFile; encInfo?: IEncryptedFile;
markedAsSpoiler?: boolean;
spoilerReason?: string;
}; };
type MImageProps = { type MImageProps = {
content: IImageContent; content: IImageContent;
@@ -204,6 +208,8 @@ export function MImage({ content, renderImageContent, outlined }: MImageProps) {
mimeType: imgInfo?.mimetype, mimeType: imgInfo?.mimetype,
url: mxcUrl, url: mxcUrl,
encInfo: content.file, encInfo: content.file,
markedAsSpoiler: content[MATRIX_SPOILER_PROPERTY_NAME],
spoilerReason: content[MATRIX_SPOILER_REASON_PROPERTY_NAME],
})} })}
</AttachmentBox> </AttachmentBox>
</Attachment> </Attachment>

View File

@@ -3,6 +3,7 @@ import {
Badge, Badge,
Box, Box,
Button, Button,
Chip,
Icon, Icon,
Icons, Icons,
Modal, Modal,
@@ -51,6 +52,8 @@ export type ImageContentProps = {
info?: IImageInfo; info?: IImageInfo;
encInfo?: EncryptedAttachmentInfo; encInfo?: EncryptedAttachmentInfo;
autoPlay?: boolean; autoPlay?: boolean;
markedAsSpoiler?: boolean;
spoilerReason?: string;
renderViewer: (props: RenderViewerProps) => ReactNode; renderViewer: (props: RenderViewerProps) => ReactNode;
renderImage: (props: RenderImageProps) => ReactNode; renderImage: (props: RenderImageProps) => ReactNode;
}; };
@@ -64,6 +67,8 @@ export const ImageContent = as<'div', ImageContentProps>(
info, info,
encInfo, encInfo,
autoPlay, autoPlay,
markedAsSpoiler,
spoilerReason,
renderViewer, renderViewer,
renderImage, renderImage,
...props ...props
@@ -77,6 +82,7 @@ export const ImageContent = as<'div', ImageContentProps>(
const [load, setLoad] = useState(false); const [load, setLoad] = useState(false);
const [error, setError] = useState(false); const [error, setError] = useState(false);
const [viewer, setViewer] = useState(false); const [viewer, setViewer] = useState(false);
const [blurred, setBlurred] = useState(markedAsSpoiler ?? false);
const [srcState, loadSrc] = useAsyncCallback( const [srcState, loadSrc] = useAsyncCallback(
useCallback(async () => { useCallback(async () => {
@@ -145,7 +151,7 @@ export const ImageContent = as<'div', ImageContentProps>(
punch={1} punch={1}
/> />
)} )}
{!autoPlay && srcState.status === AsyncStatus.Idle && ( {!autoPlay && !markedAsSpoiler && srcState.status === AsyncStatus.Idle && (
<Box className={css.AbsoluteContainer} alignItems="Center" justifyContent="Center"> <Box className={css.AbsoluteContainer} alignItems="Center" justifyContent="Center">
<Button <Button
variant="Secondary" variant="Secondary"
@@ -160,7 +166,7 @@ export const ImageContent = as<'div', ImageContentProps>(
</Box> </Box>
)} )}
{srcState.status === AsyncStatus.Success && ( {srcState.status === AsyncStatus.Success && (
<Box className={css.AbsoluteContainer}> <Box className={classNames(css.AbsoluteContainer, blurred && css.Blur)}>
{renderImage({ {renderImage({
alt: body, alt: body,
title: body, title: body,
@@ -172,8 +178,42 @@ export const ImageContent = as<'div', ImageContentProps>(
})} })}
</Box> </Box>
)} )}
{blurred && !error && srcState.status !== AsyncStatus.Error && (
<Box className={css.AbsoluteContainer} alignItems="Center" justifyContent="Center">
<TooltipProvider
tooltip={
typeof spoilerReason === 'string' && (
<Tooltip variant="Secondary">
<Text>{spoilerReason}</Text>
</Tooltip>
)
}
position="Top"
align="Center"
>
{(triggerRef) => (
<Chip
ref={triggerRef}
variant="Secondary"
radii="Pill"
size="500"
outlined
onClick={() => {
setBlurred(false);
if (srcState.status === AsyncStatus.Idle) {
loadSrc();
}
}}
>
<Text size="B300">Spoiler</Text>
</Chip>
)}
</TooltipProvider>
</Box>
)}
{(srcState.status === AsyncStatus.Loading || srcState.status === AsyncStatus.Success) && {(srcState.status === AsyncStatus.Loading || srcState.status === AsyncStatus.Success) &&
!load && ( !load &&
!markedAsSpoiler && (
<Box className={css.AbsoluteContainer} alignItems="Center" justifyContent="Center"> <Box className={css.AbsoluteContainer} alignItems="Center" justifyContent="Center">
<Spinner variant="Secondary" /> <Spinner variant="Secondary" />
</Box> </Box>

View File

@@ -30,3 +30,10 @@ export const AbsoluteFooter = style([
right: config.space.S100, right: config.space.S100,
}, },
]); ]);
export const Blur = style([
DefaultReset,
{
filter: 'blur(44px)',
},
]);

View File

@@ -1,29 +1,42 @@
import React, { useEffect } from 'react'; import React, { useCallback, useEffect } from 'react';
import { Chip, Icon, IconButton, Icons, Text, color } from 'folds'; import { Chip, Icon, IconButton, Icons, Text, Tooltip, TooltipProvider, color } from 'folds';
import { UploadCard, UploadCardError, UploadCardProgress } from './UploadCard'; import { UploadCard, UploadCardError, UploadCardProgress } from './UploadCard';
import { TUploadAtom, UploadStatus, UploadSuccess, useBindUploadAtom } from '../../state/upload'; import { UploadStatus, UploadSuccess, useBindUploadAtom } from '../../state/upload';
import { useMatrixClient } from '../../hooks/useMatrixClient'; import { useMatrixClient } from '../../hooks/useMatrixClient';
import { TUploadContent } from '../../utils/matrix'; import { TUploadContent } from '../../utils/matrix';
import { getFileTypeIcon } from '../../utils/common'; import { getFileTypeIcon } from '../../utils/common';
import {
roomUploadAtomFamily,
TUploadItem,
TUploadMetadata,
} from '../../state/room/roomInputDrafts';
type UploadCardRendererProps = { type UploadCardRendererProps = {
isEncrypted?: boolean; isEncrypted?: boolean;
uploadAtom: TUploadAtom; fileItem: TUploadItem;
setMetadata: (metadata: TUploadMetadata) => void;
onRemove: (file: TUploadContent) => void; onRemove: (file: TUploadContent) => void;
onComplete?: (upload: UploadSuccess) => void; onComplete?: (upload: UploadSuccess) => void;
}; };
export function UploadCardRenderer({ export function UploadCardRenderer({
isEncrypted, isEncrypted,
uploadAtom, fileItem,
setMetadata,
onRemove, onRemove,
onComplete, onComplete,
}: UploadCardRendererProps) { }: UploadCardRendererProps) {
const mx = useMatrixClient(); const mx = useMatrixClient();
const uploadAtom = roomUploadAtomFamily(fileItem.file);
const { metadata } = fileItem;
const { upload, startUpload, cancelUpload } = useBindUploadAtom(mx, uploadAtom, isEncrypted); const { upload, startUpload, cancelUpload } = useBindUploadAtom(mx, uploadAtom, isEncrypted);
const { file } = upload; const { file } = upload;
if (upload.status === UploadStatus.Idle) startUpload(); if (upload.status === UploadStatus.Idle) startUpload();
const toggleSpoiler = useCallback(() => {
setMetadata({ ...metadata, markedAsSpoiler: !metadata.markedAsSpoiler });
}, [setMetadata, metadata]);
const removeUpload = () => { const removeUpload = () => {
cancelUpload(); cancelUpload();
onRemove(file); onRemove(file);
@@ -53,6 +66,31 @@ export function UploadCardRenderer({
<Text size="B300">Retry</Text> <Text size="B300">Retry</Text>
</Chip> </Chip>
)} )}
{file.type.startsWith('image') && (
<TooltipProvider
tooltip={
<Tooltip variant="SurfaceVariant">
<Text>Mark as Spoiler</Text>
</Tooltip>
}
position="Top"
align="Center"
>
{(triggerRef) => (
<IconButton
ref={triggerRef}
onClick={toggleSpoiler}
aria-label="Mark as Spoiler"
variant="SurfaceVariant"
radii="Pill"
size="300"
aria-pressed={metadata.markedAsSpoiler}
>
<Icon src={Icons.EyeBlind} size="200" />
</IconButton>
)}
</TooltipProvider>
)}
<IconButton <IconButton
onClick={removeUpload} onClick={removeUpload}
aria-label="Cancel Upload" aria-label="Cancel Upload"

View File

@@ -155,7 +155,7 @@ function SettingsMenuItem({
disabled?: boolean; disabled?: boolean;
}) { }) {
const handleSettings = () => { const handleSettings = () => {
if (item.space) { if ('space' in item) {
openSpaceSettings(item.roomId); openSpaceSettings(item.roomId);
} else { } else {
toggleRoomSettings(item.roomId); toggleRoomSettings(item.roomId);
@@ -271,7 +271,7 @@ export function HierarchyItemMenu({
</Text> </Text>
</MenuItem> </MenuItem>
{promptLeave && {promptLeave &&
(item.space ? ( ('space' in item ? (
<LeaveSpacePrompt <LeaveSpacePrompt
roomId={item.roomId} roomId={item.roomId}
onDone={handleRequestClose} onDone={handleRequestClose}

View File

@@ -5,9 +5,15 @@ import { useAtom, useAtomValue } from 'jotai';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { JoinRule, RestrictedAllowType, Room } from 'matrix-js-sdk'; import { JoinRule, RestrictedAllowType, Room } from 'matrix-js-sdk';
import { RoomJoinRulesEventContent } from 'matrix-js-sdk/lib/types'; import { RoomJoinRulesEventContent } from 'matrix-js-sdk/lib/types';
import { IHierarchyRoom } from 'matrix-js-sdk/lib/@types/spaces';
import produce from 'immer';
import { useSpace } from '../../hooks/useSpace'; import { useSpace } from '../../hooks/useSpace';
import { Page, PageContent, PageContentCenter, PageHeroSection } from '../../components/page'; import { Page, PageContent, PageContentCenter, PageHeroSection } from '../../components/page';
import { HierarchyItem, useSpaceHierarchy } from '../../hooks/useSpaceHierarchy'; import {
HierarchyItem,
HierarchyItemSpace,
useSpaceHierarchy,
} from '../../hooks/useSpaceHierarchy';
import { VirtualTile } from '../../components/virtualizer'; import { VirtualTile } from '../../components/virtualizer';
import { spaceRoomsAtom } from '../../state/spaceRooms'; import { spaceRoomsAtom } from '../../state/spaceRooms';
import { MembersDrawer } from '../room/MembersDrawer'; import { MembersDrawer } from '../room/MembersDrawer';
@@ -25,18 +31,15 @@ import {
usePowerLevels, usePowerLevels,
useRoomsPowerLevels, useRoomsPowerLevels,
} from '../../hooks/usePowerLevels'; } from '../../hooks/usePowerLevels';
import { RoomItemCard } from './RoomItem';
import { mDirectAtom } from '../../state/mDirectList'; import { mDirectAtom } from '../../state/mDirectList';
import { SpaceItemCard } from './SpaceItem';
import { makeLobbyCategoryId } from '../../state/closedLobbyCategories'; import { makeLobbyCategoryId } from '../../state/closedLobbyCategories';
import { useCategoryHandler } from '../../hooks/useCategoryHandler'; import { useCategoryHandler } from '../../hooks/useCategoryHandler';
import { useMatrixClient } from '../../hooks/useMatrixClient'; import { useMatrixClient } from '../../hooks/useMatrixClient';
import { allRoomsAtom } from '../../state/room-list/roomList'; import { allRoomsAtom } from '../../state/room-list/roomList';
import { getCanonicalAliasOrRoomId } from '../../utils/matrix'; import { getCanonicalAliasOrRoomId } from '../../utils/matrix';
import { getSpaceRoomPath } from '../../pages/pathUtils'; import { getSpaceRoomPath } from '../../pages/pathUtils';
import { HierarchyItemMenu } from './HierarchyItemMenu';
import { StateEvent } from '../../../types/matrix/room'; import { StateEvent } from '../../../types/matrix/room';
import { AfterItemDropTarget, CanDropCallback, useDnDMonitor } from './DnD'; import { CanDropCallback, useDnDMonitor } from './DnD';
import { ASCIILexicalTable, orderKeys } from '../../utils/ASCIILexicalTable'; import { ASCIILexicalTable, orderKeys } from '../../utils/ASCIILexicalTable';
import { getStateEvent } from '../../utils/room'; import { getStateEvent } from '../../utils/room';
import { useClosedLobbyCategoriesAtom } from '../../state/hooks/closedLobbyCategories'; import { useClosedLobbyCategoriesAtom } from '../../state/hooks/closedLobbyCategories';
@@ -49,6 +52,7 @@ import { useOrphanSpaces } from '../../state/hooks/roomList';
import { roomToParentsAtom } from '../../state/room/roomToParents'; import { roomToParentsAtom } from '../../state/room/roomToParents';
import { AccountDataEvent } from '../../../types/matrix/accountData'; import { AccountDataEvent } from '../../../types/matrix/accountData';
import { useRoomMembers } from '../../hooks/useRoomMembers'; import { useRoomMembers } from '../../hooks/useRoomMembers';
import { SpaceHierarchy } from './SpaceHierarchy';
export function Lobby() { export function Lobby() {
const navigate = useNavigate(); const navigate = useNavigate();
@@ -81,6 +85,8 @@ export function Lobby() {
return new Set(sideSpaces); return new Set(sideSpaces);
}, [sidebarItems]); }, [sidebarItems]);
const [spacesItems, setSpacesItem] = useState<Map<string, IHierarchyRoom>>(() => new Map());
useElementSizeObserver( useElementSizeObserver(
useCallback(() => heroSectionRef.current, []), useCallback(() => heroSectionRef.current, []),
useCallback((w, height) => setHeroSectionHeight(height), []) useCallback((w, height) => setHeroSectionHeight(height), [])
@@ -107,19 +113,20 @@ export function Lobby() {
); );
const [draggingItem, setDraggingItem] = useState<HierarchyItem>(); const [draggingItem, setDraggingItem] = useState<HierarchyItem>();
const flattenHierarchy = useSpaceHierarchy( const hierarchy = useSpaceHierarchy(
space.roomId, space.roomId,
spaceRooms, spaceRooms,
getRoom, getRoom,
useCallback( useCallback(
(childId) => (childId) =>
closedCategories.has(makeLobbyCategoryId(space.roomId, childId)) || !!draggingItem?.space, closedCategories.has(makeLobbyCategoryId(space.roomId, childId)) ||
(draggingItem ? 'space' in draggingItem : false),
[closedCategories, space.roomId, draggingItem] [closedCategories, space.roomId, draggingItem]
) )
); );
const virtualizer = useVirtualizer({ const virtualizer = useVirtualizer({
count: flattenHierarchy.length, count: hierarchy.length,
getScrollElement: () => scrollRef.current, getScrollElement: () => scrollRef.current,
estimateSize: () => 1, estimateSize: () => 1,
overscan: 2, overscan: 2,
@@ -129,8 +136,17 @@ export function Lobby() {
const roomsPowerLevels = useRoomsPowerLevels( const roomsPowerLevels = useRoomsPowerLevels(
useMemo( useMemo(
() => flattenHierarchy.map((i) => mx.getRoom(i.roomId)).filter((r) => !!r) as Room[], () =>
[mx, flattenHierarchy] hierarchy
.flatMap((i) => {
const childRooms = Array.isArray(i.rooms)
? i.rooms.map((r) => mx.getRoom(r.roomId))
: [];
return [mx.getRoom(i.space.roomId), ...childRooms];
})
.filter((r) => !!r) as Room[],
[mx, hierarchy]
) )
); );
@@ -142,8 +158,8 @@ export function Lobby() {
return false; return false;
} }
if (item.space) { if ('space' in item) {
if (!container.item.space) return false; if (!('space' in container.item)) return false;
const containerSpaceId = space.roomId; const containerSpaceId = space.roomId;
if ( if (
@@ -156,9 +172,8 @@ export function Lobby() {
return true; return true;
} }
const containerSpaceId = container.item.space const containerSpaceId =
? container.item.roomId 'space' in container.item ? container.item.roomId : container.item.parentId;
: container.item.parentId;
const dropOutsideSpace = item.parentId !== containerSpaceId; const dropOutsideSpace = item.parentId !== containerSpaceId;
@@ -192,22 +207,22 @@ export function Lobby() {
); );
const reorderSpace = useCallback( const reorderSpace = useCallback(
(item: HierarchyItem, containerItem: HierarchyItem) => { (item: HierarchyItemSpace, containerItem: HierarchyItem) => {
if (!item.parentId) return; if (!item.parentId) return;
const childItems = flattenHierarchy const itemSpaces: HierarchyItemSpace[] = hierarchy
.filter((i) => i.parentId && i.space) .map((i) => i.space)
.filter((i) => i.roomId !== item.roomId); .filter((i) => i.roomId !== item.roomId);
const beforeIndex = childItems.findIndex((i) => i.roomId === containerItem.roomId); const beforeIndex = itemSpaces.findIndex((i) => i.roomId === containerItem.roomId);
const insertIndex = beforeIndex + 1; const insertIndex = beforeIndex + 1;
childItems.splice(insertIndex, 0, { itemSpaces.splice(insertIndex, 0, {
...item, ...item,
content: { ...item.content, order: undefined }, content: { ...item.content, order: undefined },
}); });
const currentOrders = childItems.map((i) => { const currentOrders = itemSpaces.map((i) => {
if (typeof i.content.order === 'string' && lex.has(i.content.order)) { if (typeof i.content.order === 'string' && lex.has(i.content.order)) {
return i.content.order; return i.content.order;
} }
@@ -217,21 +232,21 @@ export function Lobby() {
const newOrders = orderKeys(lex, currentOrders); const newOrders = orderKeys(lex, currentOrders);
newOrders?.forEach((orderKey, index) => { newOrders?.forEach((orderKey, index) => {
const itm = childItems[index]; const itm = itemSpaces[index];
if (!itm || !itm.parentId) return; if (!itm || !itm.parentId) return;
const parentPL = roomsPowerLevels.get(itm.parentId); const parentPL = roomsPowerLevels.get(itm.parentId);
const canEdit = parentPL && canEditSpaceChild(parentPL); const canEdit = parentPL && canEditSpaceChild(parentPL);
if (canEdit && orderKey !== currentOrders[index]) { if (canEdit && orderKey !== currentOrders[index]) {
mx.sendStateEvent( mx.sendStateEvent(
itm.parentId, itm.parentId,
StateEvent.SpaceChild, StateEvent.SpaceChild as any,
{ ...itm.content, order: orderKey }, { ...itm.content, order: orderKey },
itm.roomId itm.roomId
); );
} }
}); });
}, },
[mx, flattenHierarchy, lex, roomsPowerLevels, canEditSpaceChild] [mx, hierarchy, lex, roomsPowerLevels, canEditSpaceChild]
); );
const reorderRoom = useCallback( const reorderRoom = useCallback(
@@ -240,13 +255,12 @@ export function Lobby() {
if (!item.parentId) { if (!item.parentId) {
return; return;
} }
const containerParentId: string = containerItem.space const containerParentId: string =
? containerItem.roomId 'space' in containerItem ? containerItem.roomId : containerItem.parentId;
: containerItem.parentId;
const itemContent = item.content; const itemContent = item.content;
if (item.parentId !== containerParentId) { if (item.parentId !== containerParentId) {
mx.sendStateEvent(item.parentId, StateEvent.SpaceChild, {}, item.roomId); mx.sendStateEvent(item.parentId, StateEvent.SpaceChild as any, {}, item.roomId);
} }
if ( if (
@@ -265,28 +279,29 @@ export function Lobby() {
const allow = const allow =
joinRuleContent.allow?.filter((allowRule) => allowRule.room_id !== item.parentId) ?? []; joinRuleContent.allow?.filter((allowRule) => allowRule.room_id !== item.parentId) ?? [];
allow.push({ type: RestrictedAllowType.RoomMembership, room_id: containerParentId }); allow.push({ type: RestrictedAllowType.RoomMembership, room_id: containerParentId });
mx.sendStateEvent(itemRoom.roomId, StateEvent.RoomJoinRules, { mx.sendStateEvent(itemRoom.roomId, StateEvent.RoomJoinRules as any, {
...joinRuleContent, ...joinRuleContent,
allow, allow,
}); });
} }
} }
const childItems = flattenHierarchy const itemSpaces = Array.from(
.filter((i) => i.parentId === containerParentId && !i.space) hierarchy?.find((i) => i.space.roomId === containerParentId)?.rooms ?? []
.filter((i) => i.roomId !== item.roomId); );
const beforeItem: HierarchyItem | undefined = containerItem.space ? undefined : containerItem; const beforeItem: HierarchyItem | undefined =
const beforeIndex = childItems.findIndex((i) => i.roomId === beforeItem?.roomId); 'space' in containerItem ? undefined : containerItem;
const beforeIndex = itemSpaces.findIndex((i) => i.roomId === beforeItem?.roomId);
const insertIndex = beforeIndex + 1; const insertIndex = beforeIndex + 1;
childItems.splice(insertIndex, 0, { itemSpaces.splice(insertIndex, 0, {
...item, ...item,
parentId: containerParentId, parentId: containerParentId,
content: { ...itemContent, order: undefined }, content: { ...itemContent, order: undefined },
}); });
const currentOrders = childItems.map((i) => { const currentOrders = itemSpaces.map((i) => {
if (typeof i.content.order === 'string' && lex.has(i.content.order)) { if (typeof i.content.order === 'string' && lex.has(i.content.order)) {
return i.content.order; return i.content.order;
} }
@@ -296,18 +311,18 @@ export function Lobby() {
const newOrders = orderKeys(lex, currentOrders); const newOrders = orderKeys(lex, currentOrders);
newOrders?.forEach((orderKey, index) => { newOrders?.forEach((orderKey, index) => {
const itm = childItems[index]; const itm = itemSpaces[index];
if (itm && orderKey !== currentOrders[index]) { if (itm && orderKey !== currentOrders[index]) {
mx.sendStateEvent( mx.sendStateEvent(
containerParentId, containerParentId,
StateEvent.SpaceChild, StateEvent.SpaceChild as any,
{ ...itm.content, order: orderKey }, { ...itm.content, order: orderKey },
itm.roomId itm.roomId
); );
} }
}); });
}, },
[mx, flattenHierarchy, lex] [mx, hierarchy, lex]
); );
useDnDMonitor( useDnDMonitor(
@@ -318,7 +333,7 @@ export function Lobby() {
if (!canDrop(item, container)) { if (!canDrop(item, container)) {
return; return;
} }
if (item.space) { if ('space' in item) {
reorderSpace(item, container.item); reorderSpace(item, container.item);
} else { } else {
reorderRoom(item, container.item); reorderRoom(item, container.item);
@@ -328,8 +343,16 @@ export function Lobby() {
) )
); );
const addSpaceRoom = useCallback( const handleSpacesFound = useCallback(
(roomId: string) => setSpaceRooms({ type: 'PUT', roomId }), (sItems: IHierarchyRoom[]) => {
setSpaceRooms({ type: 'PUT', roomIds: sItems.map((i) => i.room_id) });
setSpacesItem((current) => {
const newItems = produce(current, (draft) => {
sItems.forEach((item) => draft.set(item.room_id, item));
});
return current.size === newItems.size ? current : newItems;
});
},
[setSpaceRooms] [setSpaceRooms]
); );
@@ -394,121 +417,44 @@ export function Lobby() {
<LobbyHero /> <LobbyHero />
</PageHeroSection> </PageHeroSection>
{vItems.map((vItem) => { {vItems.map((vItem) => {
const item = flattenHierarchy[vItem.index]; const item = hierarchy[vItem.index];
if (!item) return null; if (!item) return null;
const itemPowerLevel = roomsPowerLevels.get(item.roomId) ?? {}; const nextSpaceId = hierarchy[vItem.index + 1]?.space.roomId;
const userPLInItem = powerLevelAPI.getPowerLevel(
itemPowerLevel,
mx.getUserId() ?? undefined
);
const canInvite = powerLevelAPI.canDoAction(
itemPowerLevel,
'invite',
userPLInItem
);
const isJoined = allJoinedRooms.has(item.roomId);
const nextRoomId: string | undefined = const categoryId = makeLobbyCategoryId(space.roomId, item.space.roomId);
flattenHierarchy[vItem.index + 1]?.roomId;
const dragging =
draggingItem?.roomId === item.roomId &&
draggingItem.parentId === item.parentId;
if (item.space) {
const categoryId = makeLobbyCategoryId(space.roomId, item.roomId);
const { parentId } = item;
const parentPowerLevels = parentId
? roomsPowerLevels.get(parentId) ?? {}
: undefined;
return (
<VirtualTile
virtualItem={vItem}
style={{
paddingTop: vItem.index === 0 ? 0 : config.space.S500,
}}
ref={virtualizer.measureElement}
key={vItem.index}
>
<SpaceItemCard
item={item}
joined={allJoinedRooms.has(item.roomId)}
categoryId={categoryId}
closed={closedCategories.has(categoryId) || !!draggingItem?.space}
handleClose={handleCategoryClick}
getRoom={getRoom}
canEditChild={canEditSpaceChild(
roomsPowerLevels.get(item.roomId) ?? {}
)}
canReorder={
parentPowerLevels ? canEditSpaceChild(parentPowerLevels) : false
}
options={
parentId &&
parentPowerLevels && (
<HierarchyItemMenu
item={{ ...item, parentId }}
canInvite={canInvite}
joined={isJoined}
canEditChild={canEditSpaceChild(parentPowerLevels)}
pinned={sidebarSpaces.has(item.roomId)}
onTogglePin={togglePinToSidebar}
/>
)
}
before={item.parentId ? undefined : undefined}
after={
<AfterItemDropTarget
item={item}
nextRoomId={nextRoomId}
afterSpace
canDrop={canDrop}
/>
}
onDragging={setDraggingItem}
data-dragging={dragging}
/>
</VirtualTile>
);
}
const parentPowerLevels = roomsPowerLevels.get(item.parentId) ?? {};
const prevItem: HierarchyItem | undefined = flattenHierarchy[vItem.index - 1];
const nextItem: HierarchyItem | undefined = flattenHierarchy[vItem.index + 1];
return ( return (
<VirtualTile <VirtualTile
virtualItem={vItem} virtualItem={vItem}
style={{ paddingTop: config.space.S100 }} style={{
paddingTop: vItem.index === 0 ? 0 : config.space.S500,
}}
ref={virtualizer.measureElement} ref={virtualizer.measureElement}
key={vItem.index} key={vItem.index}
> >
<RoomItemCard <SpaceHierarchy
item={item} spaceItem={item.space}
onSpaceFound={addSpaceRoom} summary={spacesItems.get(item.space.roomId)}
dm={mDirects.has(item.roomId)} roomItems={item.rooms}
firstChild={!prevItem || prevItem.space === true} allJoinedRooms={allJoinedRooms}
lastChild={!nextItem || nextItem.space === true} mDirects={mDirects}
onOpen={handleOpenRoom} roomsPowerLevels={roomsPowerLevels}
getRoom={getRoom} canEditSpaceChild={canEditSpaceChild}
canReorder={canEditSpaceChild(parentPowerLevels)} categoryId={categoryId}
options={ closed={
<HierarchyItemMenu closedCategories.has(categoryId) ||
item={item} (draggingItem ? 'space' in draggingItem : false)
canInvite={canInvite}
joined={isJoined}
canEditChild={canEditSpaceChild(parentPowerLevels)}
/>
} }
after={ handleClose={handleCategoryClick}
<AfterItemDropTarget draggingItem={draggingItem}
item={item}
nextRoomId={nextRoomId}
canDrop={canDrop}
/>
}
data-dragging={dragging}
onDragging={setDraggingItem} onDragging={setDraggingItem}
canDrop={canDrop}
nextSpaceId={nextSpaceId}
getRoom={getRoom}
pinned={sidebarSpaces.has(item.space.roomId)}
togglePinToSidebar={togglePinToSidebar}
onSpacesFound={handleSpacesFound}
onOpenRoom={handleOpenRoom}
/> />
</VirtualTile> </VirtualTile>
); );

View File

@@ -1,4 +1,4 @@
import React, { MouseEventHandler, ReactNode, useCallback, useEffect, useRef } from 'react'; import React, { MouseEventHandler, ReactNode, useCallback, useRef } from 'react';
import { import {
Avatar, Avatar,
Badge, Badge,
@@ -20,23 +20,20 @@ import {
} from 'folds'; } from 'folds';
import FocusTrap from 'focus-trap-react'; import FocusTrap from 'focus-trap-react';
import { JoinRule, MatrixError, Room } from 'matrix-js-sdk'; import { JoinRule, MatrixError, Room } from 'matrix-js-sdk';
import { IHierarchyRoom } from 'matrix-js-sdk/lib/@types/spaces';
import { RoomAvatar, RoomIcon } from '../../components/room-avatar'; import { RoomAvatar, RoomIcon } from '../../components/room-avatar';
import { SequenceCard } from '../../components/sequence-card'; import { SequenceCard } from '../../components/sequence-card';
import { useMatrixClient } from '../../hooks/useMatrixClient'; import { useMatrixClient } from '../../hooks/useMatrixClient';
import { HierarchyItem } from '../../hooks/useSpaceHierarchy'; import { HierarchyItem } from '../../hooks/useSpaceHierarchy';
import { millify } from '../../plugins/millify'; import { millify } from '../../plugins/millify';
import { import { LocalRoomSummaryLoader } from '../../components/RoomSummaryLoader';
HierarchyRoomSummaryLoader,
LocalRoomSummaryLoader,
} from '../../components/RoomSummaryLoader';
import { UseStateProvider } from '../../components/UseStateProvider'; import { UseStateProvider } from '../../components/UseStateProvider';
import { RoomTopicViewer } from '../../components/room-topic-viewer'; import { RoomTopicViewer } from '../../components/room-topic-viewer';
import { onEnterOrSpace, stopPropagation } from '../../utils/keyboard'; import { onEnterOrSpace, stopPropagation } from '../../utils/keyboard';
import { Membership, RoomType } from '../../../types/matrix/room'; import { Membership } from '../../../types/matrix/room';
import * as css from './RoomItem.css'; import * as css from './RoomItem.css';
import * as styleCss from './style.css'; import * as styleCss from './style.css';
import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback'; import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback';
import { ErrorCode } from '../../cs-errorcode';
import { getDirectRoomAvatarUrl, getRoomAvatarUrl } from '../../utils/room'; import { getDirectRoomAvatarUrl, getRoomAvatarUrl } from '../../utils/room';
import { ItemDraggableTarget, useDraggableItem } from './DnD'; import { ItemDraggableTarget, useDraggableItem } from './DnD';
import { mxcUrlToHttp } from '../../utils/matrix'; import { mxcUrlToHttp } from '../../utils/matrix';
@@ -125,13 +122,11 @@ function RoomProfileLoading() {
type RoomProfileErrorProps = { type RoomProfileErrorProps = {
roomId: string; roomId: string;
error: Error; inaccessibleRoom: boolean;
suggested?: boolean; suggested?: boolean;
via?: string[]; via?: string[];
}; };
function RoomProfileError({ roomId, suggested, error, via }: RoomProfileErrorProps) { function RoomProfileError({ roomId, suggested, inaccessibleRoom, via }: RoomProfileErrorProps) {
const privateRoom = error.name === ErrorCode.M_FORBIDDEN;
return ( return (
<Box grow="Yes" gap="300"> <Box grow="Yes" gap="300">
<Avatar> <Avatar>
@@ -142,7 +137,7 @@ function RoomProfileError({ roomId, suggested, error, via }: RoomProfileErrorPro
renderFallback={() => ( renderFallback={() => (
<RoomIcon <RoomIcon
size="300" size="300"
joinRule={privateRoom ? JoinRule.Invite : JoinRule.Restricted} joinRule={inaccessibleRoom ? JoinRule.Invite : JoinRule.Restricted}
filled filled
/> />
)} )}
@@ -162,25 +157,18 @@ function RoomProfileError({ roomId, suggested, error, via }: RoomProfileErrorPro
)} )}
</Box> </Box>
<Box gap="200" alignItems="Center"> <Box gap="200" alignItems="Center">
{privateRoom && ( {inaccessibleRoom ? (
<> <Badge variant="Secondary" fill="Soft" radii="300" size="500">
<Badge variant="Secondary" fill="Soft" radii="Pill" outlined> <Text size="L400">Inaccessible</Text>
<Text size="L400">Private Room</Text> </Badge>
</Badge> ) : (
<Line <Text size="T200" truncate>
variant="SurfaceVariant" {roomId}
style={{ height: toRem(12) }} </Text>
direction="Vertical"
size="400"
/>
</>
)} )}
<Text size="T200" truncate>
{roomId}
</Text>
</Box> </Box>
</Box> </Box>
{!privateRoom && <RoomJoinButton roomId={roomId} via={via} />} {!inaccessibleRoom && <RoomJoinButton roomId={roomId} via={via} />}
</Box> </Box>
); );
} }
@@ -288,23 +276,11 @@ function RoomProfile({
); );
} }
function CallbackOnFoundSpace({
roomId,
onSpaceFound,
}: {
roomId: string;
onSpaceFound: (roomId: string) => void;
}) {
useEffect(() => {
onSpaceFound(roomId);
}, [roomId, onSpaceFound]);
return null;
}
type RoomItemCardProps = { type RoomItemCardProps = {
item: HierarchyItem; item: HierarchyItem;
onSpaceFound: (roomId: string) => void; loading: boolean;
error: Error | null;
summary: IHierarchyRoom | undefined;
dm?: boolean; dm?: boolean;
firstChild?: boolean; firstChild?: boolean;
lastChild?: boolean; lastChild?: boolean;
@@ -320,10 +296,10 @@ export const RoomItemCard = as<'div', RoomItemCardProps>(
( (
{ {
item, item,
onSpaceFound, loading,
error,
summary,
dm, dm,
firstChild,
lastChild,
onOpen, onOpen,
options, options,
before, before,
@@ -348,8 +324,6 @@ export const RoomItemCard = as<'div', RoomItemCardProps>(
return ( return (
<SequenceCard <SequenceCard
className={css.RoomItemCard} className={css.RoomItemCard}
firstChild={firstChild}
lastChild={lastChild}
variant="SurfaceVariant" variant="SurfaceVariant"
gap="300" gap="300"
alignItems="Center" alignItems="Center"
@@ -367,7 +341,9 @@ export const RoomItemCard = as<'div', RoomItemCardProps>(
name={localSummary.name} name={localSummary.name}
topic={localSummary.topic} topic={localSummary.topic}
avatarUrl={ avatarUrl={
dm ? getDirectRoomAvatarUrl(mx, room, 96, useAuthentication) : getRoomAvatarUrl(mx, room, 96, useAuthentication) dm
? getDirectRoomAvatarUrl(mx, room, 96, useAuthentication)
: getRoomAvatarUrl(mx, room, 96, useAuthentication)
} }
memberCount={localSummary.memberCount} memberCount={localSummary.memberCount}
suggested={content.suggested} suggested={content.suggested}
@@ -395,46 +371,46 @@ export const RoomItemCard = as<'div', RoomItemCardProps>(
)} )}
</LocalRoomSummaryLoader> </LocalRoomSummaryLoader>
) : ( ) : (
<HierarchyRoomSummaryLoader roomId={roomId}> <>
{(summaryState) => ( {!summary &&
<> (error ? (
{summaryState.status === AsyncStatus.Loading && <RoomProfileLoading />} <RoomProfileError
{summaryState.status === AsyncStatus.Error && ( roomId={roomId}
<RoomProfileError inaccessibleRoom={false}
roomId={roomId} suggested={content.suggested}
error={summaryState.error} via={content.via}
suggested={content.suggested} />
via={content.via} ) : (
/> <>
)} {loading && <RoomProfileLoading />}
{summaryState.status === AsyncStatus.Success && ( {!loading && (
<> <RoomProfileError
{summaryState.data.room_type === RoomType.Space && (
<CallbackOnFoundSpace
roomId={summaryState.data.room_id}
onSpaceFound={onSpaceFound}
/>
)}
<RoomProfile
roomId={roomId} roomId={roomId}
name={summaryState.data.name || summaryState.data.canonical_alias || roomId} inaccessibleRoom
topic={summaryState.data.topic}
avatarUrl={
summaryState.data?.avatar_url
? mxcUrlToHttp(mx, summaryState.data.avatar_url, useAuthentication, 96, 96, 'crop') ??
undefined
: undefined
}
memberCount={summaryState.data.num_joined_members}
suggested={content.suggested} suggested={content.suggested}
joinRule={summaryState.data.join_rule} via={content.via}
options={<RoomJoinButton roomId={roomId} via={content.via} />}
/> />
</> )}
)} </>
</> ))}
{summary && (
<RoomProfile
roomId={roomId}
name={summary.name || summary.canonical_alias || roomId}
topic={summary.topic}
avatarUrl={
summary?.avatar_url
? mxcUrlToHttp(mx, summary.avatar_url, useAuthentication, 96, 96, 'crop') ??
undefined
: undefined
}
memberCount={summary.num_joined_members}
suggested={content.suggested}
joinRule={summary.join_rule}
options={<RoomJoinButton roomId={roomId} via={content.via} />}
/>
)} )}
</HierarchyRoomSummaryLoader> </>
)} )}
</Box> </Box>
{options} {options}

View File

@@ -0,0 +1,225 @@
import React, { forwardRef, MouseEventHandler, useEffect, useMemo } from 'react';
import { MatrixError, Room } from 'matrix-js-sdk';
import { IHierarchyRoom } from 'matrix-js-sdk/lib/@types/spaces';
import { Box, config, Text } from 'folds';
import {
HierarchyItem,
HierarchyItemRoom,
HierarchyItemSpace,
useFetchSpaceHierarchyLevel,
} from '../../hooks/useSpaceHierarchy';
import { IPowerLevels, powerLevelAPI } from '../../hooks/usePowerLevels';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import { SpaceItemCard } from './SpaceItem';
import { AfterItemDropTarget, CanDropCallback } from './DnD';
import { HierarchyItemMenu } from './HierarchyItemMenu';
import { RoomItemCard } from './RoomItem';
import { RoomType } from '../../../types/matrix/room';
import { SequenceCard } from '../../components/sequence-card';
type SpaceHierarchyProps = {
summary: IHierarchyRoom | undefined;
spaceItem: HierarchyItemSpace;
roomItems?: HierarchyItemRoom[];
allJoinedRooms: Set<string>;
mDirects: Set<string>;
roomsPowerLevels: Map<string, IPowerLevels>;
canEditSpaceChild: (powerLevels: IPowerLevels) => boolean;
categoryId: string;
closed: boolean;
handleClose: MouseEventHandler<HTMLButtonElement>;
draggingItem?: HierarchyItem;
onDragging: (item?: HierarchyItem) => void;
canDrop: CanDropCallback;
nextSpaceId?: string;
getRoom: (roomId: string) => Room | undefined;
pinned: boolean;
togglePinToSidebar: (roomId: string) => void;
onSpacesFound: (spaceItems: IHierarchyRoom[]) => void;
onOpenRoom: MouseEventHandler<HTMLButtonElement>;
};
export const SpaceHierarchy = forwardRef<HTMLDivElement, SpaceHierarchyProps>(
(
{
summary,
spaceItem,
roomItems,
allJoinedRooms,
mDirects,
roomsPowerLevels,
canEditSpaceChild,
categoryId,
closed,
handleClose,
draggingItem,
onDragging,
canDrop,
nextSpaceId,
getRoom,
pinned,
togglePinToSidebar,
onOpenRoom,
onSpacesFound,
},
ref
) => {
const mx = useMatrixClient();
const { fetching, error, rooms } = useFetchSpaceHierarchyLevel(spaceItem.roomId, true);
const subspaces = useMemo(() => {
const s: Map<string, IHierarchyRoom> = new Map();
rooms.forEach((r) => {
if (r.room_type === RoomType.Space) {
s.set(r.room_id, r);
}
});
return s;
}, [rooms]);
const spacePowerLevels = roomsPowerLevels.get(spaceItem.roomId) ?? {};
const userPLInSpace = powerLevelAPI.getPowerLevel(
spacePowerLevels,
mx.getUserId() ?? undefined
);
const canInviteInSpace = powerLevelAPI.canDoAction(spacePowerLevels, 'invite', userPLInSpace);
const draggingSpace =
draggingItem?.roomId === spaceItem.roomId && draggingItem.parentId === spaceItem.parentId;
const { parentId } = spaceItem;
const parentPowerLevels = parentId ? roomsPowerLevels.get(parentId) ?? {} : undefined;
useEffect(() => {
onSpacesFound(Array.from(subspaces.values()));
}, [subspaces, onSpacesFound]);
let childItems = roomItems?.filter((i) => !subspaces.has(i.roomId));
if (!canEditSpaceChild(spacePowerLevels)) {
// hide unknown rooms for normal user
childItems = childItems?.filter((i) => {
const forbidden = error instanceof MatrixError ? error.errcode === 'M_FORBIDDEN' : false;
const inaccessibleRoom = !rooms.get(i.roomId) && !fetching && (error ? forbidden : true);
return !inaccessibleRoom;
});
}
return (
<Box direction="Column" gap="100" ref={ref}>
<SpaceItemCard
summary={rooms.get(spaceItem.roomId) ?? summary}
loading={fetching}
item={spaceItem}
joined={allJoinedRooms.has(spaceItem.roomId)}
categoryId={categoryId}
closed={closed}
handleClose={handleClose}
getRoom={getRoom}
canEditChild={canEditSpaceChild(spacePowerLevels)}
canReorder={parentPowerLevels ? canEditSpaceChild(parentPowerLevels) : false}
options={
parentId &&
parentPowerLevels && (
<HierarchyItemMenu
item={{ ...spaceItem, parentId }}
canInvite={canInviteInSpace}
joined={allJoinedRooms.has(spaceItem.roomId)}
canEditChild={canEditSpaceChild(parentPowerLevels)}
pinned={pinned}
onTogglePin={togglePinToSidebar}
/>
)
}
after={
<AfterItemDropTarget
item={spaceItem}
nextRoomId={closed ? nextSpaceId : childItems?.[0]?.roomId}
afterSpace
canDrop={canDrop}
/>
}
onDragging={onDragging}
data-dragging={draggingSpace}
/>
{childItems && childItems.length > 0 ? (
<Box direction="Column" gap="100">
{childItems.map((roomItem, index) => {
const roomSummary = rooms.get(roomItem.roomId);
const roomPowerLevels = roomsPowerLevels.get(roomItem.roomId) ?? {};
const userPLInRoom = powerLevelAPI.getPowerLevel(
roomPowerLevels,
mx.getUserId() ?? undefined
);
const canInviteInRoom = powerLevelAPI.canDoAction(
roomPowerLevels,
'invite',
userPLInRoom
);
const lastItem = index === childItems.length;
const nextRoomId = lastItem ? nextSpaceId : childItems[index + 1]?.roomId;
const roomDragging =
draggingItem?.roomId === roomItem.roomId &&
draggingItem.parentId === roomItem.parentId;
return (
<RoomItemCard
key={roomItem.roomId}
item={roomItem}
loading={fetching}
error={error}
summary={roomSummary}
dm={mDirects.has(roomItem.roomId)}
onOpen={onOpenRoom}
getRoom={getRoom}
canReorder={canEditSpaceChild(spacePowerLevels)}
options={
<HierarchyItemMenu
item={roomItem}
canInvite={canInviteInRoom}
joined={allJoinedRooms.has(roomItem.roomId)}
canEditChild={canEditSpaceChild(spacePowerLevels)}
/>
}
after={
<AfterItemDropTarget
item={roomItem}
nextRoomId={nextRoomId}
canDrop={canDrop}
/>
}
data-dragging={roomDragging}
onDragging={onDragging}
/>
);
})}
</Box>
) : (
childItems && (
<SequenceCard variant="SurfaceVariant" gap="300" alignItems="Center">
<Box
grow="Yes"
style={{
padding: config.space.S700,
}}
direction="Column"
alignItems="Center"
justifyContent="Center"
gap="100"
>
<Text size="H5" align="Center">
No Rooms
</Text>
<Text align="Center" size="T300" priority="300">
This space does not contains rooms yet.
</Text>
</Box>
</SequenceCard>
)
)}
</Box>
);
}
);

View File

@@ -19,19 +19,16 @@ import {
import FocusTrap from 'focus-trap-react'; import FocusTrap from 'focus-trap-react';
import classNames from 'classnames'; import classNames from 'classnames';
import { MatrixError, Room } from 'matrix-js-sdk'; import { MatrixError, Room } from 'matrix-js-sdk';
import { IHierarchyRoom } from 'matrix-js-sdk/lib/@types/spaces';
import { HierarchyItem } from '../../hooks/useSpaceHierarchy'; import { HierarchyItem } from '../../hooks/useSpaceHierarchy';
import { useMatrixClient } from '../../hooks/useMatrixClient'; import { useMatrixClient } from '../../hooks/useMatrixClient';
import { RoomAvatar } from '../../components/room-avatar'; import { RoomAvatar } from '../../components/room-avatar';
import { nameInitials } from '../../utils/common'; import { nameInitials } from '../../utils/common';
import { import { LocalRoomSummaryLoader } from '../../components/RoomSummaryLoader';
HierarchyRoomSummaryLoader,
LocalRoomSummaryLoader,
} from '../../components/RoomSummaryLoader';
import { getRoomAvatarUrl } from '../../utils/room'; import { getRoomAvatarUrl } from '../../utils/room';
import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback'; import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback';
import * as css from './SpaceItem.css'; import * as css from './SpaceItem.css';
import * as styleCss from './style.css'; import * as styleCss from './style.css';
import { ErrorCode } from '../../cs-errorcode';
import { useDraggableItem } from './DnD'; import { useDraggableItem } from './DnD';
import { openCreateRoom, openSpaceAddExisting } from '../../../client/action/navigation'; import { openCreateRoom, openSpaceAddExisting } from '../../../client/action/navigation';
import { stopPropagation } from '../../utils/keyboard'; import { stopPropagation } from '../../utils/keyboard';
@@ -53,18 +50,11 @@ function SpaceProfileLoading() {
); );
} }
type UnknownPrivateSpaceProfileProps = { type InaccessibleSpaceProfileProps = {
roomId: string; roomId: string;
name?: string;
avatarUrl?: string;
suggested?: boolean; suggested?: boolean;
}; };
function UnknownPrivateSpaceProfile({ function InaccessibleSpaceProfile({ roomId, suggested }: InaccessibleSpaceProfileProps) {
roomId,
name,
avatarUrl,
suggested,
}: UnknownPrivateSpaceProfileProps) {
return ( return (
<Chip <Chip
as="span" as="span"
@@ -75,11 +65,9 @@ function UnknownPrivateSpaceProfile({
<Avatar size="200" radii="300"> <Avatar size="200" radii="300">
<RoomAvatar <RoomAvatar
roomId={roomId} roomId={roomId}
src={avatarUrl}
alt={name}
renderFallback={() => ( renderFallback={() => (
<Text as="span" size="H6"> <Text as="span" size="H6">
{nameInitials(name)} U
</Text> </Text>
)} )}
/> />
@@ -88,11 +76,11 @@ function UnknownPrivateSpaceProfile({
> >
<Box alignItems="Center" gap="200"> <Box alignItems="Center" gap="200">
<Text size="H4" truncate> <Text size="H4" truncate>
{name || 'Unknown'} Unknown
</Text> </Text>
<Badge variant="Secondary" fill="Soft" radii="Pill" outlined> <Badge variant="Secondary" fill="Soft" radii="Pill" outlined>
<Text size="L400">Private Space</Text> <Text size="L400">Inaccessible</Text>
</Badge> </Badge>
{suggested && ( {suggested && (
<Badge variant="Success" fill="Soft" radii="Pill" outlined> <Badge variant="Success" fill="Soft" radii="Pill" outlined>
@@ -104,20 +92,20 @@ function UnknownPrivateSpaceProfile({
); );
} }
type UnknownSpaceProfileProps = { type UnjoinedSpaceProfileProps = {
roomId: string; roomId: string;
via?: string[]; via?: string[];
name?: string; name?: string;
avatarUrl?: string; avatarUrl?: string;
suggested?: boolean; suggested?: boolean;
}; };
function UnknownSpaceProfile({ function UnjoinedSpaceProfile({
roomId, roomId,
via, via,
name, name,
avatarUrl, avatarUrl,
suggested, suggested,
}: UnknownSpaceProfileProps) { }: UnjoinedSpaceProfileProps) {
const mx = useMatrixClient(); const mx = useMatrixClient();
const [joinState, join] = useAsyncCallback<Room, MatrixError, []>( const [joinState, join] = useAsyncCallback<Room, MatrixError, []>(
@@ -376,6 +364,8 @@ function AddSpaceButton({ item }: { item: HierarchyItem }) {
} }
type SpaceItemCardProps = { type SpaceItemCardProps = {
summary: IHierarchyRoom | undefined;
loading?: boolean;
item: HierarchyItem; item: HierarchyItem;
joined?: boolean; joined?: boolean;
categoryId: string; categoryId: string;
@@ -393,6 +383,8 @@ export const SpaceItemCard = as<'div', SpaceItemCardProps>(
( (
{ {
className, className,
summary,
loading,
joined, joined,
closed, closed,
categoryId, categoryId,
@@ -451,37 +443,31 @@ export const SpaceItemCard = as<'div', SpaceItemCardProps>(
} }
</LocalRoomSummaryLoader> </LocalRoomSummaryLoader>
) : ( ) : (
<HierarchyRoomSummaryLoader roomId={roomId}> <>
{(summaryState) => ( {!summary &&
<> (loading ? (
{summaryState.status === AsyncStatus.Loading && <SpaceProfileLoading />} <SpaceProfileLoading />
{summaryState.status === AsyncStatus.Error && ) : (
(summaryState.error.name === ErrorCode.M_FORBIDDEN ? ( <InaccessibleSpaceProfile
<UnknownPrivateSpaceProfile roomId={roomId} suggested={content.suggested} /> roomId={item.roomId}
) : ( suggested={item.content.suggested}
<UnknownSpaceProfile />
roomId={roomId} ))}
via={item.content.via} {summary && (
suggested={content.suggested} <UnjoinedSpaceProfile
/> roomId={roomId}
))} via={item.content.via}
{summaryState.status === AsyncStatus.Success && ( name={summary.name || summary.canonical_alias || roomId}
<UnknownSpaceProfile avatarUrl={
roomId={roomId} summary?.avatar_url
via={item.content.via} ? mxcUrlToHttp(mx, summary.avatar_url, useAuthentication, 96, 96, 'crop') ??
name={summaryState.data.name || summaryState.data.canonical_alias || roomId} undefined
avatarUrl={ : undefined
summaryState.data?.avatar_url }
? mxcUrlToHttp(mx, summaryState.data.avatar_url, useAuthentication, 96, 96, 'crop') ?? suggested={content.suggested}
undefined />
: undefined
}
suggested={content.suggested}
/>
)}
</>
)} )}
</HierarchyRoomSummaryLoader> </>
)} )}
</Box> </Box>
{canEditChild && ( {canEditChild && (

View File

@@ -182,7 +182,9 @@ export function RoomNavItem({
const { focusWithinProps } = useFocusWithin({ onFocusWithinChange: setHover }); const { focusWithinProps } = useFocusWithin({ onFocusWithinChange: setHover });
const [menuAnchor, setMenuAnchor] = useState<RectCords>(); const [menuAnchor, setMenuAnchor] = useState<RectCords>();
const unread = useRoomUnread(room.roomId, roomToUnreadAtom); const unread = useRoomUnread(room.roomId, roomToUnreadAtom);
const typingMember = useRoomTypingMember(room.roomId); const typingMember = useRoomTypingMember(room.roomId).filter(
(receipt) => receipt.userId !== mx.getUserId()
);
const handleContextMenu: MouseEventHandler<HTMLElement> = (evt) => { const handleContextMenu: MouseEventHandler<HTMLElement> = (evt) => {
evt.preventDefault(); evt.preventDefault();
@@ -219,7 +221,9 @@ export function RoomNavItem({
<RoomAvatar <RoomAvatar
roomId={room.roomId} roomId={room.roomId}
src={ src={
direct ? getDirectRoomAvatarUrl(mx, room, 96, useAuthentication) : getRoomAvatarUrl(mx, room, 96, useAuthentication) direct
? getDirectRoomAvatarUrl(mx, room, 96, useAuthentication)
: getRoomAvatarUrl(mx, room, 96, useAuthentication)
} }
alt={room.name} alt={room.name}
renderFallback={() => ( renderFallback={() => (

View File

@@ -156,7 +156,7 @@ export type MembersFilterOptions = {
}; };
const SEARCH_OPTIONS: UseAsyncSearchOptions = { const SEARCH_OPTIONS: UseAsyncSearchOptions = {
limit: 100, limit: 1000,
matchOptions: { matchOptions: {
contain: true, contain: true,
}, },
@@ -428,8 +428,9 @@ export function MembersDrawer({ room, members }: MembersDrawerProps) {
}} }}
after={<Icon size="50" src={Icons.Cross} />} after={<Icon size="50" src={Icons.Cross} />}
> >
<Text size="B300">{`${result.items.length || 'No'} ${result.items.length === 1 ? 'Result' : 'Results' <Text size="B300">{`${result.items.length || 'No'} ${
}`}</Text> result.items.length === 1 ? 'Result' : 'Results'
}`}</Text>
</Chip> </Chip>
) )
} }
@@ -485,15 +486,17 @@ export function MembersDrawer({ room, members }: MembersDrawerProps) {
const member = tagOrMember; const member = tagOrMember;
const name = getName(member); const name = getName(member);
const avatarMxcUrl = member.getMxcAvatarUrl(); const avatarMxcUrl = member.getMxcAvatarUrl();
const avatarUrl = avatarMxcUrl ? mx.mxcUrlToHttp( const avatarUrl = avatarMxcUrl
avatarMxcUrl, ? mx.mxcUrlToHttp(
100, avatarMxcUrl,
100, 100,
'crop', 100,
undefined, 'crop',
false, undefined,
useAuthentication false,
) : undefined; useAuthentication
)
: undefined;
return ( return (
<MenuItem <MenuItem

View File

@@ -53,6 +53,7 @@ import {
isEmptyEditor, isEmptyEditor,
getBeginCommand, getBeginCommand,
trimCommand, trimCommand,
getMentions,
} from '../../components/editor'; } from '../../components/editor';
import { EmojiBoard, EmojiBoardTab } from '../../components/emoji-board'; import { EmojiBoard, EmojiBoardTab } from '../../components/emoji-board';
import { UseStateProvider } from '../../components/UseStateProvider'; import { UseStateProvider } from '../../components/UseStateProvider';
@@ -102,12 +103,9 @@ import colorMXID from '../../../util/colorMXID';
import { import {
getAllParents, getAllParents,
getMemberDisplayName, getMemberDisplayName,
parseReplyBody, getMentionContent,
parseReplyFormattedBody,
trimReplyFromBody, trimReplyFromBody,
trimReplyFromFormattedBody,
} from '../../utils/room'; } from '../../utils/room';
import { sanitizeText } from '../../utils/sanitize';
import { CommandAutocomplete } from './CommandAutocomplete'; import { CommandAutocomplete } from './CommandAutocomplete';
import { Command, SHRUG, TABLEFLIP, UNFLIP, useCommands } from '../../hooks/useCommands'; import { Command, SHRUG, TABLEFLIP, UNFLIP, useCommands } from '../../hooks/useCommands';
import { mobileOrTablet } from '../../utils/user-agent'; import { mobileOrTablet } from '../../utils/user-agent';
@@ -167,10 +165,24 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
const encryptFiles = fulfilledPromiseSettledResult( const encryptFiles = fulfilledPromiseSettledResult(
await Promise.allSettled(safeFiles.map((f) => encryptFile(f))) await Promise.allSettled(safeFiles.map((f) => encryptFile(f)))
); );
encryptFiles.forEach((ef) => fileItems.push(ef)); encryptFiles.forEach((ef) =>
fileItems.push({
...ef,
metadata: {
markedAsSpoiler: false,
},
})
);
} else { } else {
safeFiles.forEach((f) => safeFiles.forEach((f) =>
fileItems.push({ file: f, originalFile: f, encInfo: undefined }) fileItems.push({
file: f,
originalFile: f,
encInfo: undefined,
metadata: {
markedAsSpoiler: false,
},
})
); );
} }
setSelectedFiles({ setSelectedFiles({
@@ -254,8 +266,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
uploadBoardHandlers.current?.handleSend(); uploadBoardHandlers.current?.handleSend();
const commandName = getBeginCommand(editor); const commandName = getBeginCommand(editor);
let plainText = toPlainText(editor.children, isMarkdown).trim();
let plainText = toPlainText(editor.children).trim();
let customHtml = trimCustomHtml( let customHtml = trimCustomHtml(
toMatrixCustomHTML(editor.children, { toMatrixCustomHTML(editor.children, {
allowTextFormatting: true, allowTextFormatting: true,
@@ -295,25 +306,22 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
if (plainText === '') return; if (plainText === '') return;
let body = plainText; const body = plainText;
let formattedBody = customHtml; const formattedBody = customHtml;
if (replyDraft) { const mentionData = getMentions(mx, roomId, editor);
body = parseReplyBody(replyDraft.userId, trimReplyFromBody(replyDraft.body)) + body;
formattedBody =
parseReplyFormattedBody(
roomId,
replyDraft.userId,
replyDraft.eventId,
replyDraft.formattedBody
? trimReplyFromFormattedBody(replyDraft.formattedBody)
: sanitizeText(replyDraft.body)
) + formattedBody;
}
const content: IContent = { const content: IContent = {
msgtype: msgType, msgtype: msgType,
body, body,
}; };
if (replyDraft && replyDraft.userId !== mx.getUserId()) {
mentionData.users.add(replyDraft.userId);
}
const mMentions = getMentionContent(Array.from(mentionData.users), mentionData.room);
content['m.mentions'] = mMentions;
if (replyDraft || !customHtmlEqualsPlainText(formattedBody, body)) { if (replyDraft || !customHtmlEqualsPlainText(formattedBody, body)) {
content.format = 'org.matrix.custom.html'; content.format = 'org.matrix.custom.html';
content.formatted_body = formattedBody; content.formatted_body = formattedBody;
@@ -420,7 +428,14 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
// eslint-disable-next-line react/no-array-index-key // eslint-disable-next-line react/no-array-index-key
key={index} key={index}
isEncrypted={!!fileItem.encInfo} isEncrypted={!!fileItem.encInfo}
uploadAtom={roomUploadAtomFamily(fileItem.file)} fileItem={fileItem}
setMetadata={(metadata) =>
setSelectedFiles({
type: 'REPLACE',
item: fileItem,
replacement: { ...fileItem, metadata },
})
}
onRemove={handleRemoveUpload} onRemove={handleRemoveUpload}
/> />
))} ))}

View File

@@ -586,15 +586,19 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
// so timeline can be updated with evt like: edits, reactions etc // so timeline can be updated with evt like: edits, reactions etc
if (atBottomRef.current) { if (atBottomRef.current) {
if (document.hasFocus() && (!unreadInfo || mEvt.getSender() === mx.getUserId())) { if (document.hasFocus() && (!unreadInfo || mEvt.getSender() === mx.getUserId())) {
// Check if the document is in focus (user is actively viewing the app),
// and either there are no unread messages or the latest message is from the current user.
// If either condition is met, trigger the markAsRead function to send a read receipt.
requestAnimationFrame(() => markAsRead(mx, mEvt.getRoomId()!)); requestAnimationFrame(() => markAsRead(mx, mEvt.getRoomId()!));
} }
if (document.hasFocus()) { if (!document.hasFocus() && !unreadInfo) {
scrollToBottomRef.current.count += 1;
scrollToBottomRef.current.smooth = true;
} else if (!unreadInfo) {
setUnreadInfo(getRoomUnreadInfo(room)); setUnreadInfo(getRoomUnreadInfo(room));
} }
scrollToBottomRef.current.count += 1;
scrollToBottomRef.current.smooth = true;
setTimeline((ct) => ({ setTimeline((ct) => ({
...ct, ...ct,
range: { range: {
@@ -613,6 +617,36 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
) )
); );
const handleOpenEvent = useCallback(
async (
evtId: string,
highlight = true,
onScroll: ((scrolled: boolean) => void) | undefined = undefined
) => {
const evtTimeline = getEventTimeline(room, evtId);
const absoluteIndex =
evtTimeline && getEventIdAbsoluteIndex(timeline.linkedTimelines, evtTimeline, evtId);
if (typeof absoluteIndex === 'number') {
const scrolled = scrollToItem(absoluteIndex, {
behavior: 'smooth',
align: 'center',
stopInView: true,
});
if (onScroll) onScroll(scrolled);
setFocusItem({
index: absoluteIndex,
scrollTo: false,
highlight,
});
} else {
setTimeline(getEmptyTimeline());
loadEventTimeline(evtId);
}
},
[room, timeline, scrollToItem, loadEventTimeline]
);
useLiveTimelineRefresh( useLiveTimelineRefresh(
room, room,
useCallback(() => { useCallback(() => {
@@ -646,16 +680,17 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
); );
const tryAutoMarkAsRead = useCallback(() => { const tryAutoMarkAsRead = useCallback(() => {
if (!unreadInfo) { const readUptoEventId = readUptoEventIdRef.current;
if (!readUptoEventId) {
requestAnimationFrame(() => markAsRead(mx, room.roomId)); requestAnimationFrame(() => markAsRead(mx, room.roomId));
return; return;
} }
const evtTimeline = getEventTimeline(room, unreadInfo.readUptoEventId); const evtTimeline = getEventTimeline(room, readUptoEventId);
const latestTimeline = evtTimeline && getFirstLinkedTimeline(evtTimeline, Direction.Forward); const latestTimeline = evtTimeline && getFirstLinkedTimeline(evtTimeline, Direction.Forward);
if (latestTimeline === room.getLiveTimeline()) { if (latestTimeline === room.getLiveTimeline()) {
requestAnimationFrame(() => markAsRead(mx, room.roomId)); requestAnimationFrame(() => markAsRead(mx, room.roomId));
} }
}, [mx, room, unreadInfo]); }, [mx, room]);
const debounceSetAtBottom = useDebounce( const debounceSetAtBottom = useDebounce(
useCallback((entry: IntersectionObserverEntry) => { useCallback((entry: IntersectionObserverEntry) => {
@@ -672,7 +707,9 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
if (targetEntry) debounceSetAtBottom(targetEntry); if (targetEntry) debounceSetAtBottom(targetEntry);
if (targetEntry?.isIntersecting && atLiveEndRef.current) { if (targetEntry?.isIntersecting && atLiveEndRef.current) {
setAtBottom(true); setAtBottom(true);
tryAutoMarkAsRead(); if (document.hasFocus()) {
tryAutoMarkAsRead();
}
} }
}, },
[debounceSetAtBottom, tryAutoMarkAsRead] [debounceSetAtBottom, tryAutoMarkAsRead]
@@ -691,10 +728,20 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
useCallback( useCallback(
(inFocus) => { (inFocus) => {
if (inFocus && atBottomRef.current) { if (inFocus && atBottomRef.current) {
if (unreadInfo?.inLiveTimeline) {
handleOpenEvent(unreadInfo.readUptoEventId, false, (scrolled) => {
// the unread event is already in view
// so, try mark as read;
if (!scrolled) {
tryAutoMarkAsRead();
}
});
return;
}
tryAutoMarkAsRead(); tryAutoMarkAsRead();
} }
}, },
[tryAutoMarkAsRead] [tryAutoMarkAsRead, unreadInfo, handleOpenEvent]
) )
); );
@@ -832,27 +879,9 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
async (evt) => { async (evt) => {
const targetId = evt.currentTarget.getAttribute('data-event-id'); const targetId = evt.currentTarget.getAttribute('data-event-id');
if (!targetId) return; if (!targetId) return;
const replyTimeline = getEventTimeline(room, targetId); handleOpenEvent(targetId);
const absoluteIndex =
replyTimeline && getEventIdAbsoluteIndex(timeline.linkedTimelines, replyTimeline, targetId);
if (typeof absoluteIndex === 'number') {
scrollToItem(absoluteIndex, {
behavior: 'smooth',
align: 'center',
stopInView: true,
});
setFocusItem({
index: absoluteIndex,
scrollTo: false,
highlight: true,
});
} else {
setTimeline(getEmptyTimeline());
loadEventTimeline(targetId);
}
}, },
[room, timeline, scrollToItem, loadEventTimeline] [handleOpenEvent]
); );
const handleUserClick: MouseEventHandler<HTMLButtonElement> = useCallback( const handleUserClick: MouseEventHandler<HTMLButtonElement> = useCallback(

View File

@@ -35,7 +35,7 @@ import { useHover, useFocusWithin } from 'react-aria';
import { MatrixEvent, Room } from 'matrix-js-sdk'; import { MatrixEvent, Room } from 'matrix-js-sdk';
import { Relations } from 'matrix-js-sdk/lib/models/relations'; import { Relations } from 'matrix-js-sdk/lib/models/relations';
import classNames from 'classnames'; import classNames from 'classnames';
import { EventType, RoomPinnedEventsEventContent } from 'matrix-js-sdk/lib/types'; import { RoomPinnedEventsEventContent } from 'matrix-js-sdk/lib/types';
import { import {
AvatarBase, AvatarBase,
BubbleLayout, BubbleLayout,

View File

@@ -21,7 +21,7 @@ import {
} from 'folds'; } from 'folds';
import { Editor, Transforms } from 'slate'; import { Editor, Transforms } from 'slate';
import { ReactEditor } from 'slate-react'; import { ReactEditor } from 'slate-react';
import { IContent, MatrixEvent, RelationType, Room } from 'matrix-js-sdk'; import { IContent, IMentions, MatrixEvent, RelationType, Room } from 'matrix-js-sdk';
import { isKeyHotkey } from 'is-hotkey'; import { isKeyHotkey } from 'is-hotkey';
import { import {
AUTOCOMPLETE_PREFIXES, AUTOCOMPLETE_PREFIXES,
@@ -43,6 +43,7 @@ import {
toPlainText, toPlainText,
trimCustomHtml, trimCustomHtml,
useEditor, useEditor,
getMentions,
} from '../../../components/editor'; } from '../../../components/editor';
import { useSetting } from '../../../state/hooks/settings'; import { useSetting } from '../../../state/hooks/settings';
import { settingsAtom } from '../../../state/settings'; import { settingsAtom } from '../../../state/settings';
@@ -50,7 +51,7 @@ import { UseStateProvider } from '../../../components/UseStateProvider';
import { EmojiBoard } from '../../../components/emoji-board'; import { EmojiBoard } from '../../../components/emoji-board';
import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback'; import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback';
import { useMatrixClient } from '../../../hooks/useMatrixClient'; import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { getEditedEvent, trimReplyFromFormattedBody } from '../../../utils/room'; import { getEditedEvent, getMentionContent, trimReplyFromFormattedBody } from '../../../utils/room';
import { mobileOrTablet } from '../../../utils/user-agent'; import { mobileOrTablet } from '../../../utils/user-agent';
type MessageEditorProps = { type MessageEditorProps = {
@@ -74,25 +75,29 @@ export const MessageEditor = as<'div', MessageEditorProps>(
const getPrevBodyAndFormattedBody = useCallback((): [ const getPrevBodyAndFormattedBody = useCallback((): [
string | undefined, string | undefined,
string | undefined string | undefined,
IMentions | undefined
] => { ] => {
const evtId = mEvent.getId()!; const evtId = mEvent.getId()!;
const evtTimeline = room.getTimelineForEvent(evtId); const evtTimeline = room.getTimelineForEvent(evtId);
const editedEvent = const editedEvent =
evtTimeline && getEditedEvent(evtId, mEvent, evtTimeline.getTimelineSet()); evtTimeline && getEditedEvent(evtId, mEvent, evtTimeline.getTimelineSet());
const { body, formatted_body: customHtml }: Record<string, unknown> = const content: IContent = editedEvent?.getContent()['m.new_content'] ?? mEvent.getContent();
editedEvent?.getContent()['m.new_content'] ?? mEvent.getContent(); const { body, formatted_body: customHtml }: Record<string, unknown> = content;
const mMentions: IMentions | undefined = content['m.mentions'];
return [ return [
typeof body === 'string' ? body : undefined, typeof body === 'string' ? body : undefined,
typeof customHtml === 'string' ? customHtml : undefined, typeof customHtml === 'string' ? customHtml : undefined,
mMentions,
]; ];
}, [room, mEvent]); }, [room, mEvent]);
const [saveState, save] = useAsyncCallback( const [saveState, save] = useAsyncCallback(
useCallback(async () => { useCallback(async () => {
const plainText = toPlainText(editor.children).trim(); const plainText = toPlainText(editor.children, isMarkdown).trim();
const customHtml = trimCustomHtml( const customHtml = trimCustomHtml(
toMatrixCustomHTML(editor.children, { toMatrixCustomHTML(editor.children, {
allowTextFormatting: true, allowTextFormatting: true,
@@ -101,7 +106,7 @@ export const MessageEditor = as<'div', MessageEditorProps>(
}) })
); );
const [prevBody, prevCustomHtml] = getPrevBodyAndFormattedBody(); const [prevBody, prevCustomHtml, prevMentions] = getPrevBodyAndFormattedBody();
if (plainText === '') return undefined; if (plainText === '') return undefined;
if (prevBody) { if (prevBody) {
@@ -122,6 +127,15 @@ export const MessageEditor = as<'div', MessageEditorProps>(
body: plainText, body: plainText,
}; };
const mentionData = getMentions(mx, roomId, editor);
prevMentions?.user_ids?.forEach((prevMentionId) => {
mentionData.users.add(prevMentionId);
});
const mMentions = getMentionContent(Array.from(mentionData.users), mentionData.room);
newContent['m.mentions'] = mMentions;
if (!customHtmlEqualsPlainText(customHtml, plainText)) { if (!customHtmlEqualsPlainText(customHtml, plainText)) {
newContent.format = 'org.matrix.custom.html'; newContent.format = 'org.matrix.custom.html';
newContent.formatted_body = customHtml; newContent.formatted_body = customHtml;
@@ -192,8 +206,8 @@ export const MessageEditor = as<'div', MessageEditorProps>(
const initialValue = const initialValue =
typeof customHtml === 'string' typeof customHtml === 'string'
? htmlToEditorInput(customHtml) ? htmlToEditorInput(customHtml, isMarkdown)
: plainToEditorInput(typeof body === 'string' ? body : ''); : plainToEditorInput(typeof body === 'string' ? body : '', isMarkdown);
Transforms.select(editor, { Transforms.select(editor, {
anchor: Editor.start(editor, []), anchor: Editor.start(editor, []),
@@ -202,7 +216,7 @@ export const MessageEditor = as<'div', MessageEditorProps>(
editor.insertFragment(initialValue); editor.insertFragment(initialValue);
if (!mobileOrTablet()) ReactEditor.focus(editor); if (!mobileOrTablet()) ReactEditor.focus(editor);
}, [editor, getPrevBodyAndFormattedBody]); }, [editor, getPrevBodyAndFormattedBody, isMarkdown]);
useEffect(() => { useEffect(() => {
if (saveState.status === AsyncStatus.Success) { if (saveState.status === AsyncStatus.Success) {

View File

@@ -1,6 +1,10 @@
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, MATRIX_BLUR_HASH_PROPERTY_NAME } from '../../../types/matrix/common'; import {
IThumbnailContent,
MATRIX_BLUR_HASH_PROPERTY_NAME,
MATRIX_SPOILER_PROPERTY_NAME,
} from '../../../types/matrix/common';
import { import {
getImageFileUrl, getImageFileUrl,
getThumbnail, getThumbnail,
@@ -42,9 +46,9 @@ const generateThumbnailContent = async (
export const getImageMsgContent = async ( export const getImageMsgContent = async (
mx: MatrixClient, mx: MatrixClient,
item: TUploadItem, item: TUploadItem,
mxc: string, mxc: string
): Promise<IContent> => { ): Promise<IContent> => {
const { file, originalFile, encInfo } = item; const { file, originalFile, encInfo, metadata } = 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);
@@ -52,6 +56,7 @@ export const getImageMsgContent = async (
msgtype: MsgType.Image, msgtype: MsgType.Image,
filename: file.name, filename: file.name,
body: file.name, body: file.name,
[MATRIX_SPOILER_PROPERTY_NAME]: metadata.markedAsSpoiler,
}; };
if (imgEl) { if (imgEl) {
const blurHash = encodeBlurHash(imgEl, 512, scaleYDimension(imgEl.width, 512, imgEl.height)); const blurHash = encodeBlurHash(imgEl, 512, scaleYDimension(imgEl.width, 512, imgEl.height));
@@ -75,7 +80,7 @@ export const getImageMsgContent = async (
export const getVideoMsgContent = async ( export const getVideoMsgContent = async (
mx: MatrixClient, mx: MatrixClient,
item: TUploadItem, item: TUploadItem,
mxc: string, mxc: string
): Promise<IContent> => { ): Promise<IContent> => {
const { file, originalFile, encInfo } = item; const { file, originalFile, encInfo } = item;

View File

@@ -79,6 +79,28 @@ function GlobalPackSelector({
}); });
}; };
const addSelected = (adds: PackAddress[]) => {
setSelected((addresses) => {
const newAddresses = Array.from(addresses);
adds.forEach((address) => {
if (newAddresses.find((addr) => packAddressEqual(addr, address))) {
return;
}
newAddresses.push(address);
});
return newAddresses;
});
};
const removeSelected = (adds: PackAddress[]) => {
setSelected((addresses) => {
const newAddresses = addresses.filter(
(addr) => !adds.find((address) => packAddressEqual(addr, address))
);
return newAddresses;
});
};
const hasSelected = selected.length > 0; const hasSelected = selected.length > 0;
return ( return (
<Box grow="Yes" direction="Column"> <Box grow="Yes" direction="Column">
@@ -115,9 +137,35 @@ function GlobalPackSelector({
{Array.from(roomToPacks.entries()).map(([roomId, roomPacks]) => { {Array.from(roomToPacks.entries()).map(([roomId, roomPacks]) => {
const room = mx.getRoom(roomId); const room = mx.getRoom(roomId);
if (!room) return null; if (!room) return null;
const roomPackAddresses = roomPacks
.map((pack) => pack.address)
.filter((addr) => addr !== undefined);
const allSelected = roomPackAddresses.every((addr) =>
selected.find((address) => packAddressEqual(addr, address))
);
return ( return (
<Box key={roomId} direction="Column" gap="100"> <Box key={roomId} direction="Column" gap="100">
<Text size="L400">{room.name}</Text> <Box alignItems="Center">
<Box grow="Yes">
<Text size="L400">{room.name}</Text>
</Box>
<Box shrink="No">
<Chip
variant={allSelected ? 'Critical' : 'Surface'}
radii="Pill"
onClick={() => {
if (allSelected) {
removeSelected(roomPackAddresses);
return;
}
addSelected(roomPackAddresses);
}}
>
<Text size="B300">{allSelected ? 'Unselect All' : 'Select All'}</Text>
</Chip>
</Box>
</Box>
{roomPacks.map((pack) => { {roomPacks.map((pack) => {
const avatarMxc = pack.getAvatarUrl(ImageUsage.Emoticon); const avatarMxc = pack.getAvatarUrl(ImageUsage.Emoticon);
const avatarUrl = avatarMxc const avatarUrl = avatarMxc
@@ -126,7 +174,7 @@ function GlobalPackSelector({
const { address } = pack; const { address } = pack;
if (!address) return null; if (!address) return null;
const added = selected.find((addr) => packAddressEqual(addr, address)); const added = !!selected.find((addr) => packAddressEqual(addr, address));
return ( return (
<SequenceCard <SequenceCard
key={pack.id} key={pack.id}
@@ -152,7 +200,11 @@ function GlobalPackSelector({
</Box> </Box>
} }
after={ after={
<Checkbox variant="Success" onClick={() => toggleSelect(address)} /> <Checkbox
checked={added}
variant="Success"
onClick={() => toggleSelect(address)}
/>
} }
/> />
</SequenceCard> </SequenceCard>

View File

@@ -1,82 +1,12 @@
import React from 'react'; import React from 'react';
import { Box, Text, IconButton, Icon, Icons, Scroll, Switch, Button, color } from 'folds'; import { Box, Text, IconButton, Icon, Icons, Scroll } from 'folds';
import { Page, PageContent, PageHeader } from '../../../components/page'; import { Page, PageContent, PageHeader } from '../../../components/page';
import { SequenceCard } from '../../../components/sequence-card'; import { SystemNotification } from './SystemNotification';
import { SequenceCardStyle } from '../styles.css';
import { SettingTile } from '../../../components/setting-tile';
import { useSetting } from '../../../state/hooks/settings';
import { settingsAtom } from '../../../state/settings';
import { getNotificationState, usePermissionState } from '../../../hooks/usePermission';
import { AllMessagesNotifications } from './AllMessages'; import { AllMessagesNotifications } from './AllMessages';
import { SpecialMessagesNotifications } from './SpecialMessages'; import { SpecialMessagesNotifications } from './SpecialMessages';
import { KeywordMessagesNotifications } from './KeywordMessages'; import { KeywordMessagesNotifications } from './KeywordMessages';
import { IgnoredUserList } from './IgnoredUserList'; import { IgnoredUserList } from './IgnoredUserList';
function SystemNotification() {
const notifPermission = usePermissionState('notifications', getNotificationState());
const [showNotifications, setShowNotifications] = useSetting(settingsAtom, 'showNotifications');
const [isNotificationSounds, setIsNotificationSounds] = useSetting(
settingsAtom,
'isNotificationSounds'
);
const requestNotificationPermission = () => {
window.Notification.requestPermission();
};
return (
<Box direction="Column" gap="100">
<Text size="L400">System</Text>
<SequenceCard
className={SequenceCardStyle}
variant="SurfaceVariant"
direction="Column"
gap="400"
>
<SettingTile
title="Desktop Notifications"
description={
notifPermission === 'denied' ? (
<Text as="span" style={{ color: color.Critical.Main }} size="T200">
{'Notification' in window
? 'Notification permission is blocked. Please allow notification permission from browser address bar.'
: 'Notifications are not supported by the system.'}
</Text>
) : (
<span>Show desktop notifications when message arrive.</span>
)
}
after={
notifPermission === 'prompt' ? (
<Button size="300" radii="300" onClick={requestNotificationPermission}>
<Text size="B300">Enable</Text>
</Button>
) : (
<Switch
disabled={notifPermission !== 'granted'}
value={showNotifications}
onChange={setShowNotifications}
/>
)
}
/>
</SequenceCard>
<SequenceCard
className={SequenceCardStyle}
variant="SurfaceVariant"
direction="Column"
gap="400"
>
<SettingTile
title="Notification Sound"
description="Play sound when new message arrive."
after={<Switch value={isNotificationSounds} onChange={setIsNotificationSounds} />}
/>
</SequenceCard>
</Box>
);
}
type NotificationsProps = { type NotificationsProps = {
requestClose: () => void; requestClose: () => void;
}; };

View File

@@ -0,0 +1,158 @@
import React, { useCallback } from 'react';
import { Box, Text, Switch, Button, color, Spinner } from 'folds';
import { IPusherRequest } from 'matrix-js-sdk';
import { SequenceCard } from '../../../components/sequence-card';
import { SequenceCardStyle } from '../styles.css';
import { SettingTile } from '../../../components/setting-tile';
import { useSetting } from '../../../state/hooks/settings';
import { settingsAtom } from '../../../state/settings';
import { getNotificationState, usePermissionState } from '../../../hooks/usePermission';
import { useEmailNotifications } from '../../../hooks/useEmailNotifications';
import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
function EmailNotification() {
const mx = useMatrixClient();
const [result, refreshResult] = useEmailNotifications();
const [setState, setEnable] = useAsyncCallback(
useCallback(
async (email: string, enable: boolean) => {
if (enable) {
await mx.setPusher({
kind: 'email',
app_id: 'm.email',
pushkey: email,
app_display_name: 'Email Notifications',
device_display_name: email,
lang: 'en',
data: {
brand: 'Cinny',
},
append: true,
});
return;
}
await mx.setPusher({
pushkey: email,
app_id: 'm.email',
kind: null,
} as unknown as IPusherRequest);
},
[mx]
)
);
const handleChange = (value: boolean) => {
if (result && result.email) {
setEnable(result.email, value).then(() => {
refreshResult();
});
}
};
return (
<SettingTile
title="Email Notification"
description={
<>
{result && !result.email && (
<Text as="span" style={{ color: color.Critical.Main }} size="T200">
Your account does not have any email attached.
</Text>
)}
{result && result.email && <>Send notification to your email. {`("${result.email}")`}</>}
{result === null && (
<Text as="span" style={{ color: color.Critical.Main }} size="T200">
Unexpected Error!
</Text>
)}
{result === undefined && 'Send notification to your email.'}
</>
}
after={
<>
{setState.status !== AsyncStatus.Loading &&
typeof result === 'object' &&
result?.email && <Switch value={result.enabled} onChange={handleChange} />}
{(setState.status === AsyncStatus.Loading || result === undefined) && (
<Spinner variant="Secondary" />
)}
</>
}
/>
);
}
export function SystemNotification() {
const notifPermission = usePermissionState('notifications', getNotificationState());
const [showNotifications, setShowNotifications] = useSetting(settingsAtom, 'showNotifications');
const [isNotificationSounds, setIsNotificationSounds] = useSetting(
settingsAtom,
'isNotificationSounds'
);
const requestNotificationPermission = () => {
window.Notification.requestPermission();
};
return (
<Box direction="Column" gap="100">
<Text size="L400">System</Text>
<SequenceCard
className={SequenceCardStyle}
variant="SurfaceVariant"
direction="Column"
gap="400"
>
<SettingTile
title="Desktop Notifications"
description={
notifPermission === 'denied' ? (
<Text as="span" style={{ color: color.Critical.Main }} size="T200">
{'Notification' in window
? 'Notification permission is blocked. Please allow notification permission from browser address bar.'
: 'Notifications are not supported by the system.'}
</Text>
) : (
<span>Show desktop notifications when message arrive.</span>
)
}
after={
notifPermission === 'prompt' ? (
<Button size="300" radii="300" onClick={requestNotificationPermission}>
<Text size="B300">Enable</Text>
</Button>
) : (
<Switch
disabled={notifPermission !== 'granted'}
value={showNotifications}
onChange={setShowNotifications}
/>
)
}
/>
</SequenceCard>
<SequenceCard
className={SequenceCardStyle}
variant="SurfaceVariant"
direction="Column"
gap="400"
>
<SettingTile
title="Notification Sound"
description="Play sound when new message arrive."
after={<Switch value={isNotificationSounds} onChange={setIsNotificationSounds} />}
/>
</SequenceCard>
<SequenceCard
className={SequenceCardStyle}
variant="SurfaceVariant"
direction="Column"
gap="400"
>
<EmailNotification />
</SequenceCard>
</Box>
);
}

View File

@@ -10,6 +10,7 @@ import {
matchQuery, matchQuery,
ResultHandler, ResultHandler,
} from '../utils/AsyncSearch'; } from '../utils/AsyncSearch';
import { sanitizeForRegex } from '../utils/regex';
export type UseAsyncSearchOptions = AsyncSearchOption & { export type UseAsyncSearchOptions = AsyncSearchOption & {
matchOptions?: MatchQueryOption; matchOptions?: MatchQueryOption;
@@ -28,6 +29,81 @@ export type UseAsyncSearchResult<TSearchItem extends object | string | number> =
export type SearchResetHandler = () => void; export type SearchResetHandler = () => void;
const performMatch = (
target: string | string[],
query: string,
options?: UseAsyncSearchOptions
): string | undefined => {
if (Array.isArray(target)) {
const matchTarget = target.find((i) =>
matchQuery(normalize(i, options?.normalizeOptions), query, options?.matchOptions)
);
return matchTarget ? normalize(matchTarget, options?.normalizeOptions) : undefined;
}
const normalizedTargetStr = normalize(target, options?.normalizeOptions);
const matches = matchQuery(normalizedTargetStr, query, options?.matchOptions);
return matches ? normalizedTargetStr : undefined;
};
export const orderSearchItems = <TSearchItem extends object | string | number>(
query: string,
items: TSearchItem[],
getItemStr: SearchItemStrGetter<TSearchItem>,
options?: UseAsyncSearchOptions
): TSearchItem[] => {
const orderedItems: TSearchItem[] = Array.from(items);
// we will consider "_" as word boundary char.
// because in more use-cases it is used. (like: emojishortcode)
const boundaryRegex = new RegExp(`(\\b|_)${sanitizeForRegex(query)}`);
const perfectBoundaryRegex = new RegExp(`(\\b|_)${sanitizeForRegex(query)}(\\b|_)`);
orderedItems.sort((i1, i2) => {
const str1 = performMatch(getItemStr(i1, query), query, options);
const str2 = performMatch(getItemStr(i2, query), query, options);
if (str1 === undefined && str2 === undefined) return 0;
if (str1 === undefined) return 1;
if (str2 === undefined) return -1;
let points1 = 0;
let points2 = 0;
// short string should score more
const pointsToSmallStr = (points: number) => {
if (str1.length < str2.length) points1 += points;
else if (str2.length < str1.length) points2 += points;
};
pointsToSmallStr(1);
// closes query match should score more
const indexIn1 = str1.indexOf(query);
const indexIn2 = str2.indexOf(query);
if (indexIn1 < indexIn2) points1 += 2;
else if (indexIn2 < indexIn1) points2 += 2;
else pointsToSmallStr(2);
// query match word start on boundary should score more
const boundaryIn1 = str1.match(boundaryRegex);
const boundaryIn2 = str2.match(boundaryRegex);
if (boundaryIn1 && boundaryIn2) pointsToSmallStr(4);
else if (boundaryIn1) points1 += 4;
else if (boundaryIn2) points2 += 4;
// query match word start and end on boundary should score more
const perfectBoundaryIn1 = str1.match(perfectBoundaryRegex);
const perfectBoundaryIn2 = str2.match(perfectBoundaryRegex);
if (perfectBoundaryIn1 && perfectBoundaryIn2) pointsToSmallStr(8);
else if (perfectBoundaryIn1) points1 += 8;
else if (perfectBoundaryIn2) points2 += 8;
return points2 - points1;
});
return orderedItems;
};
export const useAsyncSearch = <TSearchItem extends object | string | number>( export const useAsyncSearch = <TSearchItem extends object | string | number>(
list: TSearchItem[], list: TSearchItem[],
getItemStr: SearchItemStrGetter<TSearchItem>, getItemStr: SearchItemStrGetter<TSearchItem>,
@@ -40,21 +116,15 @@ export const useAsyncSearch = <TSearchItem extends object | string | number>(
const handleMatch: MatchHandler<TSearchItem> = (item, query) => { const handleMatch: MatchHandler<TSearchItem> = (item, query) => {
const itemStr = getItemStr(item, query); const itemStr = getItemStr(item, query);
if (Array.isArray(itemStr))
return !!itemStr.find((i) => const strWithMatch = performMatch(itemStr, query, options);
matchQuery(normalize(i, options?.normalizeOptions), query, options?.matchOptions) return typeof strWithMatch === 'string';
);
return matchQuery(
normalize(itemStr, options?.normalizeOptions),
query,
options?.matchOptions
);
}; };
const handleResult: ResultHandler<TSearchItem> = (results, query) => const handleResult: ResultHandler<TSearchItem> = (results, query) =>
setResult({ setResult({
query, query,
items: [...results], items: orderSearchItems(query, results, getItemStr, options),
}); });
return AsyncSearch(list, handleMatch, handleResult, options); return AsyncSearch(list, handleMatch, handleResult, options);

View File

@@ -0,0 +1,55 @@
import { useCallback } from 'react';
import { AsyncStatus, useAsyncCallbackValue } from './useAsyncCallback';
import { useMatrixClient } from './useMatrixClient';
type RefreshHandler = () => void;
type EmailNotificationResult = {
enabled: boolean;
email?: string;
};
export const useEmailNotifications = (): [
EmailNotificationResult | undefined | null,
RefreshHandler
] => {
const mx = useMatrixClient();
const [emailState, refresh] = useAsyncCallbackValue<EmailNotificationResult, Error>(
useCallback(async () => {
const tpIDs = (await mx.getThreePids())?.threepids;
const emailAddresses = tpIDs.filter((id) => id.medium === 'email').map((id) => id.address);
if (emailAddresses.length === 0)
return {
enabled: false,
};
const pushers = (await mx.getPushers())?.pushers;
const emailPusher = pushers.find(
(pusher) => pusher.app_id === 'm.email' && emailAddresses.includes(pusher.pushkey)
);
if (emailPusher?.pushkey) {
return {
enabled: true,
email: emailPusher.pushkey,
};
}
return {
enabled: false,
email: emailAddresses[0],
};
}, [mx])
);
if (emailState.status === AsyncStatus.Success) {
return [emailState.data, refresh];
}
if (emailState.status === AsyncStatus.Error) {
return [null, refresh];
}
return [undefined, refresh];
};

View File

@@ -1,6 +1,8 @@
import { atom, useAtom, useAtomValue } from 'jotai'; import { atom, useAtom, useAtomValue } from 'jotai';
import { useCallback, useEffect, useState } from 'react'; import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Room } from 'matrix-js-sdk'; import { MatrixError, Room } from 'matrix-js-sdk';
import { IHierarchyRoom } from 'matrix-js-sdk/lib/@types/spaces';
import { QueryFunction, useInfiniteQuery } from '@tanstack/react-query';
import { useMatrixClient } from './useMatrixClient'; import { useMatrixClient } from './useMatrixClient';
import { roomToParentsAtom } from '../state/room/roomToParents'; import { roomToParentsAtom } from '../state/room/roomToParents';
import { MSpaceChildContent, StateEvent } from '../../types/matrix/room'; import { MSpaceChildContent, StateEvent } from '../../types/matrix/room';
@@ -8,22 +10,24 @@ import { getAllParents, getStateEvents, isValidChild } from '../utils/room';
import { isRoomId } from '../utils/matrix'; import { isRoomId } from '../utils/matrix';
import { SortFunc, byOrderKey, byTsOldToNew, factoryRoomIdByActivity } from '../utils/sort'; import { SortFunc, byOrderKey, byTsOldToNew, factoryRoomIdByActivity } from '../utils/sort';
import { useStateEventCallback } from './useStateEventCallback'; import { useStateEventCallback } from './useStateEventCallback';
import { ErrorCode } from '../cs-errorcode';
export type HierarchyItem = export type HierarchyItemSpace = {
| { roomId: string;
roomId: string; content: MSpaceChildContent;
content: MSpaceChildContent; ts: number;
ts: number; space: true;
space: true; parentId?: string;
parentId?: string; };
}
| { export type HierarchyItemRoom = {
roomId: string; roomId: string;
content: MSpaceChildContent; content: MSpaceChildContent;
ts: number; ts: number;
space?: false; parentId: string;
parentId: string; };
};
export type HierarchyItem = HierarchyItemSpace | HierarchyItemRoom;
type GetRoomCallback = (roomId: string) => Room | undefined; type GetRoomCallback = (roomId: string) => Room | undefined;
@@ -35,16 +39,16 @@ const getHierarchySpaces = (
rootSpaceId: string, rootSpaceId: string,
getRoom: GetRoomCallback, getRoom: GetRoomCallback,
spaceRooms: Set<string> spaceRooms: Set<string>
): HierarchyItem[] => { ): HierarchyItemSpace[] => {
const rootSpaceItem: HierarchyItem = { const rootSpaceItem: HierarchyItemSpace = {
roomId: rootSpaceId, roomId: rootSpaceId,
content: { via: [] }, content: { via: [] },
ts: 0, ts: 0,
space: true, space: true,
}; };
let spaceItems: HierarchyItem[] = []; let spaceItems: HierarchyItemSpace[] = [];
const findAndCollectHierarchySpaces = (spaceItem: HierarchyItem) => { const findAndCollectHierarchySpaces = (spaceItem: HierarchyItemSpace) => {
if (spaceItems.find((item) => item.roomId === spaceItem.roomId)) return; if (spaceItems.find((item) => item.roomId === spaceItem.roomId)) return;
const space = getRoom(spaceItem.roomId); const space = getRoom(spaceItem.roomId);
spaceItems.push(spaceItem); spaceItems.push(spaceItem);
@@ -61,7 +65,7 @@ const getHierarchySpaces = (
// or requesting room summary, we will look it into spaceRooms local // or requesting room summary, we will look it into spaceRooms local
// cache which we maintain as we load summary in UI. // cache which we maintain as we load summary in UI.
if (getRoom(childId)?.isSpaceRoom() || spaceRooms.has(childId)) { if (getRoom(childId)?.isSpaceRoom() || spaceRooms.has(childId)) {
const childItem: HierarchyItem = { const childItem: HierarchyItemSpace = {
roomId: childId, roomId: childId,
content: childEvent.getContent<MSpaceChildContent>(), content: childEvent.getContent<MSpaceChildContent>(),
ts: childEvent.getTs(), ts: childEvent.getTs(),
@@ -85,28 +89,34 @@ const getHierarchySpaces = (
return spaceItems; return spaceItems;
}; };
export type SpaceHierarchy = {
space: HierarchyItemSpace;
rooms?: HierarchyItemRoom[];
};
const getSpaceHierarchy = ( const getSpaceHierarchy = (
rootSpaceId: string, rootSpaceId: string,
spaceRooms: Set<string>, spaceRooms: Set<string>,
getRoom: (roomId: string) => Room | undefined, getRoom: (roomId: string) => Room | undefined,
closedCategory: (spaceId: string) => boolean closedCategory: (spaceId: string) => boolean
): HierarchyItem[] => { ): SpaceHierarchy[] => {
const spaceItems: HierarchyItem[] = getHierarchySpaces(rootSpaceId, getRoom, spaceRooms); const spaceItems: HierarchyItemSpace[] = getHierarchySpaces(rootSpaceId, getRoom, spaceRooms);
const hierarchy: HierarchyItem[] = spaceItems.flatMap((spaceItem) => { const hierarchy: SpaceHierarchy[] = spaceItems.map((spaceItem) => {
const space = getRoom(spaceItem.roomId); const space = getRoom(spaceItem.roomId);
if (!space || closedCategory(spaceItem.roomId)) { if (!space || closedCategory(spaceItem.roomId)) {
return [spaceItem]; return {
space: spaceItem,
};
} }
const childEvents = getStateEvents(space, StateEvent.SpaceChild); const childEvents = getStateEvents(space, StateEvent.SpaceChild);
const childItems: HierarchyItem[] = []; const childItems: HierarchyItemRoom[] = [];
childEvents.forEach((childEvent) => { childEvents.forEach((childEvent) => {
if (!isValidChild(childEvent)) return; if (!isValidChild(childEvent)) return;
const childId = childEvent.getStateKey(); const childId = childEvent.getStateKey();
if (!childId || !isRoomId(childId)) return; if (!childId || !isRoomId(childId)) return;
if (getRoom(childId)?.isSpaceRoom() || spaceRooms.has(childId)) return; if (getRoom(childId)?.isSpaceRoom() || spaceRooms.has(childId)) return;
const childItem: HierarchyItem = { const childItem: HierarchyItemRoom = {
roomId: childId, roomId: childId,
content: childEvent.getContent<MSpaceChildContent>(), content: childEvent.getContent<MSpaceChildContent>(),
ts: childEvent.getTs(), ts: childEvent.getTs(),
@@ -114,7 +124,11 @@ const getSpaceHierarchy = (
}; };
childItems.push(childItem); childItems.push(childItem);
}); });
return [spaceItem, ...childItems.sort(hierarchyItemTs).sort(hierarchyItemByOrder)];
return {
space: spaceItem,
rooms: childItems.sort(hierarchyItemTs).sort(hierarchyItemByOrder),
};
}); });
return hierarchy; return hierarchy;
@@ -125,7 +139,7 @@ export const useSpaceHierarchy = (
spaceRooms: Set<string>, spaceRooms: Set<string>,
getRoom: (roomId: string) => Room | undefined, getRoom: (roomId: string) => Room | undefined,
closedCategory: (spaceId: string) => boolean closedCategory: (spaceId: string) => boolean
): HierarchyItem[] => { ): SpaceHierarchy[] => {
const mx = useMatrixClient(); const mx = useMatrixClient();
const roomToParents = useAtomValue(roomToParentsAtom); const roomToParents = useAtomValue(roomToParentsAtom);
@@ -163,7 +177,7 @@ const getSpaceJoinedHierarchy = (
excludeRoom: (parentId: string, roomId: string) => boolean, excludeRoom: (parentId: string, roomId: string) => boolean,
sortRoomItems: (parentId: string, items: HierarchyItem[]) => HierarchyItem[] sortRoomItems: (parentId: string, items: HierarchyItem[]) => HierarchyItem[]
): HierarchyItem[] => { ): HierarchyItem[] => {
const spaceItems: HierarchyItem[] = getHierarchySpaces(rootSpaceId, getRoom, new Set()); const spaceItems: HierarchyItemSpace[] = getHierarchySpaces(rootSpaceId, getRoom, new Set());
const hierarchy: HierarchyItem[] = spaceItems.flatMap((spaceItem) => { const hierarchy: HierarchyItem[] = spaceItems.flatMap((spaceItem) => {
const space = getRoom(spaceItem.roomId); const space = getRoom(spaceItem.roomId);
@@ -182,14 +196,14 @@ const getSpaceJoinedHierarchy = (
if (joinedRoomEvents.length === 0) return []; if (joinedRoomEvents.length === 0) return [];
const childItems: HierarchyItem[] = []; const childItems: HierarchyItemRoom[] = [];
joinedRoomEvents.forEach((childEvent) => { joinedRoomEvents.forEach((childEvent) => {
const childId = childEvent.getStateKey(); const childId = childEvent.getStateKey();
if (!childId) return; if (!childId) return;
if (excludeRoom(space.roomId, childId)) return; if (excludeRoom(space.roomId, childId)) return;
const childItem: HierarchyItem = { const childItem: HierarchyItemRoom = {
roomId: childId, roomId: childId,
content: childEvent.getContent<MSpaceChildContent>(), content: childEvent.getContent<MSpaceChildContent>(),
ts: childEvent.getTs(), ts: childEvent.getTs(),
@@ -251,3 +265,85 @@ export const useSpaceJoinedHierarchy = (
return hierarchy; return hierarchy;
}; };
// we will paginate until 5000 items
const PER_PAGE_COUNT = 100;
const MAX_AUTO_PAGE_COUNT = 50;
export type FetchSpaceHierarchyLevelData = {
fetching: boolean;
error: Error | null;
rooms: Map<string, IHierarchyRoom>;
};
export const useFetchSpaceHierarchyLevel = (
roomId: string,
enable: boolean
): FetchSpaceHierarchyLevelData => {
const mx = useMatrixClient();
const pageNoRef = useRef(0);
const fetchLevel: QueryFunction<
Awaited<ReturnType<typeof mx.getRoomHierarchy>>,
string[],
string | undefined
> = useCallback(
({ pageParam }) => mx.getRoomHierarchy(roomId, PER_PAGE_COUNT, 1, false, pageParam),
[roomId, mx]
);
const queryResponse = useInfiniteQuery({
refetchOnMount: enable,
queryKey: [roomId, 'hierarchy_level'],
initialPageParam: undefined,
queryFn: fetchLevel,
getNextPageParam: (result) => {
if (result.next_batch) return result.next_batch;
return undefined;
},
retry: 5,
retryDelay: (failureCount, error) => {
if (error instanceof MatrixError && error.errcode === ErrorCode.M_LIMIT_EXCEEDED) {
const { retry_after_ms: delay } = error.data;
if (typeof delay === 'number') {
return delay;
}
}
return 500 * failureCount;
},
});
const { data, isLoading, isFetchingNextPage, error, fetchNextPage, hasNextPage } = queryResponse;
useEffect(() => {
if (
hasNextPage &&
pageNoRef.current <= MAX_AUTO_PAGE_COUNT &&
!error &&
data &&
data.pages.length > 0
) {
pageNoRef.current += 1;
fetchNextPage();
}
}, [fetchNextPage, hasNextPage, data, error]);
const rooms: Map<string, IHierarchyRoom> = useMemo(() => {
const roomsMap: Map<string, IHierarchyRoom> = new Map();
if (!data) return roomsMap;
const rms = data.pages.flatMap((result) => result.rooms);
rms.forEach((r) => {
roomsMap.set(r.room_id, r);
});
return roomsMap;
}, [data]);
const fetching = isLoading || isFetchingNextPage;
return {
fetching,
error,
rooms,
};
};

View File

@@ -26,8 +26,23 @@ export type ScrollToOptions = {
stopInView?: boolean; stopInView?: boolean;
}; };
export type ScrollToElement = (element: HTMLElement, opts?: ScrollToOptions) => void; /**
export type ScrollToItem = (index: number, opts?: ScrollToOptions) => void; * Scrolls the page to a specified element in the DOM.
*
* @param {HTMLElement} element - The DOM element to scroll to.
* @param {ScrollToOptions} [opts] - Optional configuration for the scroll behavior (e.g., smooth scrolling, alignment).
* @returns {boolean} - Returns `true` if the scroll was successful, otherwise returns `false`.
*/
export type ScrollToElement = (element: HTMLElement, opts?: ScrollToOptions) => boolean;
/**
* Scrolls the page to an item at the specified index within a scrollable container.
*
* @param {number} index - The index of the item to scroll to.
* @param {ScrollToOptions} [opts] - Optional configuration for the scroll behavior (e.g., smooth scrolling, alignment).
* @returns {boolean} - Returns `true` if the scroll was successful, otherwise returns `false`.
*/
export type ScrollToItem = (index: number, opts?: ScrollToOptions) => boolean;
type HandleObserveAnchor = (element: HTMLElement | null) => void; type HandleObserveAnchor = (element: HTMLElement | null) => void;
@@ -186,10 +201,10 @@ export const useVirtualPaginator = <TScrollElement extends HTMLElement>(
const scrollToElement = useCallback<ScrollToElement>( const scrollToElement = useCallback<ScrollToElement>(
(element, opts) => { (element, opts) => {
const scrollElement = getScrollElement(); const scrollElement = getScrollElement();
if (!scrollElement) return; if (!scrollElement) return false;
if (opts?.stopInView && isInScrollView(scrollElement, element)) { if (opts?.stopInView && isInScrollView(scrollElement, element)) {
return; return false;
} }
let scrollTo = element.offsetTop; let scrollTo = element.offsetTop;
if (opts?.align === 'center' && canFitInScrollView(scrollElement, element)) { if (opts?.align === 'center' && canFitInScrollView(scrollElement, element)) {
@@ -207,6 +222,7 @@ export const useVirtualPaginator = <TScrollElement extends HTMLElement>(
top: scrollTo - (opts?.offset ?? 0), top: scrollTo - (opts?.offset ?? 0),
behavior: opts?.behavior, behavior: opts?.behavior,
}); });
return true;
}, },
[getScrollElement] [getScrollElement]
); );
@@ -215,7 +231,7 @@ export const useVirtualPaginator = <TScrollElement extends HTMLElement>(
(index, opts) => { (index, opts) => {
const { range: currentRange, limit: currentLimit, count: currentCount } = propRef.current; const { range: currentRange, limit: currentLimit, count: currentCount } = propRef.current;
if (index < 0 || index >= currentCount) return; if (index < 0 || index >= currentCount) return false;
// index is not in range change range // index is not in range change range
// and trigger scrollToItem in layoutEffect hook // and trigger scrollToItem in layoutEffect hook
if (index < currentRange.start || index >= currentRange.end) { if (index < currentRange.start || index >= currentRange.end) {
@@ -227,7 +243,7 @@ export const useVirtualPaginator = <TScrollElement extends HTMLElement>(
index, index,
opts, opts,
}; };
return; return true;
} }
// find target or it's previous rendered element to scroll to // find target or it's previous rendered element to scroll to
@@ -241,9 +257,9 @@ export const useVirtualPaginator = <TScrollElement extends HTMLElement>(
top: opts?.offset ?? 0, top: opts?.offset ?? 0,
behavior: opts?.behavior, behavior: opts?.behavior,
}); });
return; return true;
} }
scrollToElement(itemElement, opts); return scrollToElement(itemElement, opts);
}, },
[getScrollElement, scrollToElement, getItemElement, onRangeChange] [getScrollElement, scrollToElement, getItemElement, onRangeChange]
); );

View File

@@ -15,7 +15,7 @@ export function AuthFooter() {
target="_blank" target="_blank"
rel="noreferrer" rel="noreferrer"
> >
v4.3.2 v4.4.0
</Text> </Text>
<Text as="a" size="T300" href="https://twitter.com/cinnyapp" target="_blank" rel="noreferrer"> <Text as="a" size="T300" href="https://twitter.com/cinnyapp" target="_blank" rel="noreferrer">
Twitter Twitter

View File

@@ -24,7 +24,7 @@ export function WelcomePage() {
target="_blank" target="_blank"
rel="noreferrer noopener" rel="noreferrer noopener"
> >
v4.3.2 v4.4.0
</a> </a>
</span> </span>
} }

View File

@@ -1,368 +0,0 @@
export type MatchResult = RegExpMatchArray | RegExpExecArray;
export type RuleMatch = (text: string) => MatchResult | null;
export const beforeMatch = (text: string, match: RegExpMatchArray | RegExpExecArray): string =>
text.slice(0, match.index);
export const afterMatch = (text: string, match: RegExpMatchArray | RegExpExecArray): string =>
text.slice((match.index ?? 0) + match[0].length);
export const replaceMatch = <C>(
convertPart: (txt: string) => Array<string | C>,
text: string,
match: MatchResult,
content: C
): Array<string | C> => [
...convertPart(beforeMatch(text, match)),
content,
...convertPart(afterMatch(text, match)),
];
/*
*****************
* INLINE PARSER *
*****************
*/
export type InlineMDParser = (text: string) => string;
export type InlineMatchConverter = (parse: InlineMDParser, match: MatchResult) => string;
export type InlineMDRule = {
match: RuleMatch;
html: InlineMatchConverter;
};
export type InlineRuleRunner = (
parse: InlineMDParser,
text: string,
rule: InlineMDRule
) => string | undefined;
export type InlineRulesRunner = (
parse: InlineMDParser,
text: string,
rules: InlineMDRule[]
) => string | undefined;
const MIN_ANY = '(.+?)';
const URL_NEG_LB = '(?<!(https?|ftp|mailto|magnet):\\/\\/\\S*)';
const BOLD_MD_1 = '**';
const BOLD_PREFIX_1 = '\\*{2}';
const BOLD_NEG_LA_1 = '(?!\\*)';
const BOLD_REG_1 = new RegExp(
`${URL_NEG_LB}${BOLD_PREFIX_1}${MIN_ANY}${BOLD_PREFIX_1}${BOLD_NEG_LA_1}`
);
const BoldRule: InlineMDRule = {
match: (text) => text.match(BOLD_REG_1),
html: (parse, match) => {
const [, , g2] = match;
return `<strong data-md="${BOLD_MD_1}">${parse(g2)}</strong>`;
},
};
const ITALIC_MD_1 = '*';
const ITALIC_PREFIX_1 = '\\*';
const ITALIC_NEG_LA_1 = '(?!\\*)';
const ITALIC_REG_1 = new RegExp(
`${URL_NEG_LB}${ITALIC_PREFIX_1}${MIN_ANY}${ITALIC_PREFIX_1}${ITALIC_NEG_LA_1}`
);
const ItalicRule1: InlineMDRule = {
match: (text) => text.match(ITALIC_REG_1),
html: (parse, match) => {
const [, , g2] = match;
return `<i data-md="${ITALIC_MD_1}">${parse(g2)}</i>`;
},
};
const ITALIC_MD_2 = '_';
const ITALIC_PREFIX_2 = '_';
const ITALIC_NEG_LA_2 = '(?!_)';
const ITALIC_REG_2 = new RegExp(
`${URL_NEG_LB}${ITALIC_PREFIX_2}${MIN_ANY}${ITALIC_PREFIX_2}${ITALIC_NEG_LA_2}`
);
const ItalicRule2: InlineMDRule = {
match: (text) => text.match(ITALIC_REG_2),
html: (parse, match) => {
const [, , g2] = match;
return `<i data-md="${ITALIC_MD_2}">${parse(g2)}</i>`;
},
};
const UNDERLINE_MD_1 = '__';
const UNDERLINE_PREFIX_1 = '_{2}';
const UNDERLINE_NEG_LA_1 = '(?!_)';
const UNDERLINE_REG_1 = new RegExp(
`${URL_NEG_LB}${UNDERLINE_PREFIX_1}${MIN_ANY}${UNDERLINE_PREFIX_1}${UNDERLINE_NEG_LA_1}`
);
const UnderlineRule: InlineMDRule = {
match: (text) => text.match(UNDERLINE_REG_1),
html: (parse, match) => {
const [, , g2] = match;
return `<u data-md="${UNDERLINE_MD_1}">${parse(g2)}</u>`;
},
};
const STRIKE_MD_1 = '~~';
const STRIKE_PREFIX_1 = '~{2}';
const STRIKE_NEG_LA_1 = '(?!~)';
const STRIKE_REG_1 = new RegExp(
`${URL_NEG_LB}${STRIKE_PREFIX_1}${MIN_ANY}${STRIKE_PREFIX_1}${STRIKE_NEG_LA_1}`
);
const StrikeRule: InlineMDRule = {
match: (text) => text.match(STRIKE_REG_1),
html: (parse, match) => {
const [, , g2] = match;
return `<del data-md="${STRIKE_MD_1}">${parse(g2)}</del>`;
},
};
const CODE_MD_1 = '`';
const CODE_PREFIX_1 = '`';
const CODE_NEG_LA_1 = '(?!`)';
const CODE_REG_1 = new RegExp(`${URL_NEG_LB}${CODE_PREFIX_1}(.+?)${CODE_PREFIX_1}${CODE_NEG_LA_1}`);
const CodeRule: InlineMDRule = {
match: (text) => text.match(CODE_REG_1),
html: (parse, match) => {
const [, , g2] = match;
return `<code data-md="${CODE_MD_1}">${g2}</code>`;
},
};
const SPOILER_MD_1 = '||';
const SPOILER_PREFIX_1 = '\\|{2}';
const SPOILER_NEG_LA_1 = '(?!\\|)';
const SPOILER_REG_1 = new RegExp(
`${URL_NEG_LB}${SPOILER_PREFIX_1}${MIN_ANY}${SPOILER_PREFIX_1}${SPOILER_NEG_LA_1}`
);
const SpoilerRule: InlineMDRule = {
match: (text) => text.match(SPOILER_REG_1),
html: (parse, match) => {
const [, , g2] = match;
return `<span data-md="${SPOILER_MD_1}" data-mx-spoiler>${parse(g2)}</span>`;
},
};
const LINK_ALT = `\\[${MIN_ANY}\\]`;
const LINK_URL = `\\((https?:\\/\\/.+?)\\)`;
const LINK_REG_1 = new RegExp(`${LINK_ALT}${LINK_URL}`);
const LinkRule: InlineMDRule = {
match: (text) => text.match(LINK_REG_1),
html: (parse, match) => {
const [, g1, g2] = match;
return `<a data-md href="${g2}">${parse(g1)}</a>`;
},
};
const runInlineRule: InlineRuleRunner = (parse, text, rule) => {
const matchResult = rule.match(text);
if (matchResult) {
const content = rule.html(parse, matchResult);
return replaceMatch((txt) => [parse(txt)], text, matchResult, content).join('');
}
return undefined;
};
/**
* Runs multiple rules at the same time to better handle nested rules.
* Rules will be run in the order they appear.
*/
const runInlineRules: InlineRulesRunner = (parse, text, rules) => {
const matchResults = rules.map((rule) => rule.match(text));
let targetRule: InlineMDRule | undefined;
let targetResult: MatchResult | undefined;
for (let i = 0; i < matchResults.length; i += 1) {
const currentResult = matchResults[i];
if (currentResult && typeof currentResult.index === 'number') {
if (
!targetResult ||
(typeof targetResult?.index === 'number' && currentResult.index < targetResult.index)
) {
targetResult = currentResult;
targetRule = rules[i];
}
}
}
if (targetRule && targetResult) {
const content = targetRule.html(parse, targetResult);
return replaceMatch((txt) => [parse(txt)], text, targetResult, content).join('');
}
return undefined;
};
const LeveledRules = [
BoldRule,
ItalicRule1,
UnderlineRule,
ItalicRule2,
StrikeRule,
SpoilerRule,
LinkRule,
];
export const parseInlineMD: InlineMDParser = (text) => {
if (text === '') return text;
let result: string | undefined;
if (!result) result = runInlineRule(parseInlineMD, text, CodeRule);
if (!result) result = runInlineRules(parseInlineMD, text, LeveledRules);
return result ?? text;
};
/*
****************
* BLOCK PARSER *
****************
*/
export type BlockMDParser = (test: string, parseInline?: (txt: string) => string) => string;
export type BlockMatchConverter = (
match: MatchResult,
parseInline?: (txt: string) => string
) => string;
export type BlockMDRule = {
match: RuleMatch;
html: BlockMatchConverter;
};
export type BlockRuleRunner = (
parse: BlockMDParser,
text: string,
rule: BlockMDRule,
parseInline?: (txt: string) => string
) => string | undefined;
const HEADING_REG_1 = /^(#{1,6}) +(.+)\n?/m;
const HeadingRule: BlockMDRule = {
match: (text) => text.match(HEADING_REG_1),
html: (match, parseInline) => {
const [, g1, g2] = match;
const level = g1.length;
return `<h${level} data-md="${g1}">${parseInline ? parseInline(g2) : g2}</h${level}>`;
},
};
const CODEBLOCK_MD_1 = '```';
const CODEBLOCK_REG_1 = /^`{3}(\S*)\n((?:.*\n)+?)`{3} *(?!.)\n?/m;
const CodeBlockRule: BlockMDRule = {
match: (text) => text.match(CODEBLOCK_REG_1),
html: (match) => {
const [, g1, g2] = match;
const classNameAtt = g1 ? ` class="language-${g1}"` : '';
return `<pre data-md="${CODEBLOCK_MD_1}"><code${classNameAtt}>${g2}</code></pre>`;
},
};
const BLOCKQUOTE_MD_1 = '>';
const QUOTE_LINE_PREFIX = /^> */;
const BLOCKQUOTE_TRAILING_NEWLINE = /\n$/;
const BLOCKQUOTE_REG_1 = /(^>.*\n?)+/m;
const BlockQuoteRule: BlockMDRule = {
match: (text) => text.match(BLOCKQUOTE_REG_1),
html: (match, parseInline) => {
const [blockquoteText] = match;
const lines = blockquoteText
.replace(BLOCKQUOTE_TRAILING_NEWLINE, '')
.split('\n')
.map((lineText) => {
const line = lineText.replace(QUOTE_LINE_PREFIX, '');
if (parseInline) return `${parseInline(line)}<br/>`;
return `${line}<br/>`;
})
.join('');
return `<blockquote data-md="${BLOCKQUOTE_MD_1}">${lines}</blockquote>`;
},
};
const ORDERED_LIST_MD_1 = '-';
const O_LIST_ITEM_PREFIX = /^(-|[\da-zA-Z]\.) */;
const O_LIST_START = /^([\d])\./;
const O_LIST_TYPE = /^([aAiI])\./;
const O_LIST_TRAILING_NEWLINE = /\n$/;
const ORDERED_LIST_REG_1 = /(^(?:-|[\da-zA-Z]\.) +.+\n?)+/m;
const OrderedListRule: BlockMDRule = {
match: (text) => text.match(ORDERED_LIST_REG_1),
html: (match, parseInline) => {
const [listText] = match;
const [, listStart] = listText.match(O_LIST_START) ?? [];
const [, listType] = listText.match(O_LIST_TYPE) ?? [];
const lines = listText
.replace(O_LIST_TRAILING_NEWLINE, '')
.split('\n')
.map((lineText) => {
const line = lineText.replace(O_LIST_ITEM_PREFIX, '');
const txt = parseInline ? parseInline(line) : line;
return `<li><p>${txt}</p></li>`;
})
.join('');
const dataMdAtt = `data-md="${listType || listStart || ORDERED_LIST_MD_1}"`;
const startAtt = listStart ? ` start="${listStart}"` : '';
const typeAtt = listType ? ` type="${listType}"` : '';
return `<ol ${dataMdAtt}${startAtt}${typeAtt}>${lines}</ol>`;
},
};
const UNORDERED_LIST_MD_1 = '*';
const U_LIST_ITEM_PREFIX = /^\* */;
const U_LIST_TRAILING_NEWLINE = /\n$/;
const UNORDERED_LIST_REG_1 = /(^\* +.+\n?)+/m;
const UnorderedListRule: BlockMDRule = {
match: (text) => text.match(UNORDERED_LIST_REG_1),
html: (match, parseInline) => {
const [listText] = match;
const lines = listText
.replace(U_LIST_TRAILING_NEWLINE, '')
.split('\n')
.map((lineText) => {
const line = lineText.replace(U_LIST_ITEM_PREFIX, '');
const txt = parseInline ? parseInline(line) : line;
return `<li><p>${txt}</p></li>`;
})
.join('');
return `<ul data-md="${UNORDERED_LIST_MD_1}">${lines}</ul>`;
},
};
const runBlockRule: BlockRuleRunner = (parse, text, rule, parseInline) => {
const matchResult = rule.match(text);
if (matchResult) {
const content = rule.html(matchResult, parseInline);
return replaceMatch((txt) => [parse(txt, parseInline)], text, matchResult, content).join('');
}
return undefined;
};
export const parseBlockMD: BlockMDParser = (text, parseInline) => {
if (text === '') return text;
let result: string | undefined;
if (!result) result = runBlockRule(parseBlockMD, text, CodeBlockRule, parseInline);
if (!result) result = runBlockRule(parseBlockMD, text, BlockQuoteRule, parseInline);
if (!result) result = runBlockRule(parseBlockMD, text, OrderedListRule, parseInline);
if (!result) result = runBlockRule(parseBlockMD, text, UnorderedListRule, parseInline);
if (!result) result = runBlockRule(parseBlockMD, text, HeadingRule, parseInline);
// replace \n with <br/> because want to preserve empty lines
if (!result) {
if (parseInline) {
result = text
.split('\n')
.map((lineText) => parseInline(lineText))
.join('<br/>');
} else {
result = text.replace(/\n/g, '<br/>');
}
}
return result ?? text;
};

View File

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

View File

@@ -0,0 +1,47 @@
import { replaceMatch } from '../internal';
import {
BlockQuoteRule,
CodeBlockRule,
ESC_BLOCK_SEQ,
HeadingRule,
OrderedListRule,
UnorderedListRule,
} from './rules';
import { runBlockRule } from './runner';
import { BlockMDParser } from './type';
/**
* Parses block-level markdown text into HTML using defined block rules.
*
* @param text - The markdown text to be parsed.
* @param parseInline - Optional function to parse inline elements.
* @returns The parsed HTML or the original text if no block-level markdown was found.
*/
export const parseBlockMD: BlockMDParser = (text, parseInline) => {
if (text === '') return text;
let result: string | undefined;
if (!result) result = runBlockRule(text, CodeBlockRule, parseBlockMD, parseInline);
if (!result) result = runBlockRule(text, BlockQuoteRule, parseBlockMD, parseInline);
if (!result) result = runBlockRule(text, OrderedListRule, parseBlockMD, parseInline);
if (!result) result = runBlockRule(text, UnorderedListRule, parseBlockMD, parseInline);
if (!result) result = runBlockRule(text, HeadingRule, parseBlockMD, parseInline);
// replace \n with <br/> because want to preserve empty lines
if (!result) {
result = text
.split('\n')
.map((lineText) => {
const match = lineText.match(ESC_BLOCK_SEQ);
if (!match) {
return parseInline?.(lineText) ?? lineText;
}
const [, g1] = match;
return replaceMatch(lineText, match, g1, (t) => [parseInline?.(t) ?? t]).join('');
})
.join('<br/>');
}
return result ?? text;
};

View File

@@ -0,0 +1,100 @@
import { BlockMDRule } from './type';
const HEADING_REG_1 = /^(#{1,6}) +(.+)\n?/m;
export const HeadingRule: BlockMDRule = {
match: (text) => text.match(HEADING_REG_1),
html: (match, parseInline) => {
const [, g1, g2] = match;
const level = g1.length;
return `<h${level} data-md="${g1}">${parseInline ? parseInline(g2) : g2}</h${level}>`;
},
};
const CODEBLOCK_MD_1 = '```';
const CODEBLOCK_REG_1 = /^`{3}(\S*)\n((?:.*\n)+?)`{3} *(?!.)\n?/m;
export const CodeBlockRule: BlockMDRule = {
match: (text) => text.match(CODEBLOCK_REG_1),
html: (match) => {
const [, g1, g2] = match;
const classNameAtt = g1 ? ` class="language-${g1}"` : '';
return `<pre data-md="${CODEBLOCK_MD_1}"><code${classNameAtt}>${g2}</code></pre>`;
},
};
const BLOCKQUOTE_MD_1 = '>';
const QUOTE_LINE_PREFIX = /^> */;
const BLOCKQUOTE_TRAILING_NEWLINE = /\n$/;
const BLOCKQUOTE_REG_1 = /(^>.*\n?)+/m;
export const BlockQuoteRule: BlockMDRule = {
match: (text) => text.match(BLOCKQUOTE_REG_1),
html: (match, parseInline) => {
const [blockquoteText] = match;
const lines = blockquoteText
.replace(BLOCKQUOTE_TRAILING_NEWLINE, '')
.split('\n')
.map((lineText) => {
const line = lineText.replace(QUOTE_LINE_PREFIX, '');
if (parseInline) return `${parseInline(line)}<br/>`;
return `${line}<br/>`;
})
.join('');
return `<blockquote data-md="${BLOCKQUOTE_MD_1}">${lines}</blockquote>`;
},
};
const ORDERED_LIST_MD_1 = '-';
const O_LIST_ITEM_PREFIX = /^(-|[\da-zA-Z]\.) */;
const O_LIST_START = /^([\d])\./;
const O_LIST_TYPE = /^([aAiI])\./;
const O_LIST_TRAILING_NEWLINE = /\n$/;
const ORDERED_LIST_REG_1 = /(^(?:-|[\da-zA-Z]\.) +.+\n?)+/m;
export const OrderedListRule: BlockMDRule = {
match: (text) => text.match(ORDERED_LIST_REG_1),
html: (match, parseInline) => {
const [listText] = match;
const [, listStart] = listText.match(O_LIST_START) ?? [];
const [, listType] = listText.match(O_LIST_TYPE) ?? [];
const lines = listText
.replace(O_LIST_TRAILING_NEWLINE, '')
.split('\n')
.map((lineText) => {
const line = lineText.replace(O_LIST_ITEM_PREFIX, '');
const txt = parseInline ? parseInline(line) : line;
return `<li><p>${txt}</p></li>`;
})
.join('');
const dataMdAtt = `data-md="${listType || listStart || ORDERED_LIST_MD_1}"`;
const startAtt = listStart ? ` start="${listStart}"` : '';
const typeAtt = listType ? ` type="${listType}"` : '';
return `<ol ${dataMdAtt}${startAtt}${typeAtt}>${lines}</ol>`;
},
};
const UNORDERED_LIST_MD_1 = '*';
const U_LIST_ITEM_PREFIX = /^\* */;
const U_LIST_TRAILING_NEWLINE = /\n$/;
const UNORDERED_LIST_REG_1 = /(^\* +.+\n?)+/m;
export const UnorderedListRule: BlockMDRule = {
match: (text) => text.match(UNORDERED_LIST_REG_1),
html: (match, parseInline) => {
const [listText] = match;
const lines = listText
.replace(U_LIST_TRAILING_NEWLINE, '')
.split('\n')
.map((lineText) => {
const line = lineText.replace(U_LIST_ITEM_PREFIX, '');
const txt = parseInline ? parseInline(line) : line;
return `<li><p>${txt}</p></li>`;
})
.join('');
return `<ul data-md="${UNORDERED_LIST_MD_1}">${lines}</ul>`;
},
};
export const UN_ESC_BLOCK_SEQ = /^\\*(#{1,6} +|```|>|(-|[\da-zA-Z]\.) +|\* +)/;
export const ESC_BLOCK_SEQ = /^\\(\\*(#{1,6} +|```|>|(-|[\da-zA-Z]\.) +|\* +))/;

View File

@@ -0,0 +1,25 @@
import { replaceMatch } from '../internal';
import { BlockMDParser, BlockMDRule } from './type';
/**
* Parses block-level markdown text into HTML using defined block rules.
*
* @param text - The text to parse.
* @param rule - The markdown rule to run.
* @param parse - A function that run the parser on remaining parts..
* @param parseInline - Optional function to parse inline elements.
* @returns The text with the markdown rule applied or `undefined` if no match is found.
*/
export const runBlockRule = (
text: string,
rule: BlockMDRule,
parse: BlockMDParser,
parseInline?: (txt: string) => string
): string | undefined => {
const matchResult = rule.match(text);
if (matchResult) {
const content = rule.html(matchResult, parseInline);
return replaceMatch(text, matchResult, content, (txt) => [parse(txt, parseInline)]).join('');
}
return undefined;
};

View File

@@ -0,0 +1,30 @@
import { MatchResult, MatchRule } from '../internal';
/**
* Type for a function that parses block-level markdown into HTML.
*
* @param text - The markdown text to be parsed.
* @param parseInline - Optional function to parse inline elements.
* @returns The parsed HTML.
*/
export type BlockMDParser = (text: string, parseInline?: (txt: string) => string) => string;
/**
* Type for a function that converts a block match to output.
*
* @param match - The match result.
* @param parseInline - Optional function to parse inline elements.
* @returns The output string after processing the match.
*/
export type BlockMatchConverter = (
match: MatchResult,
parseInline?: (txt: string) => string
) => string;
/**
* Type representing a block-level markdown rule that includes a matching pattern and HTML conversion.
*/
export type BlockMDRule = {
match: MatchRule; // A function that matches a specific markdown pattern.
html: BlockMatchConverter; // A function that converts the match to HTML.
};

View File

@@ -0,0 +1,3 @@
export * from './utils';
export * from './block';
export * from './inline';

View File

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

View File

@@ -0,0 +1,40 @@
import {
BoldRule,
CodeRule,
EscapeRule,
ItalicRule1,
ItalicRule2,
LinkRule,
SpoilerRule,
StrikeRule,
UnderlineRule,
} from './rules';
import { runInlineRule, runInlineRules } from './runner';
import { InlineMDParser } from './type';
const LeveledRules = [
BoldRule,
ItalicRule1,
UnderlineRule,
ItalicRule2,
StrikeRule,
SpoilerRule,
LinkRule,
EscapeRule,
];
/**
* Parses inline markdown text into HTML using defined rules.
*
* @param text - The markdown text to be parsed.
* @returns The parsed HTML or the original text if no markdown was found.
*/
export const parseInlineMD: InlineMDParser = (text) => {
if (text === '') return text;
let result: string | undefined;
if (!result) result = runInlineRule(text, CodeRule, parseInlineMD);
if (!result) result = runInlineRules(text, LeveledRules, parseInlineMD);
return result ?? text;
};

View File

@@ -0,0 +1,123 @@
import { InlineMDRule } from './type';
const MIN_ANY = '(.+?)';
const URL_NEG_LB = '(?<!(https?|ftp|mailto|magnet):\\/\\/\\S*)';
const ESC_NEG_LB = '(?<!\\\\)';
const BOLD_MD_1 = '**';
const BOLD_PREFIX_1 = `${ESC_NEG_LB}\\*{2}`;
const BOLD_NEG_LA_1 = '(?!\\*)';
const BOLD_REG_1 = new RegExp(
`${URL_NEG_LB}${BOLD_PREFIX_1}${MIN_ANY}${BOLD_PREFIX_1}${BOLD_NEG_LA_1}`
);
export const BoldRule: InlineMDRule = {
match: (text) => text.match(BOLD_REG_1),
html: (parse, match) => {
const [, , g2] = match;
return `<strong data-md="${BOLD_MD_1}">${parse(g2)}</strong>`;
},
};
const ITALIC_MD_1 = '*';
const ITALIC_PREFIX_1 = `${ESC_NEG_LB}\\*`;
const ITALIC_NEG_LA_1 = '(?!\\*)';
const ITALIC_REG_1 = new RegExp(
`${URL_NEG_LB}${ITALIC_PREFIX_1}${MIN_ANY}${ITALIC_PREFIX_1}${ITALIC_NEG_LA_1}`
);
export const ItalicRule1: InlineMDRule = {
match: (text) => text.match(ITALIC_REG_1),
html: (parse, match) => {
const [, , g2] = match;
return `<i data-md="${ITALIC_MD_1}">${parse(g2)}</i>`;
},
};
const ITALIC_MD_2 = '_';
const ITALIC_PREFIX_2 = `${ESC_NEG_LB}_`;
const ITALIC_NEG_LA_2 = '(?!_)';
const ITALIC_REG_2 = new RegExp(
`${URL_NEG_LB}${ITALIC_PREFIX_2}${MIN_ANY}${ITALIC_PREFIX_2}${ITALIC_NEG_LA_2}`
);
export const ItalicRule2: InlineMDRule = {
match: (text) => text.match(ITALIC_REG_2),
html: (parse, match) => {
const [, , g2] = match;
return `<i data-md="${ITALIC_MD_2}">${parse(g2)}</i>`;
},
};
const UNDERLINE_MD_1 = '__';
const UNDERLINE_PREFIX_1 = `${ESC_NEG_LB}_{2}`;
const UNDERLINE_NEG_LA_1 = '(?!_)';
const UNDERLINE_REG_1 = new RegExp(
`${URL_NEG_LB}${UNDERLINE_PREFIX_1}${MIN_ANY}${UNDERLINE_PREFIX_1}${UNDERLINE_NEG_LA_1}`
);
export const UnderlineRule: InlineMDRule = {
match: (text) => text.match(UNDERLINE_REG_1),
html: (parse, match) => {
const [, , g2] = match;
return `<u data-md="${UNDERLINE_MD_1}">${parse(g2)}</u>`;
},
};
const STRIKE_MD_1 = '~~';
const STRIKE_PREFIX_1 = `${ESC_NEG_LB}~{2}`;
const STRIKE_NEG_LA_1 = '(?!~)';
const STRIKE_REG_1 = new RegExp(
`${URL_NEG_LB}${STRIKE_PREFIX_1}${MIN_ANY}${STRIKE_PREFIX_1}${STRIKE_NEG_LA_1}`
);
export const StrikeRule: InlineMDRule = {
match: (text) => text.match(STRIKE_REG_1),
html: (parse, match) => {
const [, , g2] = match;
return `<s data-md="${STRIKE_MD_1}">${parse(g2)}</s>`;
},
};
const CODE_MD_1 = '`';
const CODE_PREFIX_1 = `${ESC_NEG_LB}\``;
const CODE_NEG_LA_1 = '(?!`)';
const CODE_REG_1 = new RegExp(`${URL_NEG_LB}${CODE_PREFIX_1}(.+?)${CODE_PREFIX_1}${CODE_NEG_LA_1}`);
export const CodeRule: InlineMDRule = {
match: (text) => text.match(CODE_REG_1),
html: (parse, match) => {
const [, , g2] = match;
return `<code data-md="${CODE_MD_1}">${g2}</code>`;
},
};
const SPOILER_MD_1 = '||';
const SPOILER_PREFIX_1 = `${ESC_NEG_LB}\\|{2}`;
const SPOILER_NEG_LA_1 = '(?!\\|)';
const SPOILER_REG_1 = new RegExp(
`${URL_NEG_LB}${SPOILER_PREFIX_1}${MIN_ANY}${SPOILER_PREFIX_1}${SPOILER_NEG_LA_1}`
);
export const SpoilerRule: InlineMDRule = {
match: (text) => text.match(SPOILER_REG_1),
html: (parse, match) => {
const [, , g2] = match;
return `<span data-md="${SPOILER_MD_1}" data-mx-spoiler>${parse(g2)}</span>`;
},
};
const LINK_ALT = `\\[${MIN_ANY}\\]`;
const LINK_URL = `\\((https?:\\/\\/.+?)\\)`;
const LINK_REG_1 = new RegExp(`${LINK_ALT}${LINK_URL}`);
export const LinkRule: InlineMDRule = {
match: (text) => text.match(LINK_REG_1),
html: (parse, match) => {
const [, g1, g2] = match;
return `<a data-md href="${g2}">${parse(g1)}</a>`;
},
};
export const INLINE_SEQUENCE_SET = '[*_~`|]';
const ESC_SEQ_1 = `\\\\(${INLINE_SEQUENCE_SET})`;
const ESC_REG_1 = new RegExp(`${URL_NEG_LB}${ESC_SEQ_1}`);
export const EscapeRule: InlineMDRule = {
match: (text) => text.match(ESC_REG_1),
html: (parse, match) => {
const [, , g2] = match;
return g2;
},
};

View File

@@ -0,0 +1,62 @@
import { MatchResult, replaceMatch } from '../internal';
import { InlineMDParser, InlineMDRule } from './type';
/**
* Runs a single markdown rule on the provided text.
*
* @param text - The text to parse.
* @param rule - The markdown rule to run.
* @param parse - A function that run the parser on remaining parts.
* @returns The text with the markdown rule applied or `undefined` if no match is found.
*/
export const runInlineRule = (
text: string,
rule: InlineMDRule,
parse: InlineMDParser
): string | undefined => {
const matchResult = rule.match(text);
if (matchResult) {
const content = rule.html(parse, matchResult);
return replaceMatch(text, matchResult, content, (txt) => [parse(txt)]).join('');
}
return undefined;
};
/**
* Runs multiple rules at the same time to better handle nested rules.
* Rules will be run in the order they appear.
*
* @param text - The text to parse.
* @param rules - The markdown rules to run.
* @param parse - A function that run the parser on remaining parts.
* @returns The text with the markdown rules applied or `undefined` if no match is found.
*/
export const runInlineRules = (
text: string,
rules: InlineMDRule[],
parse: InlineMDParser
): string | undefined => {
const matchResults = rules.map((rule) => rule.match(text));
let targetRule: InlineMDRule | undefined;
let targetResult: MatchResult | undefined;
for (let i = 0; i < matchResults.length; i += 1) {
const currentResult = matchResults[i];
if (currentResult && typeof currentResult.index === 'number') {
if (
!targetResult ||
(typeof targetResult?.index === 'number' && currentResult.index < targetResult.index)
) {
targetResult = currentResult;
targetRule = rules[i];
}
}
}
if (targetRule && targetResult) {
const content = targetRule.html(parse, targetResult);
return replaceMatch(text, targetResult, content, (txt) => [parse(txt)]).join('');
}
return undefined;
};

View File

@@ -0,0 +1,26 @@
import { MatchResult, MatchRule } from '../internal';
/**
* Type for a function that parses inline markdown into HTML.
*
* @param text - The markdown text to be parsed.
* @returns The parsed HTML.
*/
export type InlineMDParser = (text: string) => string;
/**
* Type for a function that converts a match to output.
*
* @param parse - The inline markdown parser function.
* @param match - The match result.
* @returns The output string after processing the match.
*/
export type InlineMatchConverter = (parse: InlineMDParser, match: MatchResult) => string;
/**
* Type representing a markdown rule that includes a matching pattern and HTML conversion.
*/
export type InlineMDRule = {
match: MatchRule; // A function that matches a specific markdown pattern.
html: InlineMatchConverter; // A function that converts the match to HTML.
};

View File

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

View File

@@ -0,0 +1,61 @@
/**
* @typedef {RegExpMatchArray | RegExpExecArray} MatchResult
*
* Represents the result of a regular expression match.
* This type can be either a `RegExpMatchArray` or a `RegExpExecArray`,
* which are returned when performing a match with a regular expression.
*
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec}
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match}
*/
export type MatchResult = RegExpMatchArray | RegExpExecArray;
/**
* @typedef {function(string): MatchResult | null} MatchRule
*
* A function type that takes a string and returns a `MatchResult` or `null` if no match is found.
*
* @param {string} text The string to match against.
* @returns {MatchResult | null} The result of the regular expression match, or `null` if no match is found.
*/
export type MatchRule = (text: string) => MatchResult | null;
/**
* Returns the part of the text before a match.
*
* @param text - The input text string.
* @param match - The match result (e.g., `RegExpMatchArray` or `RegExpExecArray`).
* @returns A string containing the part of the text before the match.
*/
export const beforeMatch = (text: string, match: RegExpMatchArray | RegExpExecArray): string =>
text.slice(0, match.index);
/**
* Returns the part of the text after a match.
*
* @param text - The input text string.
* @param match - The match result (e.g., `RegExpMatchArray` or `RegExpExecArray`).
* @returns A string containing the part of the text after the match.
*/
export const afterMatch = (text: string, match: RegExpMatchArray | RegExpExecArray): string =>
text.slice((match.index ?? 0) + match[0].length);
/**
* Replaces a match in the text with a content.
*
* @param text - The input text string.
* @param match - The match result (e.g., `RegExpMatchArray` or `RegExpExecArray`).
* @param content - The content to replace the match with.
* @param processPart - A function to further process remaining parts of the text.
* @returns An array containing the processed parts of the text, including the content.
*/
export const replaceMatch = <C>(
text: string,
match: MatchResult,
content: C,
processPart: (txt: string) => Array<string | C>
): Array<string | C> => [
...processPart(beforeMatch(text, match)),
content,
...processPart(afterMatch(text, match)),
];

View File

@@ -0,0 +1,83 @@
import { findAndReplace } from '../../utils/findAndReplace';
import { ESC_BLOCK_SEQ, UN_ESC_BLOCK_SEQ } from './block/rules';
import { EscapeRule, INLINE_SEQUENCE_SET } from './inline/rules';
import { runInlineRule } from './inline/runner';
import { replaceMatch } from './internal';
/**
* Removes escape sequences from markdown inline elements in the given plain-text.
* This function unescapes characters that are escaped with backslashes (e.g., `\*`, `\_`)
* in markdown syntax, returning the original plain-text with markdown characters in effect.
*
* @param text - The input markdown plain-text containing escape characters (e.g., `"some \*italic\*"`)
* @returns The plain-text with markdown escape sequences removed (e.g., `"some *italic*"`)
*/
export const unescapeMarkdownInlineSequences = (text: string): string =>
runInlineRule(text, EscapeRule, (t) => {
if (t === '') return t;
return unescapeMarkdownInlineSequences(t);
}) ?? text;
/**
* Recovers the markdown escape sequences in the given plain-text.
* This function adds backslashes (`\`) before markdown characters that may need escaping
* (e.g., `*`, `_`) to ensure they are treated as literal characters and not part of markdown formatting.
*
* @param text - The input plain-text that may contain markdown sequences (e.g., `"some *italic*"`)
* @returns The plain-text with markdown escape sequences added (e.g., `"some \*italic\*"`)
*/
export const escapeMarkdownInlineSequences = (text: string): string => {
const regex = new RegExp(`(${INLINE_SEQUENCE_SET})`, 'g');
const parts = findAndReplace(
text,
regex,
(match) => {
const [, g1] = match;
return `\\${g1}`;
},
(t) => t
);
return parts.join('');
};
/**
* Removes escape sequences from markdown block elements in the given plain-text.
* This function unescapes characters that are escaped with backslashes (e.g., `\>`, `\#`)
* in markdown syntax, returning the original plain-text with markdown characters in effect.
*
* @param {string} text - The input markdown plain-text containing escape characters (e.g., `\> block quote`).
* @param {function} processPart - It takes the plain-text as input and returns a modified version of it.
* @returns {string} The plain-text with markdown escape sequences removed and markdown formatting applied.
*/
export const unescapeMarkdownBlockSequences = (
text: string,
processPart: (text: string) => string
): string => {
const match = text.match(ESC_BLOCK_SEQ);
if (!match) return processPart(text);
const [, g1] = match;
return replaceMatch(text, match, g1, (t) => [processPart(t)]).join('');
};
/**
* Escapes markdown block elements by adding backslashes before markdown characters
* (e.g., `\>`, `\#`) that are normally interpreted as markdown syntax.
*
* @param {string} text - The input markdown plain-text that may contain markdown elements (e.g., `> block quote`).
* @param {function} processPart - It takes the plain-text as input and returns a modified version of it.
* @returns {string} The plain-text with markdown escape sequences added, preventing markdown formatting.
*/
export const escapeMarkdownBlockSequences = (
text: string,
processPart: (text: string) => string
): string => {
const match = text.match(UN_ESC_BLOCK_SEQ);
if (!match) return processPart(text);
const [, g1] = match;
return replaceMatch(text, match, `\\${g1}`, (t) => [processPart(t)]).join('');
};

View File

@@ -21,7 +21,7 @@ import {
mxcUrlToHttp, mxcUrlToHttp,
} from '../utils/matrix'; } from '../utils/matrix';
import { getMemberDisplayName } from '../utils/room'; import { getMemberDisplayName } from '../utils/room';
import { EMOJI_PATTERN, URL_NEG_LB } from '../utils/regex'; import { EMOJI_PATTERN, sanitizeForRegex, URL_NEG_LB } from '../utils/regex';
import { getHexcodeForEmoji, getShortcodeFor } from './emoji'; import { getHexcodeForEmoji, getShortcodeFor } from './emoji';
import { findAndReplace } from '../utils/findAndReplace'; import { findAndReplace } from '../utils/findAndReplace';
import { import {
@@ -171,7 +171,7 @@ export const scaleSystemEmoji = (text: string): (string | JSX.Element)[] =>
); );
export const makeHighlightRegex = (highlights: string[]): RegExp | undefined => { export const makeHighlightRegex = (highlights: string[]): RegExp | undefined => {
const pattern = highlights.join('|'); const pattern = highlights.map(sanitizeForRegex).join('|');
if (!pattern) return undefined; if (!pattern) return undefined;
return new RegExp(pattern, 'gi'); return new RegExp(pattern, 'gi');
}; };

19
src/app/plugins/utils.ts Normal file
View File

@@ -0,0 +1,19 @@
import { SearchItemStrGetter } from '../hooks/useAsyncSearch';
import { PackImageReader } from './custom-emoji';
import { IEmoji } from './emoji';
export const getEmoticonSearchStr: SearchItemStrGetter<PackImageReader | IEmoji> = (item) => {
const shortcode = `:${item.shortcode}:`;
if (item instanceof PackImageReader) {
if (item.body) {
return [shortcode, item.body];
}
return shortcode;
}
const names = [shortcode, item.label];
if (Array.isArray(item.shortcodes)) {
return names.concat(item.shortcodes);
}
return names;
};

View File

@@ -5,6 +5,11 @@ export type ListAction<T> =
type: 'PUT'; type: 'PUT';
item: T | T[]; item: T | T[];
} }
| {
type: 'REPLACE';
item: T;
replacement: T;
}
| { | {
type: 'DELETE'; type: 'DELETE';
item: T | T[]; item: T | T[];
@@ -26,8 +31,12 @@ export const createListAtom = <T>() => {
} }
if (action.type === 'PUT') { if (action.type === 'PUT') {
set(baseListAtom, [...items, ...newItems]); set(baseListAtom, [...items, ...newItems]);
return;
}
if (action.type === 'REPLACE') {
set(baseListAtom, items.map((item) => item === action.item ? action.replacement : item));
} }
} }
); );
}; };
export type TListAtom<T> = ReturnType<typeof createListAtom<T>>; export type TListAtom<T> = ReturnType<typeof createListAtom<T>>;

View File

@@ -3,22 +3,29 @@ import { atomFamily } from 'jotai/utils';
import { Descendant } from 'slate'; import { Descendant } from 'slate';
import { EncryptedAttachmentInfo } from 'browser-encrypt-attachment'; import { EncryptedAttachmentInfo } from 'browser-encrypt-attachment';
import { IEventRelation } from 'matrix-js-sdk'; import { IEventRelation } from 'matrix-js-sdk';
import { TListAtom, createListAtom } from '../list';
import { createUploadAtomFamily } from '../upload'; import { createUploadAtomFamily } from '../upload';
import { TUploadContent } from '../../utils/matrix'; import { TUploadContent } from '../../utils/matrix';
import { createListAtom } from '../list';
export const roomUploadAtomFamily = createUploadAtomFamily(); export type TUploadMetadata = {
markedAsSpoiler: boolean;
};
export type TUploadItem = { export type TUploadItem = {
file: TUploadContent; file: TUploadContent;
originalFile: TUploadContent; originalFile: TUploadContent;
metadata: TUploadMetadata;
encInfo: EncryptedAttachmentInfo | undefined; encInfo: EncryptedAttachmentInfo | undefined;
}; };
export const roomIdToUploadItemsAtomFamily = atomFamily<string, TListAtom<TUploadItem>>( export type TUploadListAtom = ReturnType<typeof createListAtom<TUploadItem>>;
export const roomIdToUploadItemsAtomFamily = atomFamily<string, TUploadListAtom>(
createListAtom createListAtom
); );
export const roomUploadAtomFamily = createUploadAtomFamily();
export type RoomIdToMsgAction = export type RoomIdToMsgAction =
| { | {
type: 'PUT'; type: 'PUT';

View File

@@ -23,32 +23,37 @@ const baseSpaceRoomsAtom = atomWithLocalStorage<Set<string>>(
type SpaceRoomsAction = type SpaceRoomsAction =
| { | {
type: 'PUT'; type: 'PUT';
roomId: string; roomIds: string[];
} }
| { | {
type: 'DELETE'; type: 'DELETE';
roomId: string; roomIds: string[];
}; };
export const spaceRoomsAtom = atom<Set<string>, [SpaceRoomsAction], undefined>( export const spaceRoomsAtom = atom<Set<string>, [SpaceRoomsAction], undefined>(
(get) => get(baseSpaceRoomsAtom), (get) => get(baseSpaceRoomsAtom),
(get, set, action) => { (get, set, action) => {
if (action.type === 'DELETE') { const current = get(baseSpaceRoomsAtom);
const { type, roomIds } = action;
if (type === 'DELETE' && roomIds.find((roomId) => current.has(roomId))) {
set( set(
baseSpaceRoomsAtom, baseSpaceRoomsAtom,
produce(get(baseSpaceRoomsAtom), (draft) => { produce(current, (draft) => {
draft.delete(action.roomId); roomIds.forEach((roomId) => draft.delete(roomId));
}) })
); );
return; return;
} }
if (action.type === 'PUT') { if (type === 'PUT') {
set( const newEntries = roomIds.filter((roomId) => !current.has(roomId));
baseSpaceRoomsAtom, if (newEntries.length > 0)
produce(get(baseSpaceRoomsAtom), (draft) => { set(
draft.add(action.roomId); baseSpaceRoomsAtom,
}) produce(current, (draft) => {
); newEntries.forEach((roomId) => draft.add(roomId));
})
);
} }
} }
); );

View File

@@ -1,3 +1,9 @@
/**
* https://www.npmjs.com/package/escape-string-regexp
*/
export const sanitizeForRegex = (unsafeText: string): string =>
unsafeText.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d');
export const HTTP_URL_PATTERN = `https?:\\/\\/(?:www\\.)?(?:[^\\s)]*)(?<![.,:;!/?()[\\]\\s]+)`; export const HTTP_URL_PATTERN = `https?:\\/\\/(?:www\\.)?(?:[^\\s)]*)(?<![.,:;!/?()[\\]\\s]+)`;
export const URL_REG = new RegExp(HTTP_URL_PATTERN, 'g'); export const URL_REG = new RegExp(HTTP_URL_PATTERN, 'g');

View File

@@ -4,6 +4,7 @@ import {
EventTimeline, EventTimeline,
EventTimelineSet, EventTimelineSet,
EventType, EventType,
IMentions,
IPushRule, IPushRule,
IPushRules, IPushRules,
JoinRule, JoinRule,
@@ -430,3 +431,15 @@ export const getLatestEditableEvt = (
export const reactionOrEditEvent = (mEvent: MatrixEvent) => export const reactionOrEditEvent = (mEvent: MatrixEvent) =>
mEvent.getRelation()?.rel_type === RelationType.Annotation || mEvent.getRelation()?.rel_type === RelationType.Annotation ||
mEvent.getRelation()?.rel_type === RelationType.Replace; mEvent.getRelation()?.rel_type === RelationType.Replace;
export const getMentionContent = (userIds: string[], room: boolean): IMentions => {
const mMentions: IMentions = {};
if (userIds.length > 0) {
mMentions.user_ids = userIds;
}
if (room) {
mMentions.room = true;
}
return mMentions;
};

View File

@@ -1,5 +1,5 @@
const cons = { const cons = {
version: '4.3.2', version: '4.4.0',
secretKey: { secretKey: {
ACCESS_TOKEN: 'cinny_access_token', ACCESS_TOKEN: 'cinny_access_token',
DEVICE_ID: 'cinny_device_id', DEVICE_ID: 'cinny_device_id',

View File

@@ -427,6 +427,12 @@ a {
text-decoration: underline; text-decoration: underline;
} }
} }
[data-mx-spoiler][aria-pressed='true'] a {
color: transparent;
pointer-events: none;
}
b { b {
font-weight: var(--fw-medium); font-weight: var(--fw-medium);
} }

View File

@@ -2,6 +2,8 @@ import { EncryptedAttachmentInfo } from 'browser-encrypt-attachment';
import { MsgType } from 'matrix-js-sdk'; import { MsgType } from 'matrix-js-sdk';
export const MATRIX_BLUR_HASH_PROPERTY_NAME = 'xyz.amorgan.blurhash'; export const MATRIX_BLUR_HASH_PROPERTY_NAME = 'xyz.amorgan.blurhash';
export const MATRIX_SPOILER_PROPERTY_NAME = 'page.codeberg.everypizza.msc4193.spoiler';
export const MATRIX_SPOILER_REASON_PROPERTY_NAME = 'page.codeberg.everypizza.msc4193.spoiler.reason';
export type IImageInfo = { export type IImageInfo = {
w?: number; w?: number;
@@ -47,6 +49,8 @@ export type IImageContent = {
url?: string; url?: string;
info?: IImageInfo & IThumbnailContent; info?: IImageInfo & IThumbnailContent;
file?: IEncryptedFile; file?: IEncryptedFile;
[MATRIX_SPOILER_PROPERTY_NAME]?: boolean;
[MATRIX_SPOILER_REASON_PROPERTY_NAME]?: string;
}; };
export type IVideoContent = { export type IVideoContent = {
@@ -56,6 +60,8 @@ export type IVideoContent = {
url?: string; url?: string;
info?: IVideoInfo & IThumbnailContent; info?: IVideoInfo & IThumbnailContent;
file?: IEncryptedFile; file?: IEncryptedFile;
[MATRIX_SPOILER_PROPERTY_NAME]?: boolean;
[MATRIX_SPOILER_REASON_PROPERTY_NAME]?: string;
}; };
export type IAudioContent = { export type IAudioContent = {