Refactor state & Custom editor (#1190)
* Fix eslint * Enable ts strict mode * install folds, jotai & immer * Enable immer map/set * change cross-signing alert anim to 30 iteration * Add function to access matrix client * Add new types * Add disposable util * Add room utils * Add mDirect list atom * Add invite list atom * add room list atom * add utils for jotai atoms * Add room id to parents atom * Add mute list atom * Add room to unread atom * Use hook to bind atoms with sdk * Add settings atom * Add settings hook * Extract set settings hook * Add Sidebar components * WIP * Add bind atoms hook * Fix init muted room list atom * add navigation atoms * Add custom editor * Fix hotkeys * Update folds * Add editor output function * Add matrix client context * Add tooltip to editor toolbar items * WIP - Add editor to room input * Refocus editor on toolbar item click * Add Mentions - WIP * update folds * update mention focus outline * rename emoji element type * Add auto complete menu * add autocomplete query functions * add index file for editor * fix bug in getPrevWord function * Show room mention autocomplete * Add async search function * add use async search hook * use async search in room mention autocomplete * remove folds prefer font for now * allow number array in async search * reset search with empty query * Autocomplete unknown room mention * Autocomplete first room mention on tab * fix roomAliasFromQueryText * change mention color to primary * add isAlive hook * add getMxIdLocalPart to mx utils * fix getRoomAvatarUrl size * fix types * add room members hook * fix bug in room mention * add user mention autocomplete * Fix async search giving prev result after no match * update folds * add twemoji font * add use state provider hook * add prevent scroll with arrow key util * add ts to custom-emoji and emoji files * add types * add hook for emoji group labels * add hook for emoji group icons * add emoji board with basic emoji * add emojiboard in room input * select multiple emoji with shift press * display custom emoji in emojiboard * Add emoji preview * focus element on hover * update folds * position emojiboard properly * convert recent-emoji.js to ts * add use recent emoji hook * add io.element.recent_emoji to account data evt * Render recent emoji in emoji board * show custom emoji from parent spaces * show room emoji * improve emoji sidebar * update folds * fix pack avatar and name fallback in emoji board * add stickers to emoji board * fix bug in emoji preview * Add sticker icon in room input * add debounce hook * add search in emoji board * Optimize emoji board * fix emoji board sidebar divider * sync emojiboard sidebar with scroll & update ui * Add use throttle hook * support custom emoji in editor * remove duplicate emoji selection function * fix emoji and mention spacing * add emoticon autocomplete in editor * fix string * makes emoji size relative to font size in editor * add option to render link element * add spoiler in editor * fix sticker in emoji board search using wrong type * render custom placeholder * update hotkey for block quote and block code * add terminate search function in async search * add getImageInfo to matrix utils * send stickers * add resize observer hook * move emoji board component hooks in hooks dir * prevent editor expand hides room timeline * send typing notifications * improve emoji style and performance * fix imports * add on paste param to editor * add selectFile utils * add file picker hook * add file paste handler hook * add file drop handler * update folds * Add file upload card * add bytes to size util * add blurHash util * add await to js lib * add browser-encrypt-attachment types * add list atom * convert mimetype file to ts * add matrix types * add matrix file util * add file related dom utils * add common utils * add upload atom * add room input draft atom * add upload card renderer component * add upload board component * add support for file upload in editor * send files with message / enter * fix circular deps * store editor toolbar state in local store * move msg content util to separate file * store msg draft on room switch * fix following member not updating on msg sent * add theme for folds component * fix system default theme * Add reply support in editor * prevent initMatrix to init multiple time * add state event hooks * add async callback hook * Show tombstone info for tombstone room * fix room tombstone component border * add power level hook * Add room input placeholder component * Show input placeholder for muted member
This commit is contained in:
parent
2055d7a07f
commit
0b06bed1db
128 changed files with 8799 additions and 409 deletions
|
|
@ -27,6 +27,7 @@ module.exports = {
|
||||||
rules: {
|
rules: {
|
||||||
'linebreak-style': 0,
|
'linebreak-style': 0,
|
||||||
'no-underscore-dangle': 0,
|
'no-underscore-dangle': 0,
|
||||||
|
"no-shadow": "off",
|
||||||
|
|
||||||
"import/prefer-default-export": "off",
|
"import/prefer-default-export": "off",
|
||||||
"import/extensions": "off",
|
"import/extensions": "off",
|
||||||
|
|
@ -55,5 +56,6 @@ module.exports = {
|
||||||
"react-hooks/exhaustive-deps": "error",
|
"react-hooks/exhaustive-deps": "error",
|
||||||
|
|
||||||
"@typescript-eslint/no-unused-vars": "error",
|
"@typescript-eslint/no-unused-vars": "error",
|
||||||
|
"@typescript-eslint/no-shadow": "error"
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -27,7 +27,7 @@
|
||||||
|
|
||||||
<link id="favicon" rel="shortcut icon" href="./public/favicon.ico" />
|
<link id="favicon" rel="shortcut icon" href="./public/favicon.ico" />
|
||||||
|
|
||||||
<link rel="manifest" href="./manifest.json" />
|
<link rel="manifest" href="./public/manifest.json" />
|
||||||
<meta name="mobile-web-app-capable" content="yes" />
|
<meta name="mobile-web-app-capable" content="yes" />
|
||||||
<meta name="application-name" content="Cinny" />
|
<meta name="application-name" content="Cinny" />
|
||||||
<meta name="apple-mobile-web-app-title" content="Cinny" />
|
<meta name="apple-mobile-web-app-title" content="Cinny" />
|
||||||
|
|
|
||||||
764
package-lock.json
generated
764
package-lock.json
generated
File diff suppressed because it is too large
Load diff
19
package.json
19
package.json
|
|
@ -24,14 +24,25 @@
|
||||||
"@khanacademy/simple-markdown": "0.8.6",
|
"@khanacademy/simple-markdown": "0.8.6",
|
||||||
"@matrix-org/olm": "3.2.14",
|
"@matrix-org/olm": "3.2.14",
|
||||||
"@tippyjs/react": "4.2.6",
|
"@tippyjs/react": "4.2.6",
|
||||||
|
"@vanilla-extract/css": "1.9.3",
|
||||||
|
"@vanilla-extract/recipes": "0.3.0",
|
||||||
|
"@vanilla-extract/vite-plugin": "3.7.1",
|
||||||
|
"await-to-js": "3.0.0",
|
||||||
"blurhash": "2.0.4",
|
"blurhash": "2.0.4",
|
||||||
"browser-encrypt-attachment": "0.3.0",
|
"browser-encrypt-attachment": "0.3.0",
|
||||||
|
"classnames": "2.3.2",
|
||||||
"dateformat": "5.0.3",
|
"dateformat": "5.0.3",
|
||||||
|
"emojibase": "6.1.0",
|
||||||
"emojibase-data": "7.0.1",
|
"emojibase-data": "7.0.1",
|
||||||
"file-saver": "2.0.5",
|
"file-saver": "2.0.5",
|
||||||
"flux": "4.0.3",
|
"flux": "4.0.3",
|
||||||
|
"focus-trap-react": "10.0.2",
|
||||||
|
"folds": "1.2.1",
|
||||||
"formik": "2.2.9",
|
"formik": "2.2.9",
|
||||||
"html-react-parser": "3.0.4",
|
"html-react-parser": "3.0.4",
|
||||||
|
"immer": "9.0.16",
|
||||||
|
"is-hotkey": "0.2.0",
|
||||||
|
"jotai": "1.12.0",
|
||||||
"katex": "0.16.4",
|
"katex": "0.16.4",
|
||||||
"linkify-html": "4.0.2",
|
"linkify-html": "4.0.2",
|
||||||
"linkifyjs": "4.0.2",
|
"linkifyjs": "4.0.2",
|
||||||
|
|
@ -46,8 +57,11 @@
|
||||||
"react-google-recaptcha": "2.1.0",
|
"react-google-recaptcha": "2.1.0",
|
||||||
"react-modal": "3.16.1",
|
"react-modal": "3.16.1",
|
||||||
"sanitize-html": "2.8.0",
|
"sanitize-html": "2.8.0",
|
||||||
|
"slate": "0.90.0",
|
||||||
|
"slate-react": "0.90.0",
|
||||||
"tippy.js": "6.3.7",
|
"tippy.js": "6.3.7",
|
||||||
"twemoji": "14.0.2"
|
"twemoji": "14.0.2",
|
||||||
|
"ua-parser-js": "1.0.35"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@esbuild-plugins/node-globals-polyfill": "0.2.3",
|
"@esbuild-plugins/node-globals-polyfill": "0.2.3",
|
||||||
|
|
@ -56,6 +70,7 @@
|
||||||
"@types/node": "18.11.18",
|
"@types/node": "18.11.18",
|
||||||
"@types/react": "18.0.26",
|
"@types/react": "18.0.26",
|
||||||
"@types/react-dom": "18.0.9",
|
"@types/react-dom": "18.0.9",
|
||||||
|
"@types/ua-parser-js": "0.7.36",
|
||||||
"@typescript-eslint/eslint-plugin": "5.46.1",
|
"@typescript-eslint/eslint-plugin": "5.46.1",
|
||||||
"@typescript-eslint/parser": "5.46.1",
|
"@typescript-eslint/parser": "5.46.1",
|
||||||
"@vitejs/plugin-react": "3.0.0",
|
"@vitejs/plugin-react": "3.0.0",
|
||||||
|
|
@ -71,7 +86,7 @@
|
||||||
"prettier": "2.8.1",
|
"prettier": "2.8.1",
|
||||||
"sass": "1.56.2",
|
"sass": "1.56.2",
|
||||||
"typescript": "4.9.4",
|
"typescript": "4.9.4",
|
||||||
"vite": "4.0.1",
|
"vite": "4.0.4",
|
||||||
"vite-plugin-static-copy": "0.13.0"
|
"vite-plugin-static-copy": "0.13.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
BIN
public/font/Twemoji.Mozilla.v.7.0.woff2
Normal file
BIN
public/font/Twemoji.Mozilla.v.7.0.woff2
Normal file
Binary file not shown.
BIN
public/font/Twemoji.Mozilla.v0.7.0.ttf
Normal file
BIN
public/font/Twemoji.Mozilla.v0.7.0.ttf
Normal file
Binary file not shown.
9
src/app/components/UseStateProvider.tsx
Normal file
9
src/app/components/UseStateProvider.tsx
Normal file
|
|
@ -0,0 +1,9 @@
|
||||||
|
import { Dispatch, ReactElement, SetStateAction, useState } from 'react';
|
||||||
|
|
||||||
|
type UseStateProviderProps<T> = {
|
||||||
|
initial: T | (() => T);
|
||||||
|
children: (value: T, setter: Dispatch<SetStateAction<T>>) => ReactElement;
|
||||||
|
};
|
||||||
|
export function UseStateProvider<T>({ initial, children }: UseStateProviderProps<T>) {
|
||||||
|
return children(...useState(initial));
|
||||||
|
}
|
||||||
63
src/app/components/editor/Editor.css.ts
Normal file
63
src/app/components/editor/Editor.css.ts
Normal file
|
|
@ -0,0 +1,63 @@
|
||||||
|
import { style } from '@vanilla-extract/css';
|
||||||
|
import { color, config, DefaultReset, toRem } from 'folds';
|
||||||
|
|
||||||
|
export const Editor = style([
|
||||||
|
DefaultReset,
|
||||||
|
{
|
||||||
|
backgroundColor: color.SurfaceVariant.Container,
|
||||||
|
color: color.SurfaceVariant.OnContainer,
|
||||||
|
boxShadow: `inset 0 0 0 ${config.borderWidth.B300} ${color.SurfaceVariant.ContainerLine}`,
|
||||||
|
borderRadius: config.radii.R400,
|
||||||
|
overflow: 'hidden',
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const EditorOptions = style([
|
||||||
|
DefaultReset,
|
||||||
|
{
|
||||||
|
padding: config.space.S200,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const EditorTextareaScroll = style({});
|
||||||
|
|
||||||
|
export const EditorTextarea = style([
|
||||||
|
DefaultReset,
|
||||||
|
{
|
||||||
|
flexGrow: 1,
|
||||||
|
height: '100%',
|
||||||
|
padding: `${toRem(13)} 0`,
|
||||||
|
selectors: {
|
||||||
|
[`${EditorTextareaScroll}:first-child &`]: {
|
||||||
|
paddingLeft: toRem(13),
|
||||||
|
},
|
||||||
|
[`${EditorTextareaScroll}:last-child &`]: {
|
||||||
|
paddingRight: toRem(13),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const EditorPlaceholder = style([
|
||||||
|
DefaultReset,
|
||||||
|
{
|
||||||
|
position: 'absolute',
|
||||||
|
zIndex: 1,
|
||||||
|
opacity: config.opacity.Placeholder,
|
||||||
|
pointerEvents: 'none',
|
||||||
|
userSelect: 'none',
|
||||||
|
|
||||||
|
selectors: {
|
||||||
|
'&:not(:first-child)': {
|
||||||
|
display: 'none',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const EditorToolbar = style([
|
||||||
|
DefaultReset,
|
||||||
|
{
|
||||||
|
padding: config.space.S100,
|
||||||
|
},
|
||||||
|
]);
|
||||||
82
src/app/components/editor/Editor.preview.tsx
Normal file
82
src/app/components/editor/Editor.preview.tsx
Normal file
|
|
@ -0,0 +1,82 @@
|
||||||
|
import React, { useState } from 'react';
|
||||||
|
import FocusTrap from 'focus-trap-react';
|
||||||
|
import {
|
||||||
|
config,
|
||||||
|
Icon,
|
||||||
|
IconButton,
|
||||||
|
Icons,
|
||||||
|
Line,
|
||||||
|
Modal,
|
||||||
|
Overlay,
|
||||||
|
OverlayBackdrop,
|
||||||
|
OverlayCenter,
|
||||||
|
} from 'folds';
|
||||||
|
|
||||||
|
import { CustomEditor, useEditor } from './Editor';
|
||||||
|
import { Toolbar } from './Toolbar';
|
||||||
|
|
||||||
|
export function EditorPreview() {
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
const editor = useEditor();
|
||||||
|
const [toolbar, setToolbar] = useState(false);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<IconButton variant="SurfaceVariant" onClick={() => setOpen(!open)}>
|
||||||
|
<Icon src={Icons.BlockQuote} />
|
||||||
|
</IconButton>
|
||||||
|
<Overlay open={open} backdrop={<OverlayBackdrop />}>
|
||||||
|
<OverlayCenter>
|
||||||
|
<FocusTrap
|
||||||
|
focusTrapOptions={{
|
||||||
|
initialFocus: false,
|
||||||
|
onDeactivate: () => setOpen(false),
|
||||||
|
clickOutsideDeactivates: true,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Modal size="500">
|
||||||
|
<div style={{ padding: config.space.S400 }}>
|
||||||
|
<CustomEditor
|
||||||
|
editor={editor}
|
||||||
|
placeholder="Send a message..."
|
||||||
|
before={
|
||||||
|
<IconButton variant="SurfaceVariant" size="300" radii="300">
|
||||||
|
<Icon src={Icons.PlusCircle} />
|
||||||
|
</IconButton>
|
||||||
|
}
|
||||||
|
after={
|
||||||
|
<>
|
||||||
|
<IconButton
|
||||||
|
variant="SurfaceVariant"
|
||||||
|
size="300"
|
||||||
|
radii="300"
|
||||||
|
onClick={() => setToolbar(!toolbar)}
|
||||||
|
aria-pressed={toolbar}
|
||||||
|
>
|
||||||
|
<Icon src={toolbar ? Icons.AlphabetUnderline : Icons.Alphabet} />
|
||||||
|
</IconButton>
|
||||||
|
<IconButton variant="SurfaceVariant" size="300" radii="300">
|
||||||
|
<Icon src={Icons.Smile} />
|
||||||
|
</IconButton>
|
||||||
|
<IconButton variant="SurfaceVariant" size="300" radii="300">
|
||||||
|
<Icon src={Icons.Send} />
|
||||||
|
</IconButton>
|
||||||
|
</>
|
||||||
|
}
|
||||||
|
bottom={
|
||||||
|
toolbar && (
|
||||||
|
<div>
|
||||||
|
<Line variant="SurfaceVariant" size="300" />
|
||||||
|
<Toolbar />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
</FocusTrap>
|
||||||
|
</OverlayCenter>
|
||||||
|
</Overlay>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
151
src/app/components/editor/Editor.tsx
Normal file
151
src/app/components/editor/Editor.tsx
Normal file
|
|
@ -0,0 +1,151 @@
|
||||||
|
/* eslint-disable no-param-reassign */
|
||||||
|
import React, {
|
||||||
|
ClipboardEventHandler,
|
||||||
|
KeyboardEventHandler,
|
||||||
|
ReactNode,
|
||||||
|
forwardRef,
|
||||||
|
useCallback,
|
||||||
|
useState,
|
||||||
|
} from 'react';
|
||||||
|
|
||||||
|
import { Box, Scroll, Text } from 'folds';
|
||||||
|
import { Descendant, Editor, createEditor } from 'slate';
|
||||||
|
import {
|
||||||
|
Slate,
|
||||||
|
Editable,
|
||||||
|
withReact,
|
||||||
|
RenderLeafProps,
|
||||||
|
RenderElementProps,
|
||||||
|
RenderPlaceholderProps,
|
||||||
|
} from 'slate-react';
|
||||||
|
import { BlockType, RenderElement, RenderLeaf } from './Elements';
|
||||||
|
import { CustomElement } from './slate';
|
||||||
|
import * as css from './Editor.css';
|
||||||
|
import { toggleKeyboardShortcut } from './keyboard';
|
||||||
|
|
||||||
|
const initialValue: CustomElement[] = [
|
||||||
|
{
|
||||||
|
type: BlockType.Paragraph,
|
||||||
|
children: [{ text: '' }],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const withInline = (editor: Editor): Editor => {
|
||||||
|
const { isInline } = editor;
|
||||||
|
|
||||||
|
editor.isInline = (element) =>
|
||||||
|
[BlockType.Mention, BlockType.Emoticon, BlockType.Link].includes(element.type) ||
|
||||||
|
isInline(element);
|
||||||
|
|
||||||
|
return editor;
|
||||||
|
};
|
||||||
|
|
||||||
|
const withVoid = (editor: Editor): Editor => {
|
||||||
|
const { isVoid } = editor;
|
||||||
|
|
||||||
|
editor.isVoid = (element) =>
|
||||||
|
[BlockType.Mention, BlockType.Emoticon].includes(element.type) || isVoid(element);
|
||||||
|
|
||||||
|
return editor;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const useEditor = (): Editor => {
|
||||||
|
const [editor] = useState(withInline(withVoid(withReact(createEditor()))));
|
||||||
|
return editor;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type EditorChangeHandler = ((value: Descendant[]) => void) | undefined;
|
||||||
|
type CustomEditorProps = {
|
||||||
|
top?: ReactNode;
|
||||||
|
bottom?: ReactNode;
|
||||||
|
before?: ReactNode;
|
||||||
|
after?: ReactNode;
|
||||||
|
maxHeight?: string;
|
||||||
|
editor: Editor;
|
||||||
|
placeholder?: string;
|
||||||
|
onKeyDown?: KeyboardEventHandler;
|
||||||
|
onChange?: EditorChangeHandler;
|
||||||
|
onPaste?: ClipboardEventHandler;
|
||||||
|
};
|
||||||
|
export const CustomEditor = forwardRef<HTMLDivElement, CustomEditorProps>(
|
||||||
|
(
|
||||||
|
{
|
||||||
|
top,
|
||||||
|
bottom,
|
||||||
|
before,
|
||||||
|
after,
|
||||||
|
maxHeight = '50vh',
|
||||||
|
editor,
|
||||||
|
placeholder,
|
||||||
|
onKeyDown,
|
||||||
|
onChange,
|
||||||
|
onPaste,
|
||||||
|
},
|
||||||
|
ref
|
||||||
|
) => {
|
||||||
|
const renderElement = useCallback(
|
||||||
|
(props: RenderElementProps) => <RenderElement {...props} />,
|
||||||
|
[]
|
||||||
|
);
|
||||||
|
|
||||||
|
const renderLeaf = useCallback((props: RenderLeafProps) => <RenderLeaf {...props} />, []);
|
||||||
|
|
||||||
|
const handleKeydown: KeyboardEventHandler = useCallback(
|
||||||
|
(evt) => {
|
||||||
|
onKeyDown?.(evt);
|
||||||
|
toggleKeyboardShortcut(editor, evt);
|
||||||
|
},
|
||||||
|
[editor, onKeyDown]
|
||||||
|
);
|
||||||
|
|
||||||
|
const renderPlaceholder = useCallback(({ attributes, children }: RenderPlaceholderProps) => {
|
||||||
|
// drop style attribute as we use our custom placeholder css.
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||||
|
const { style, ...props } = attributes;
|
||||||
|
return (
|
||||||
|
<Text as="span" {...props} className={css.EditorPlaceholder} contentEditable={false}>
|
||||||
|
{children}
|
||||||
|
</Text>
|
||||||
|
);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={css.Editor} ref={ref}>
|
||||||
|
<Slate editor={editor} value={initialValue} onChange={onChange}>
|
||||||
|
{top}
|
||||||
|
<Box alignItems="Start">
|
||||||
|
{before && (
|
||||||
|
<Box className={css.EditorOptions} alignItems="Center" gap="100" shrink="No">
|
||||||
|
{before}
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
<Scroll
|
||||||
|
className={css.EditorTextareaScroll}
|
||||||
|
variant="SurfaceVariant"
|
||||||
|
style={{ maxHeight }}
|
||||||
|
size="300"
|
||||||
|
visibility="Hover"
|
||||||
|
hideTrack
|
||||||
|
>
|
||||||
|
<Editable
|
||||||
|
className={css.EditorTextarea}
|
||||||
|
placeholder={placeholder}
|
||||||
|
renderPlaceholder={renderPlaceholder}
|
||||||
|
renderElement={renderElement}
|
||||||
|
renderLeaf={renderLeaf}
|
||||||
|
onKeyDown={handleKeydown}
|
||||||
|
onPaste={onPaste}
|
||||||
|
/>
|
||||||
|
</Scroll>
|
||||||
|
{after && (
|
||||||
|
<Box className={css.EditorOptions} alignItems="Center" gap="100" shrink="No">
|
||||||
|
{after}
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
{bottom}
|
||||||
|
</Slate>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
);
|
||||||
142
src/app/components/editor/Elements.css.ts
Normal file
142
src/app/components/editor/Elements.css.ts
Normal file
|
|
@ -0,0 +1,142 @@
|
||||||
|
import { style } from '@vanilla-extract/css';
|
||||||
|
import { recipe } from '@vanilla-extract/recipes';
|
||||||
|
import { color, config, DefaultReset, toRem } from 'folds';
|
||||||
|
|
||||||
|
const MarginBottom = style({
|
||||||
|
marginBottom: config.space.S200,
|
||||||
|
selectors: {
|
||||||
|
'&:last-child': {
|
||||||
|
marginBottom: 0,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export const Paragraph = style([MarginBottom]);
|
||||||
|
|
||||||
|
export const Heading = style([MarginBottom]);
|
||||||
|
|
||||||
|
export const BlockQuote = style([
|
||||||
|
DefaultReset,
|
||||||
|
MarginBottom,
|
||||||
|
{
|
||||||
|
paddingLeft: config.space.S200,
|
||||||
|
borderLeft: `${config.borderWidth.B700} solid ${color.SurfaceVariant.ContainerLine}`,
|
||||||
|
fontStyle: 'italic',
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
const BaseCode = style({
|
||||||
|
fontFamily: 'monospace',
|
||||||
|
color: color.Warning.OnContainer,
|
||||||
|
background: color.Warning.Container,
|
||||||
|
border: `${config.borderWidth.B300} solid ${color.Warning.ContainerLine}`,
|
||||||
|
borderRadius: config.radii.R300,
|
||||||
|
});
|
||||||
|
|
||||||
|
export const Code = style([
|
||||||
|
DefaultReset,
|
||||||
|
BaseCode,
|
||||||
|
{
|
||||||
|
padding: `0 ${config.space.S100}`,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
export const Spoiler = style([
|
||||||
|
DefaultReset,
|
||||||
|
{
|
||||||
|
padding: `0 ${config.space.S100}`,
|
||||||
|
backgroundColor: color.SurfaceVariant.ContainerActive,
|
||||||
|
borderRadius: config.radii.R300,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const CodeBlock = style([DefaultReset, BaseCode, MarginBottom]);
|
||||||
|
export const CodeBlockInternal = style({
|
||||||
|
padding: `${config.space.S200} ${config.space.S200} 0`,
|
||||||
|
});
|
||||||
|
|
||||||
|
export const List = style([
|
||||||
|
DefaultReset,
|
||||||
|
MarginBottom,
|
||||||
|
{
|
||||||
|
padding: `0 ${config.space.S100}`,
|
||||||
|
paddingLeft: config.space.S600,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const InlineChromiumBugfix = style({
|
||||||
|
fontSize: 0,
|
||||||
|
lineHeight: 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
export const Mention = recipe({
|
||||||
|
base: [
|
||||||
|
DefaultReset,
|
||||||
|
{
|
||||||
|
backgroundColor: color.Secondary.Container,
|
||||||
|
color: color.Secondary.OnContainer,
|
||||||
|
boxShadow: `0 0 0 ${config.borderWidth.B300} ${color.Secondary.ContainerLine}`,
|
||||||
|
padding: `0 ${toRem(2)}`,
|
||||||
|
borderRadius: config.radii.R300,
|
||||||
|
fontWeight: config.fontWeight.W500,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
variants: {
|
||||||
|
highlight: {
|
||||||
|
true: {
|
||||||
|
backgroundColor: color.Primary.Container,
|
||||||
|
color: color.Primary.OnContainer,
|
||||||
|
boxShadow: `0 0 0 ${config.borderWidth.B300} ${color.Primary.ContainerLine}`,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
focus: {
|
||||||
|
true: {
|
||||||
|
boxShadow: `0 0 0 ${config.borderWidth.B300} ${color.SurfaceVariant.OnContainer}`,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export const EmoticonBase = style([
|
||||||
|
DefaultReset,
|
||||||
|
{
|
||||||
|
display: 'inline-block',
|
||||||
|
padding: '0.05rem',
|
||||||
|
height: '1em',
|
||||||
|
verticalAlign: 'middle',
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const Emoticon = recipe({
|
||||||
|
base: [
|
||||||
|
DefaultReset,
|
||||||
|
{
|
||||||
|
display: 'inline-flex',
|
||||||
|
justifyContent: 'center',
|
||||||
|
alignItems: 'center',
|
||||||
|
|
||||||
|
height: '1em',
|
||||||
|
minWidth: '1em',
|
||||||
|
fontSize: '1.47em',
|
||||||
|
lineHeight: '1em',
|
||||||
|
verticalAlign: 'middle',
|
||||||
|
position: 'relative',
|
||||||
|
top: '-0.25em',
|
||||||
|
borderRadius: config.radii.R300,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
variants: {
|
||||||
|
focus: {
|
||||||
|
true: {
|
||||||
|
boxShadow: `0 0 0 ${config.borderWidth.B300} ${color.SurfaceVariant.OnContainer}`,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export const EmoticonImg = style([
|
||||||
|
DefaultReset,
|
||||||
|
{
|
||||||
|
height: '1em',
|
||||||
|
cursor: 'default',
|
||||||
|
},
|
||||||
|
]);
|
||||||
254
src/app/components/editor/Elements.tsx
Normal file
254
src/app/components/editor/Elements.tsx
Normal file
|
|
@ -0,0 +1,254 @@
|
||||||
|
import { Scroll, Text } from 'folds';
|
||||||
|
import React from 'react';
|
||||||
|
import { RenderElementProps, RenderLeafProps, useFocused, useSelected } from 'slate-react';
|
||||||
|
|
||||||
|
import * as css from './Elements.css';
|
||||||
|
import { EmoticonElement, LinkElement, MentionElement } from './slate';
|
||||||
|
import { useMatrixClient } from '../../hooks/useMatrixClient';
|
||||||
|
|
||||||
|
export enum MarkType {
|
||||||
|
Bold = 'bold',
|
||||||
|
Italic = 'italic',
|
||||||
|
Underline = 'underline',
|
||||||
|
StrikeThrough = 'strikeThrough',
|
||||||
|
Code = 'code',
|
||||||
|
Spoiler = 'spoiler',
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum BlockType {
|
||||||
|
Paragraph = 'paragraph',
|
||||||
|
Heading = 'heading',
|
||||||
|
CodeLine = 'code-line',
|
||||||
|
CodeBlock = 'code-block',
|
||||||
|
QuoteLine = 'quote-line',
|
||||||
|
BlockQuote = 'block-quote',
|
||||||
|
ListItem = 'list-item',
|
||||||
|
OrderedList = 'ordered-list',
|
||||||
|
UnorderedList = 'unordered-list',
|
||||||
|
Mention = 'mention',
|
||||||
|
Emoticon = 'emoticon',
|
||||||
|
Link = 'link',
|
||||||
|
}
|
||||||
|
|
||||||
|
// Put this at the start and end of an inline component to work around this Chromium bug:
|
||||||
|
// https://bugs.chromium.org/p/chromium/issues/detail?id=1249405
|
||||||
|
function InlineChromiumBugfix() {
|
||||||
|
return (
|
||||||
|
<span className={css.InlineChromiumBugfix} contentEditable={false}>
|
||||||
|
{String.fromCodePoint(160) /* Non-breaking space */}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function RenderMentionElement({
|
||||||
|
attributes,
|
||||||
|
element,
|
||||||
|
children,
|
||||||
|
}: { element: MentionElement } & RenderElementProps) {
|
||||||
|
const selected = useSelected();
|
||||||
|
const focused = useFocused();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
{...attributes}
|
||||||
|
className={css.Mention({
|
||||||
|
highlight: element.highlight,
|
||||||
|
focus: selected && focused,
|
||||||
|
})}
|
||||||
|
contentEditable={false}
|
||||||
|
>
|
||||||
|
{element.name}
|
||||||
|
{children}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function RenderEmoticonElement({
|
||||||
|
attributes,
|
||||||
|
element,
|
||||||
|
children,
|
||||||
|
}: { element: EmoticonElement } & RenderElementProps) {
|
||||||
|
const mx = useMatrixClient();
|
||||||
|
const selected = useSelected();
|
||||||
|
const focused = useFocused();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<span className={css.EmoticonBase} {...attributes}>
|
||||||
|
<span
|
||||||
|
className={css.Emoticon({
|
||||||
|
focus: selected && focused,
|
||||||
|
})}
|
||||||
|
contentEditable={false}
|
||||||
|
>
|
||||||
|
{element.key.startsWith('mxc://') ? (
|
||||||
|
<img
|
||||||
|
className={css.EmoticonImg}
|
||||||
|
src={mx.mxcUrlToHttp(element.key) ?? element.key}
|
||||||
|
alt={element.shortcode}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
element.key
|
||||||
|
)}
|
||||||
|
{children}
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function RenderLinkElement({
|
||||||
|
attributes,
|
||||||
|
element,
|
||||||
|
children,
|
||||||
|
}: { element: LinkElement } & RenderElementProps) {
|
||||||
|
return (
|
||||||
|
<a href={element.href} {...attributes}>
|
||||||
|
<InlineChromiumBugfix />
|
||||||
|
{children}
|
||||||
|
</a>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function RenderElement({ attributes, element, children }: RenderElementProps) {
|
||||||
|
switch (element.type) {
|
||||||
|
case BlockType.Paragraph:
|
||||||
|
return (
|
||||||
|
<Text {...attributes} className={css.Paragraph}>
|
||||||
|
{children}
|
||||||
|
</Text>
|
||||||
|
);
|
||||||
|
case BlockType.Heading:
|
||||||
|
if (element.level === 1)
|
||||||
|
return (
|
||||||
|
<Text className={css.Heading} as="h2" size="H2" {...attributes}>
|
||||||
|
{children}
|
||||||
|
</Text>
|
||||||
|
);
|
||||||
|
if (element.level === 2)
|
||||||
|
return (
|
||||||
|
<Text className={css.Heading} as="h3" size="H3" {...attributes}>
|
||||||
|
{children}
|
||||||
|
</Text>
|
||||||
|
);
|
||||||
|
if (element.level === 3)
|
||||||
|
return (
|
||||||
|
<Text className={css.Heading} as="h4" size="H4" {...attributes}>
|
||||||
|
{children}
|
||||||
|
</Text>
|
||||||
|
);
|
||||||
|
return (
|
||||||
|
<Text className={css.Heading} as="h3" size="H3" {...attributes}>
|
||||||
|
{children}
|
||||||
|
</Text>
|
||||||
|
);
|
||||||
|
case BlockType.CodeLine:
|
||||||
|
return <div {...attributes}>{children}</div>;
|
||||||
|
case BlockType.CodeBlock:
|
||||||
|
return (
|
||||||
|
<Text as="pre" className={css.CodeBlock} {...attributes}>
|
||||||
|
<Scroll direction="Horizontal" variant="Warning" size="300" visibility="Hover" hideTrack>
|
||||||
|
<div className={css.CodeBlockInternal}>{children}</div>
|
||||||
|
</Scroll>
|
||||||
|
</Text>
|
||||||
|
);
|
||||||
|
case BlockType.QuoteLine:
|
||||||
|
return <div {...attributes}>{children}</div>;
|
||||||
|
case BlockType.BlockQuote:
|
||||||
|
return (
|
||||||
|
<Text as="blockquote" className={css.BlockQuote} {...attributes}>
|
||||||
|
{children}
|
||||||
|
</Text>
|
||||||
|
);
|
||||||
|
case BlockType.ListItem:
|
||||||
|
return (
|
||||||
|
<Text as="li" {...attributes}>
|
||||||
|
{children}
|
||||||
|
</Text>
|
||||||
|
);
|
||||||
|
case BlockType.OrderedList:
|
||||||
|
return (
|
||||||
|
<ol className={css.List} {...attributes}>
|
||||||
|
{children}
|
||||||
|
</ol>
|
||||||
|
);
|
||||||
|
case BlockType.UnorderedList:
|
||||||
|
return (
|
||||||
|
<ul className={css.List} {...attributes}>
|
||||||
|
{children}
|
||||||
|
</ul>
|
||||||
|
);
|
||||||
|
case BlockType.Mention:
|
||||||
|
return (
|
||||||
|
<RenderMentionElement attributes={attributes} element={element}>
|
||||||
|
{children}
|
||||||
|
</RenderMentionElement>
|
||||||
|
);
|
||||||
|
case BlockType.Emoticon:
|
||||||
|
return (
|
||||||
|
<RenderEmoticonElement attributes={attributes} element={element}>
|
||||||
|
{children}
|
||||||
|
</RenderEmoticonElement>
|
||||||
|
);
|
||||||
|
case BlockType.Link:
|
||||||
|
return (
|
||||||
|
<RenderLinkElement attributes={attributes} element={element}>
|
||||||
|
{children}
|
||||||
|
</RenderLinkElement>
|
||||||
|
);
|
||||||
|
default:
|
||||||
|
return (
|
||||||
|
<Text className={css.Paragraph} {...attributes}>
|
||||||
|
{children}
|
||||||
|
</Text>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function RenderLeaf({ attributes, leaf, children }: RenderLeafProps) {
|
||||||
|
let child = children;
|
||||||
|
if (leaf.bold)
|
||||||
|
child = (
|
||||||
|
<strong {...attributes}>
|
||||||
|
<InlineChromiumBugfix />
|
||||||
|
{child}
|
||||||
|
</strong>
|
||||||
|
);
|
||||||
|
if (leaf.italic)
|
||||||
|
child = (
|
||||||
|
<i {...attributes}>
|
||||||
|
<InlineChromiumBugfix />
|
||||||
|
{child}
|
||||||
|
</i>
|
||||||
|
);
|
||||||
|
if (leaf.underline)
|
||||||
|
child = (
|
||||||
|
<u {...attributes}>
|
||||||
|
<InlineChromiumBugfix />
|
||||||
|
{child}
|
||||||
|
</u>
|
||||||
|
);
|
||||||
|
if (leaf.strikeThrough)
|
||||||
|
child = (
|
||||||
|
<s {...attributes}>
|
||||||
|
<InlineChromiumBugfix />
|
||||||
|
{child}
|
||||||
|
</s>
|
||||||
|
);
|
||||||
|
if (leaf.code)
|
||||||
|
child = (
|
||||||
|
<code className={css.Code} {...attributes}>
|
||||||
|
<InlineChromiumBugfix />
|
||||||
|
{child}
|
||||||
|
</code>
|
||||||
|
);
|
||||||
|
if (leaf.spoiler)
|
||||||
|
child = (
|
||||||
|
<span className={css.Spoiler} {...attributes}>
|
||||||
|
<InlineChromiumBugfix />
|
||||||
|
{child}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
|
||||||
|
if (child !== children) return child;
|
||||||
|
|
||||||
|
return <span {...attributes}>{child}</span>;
|
||||||
|
}
|
||||||
247
src/app/components/editor/Toolbar.tsx
Normal file
247
src/app/components/editor/Toolbar.tsx
Normal file
|
|
@ -0,0 +1,247 @@
|
||||||
|
import FocusTrap from 'focus-trap-react';
|
||||||
|
import {
|
||||||
|
Badge,
|
||||||
|
Box,
|
||||||
|
config,
|
||||||
|
Icon,
|
||||||
|
IconButton,
|
||||||
|
Icons,
|
||||||
|
IconSrc,
|
||||||
|
Line,
|
||||||
|
Menu,
|
||||||
|
PopOut,
|
||||||
|
Text,
|
||||||
|
Tooltip,
|
||||||
|
TooltipProvider,
|
||||||
|
toRem,
|
||||||
|
} from 'folds';
|
||||||
|
import React, { ReactNode, useState } from 'react';
|
||||||
|
import { ReactEditor, useSlate } from 'slate-react';
|
||||||
|
import { isBlockActive, isMarkActive, toggleBlock, toggleMark } from './common';
|
||||||
|
import * as css from './Editor.css';
|
||||||
|
import { BlockType, MarkType } from './Elements';
|
||||||
|
import { HeadingLevel } from './slate';
|
||||||
|
import { isMacOS } from '../../utils/user-agent';
|
||||||
|
import { KeySymbol } from '../../utils/key-symbol';
|
||||||
|
|
||||||
|
function BtnTooltip({ text, shortCode }: { text: string; shortCode?: string }) {
|
||||||
|
return (
|
||||||
|
<Tooltip style={{ padding: config.space.S300 }}>
|
||||||
|
<Box gap="200" direction="Column" alignItems="Center">
|
||||||
|
<Text align="Center">{text}</Text>
|
||||||
|
{shortCode && (
|
||||||
|
<Badge as="kbd" radii="300" size="500">
|
||||||
|
<Text size="T200" align="Center">
|
||||||
|
{shortCode}
|
||||||
|
</Text>
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
</Tooltip>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type MarkButtonProps = { format: MarkType; icon: IconSrc; tooltip: ReactNode };
|
||||||
|
export function MarkButton({ format, icon, tooltip }: MarkButtonProps) {
|
||||||
|
const editor = useSlate();
|
||||||
|
|
||||||
|
const handleClick = () => {
|
||||||
|
toggleMark(editor, format);
|
||||||
|
ReactEditor.focus(editor);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<TooltipProvider tooltip={tooltip} delay={500}>
|
||||||
|
{(triggerRef) => (
|
||||||
|
<IconButton
|
||||||
|
ref={triggerRef}
|
||||||
|
variant="SurfaceVariant"
|
||||||
|
onClick={handleClick}
|
||||||
|
aria-pressed={isMarkActive(editor, format)}
|
||||||
|
size="300"
|
||||||
|
radii="300"
|
||||||
|
>
|
||||||
|
<Icon size="50" src={icon} />
|
||||||
|
</IconButton>
|
||||||
|
)}
|
||||||
|
</TooltipProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type BlockButtonProps = {
|
||||||
|
format: BlockType;
|
||||||
|
icon: IconSrc;
|
||||||
|
tooltip: ReactNode;
|
||||||
|
};
|
||||||
|
export function BlockButton({ format, icon, tooltip }: BlockButtonProps) {
|
||||||
|
const editor = useSlate();
|
||||||
|
|
||||||
|
const handleClick = () => {
|
||||||
|
toggleBlock(editor, format, { level: 1 });
|
||||||
|
ReactEditor.focus(editor);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<TooltipProvider tooltip={tooltip} delay={500}>
|
||||||
|
{(triggerRef) => (
|
||||||
|
<IconButton
|
||||||
|
ref={triggerRef}
|
||||||
|
variant="SurfaceVariant"
|
||||||
|
onClick={handleClick}
|
||||||
|
aria-pressed={isBlockActive(editor, format)}
|
||||||
|
size="300"
|
||||||
|
radii="300"
|
||||||
|
>
|
||||||
|
<Icon size="50" src={icon} />
|
||||||
|
</IconButton>
|
||||||
|
)}
|
||||||
|
</TooltipProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function HeadingBlockButton() {
|
||||||
|
const editor = useSlate();
|
||||||
|
const [level, setLevel] = useState<HeadingLevel>(1);
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
const isActive = isBlockActive(editor, BlockType.Heading);
|
||||||
|
|
||||||
|
const handleMenuSelect = (selectedLevel: HeadingLevel) => {
|
||||||
|
setOpen(false);
|
||||||
|
setLevel(selectedLevel);
|
||||||
|
toggleBlock(editor, BlockType.Heading, { level: selectedLevel });
|
||||||
|
ReactEditor.focus(editor);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<PopOut
|
||||||
|
open={open}
|
||||||
|
align="Start"
|
||||||
|
position="Top"
|
||||||
|
content={
|
||||||
|
<FocusTrap
|
||||||
|
focusTrapOptions={{
|
||||||
|
initialFocus: false,
|
||||||
|
onDeactivate: () => setOpen(false),
|
||||||
|
clickOutsideDeactivates: true,
|
||||||
|
isKeyForward: (evt: KeyboardEvent) =>
|
||||||
|
evt.key === 'ArrowDown' || evt.key === 'ArrowRight',
|
||||||
|
isKeyBackward: (evt: KeyboardEvent) => evt.key === 'ArrowUp' || evt.key === 'ArrowLeft',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Menu style={{ padding: config.space.S100 }}>
|
||||||
|
<Box gap="100">
|
||||||
|
<IconButton onClick={() => handleMenuSelect(1)} size="300" radii="300">
|
||||||
|
<Icon size="100" src={Icons.Heading1} />
|
||||||
|
</IconButton>
|
||||||
|
<IconButton onClick={() => handleMenuSelect(2)} size="300" radii="300">
|
||||||
|
<Icon size="100" src={Icons.Heading2} />
|
||||||
|
</IconButton>
|
||||||
|
<IconButton onClick={() => handleMenuSelect(3)} size="300" radii="300">
|
||||||
|
<Icon size="100" src={Icons.Heading3} />
|
||||||
|
</IconButton>
|
||||||
|
</Box>
|
||||||
|
</Menu>
|
||||||
|
</FocusTrap>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{(ref) => (
|
||||||
|
<IconButton
|
||||||
|
style={{ width: 'unset' }}
|
||||||
|
ref={ref}
|
||||||
|
variant="SurfaceVariant"
|
||||||
|
onClick={() => (isActive ? toggleBlock(editor, BlockType.Heading) : setOpen(!open))}
|
||||||
|
aria-pressed={isActive}
|
||||||
|
size="300"
|
||||||
|
radii="300"
|
||||||
|
>
|
||||||
|
<Icon size="50" src={Icons[`Heading${level}`]} />
|
||||||
|
<Icon size="50" src={isActive ? Icons.Cross : Icons.ChevronBottom} />
|
||||||
|
</IconButton>
|
||||||
|
)}
|
||||||
|
</PopOut>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Toolbar() {
|
||||||
|
const editor = useSlate();
|
||||||
|
const allowInline = !isBlockActive(editor, BlockType.CodeBlock);
|
||||||
|
const modKey = isMacOS() ? KeySymbol.Command : 'Ctrl';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box className={css.EditorToolbar} alignItems="Center" gap="300">
|
||||||
|
<Box gap="100">
|
||||||
|
<HeadingBlockButton />
|
||||||
|
<BlockButton
|
||||||
|
format={BlockType.OrderedList}
|
||||||
|
icon={Icons.OrderList}
|
||||||
|
tooltip={
|
||||||
|
<BtnTooltip text="Ordered List" shortCode={`${modKey} + ${KeySymbol.Shift} + 0`} />
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<BlockButton
|
||||||
|
format={BlockType.UnorderedList}
|
||||||
|
icon={Icons.UnorderList}
|
||||||
|
tooltip={
|
||||||
|
<BtnTooltip text="Unordered List" shortCode={`${modKey} + ${KeySymbol.Shift} + 8`} />
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<BlockButton
|
||||||
|
format={BlockType.BlockQuote}
|
||||||
|
icon={Icons.BlockQuote}
|
||||||
|
tooltip={
|
||||||
|
<BtnTooltip text="Block Quote" shortCode={`${modKey} + ${KeySymbol.Shift} + '`} />
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<BlockButton
|
||||||
|
format={BlockType.CodeBlock}
|
||||||
|
icon={Icons.BlockCode}
|
||||||
|
tooltip={
|
||||||
|
<BtnTooltip text="Block Code" shortCode={`${modKey} + ${KeySymbol.Shift} + ;`} />
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
{allowInline && (
|
||||||
|
<>
|
||||||
|
<Line variant="SurfaceVariant" direction="Vertical" style={{ height: toRem(12) }} />
|
||||||
|
<Box gap="100">
|
||||||
|
<MarkButton
|
||||||
|
format={MarkType.Bold}
|
||||||
|
icon={Icons.Bold}
|
||||||
|
tooltip={<BtnTooltip text="Bold" shortCode={`${modKey} + B`} />}
|
||||||
|
/>
|
||||||
|
<MarkButton
|
||||||
|
format={MarkType.Italic}
|
||||||
|
icon={Icons.Italic}
|
||||||
|
tooltip={<BtnTooltip text="Italic" shortCode={`${modKey} + I`} />}
|
||||||
|
/>
|
||||||
|
<MarkButton
|
||||||
|
format={MarkType.Underline}
|
||||||
|
icon={Icons.Underline}
|
||||||
|
tooltip={<BtnTooltip text="Underline" shortCode={`${modKey} + U`} />}
|
||||||
|
/>
|
||||||
|
<MarkButton
|
||||||
|
format={MarkType.StrikeThrough}
|
||||||
|
icon={Icons.Strike}
|
||||||
|
tooltip={
|
||||||
|
<BtnTooltip
|
||||||
|
text="Strike Through"
|
||||||
|
shortCode={`${modKey} + ${KeySymbol.Shift} + U`}
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<MarkButton
|
||||||
|
format={MarkType.Code}
|
||||||
|
icon={Icons.Code}
|
||||||
|
tooltip={<BtnTooltip text="Inline Code" shortCode={`${modKey} + [`} />}
|
||||||
|
/>
|
||||||
|
<MarkButton
|
||||||
|
format={MarkType.Spoiler}
|
||||||
|
icon={Icons.EyeBlind}
|
||||||
|
tooltip={<BtnTooltip text="Spoiler" shortCode={`${modKey} + H`} />}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,35 @@
|
||||||
|
import { style } from '@vanilla-extract/css';
|
||||||
|
import { DefaultReset, config } from 'folds';
|
||||||
|
|
||||||
|
export const AutocompleteMenuBase = style([
|
||||||
|
DefaultReset,
|
||||||
|
{
|
||||||
|
position: 'relative',
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const AutocompleteMenuContainer = style([
|
||||||
|
DefaultReset,
|
||||||
|
{
|
||||||
|
position: 'absolute',
|
||||||
|
bottom: config.space.S200,
|
||||||
|
left: 0,
|
||||||
|
right: 0,
|
||||||
|
zIndex: config.zIndex.Max,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const AutocompleteMenu = style([
|
||||||
|
DefaultReset,
|
||||||
|
{
|
||||||
|
maxHeight: '30vh',
|
||||||
|
height: '100%',
|
||||||
|
display: 'flex',
|
||||||
|
flexDirection: 'column',
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const AutocompleteMenuHeader = style([
|
||||||
|
DefaultReset,
|
||||||
|
{ padding: `0 ${config.space.S300}`, flexShrink: 0 },
|
||||||
|
]);
|
||||||
40
src/app/components/editor/autocomplete/AutocompleteMenu.tsx
Normal file
40
src/app/components/editor/autocomplete/AutocompleteMenu.tsx
Normal file
|
|
@ -0,0 +1,40 @@
|
||||||
|
import React, { ReactNode } from 'react';
|
||||||
|
import FocusTrap from 'focus-trap-react';
|
||||||
|
import isHotkey from 'is-hotkey';
|
||||||
|
import { Header, Menu, Scroll, config } from 'folds';
|
||||||
|
|
||||||
|
import * as css from './AutocompleteMenu.css';
|
||||||
|
import { preventScrollWithArrowKey } from '../../../utils/keyboard';
|
||||||
|
|
||||||
|
type AutocompleteMenuProps = {
|
||||||
|
requestClose: () => void;
|
||||||
|
headerContent: ReactNode;
|
||||||
|
children: ReactNode;
|
||||||
|
};
|
||||||
|
export function AutocompleteMenu({ headerContent, requestClose, children }: AutocompleteMenuProps) {
|
||||||
|
return (
|
||||||
|
<div className={css.AutocompleteMenuBase}>
|
||||||
|
<div className={css.AutocompleteMenuContainer}>
|
||||||
|
<FocusTrap
|
||||||
|
focusTrapOptions={{
|
||||||
|
initialFocus: false,
|
||||||
|
onDeactivate: () => requestClose(),
|
||||||
|
clickOutsideDeactivates: true,
|
||||||
|
allowOutsideClick: true,
|
||||||
|
isKeyForward: (evt: KeyboardEvent) => isHotkey('arrowdown', evt),
|
||||||
|
isKeyBackward: (evt: KeyboardEvent) => isHotkey('arrowup', evt),
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Menu className={css.AutocompleteMenu}>
|
||||||
|
<Header className={css.AutocompleteMenuHeader} size="400">
|
||||||
|
{headerContent}
|
||||||
|
</Header>
|
||||||
|
<Scroll style={{ flexGrow: 1 }} onKeyDown={preventScrollWithArrowKey}>
|
||||||
|
<div style={{ padding: config.space.S200 }}>{children}</div>
|
||||||
|
</Scroll>
|
||||||
|
</Menu>
|
||||||
|
</FocusTrap>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
129
src/app/components/editor/autocomplete/EmoticonAutocomplete.tsx
Normal file
129
src/app/components/editor/autocomplete/EmoticonAutocomplete.tsx
Normal file
|
|
@ -0,0 +1,129 @@
|
||||||
|
import React, { KeyboardEvent as ReactKeyboardEvent, useEffect, useMemo } from 'react';
|
||||||
|
import { Editor } from 'slate';
|
||||||
|
import { Box, MenuItem, Text, toRem } from 'folds';
|
||||||
|
import { Room } from 'matrix-js-sdk';
|
||||||
|
|
||||||
|
import { AutocompleteQuery } from './autocompleteQuery';
|
||||||
|
import { AutocompleteMenu } from './AutocompleteMenu';
|
||||||
|
import { useMatrixClient } from '../../../hooks/useMatrixClient';
|
||||||
|
import {
|
||||||
|
SearchItemStrGetter,
|
||||||
|
UseAsyncSearchOptions,
|
||||||
|
useAsyncSearch,
|
||||||
|
} from '../../../hooks/useAsyncSearch';
|
||||||
|
import { onTabPress } from '../../../utils/keyboard';
|
||||||
|
import { createEmoticonElement, moveCursor, replaceWithElement } from '../common';
|
||||||
|
import { useRecentEmoji } from '../../../hooks/useRecentEmoji';
|
||||||
|
import { useRelevantImagePacks } from '../../../hooks/useImagePacks';
|
||||||
|
import { IEmoji, emojis } from '../../../plugins/emoji';
|
||||||
|
import { ExtendedPackImage, PackUsage } from '../../../plugins/custom-emoji';
|
||||||
|
import { useKeyDown } from '../../../hooks/useKeyDown';
|
||||||
|
|
||||||
|
type EmoticonCompleteHandler = (key: string, shortcode: string) => void;
|
||||||
|
|
||||||
|
type EmoticonSearchItem = ExtendedPackImage | IEmoji;
|
||||||
|
|
||||||
|
type EmoticonAutocompleteProps = {
|
||||||
|
imagePackRooms: Room[];
|
||||||
|
editor: Editor;
|
||||||
|
query: AutocompleteQuery<string>;
|
||||||
|
requestClose: () => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
const SEARCH_OPTIONS: UseAsyncSearchOptions = {
|
||||||
|
limit: 20,
|
||||||
|
matchOptions: {
|
||||||
|
contain: true,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const getEmoticonStr: SearchItemStrGetter<EmoticonSearchItem> = (emoticon) => [
|
||||||
|
`:${emoticon.shortcode}:`,
|
||||||
|
];
|
||||||
|
|
||||||
|
export function EmoticonAutocomplete({
|
||||||
|
imagePackRooms,
|
||||||
|
editor,
|
||||||
|
query,
|
||||||
|
requestClose,
|
||||||
|
}: EmoticonAutocompleteProps) {
|
||||||
|
const mx = useMatrixClient();
|
||||||
|
|
||||||
|
const imagePacks = useRelevantImagePacks(mx, PackUsage.Emoticon, imagePackRooms);
|
||||||
|
const recentEmoji = useRecentEmoji(mx, 20);
|
||||||
|
|
||||||
|
const searchList = useMemo(() => {
|
||||||
|
const list: Array<EmoticonSearchItem> = [];
|
||||||
|
return list.concat(
|
||||||
|
imagePacks.flatMap((pack) => pack.getImagesFor(PackUsage.Emoticon)),
|
||||||
|
emojis
|
||||||
|
);
|
||||||
|
}, [imagePacks]);
|
||||||
|
|
||||||
|
const [result, search] = useAsyncSearch(searchList, getEmoticonStr, SEARCH_OPTIONS);
|
||||||
|
const autoCompleteEmoticon = result ? result.items : recentEmoji;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
search(query.text);
|
||||||
|
}, [query.text, search]);
|
||||||
|
|
||||||
|
const handleAutocomplete: EmoticonCompleteHandler = (key, shortcode) => {
|
||||||
|
const emoticonEl = createEmoticonElement(key, shortcode);
|
||||||
|
replaceWithElement(editor, query.range, emoticonEl);
|
||||||
|
moveCursor(editor, true);
|
||||||
|
requestClose();
|
||||||
|
};
|
||||||
|
|
||||||
|
useKeyDown(window, (evt: KeyboardEvent) => {
|
||||||
|
onTabPress(evt, () => {
|
||||||
|
if (autoCompleteEmoticon.length === 0) return;
|
||||||
|
const emoticon = autoCompleteEmoticon[0];
|
||||||
|
const key = 'url' in emoticon ? emoticon.url : emoticon.unicode;
|
||||||
|
handleAutocomplete(key, emoticon.shortcode);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
return autoCompleteEmoticon.length === 0 ? null : (
|
||||||
|
<AutocompleteMenu headerContent={<Text size="L400">Emojis</Text>} requestClose={requestClose}>
|
||||||
|
{autoCompleteEmoticon.map((emoticon) => {
|
||||||
|
const isCustomEmoji = 'url' in emoticon;
|
||||||
|
const key = isCustomEmoji ? emoticon.url : emoticon.unicode;
|
||||||
|
return (
|
||||||
|
<MenuItem
|
||||||
|
key={emoticon.shortcode + key}
|
||||||
|
as="button"
|
||||||
|
radii="300"
|
||||||
|
onKeyDown={(evt: ReactKeyboardEvent<HTMLButtonElement>) =>
|
||||||
|
onTabPress(evt, () => handleAutocomplete(key, emoticon.shortcode))
|
||||||
|
}
|
||||||
|
onClick={() => handleAutocomplete(key, emoticon.shortcode)}
|
||||||
|
before={
|
||||||
|
isCustomEmoji ? (
|
||||||
|
<Box
|
||||||
|
shrink="No"
|
||||||
|
as="img"
|
||||||
|
src={mx.mxcUrlToHttp(key) || key}
|
||||||
|
alt={emoticon.shortcode}
|
||||||
|
style={{ width: toRem(24), height: toRem(24) }}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<Box
|
||||||
|
shrink="No"
|
||||||
|
as="span"
|
||||||
|
display="InlineFlex"
|
||||||
|
style={{ fontSize: toRem(24), lineHeight: toRem(24) }}
|
||||||
|
>
|
||||||
|
{key}
|
||||||
|
</Box>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<Text style={{ flexGrow: 1 }} size="B400" truncate>
|
||||||
|
:{emoticon.shortcode}:
|
||||||
|
</Text>
|
||||||
|
</MenuItem>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</AutocompleteMenu>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,181 @@
|
||||||
|
import React, { KeyboardEvent as ReactKeyboardEvent, useCallback, useEffect, useMemo } from 'react';
|
||||||
|
import { Editor } from 'slate';
|
||||||
|
import { Avatar, AvatarFallback, AvatarImage, Icon, Icons, MenuItem, Text, color } from 'folds';
|
||||||
|
import { MatrixClient } from 'matrix-js-sdk';
|
||||||
|
|
||||||
|
import { createMentionElement, moveCursor, replaceWithElement } from '../common';
|
||||||
|
import { getRoomAvatarUrl, joinRuleToIconSrc } from '../../../utils/room';
|
||||||
|
import { roomIdByActivity } from '../../../../util/sort';
|
||||||
|
import initMatrix from '../../../../client/initMatrix';
|
||||||
|
import { useMatrixClient } from '../../../hooks/useMatrixClient';
|
||||||
|
import { AutocompleteQuery } from './autocompleteQuery';
|
||||||
|
import { AutocompleteMenu } from './AutocompleteMenu';
|
||||||
|
import { getMxIdServer, validMxId } from '../../../utils/matrix';
|
||||||
|
import { UseAsyncSearchOptions, useAsyncSearch } from '../../../hooks/useAsyncSearch';
|
||||||
|
import { onTabPress } from '../../../utils/keyboard';
|
||||||
|
import { useKeyDown } from '../../../hooks/useKeyDown';
|
||||||
|
|
||||||
|
type MentionAutoCompleteHandler = (roomAliasOrId: string, name: string) => void;
|
||||||
|
|
||||||
|
const roomAliasFromQueryText = (mx: MatrixClient, text: string) =>
|
||||||
|
validMxId(`#${text}`)
|
||||||
|
? `#${text}`
|
||||||
|
: `#${text}${text.endsWith(':') ? '' : ':'}${getMxIdServer(mx.getUserId() ?? '')}`;
|
||||||
|
|
||||||
|
function UnknownRoomMentionItem({
|
||||||
|
query,
|
||||||
|
handleAutocomplete,
|
||||||
|
}: {
|
||||||
|
query: AutocompleteQuery<string>;
|
||||||
|
handleAutocomplete: MentionAutoCompleteHandler;
|
||||||
|
}) {
|
||||||
|
const mx = useMatrixClient();
|
||||||
|
const roomAlias: string = roomAliasFromQueryText(mx, query.text);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<MenuItem
|
||||||
|
as="button"
|
||||||
|
radii="300"
|
||||||
|
onKeyDown={(evt: ReactKeyboardEvent<HTMLButtonElement>) =>
|
||||||
|
onTabPress(evt, () => handleAutocomplete(roomAlias, roomAlias))
|
||||||
|
}
|
||||||
|
onClick={() => handleAutocomplete(roomAlias, roomAlias)}
|
||||||
|
before={
|
||||||
|
<Avatar size="200">
|
||||||
|
<Icon src={Icons.Hash} size="100" />
|
||||||
|
</Avatar>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<Text style={{ flexGrow: 1 }} size="B400">
|
||||||
|
{roomAlias}
|
||||||
|
</Text>
|
||||||
|
</MenuItem>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type RoomMentionAutocompleteProps = {
|
||||||
|
roomId: string;
|
||||||
|
editor: Editor;
|
||||||
|
query: AutocompleteQuery<string>;
|
||||||
|
requestClose: () => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
const SEARCH_OPTIONS: UseAsyncSearchOptions = {
|
||||||
|
limit: 20,
|
||||||
|
matchOptions: {
|
||||||
|
contain: true,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export function RoomMentionAutocomplete({
|
||||||
|
roomId,
|
||||||
|
editor,
|
||||||
|
query,
|
||||||
|
requestClose,
|
||||||
|
}: RoomMentionAutocompleteProps) {
|
||||||
|
const mx = useMatrixClient();
|
||||||
|
const dms: Set<string> = initMatrix.roomList?.directs ?? new Set();
|
||||||
|
|
||||||
|
const allRoomId: string[] = useMemo(() => {
|
||||||
|
const { spaces = [], rooms = [], directs = [] } = initMatrix.roomList ?? {};
|
||||||
|
return [...spaces, ...rooms, ...directs].sort(roomIdByActivity);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const [result, search] = useAsyncSearch(
|
||||||
|
allRoomId,
|
||||||
|
useCallback(
|
||||||
|
(rId) => {
|
||||||
|
const r = mx.getRoom(rId);
|
||||||
|
if (!r) return 'Unknown Room';
|
||||||
|
const alias = r.getCanonicalAlias();
|
||||||
|
if (alias) return [r.name, alias];
|
||||||
|
return r.name;
|
||||||
|
},
|
||||||
|
[mx]
|
||||||
|
),
|
||||||
|
SEARCH_OPTIONS
|
||||||
|
);
|
||||||
|
|
||||||
|
const autoCompleteRoomIds = result ? result.items : allRoomId.slice(0, 20);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
search(query.text);
|
||||||
|
}, [query.text, search]);
|
||||||
|
|
||||||
|
const handleAutocomplete: MentionAutoCompleteHandler = (roomAliasOrId, name) => {
|
||||||
|
const mentionEl = createMentionElement(
|
||||||
|
roomAliasOrId,
|
||||||
|
name.startsWith('#') ? name : `#${name}`,
|
||||||
|
roomId === roomAliasOrId || mx.getRoom(roomId)?.getCanonicalAlias() === roomAliasOrId
|
||||||
|
);
|
||||||
|
replaceWithElement(editor, query.range, mentionEl);
|
||||||
|
moveCursor(editor, true);
|
||||||
|
requestClose();
|
||||||
|
};
|
||||||
|
|
||||||
|
useKeyDown(window, (evt: KeyboardEvent) => {
|
||||||
|
onTabPress(evt, () => {
|
||||||
|
if (autoCompleteRoomIds.length === 0) {
|
||||||
|
const alias = roomAliasFromQueryText(mx, query.text);
|
||||||
|
handleAutocomplete(alias, alias);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const rId = autoCompleteRoomIds[0];
|
||||||
|
const name = mx.getRoom(rId)?.name ?? rId;
|
||||||
|
handleAutocomplete(rId, name);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AutocompleteMenu headerContent={<Text size="L400">Rooms</Text>} requestClose={requestClose}>
|
||||||
|
{autoCompleteRoomIds.length === 0 ? (
|
||||||
|
<UnknownRoomMentionItem query={query} handleAutocomplete={handleAutocomplete} />
|
||||||
|
) : (
|
||||||
|
autoCompleteRoomIds.map((rId) => {
|
||||||
|
const room = mx.getRoom(rId);
|
||||||
|
if (!room) return null;
|
||||||
|
const dm = dms.has(room.roomId);
|
||||||
|
const avatarUrl = getRoomAvatarUrl(mx, room);
|
||||||
|
const iconSrc = !dm && joinRuleToIconSrc(Icons, room.getJoinRule(), room.isSpaceRoom());
|
||||||
|
|
||||||
|
return (
|
||||||
|
<MenuItem
|
||||||
|
key={rId}
|
||||||
|
as="button"
|
||||||
|
radii="300"
|
||||||
|
onKeyDown={(evt: ReactKeyboardEvent<HTMLButtonElement>) =>
|
||||||
|
onTabPress(evt, () => handleAutocomplete(rId, room.name))
|
||||||
|
}
|
||||||
|
onClick={() => handleAutocomplete(rId, room.name)}
|
||||||
|
after={
|
||||||
|
<Text size="T200" priority="300" truncate>
|
||||||
|
{room.getCanonicalAlias() ?? ''}
|
||||||
|
</Text>
|
||||||
|
}
|
||||||
|
before={
|
||||||
|
<Avatar size="200">
|
||||||
|
{iconSrc && <Icon src={iconSrc} size="100" />}
|
||||||
|
{avatarUrl && !iconSrc && <AvatarImage src={avatarUrl} alt={room.name} />}
|
||||||
|
{!avatarUrl && !iconSrc && (
|
||||||
|
<AvatarFallback
|
||||||
|
style={{
|
||||||
|
backgroundColor: color.Secondary.Container,
|
||||||
|
color: color.Secondary.OnContainer,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Text size="H6">{room.name[0]}</Text>
|
||||||
|
</AvatarFallback>
|
||||||
|
)}
|
||||||
|
</Avatar>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<Text style={{ flexGrow: 1 }} size="B400" truncate>
|
||||||
|
{room.name}
|
||||||
|
</Text>
|
||||||
|
</MenuItem>
|
||||||
|
);
|
||||||
|
})
|
||||||
|
)}
|
||||||
|
</AutocompleteMenu>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,191 @@
|
||||||
|
import React, { useEffect, KeyboardEvent as ReactKeyboardEvent } from 'react';
|
||||||
|
import { Editor } from 'slate';
|
||||||
|
import { Avatar, AvatarFallback, AvatarImage, MenuItem, Text, color } from 'folds';
|
||||||
|
import { MatrixClient, RoomMember } from 'matrix-js-sdk';
|
||||||
|
|
||||||
|
import { AutocompleteQuery } from './autocompleteQuery';
|
||||||
|
import { AutocompleteMenu } from './AutocompleteMenu';
|
||||||
|
import { useRoomMembers } from '../../../hooks/useRoomMembers';
|
||||||
|
import { useMatrixClient } from '../../../hooks/useMatrixClient';
|
||||||
|
import {
|
||||||
|
SearchItemStrGetter,
|
||||||
|
UseAsyncSearchOptions,
|
||||||
|
useAsyncSearch,
|
||||||
|
} from '../../../hooks/useAsyncSearch';
|
||||||
|
import { onTabPress } from '../../../utils/keyboard';
|
||||||
|
import { createMentionElement, moveCursor, replaceWithElement } from '../common';
|
||||||
|
import { useKeyDown } from '../../../hooks/useKeyDown';
|
||||||
|
import { getMxIdLocalPart, getMxIdServer, validMxId } from '../../../utils/matrix';
|
||||||
|
|
||||||
|
type MentionAutoCompleteHandler = (userId: string, name: string) => void;
|
||||||
|
|
||||||
|
const userIdFromQueryText = (mx: MatrixClient, text: string) =>
|
||||||
|
validMxId(`@${text}`)
|
||||||
|
? `@${text}`
|
||||||
|
: `@${text}${text.endsWith(':') ? '' : ':'}${getMxIdServer(mx.getUserId() ?? '')}`;
|
||||||
|
|
||||||
|
function UnknownMentionItem({
|
||||||
|
query,
|
||||||
|
userId,
|
||||||
|
name,
|
||||||
|
handleAutocomplete,
|
||||||
|
}: {
|
||||||
|
query: AutocompleteQuery<string>;
|
||||||
|
userId: string;
|
||||||
|
name: string;
|
||||||
|
handleAutocomplete: MentionAutoCompleteHandler;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<MenuItem
|
||||||
|
as="button"
|
||||||
|
radii="300"
|
||||||
|
onKeyDown={(evt: ReactKeyboardEvent<HTMLButtonElement>) =>
|
||||||
|
onTabPress(evt, () => handleAutocomplete(userId, name))
|
||||||
|
}
|
||||||
|
onClick={() => handleAutocomplete(userId, name)}
|
||||||
|
before={
|
||||||
|
<Avatar size="200">
|
||||||
|
<AvatarFallback
|
||||||
|
style={{
|
||||||
|
backgroundColor: color.Secondary.Container,
|
||||||
|
color: color.Secondary.OnContainer,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Text size="H6">{query.text[0]}</Text>
|
||||||
|
</AvatarFallback>
|
||||||
|
</Avatar>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<Text style={{ flexGrow: 1 }} size="B400">
|
||||||
|
{name}
|
||||||
|
</Text>
|
||||||
|
</MenuItem>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type UserMentionAutocompleteProps = {
|
||||||
|
roomId: string;
|
||||||
|
editor: Editor;
|
||||||
|
query: AutocompleteQuery<string>;
|
||||||
|
requestClose: () => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
const SEARCH_OPTIONS: UseAsyncSearchOptions = {
|
||||||
|
limit: 20,
|
||||||
|
matchOptions: {
|
||||||
|
contain: true,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const getRoomMemberStr: SearchItemStrGetter<RoomMember> = (roomMember) => [
|
||||||
|
roomMember.name,
|
||||||
|
getMxIdLocalPart(roomMember.userId) ?? roomMember.userId,
|
||||||
|
roomMember.userId,
|
||||||
|
];
|
||||||
|
|
||||||
|
export function UserMentionAutocomplete({
|
||||||
|
roomId,
|
||||||
|
editor,
|
||||||
|
query,
|
||||||
|
requestClose,
|
||||||
|
}: UserMentionAutocompleteProps) {
|
||||||
|
const mx = useMatrixClient();
|
||||||
|
const room = mx.getRoom(roomId);
|
||||||
|
const roomAliasOrId = room?.getCanonicalAlias() || roomId;
|
||||||
|
const members = useRoomMembers(mx, roomId);
|
||||||
|
|
||||||
|
const [result, search] = useAsyncSearch(members, getRoomMemberStr, SEARCH_OPTIONS);
|
||||||
|
const autoCompleteMembers = result ? result.items : members.slice(0, 20);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
search(query.text);
|
||||||
|
}, [query.text, search]);
|
||||||
|
|
||||||
|
const handleAutocomplete: MentionAutoCompleteHandler = (uId, name) => {
|
||||||
|
const mentionEl = createMentionElement(
|
||||||
|
uId,
|
||||||
|
name.startsWith('@') ? name : `@${name}`,
|
||||||
|
mx.getUserId() === uId || roomAliasOrId === uId
|
||||||
|
);
|
||||||
|
replaceWithElement(editor, query.range, mentionEl);
|
||||||
|
moveCursor(editor, true);
|
||||||
|
requestClose();
|
||||||
|
};
|
||||||
|
|
||||||
|
useKeyDown(window, (evt: KeyboardEvent) => {
|
||||||
|
onTabPress(evt, () => {
|
||||||
|
if (query.text === 'room') {
|
||||||
|
handleAutocomplete(roomAliasOrId, '@room');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (autoCompleteMembers.length === 0) {
|
||||||
|
const userId = userIdFromQueryText(mx, query.text);
|
||||||
|
handleAutocomplete(userId, userId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const roomMember = autoCompleteMembers[0];
|
||||||
|
handleAutocomplete(roomMember.userId, roomMember.name);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AutocompleteMenu headerContent={<Text size="L400">Mentions</Text>} requestClose={requestClose}>
|
||||||
|
{query.text === 'room' && (
|
||||||
|
<UnknownMentionItem
|
||||||
|
query={query}
|
||||||
|
userId={roomAliasOrId}
|
||||||
|
name="@room"
|
||||||
|
handleAutocomplete={handleAutocomplete}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{autoCompleteMembers.length === 0 ? (
|
||||||
|
<UnknownMentionItem
|
||||||
|
query={query}
|
||||||
|
userId={userIdFromQueryText(mx, query.text)}
|
||||||
|
name={userIdFromQueryText(mx, query.text)}
|
||||||
|
handleAutocomplete={handleAutocomplete}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
autoCompleteMembers.map((roomMember) => {
|
||||||
|
const avatarUrl = roomMember.getAvatarUrl(mx.baseUrl, 32, 32, 'crop', undefined, false);
|
||||||
|
return (
|
||||||
|
<MenuItem
|
||||||
|
key={roomMember.userId}
|
||||||
|
as="button"
|
||||||
|
radii="300"
|
||||||
|
onKeyDown={(evt: ReactKeyboardEvent<HTMLButtonElement>) =>
|
||||||
|
onTabPress(evt, () => handleAutocomplete(roomMember.userId, roomMember.name))
|
||||||
|
}
|
||||||
|
onClick={() => handleAutocomplete(roomMember.userId, roomMember.name)}
|
||||||
|
after={
|
||||||
|
<Text size="T200" priority="300" truncate>
|
||||||
|
{roomMember.userId}
|
||||||
|
</Text>
|
||||||
|
}
|
||||||
|
before={
|
||||||
|
<Avatar size="200">
|
||||||
|
{avatarUrl ? (
|
||||||
|
<AvatarImage src={avatarUrl} alt={roomMember.userId} />
|
||||||
|
) : (
|
||||||
|
<AvatarFallback
|
||||||
|
style={{
|
||||||
|
backgroundColor: color.Secondary.Container,
|
||||||
|
color: color.Secondary.OnContainer,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Text size="H6">{roomMember.name[0] || roomMember.userId[1]}</Text>
|
||||||
|
</AvatarFallback>
|
||||||
|
)}
|
||||||
|
</Avatar>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<Text style={{ flexGrow: 1 }} size="B400" truncate>
|
||||||
|
{roomMember.name}
|
||||||
|
</Text>
|
||||||
|
</MenuItem>
|
||||||
|
);
|
||||||
|
})
|
||||||
|
)}
|
||||||
|
</AutocompleteMenu>
|
||||||
|
);
|
||||||
|
}
|
||||||
46
src/app/components/editor/autocomplete/autocompleteQuery.ts
Normal file
46
src/app/components/editor/autocomplete/autocompleteQuery.ts
Normal file
|
|
@ -0,0 +1,46 @@
|
||||||
|
import { BaseRange, Editor } from 'slate';
|
||||||
|
|
||||||
|
export enum AutocompletePrefix {
|
||||||
|
RoomMention = '#',
|
||||||
|
UserMention = '@',
|
||||||
|
Emoticon = ':',
|
||||||
|
}
|
||||||
|
export const AUTOCOMPLETE_PREFIXES: readonly AutocompletePrefix[] = [
|
||||||
|
AutocompletePrefix.RoomMention,
|
||||||
|
AutocompletePrefix.UserMention,
|
||||||
|
AutocompletePrefix.Emoticon,
|
||||||
|
];
|
||||||
|
|
||||||
|
export type AutocompleteQuery<TPrefix extends string> = {
|
||||||
|
range: BaseRange;
|
||||||
|
prefix: TPrefix;
|
||||||
|
text: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getAutocompletePrefix = <TPrefix extends string>(
|
||||||
|
editor: Editor,
|
||||||
|
queryRange: BaseRange,
|
||||||
|
validPrefixes: readonly TPrefix[]
|
||||||
|
): TPrefix | undefined => {
|
||||||
|
const world = Editor.string(editor, queryRange);
|
||||||
|
const prefix = world[0] as TPrefix | undefined;
|
||||||
|
if (!prefix) return undefined;
|
||||||
|
return validPrefixes.includes(prefix) ? prefix : undefined;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getAutocompleteQueryText = (editor: Editor, queryRange: BaseRange): string =>
|
||||||
|
Editor.string(editor, queryRange).slice(1);
|
||||||
|
|
||||||
|
export const getAutocompleteQuery = <TPrefix extends string>(
|
||||||
|
editor: Editor,
|
||||||
|
queryRange: BaseRange,
|
||||||
|
validPrefixes: readonly TPrefix[]
|
||||||
|
): AutocompleteQuery<TPrefix> | undefined => {
|
||||||
|
const prefix = getAutocompletePrefix(editor, queryRange, validPrefixes);
|
||||||
|
if (!prefix) return undefined;
|
||||||
|
return {
|
||||||
|
range: queryRange,
|
||||||
|
prefix,
|
||||||
|
text: getAutocompleteQueryText(editor, queryRange),
|
||||||
|
};
|
||||||
|
};
|
||||||
5
src/app/components/editor/autocomplete/index.ts
Normal file
5
src/app/components/editor/autocomplete/index.ts
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
export * from './AutocompleteMenu';
|
||||||
|
export * from './autocompleteQuery';
|
||||||
|
export * from './RoomMentionAutocomplete';
|
||||||
|
export * from './UserMentionAutocomplete';
|
||||||
|
export * from './EmoticonAutocomplete';
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue