added per item text inputs

This commit is contained in:
Shea Duma committed 2026-03-06 04:51:27 +02:00
1 parent fb5c5a2326
commit 7bbda34504
6 files changed
+350 -44

No files matched your search

@@ -1,4 +1,4 @@
import { ReactNode, useEffect } from 'react';
import { ReactNode, useEffect, useState } from 'react';
import { Box, Chip, Icon, IconButton, Icons, Text, color, config, toRem } from 'folds';
import { UploadStatus, UploadSuccess, useBindUploadAtom } from '$state/upload';
import { useMatrixClient } from '$hooks/useMatrixClient';
@@ -8,6 +8,7 @@ import { roomUploadAtomFamily, TUploadItem, TUploadMetadata } from '$state/room/
import { useObjectURL } from '$hooks/useObjectURL';
import { useMediaConfig } from '$hooks/useMediaConfig';
import { UploadCard, UploadCardError, UploadCardProgress } from './UploadCard';
import { DescriptionEditor } from './UploadDescriptionEditor';
type PreviewImageProps = {
fileItem: TUploadItem;
@@ -98,7 +99,7 @@ type UploadCardRendererProps = {
isEncrypted?: boolean;
fileItem: TUploadItem;
setMetadata: (fileItem: TUploadItem, metadata: TUploadMetadata) => void;
setDescription: (fileContent: TUploadContent) => void;
setDesc: (fileItem: TUploadItem, body: string, formatted_body: string) => void;
onRemove: (file: TUploadContent) => void;
onComplete?: (upload: UploadSuccess) => void;
};
@@ -106,7 +107,7 @@ export function UploadCardRenderer({
isEncrypted,
fileItem,
setMetadata,
setDescription,
setDesc,
onRemove,
onComplete,
}: UploadCardRendererProps) {
@@ -120,6 +121,8 @@ export function UploadCardRenderer({
const { file } = upload;
const fileSizeExceeded = file.size >= allowSize;
const [isDescribed, setIsDescribed] = useState(false);
if (upload.status === UploadStatus.Idle && !fileSizeExceeded) {
startUpload();
}
@@ -132,9 +135,6 @@ export function UploadCardRenderer({
cancelUpload();
onRemove(file);
};
const handleDescription = () => {
setDescription(file);
};
useEffect(() => {
if (upload.status === UploadStatus.Success) {
@@ -160,13 +160,15 @@ export function UploadCardRenderer({
</Chip>
)}
<IconButton
onClick={handleDescription}
onClick={() => {
setIsDescribed(!isDescribed);
}}
aria-label="Add Upload Description"
variant="SurfaceVariant"
radii="Pill"
size="300"
>
<Icon src={Icons.Pencil} size="50" />
<Icon src={isDescribed ? Icons.ChevronBottom : Icons.ChevronTop} size="50" />
</IconButton>
<IconButton
@@ -212,6 +214,14 @@ export function UploadCardRenderer({
</Text>
</UploadCardError>
)}
{isDescribed && (
<DescriptionEditor
value={fileItem.formatted_body || fileItem.body || fileItem.file.name || ''}
onSave={(htmlBio) => {
setDesc(fileItem, htmlBio, htmlBio);
}}
/>
)}
</>
}
>
@@ -0,0 +1,28 @@
import { style, globalStyle } from '@vanilla-extract/css';
import { config } from 'folds';
export const BioEditorContainer = style({
backgroundColor: 'var(--sable-bg-container)',
borderRadius: config.radii.R400,
overflow: 'hidden',
});
globalStyle(`${BioEditorContainer} div[class*="EditorTextarea"]`, {
backgroundColor: 'var(--sable-bg-container) !important',
border: 'none !important',
});
globalStyle(`${BioEditorContainer} [class*="Toolbar"]`, {
backgroundColor: 'var(--sable-bg-container) !important',
padding: 'var(--space-S100) !important',
borderTop: '1px solid var(--sable-outline-variant) !important',
});
globalStyle(`${BioEditorContainer} [class*="Toolbar"] button`, {
backgroundColor: 'transparent !important',
boxShadow: 'none !important',
});
globalStyle(`${BioEditorContainer} [class*="Toolbar"] button:hover`, {
backgroundColor: 'var(--sable-surface-variant) !important',
});
@@ -0,0 +1,253 @@
import { KeyboardEventHandler, useCallback, useEffect, useState, useRef } from 'react';
import {
Box,
Chip,
Icon,
IconButton,
Icons,
Line,
PopOut,
RectCords,
Spinner,
Text,
config,
} from 'folds';
import { Editor, Transforms } from 'slate';
import { ReactEditor } from 'slate-react';
import { isKeyHotkey } from 'is-hotkey';
import {
AutocompletePrefix,
AutocompleteQuery,
CustomEditor,
EmoticonAutocomplete,
Toolbar,
createEmoticonElement,
getAutocompleteQuery,
getPrevWorldRange,
htmlToEditorInput,
plainToEditorInput,
moveCursor,
toMatrixCustomHTML,
toPlainText,
trimCustomHtml,
useEditor,
} from '$components/editor';
import { useSetting } from '$state/hooks/settings';
import { settingsAtom } from '$state/settings';
import { UseStateProvider } from '$components/UseStateProvider';
import { EmojiBoard } from '$components/emoji-board';
import { mobileOrTablet } from '$utils/user-agent';
import * as css from './UploadDescriptionEditor.css';
type BioEditorProps = {
value?: string | any;
isSaving?: boolean;
imagePackRooms?: any[];
onSave: (htmlContent: string) => void;
};
export function DescriptionEditor({ value, isSaving, imagePackRooms, onSave }: BioEditorProps) {
const editor = useEditor();
const [enterForNewline] = useSetting(settingsAtom, 'enterForNewline');
const [isMarkdown] = useSetting(settingsAtom, 'isMarkdown');
const [toolbar, setToolbar] = useState(false);
const [autocompleteQuery, setAutocompleteQuery] =
useState<AutocompleteQuery<AutocompletePrefix>>();
const [hasChanged, setHasChanged] = useState(false);
const prevValue = useRef(value);
const initialized = useRef(false);
const handleSave = useCallback(() => {
const plainText = toPlainText(editor.children, isMarkdown).trim();
const customHtml = trimCustomHtml(
toMatrixCustomHTML(editor.children, {
allowTextFormatting: true,
allowBlockMarkdown: isMarkdown,
allowInlineMarkdown: isMarkdown,
})
);
onSave(customHtml || plainText);
setHasChanged(false);
}, [editor, isMarkdown, onSave]);
useEffect(() => {
const valueChanged = prevValue.current !== value;
const isFirstValidLoad = !initialized.current && value !== undefined;
if (valueChanged || isFirstValidLoad) {
prevValue.current = value;
let normalizedValue = value;
if (
typeof normalizedValue === 'object' &&
normalizedValue !== null &&
'formatted_body' in normalizedValue
) {
normalizedValue = normalizedValue.formatted_body;
}
const safeValue = typeof normalizedValue === 'string' ? normalizedValue : '';
const incomingPlainText = toPlainText(
htmlToEditorInput(safeValue, isMarkdown),
isMarkdown
).trim();
const currentPlainText = toPlainText(editor.children, isMarkdown).trim();
if (currentPlainText === incomingPlainText && initialized.current) return;
const isLikelyHtml = safeValue.includes('<') || safeValue.includes('>');
const initialValue = isLikelyHtml
? htmlToEditorInput(safeValue, isMarkdown)
: plainToEditorInput(safeValue, isMarkdown);
editor.children = initialValue;
Editor.normalize(editor, { force: true });
Transforms.select(editor, Editor.start(editor, []));
initialized.current = true;
setHasChanged(false);
}
}, [value, editor, isMarkdown]);
const handleKeyDown: KeyboardEventHandler = useCallback(
(evt) => {
if (isKeyHotkey('mod+enter', evt) || (!enterForNewline && isKeyHotkey('enter', evt))) {
evt.preventDefault();
handleSave();
}
},
[handleSave, enterForNewline]
);
const handleKeyUp: KeyboardEventHandler = useCallback(
(evt) => {
if (isKeyHotkey('escape', evt)) {
evt.preventDefault();
return;
}
const prevWordRange = getPrevWorldRange(editor);
const query = prevWordRange
? getAutocompleteQuery(editor, prevWordRange, [AutocompletePrefix.Emoticon])
: undefined;
setAutocompleteQuery(query);
},
[editor]
);
const handleCloseAutocomplete = useCallback(() => {
ReactEditor.focus(editor);
setAutocompleteQuery(undefined);
}, [editor]);
const handleEmoticonSelect = (key: string, shortcode: string) => {
editor.insertNode(createEmoticonElement(key, shortcode));
moveCursor(editor);
setHasChanged(true);
};
return (
<Box direction="Column" gap="100">
<Box className={css.BioEditorContainer} direction="Column" style={{ position: 'relative' }}>
{autocompleteQuery?.prefix === AutocompletePrefix.Emoticon && (
<EmoticonAutocomplete
imagePackRooms={imagePackRooms || []}
editor={editor}
query={autocompleteQuery}
requestClose={handleCloseAutocomplete}
/>
)}
<CustomEditor
editor={editor}
placeholder="File Description..."
onKeyDown={handleKeyDown}
onKeyUp={handleKeyUp}
maxHeight="200px"
variant="Background"
bottom={
<Box direction="Column" style={{ backgroundColor: 'var(--sable-bg-container)' }}>
<Box
style={{ padding: config.space.S200, paddingTop: 0 }}
alignItems="End"
justifyContent="SpaceBetween"
gap="100"
>
<Box gap="200" alignItems="Center">
{hasChanged && (
<Chip
onClick={handleSave}
variant="Primary"
radii="Pill"
outlined
before={
isSaving ? <Spinner variant="Primary" fill="Soft" size="100" /> : undefined
}
>
<Text size="B300">{isSaving ? 'Saving' : 'Save'}</Text>
</Chip>
)}
</Box>
<Box gap="Inherit">
<IconButton
variant="Background"
size="300"
radii="300"
onClick={() => setToolbar(!toolbar)}
>
<Icon size="400" src={toolbar ? Icons.AlphabetUnderline : Icons.Alphabet} />
</IconButton>
<UseStateProvider initial={undefined}>
{(anchor: RectCords | undefined, setAnchor) => (
<PopOut
anchor={anchor}
alignOffset={-8}
position="Top"
align="End"
content={
<EmojiBoard
imagePackRooms={imagePackRooms ?? []}
returnFocusOnDeactivate={false}
onEmojiSelect={handleEmoticonSelect}
onCustomEmojiSelect={handleEmoticonSelect}
requestClose={() =>
setAnchor((v) => {
if (v) {
if (!mobileOrTablet()) ReactEditor.focus(editor);
return undefined;
}
return v;
})
}
/>
}
>
<IconButton
aria-pressed={anchor !== undefined}
variant="Background"
size="300"
radii="300"
onClick={(evt) => setAnchor(evt.currentTarget.getBoundingClientRect())}
>
<Icon size="400" src={Icons.Smile} filled={anchor !== undefined} />
</IconButton>
</PopOut>
)}
</UseStateProvider>
</Box>
</Box>
{toolbar && (
<Box direction="Column">
<Line variant="Surface" size="300" />
<Toolbar />
</Box>
)}
</Box>
}
/>
</Box>
</Box>
);
}
+21 -32
View File
@@ -205,7 +205,6 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
const [uploadBoard, setUploadBoard] = useState(true);
const [selectedFiles, setSelectedFiles] = useAtom(roomIdToUploadItemsAtomFamily(roomId));
const [describedFile, setDescribedFile] = useState<TUploadContent | undefined>(undefined);
const uploadFamilyObserverAtom = createUploadFamilyObserverAtom(
roomUploadAtomFamily,
selectedFiles.map((f) => f.file)
@@ -238,7 +237,6 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
metadata: {
markedAsSpoiler: false,
},
body: 'aaa',
})
);
} else {
@@ -250,7 +248,6 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
metadata: {
markedAsSpoiler: false,
},
body: 'aaa',
})
);
}
@@ -340,11 +337,15 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
},
[setSelectedFiles]
);
const handleDescription = useCallback(
(fileItem: TUploadContent) => {
setDescribedFile(fileItem);
const setDesc = useCallback(
(fileItem: TUploadItem, body: string, formatted_body: string) => {
setSelectedFiles({
type: 'REPLACE',
item: fileItem,
replacement: { ...fileItem, body, formatted_body },
});
},
[setDescribedFile]
[setSelectedFiles]
);
const handleRemoveUpload = useCallback(
(upload: TUploadContent | TUploadContent[]) => {
@@ -368,19 +369,12 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
};
const handleSendUpload = async (uploads: UploadSuccess[]) => {
const plaintext = toPlainText(editor.children, isMarkdown).trim();
const plainText = toPlainText(editor.children, isMarkdown).trim();
const contentsPromises = uploads.map(async (upload) => {
const fileItem = selectedFiles.find((f) => f.file === upload.file);
if (!fileItem) throw new Error('Broken upload');
if (fileItem.file === describedFile) {
fileItem.body = plaintext;
resetEditor(editor);
resetEditorHistory(editor);
setInputKey((prev) => prev + 1);
sendTypingStatus(false);
setDescribedFile(undefined);
}
if (fileItem.file.type.startsWith('image')) {
return getImageMsgContent(mx, fileItem, upload.mxc);
}
@@ -396,7 +390,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
const contents = fulfilledPromiseSettledResult(await Promise.allSettled(contentsPromises));
if (contents.length > 0) {
const replyContent = plaintext.length === 0 ? getReplyContent(replyDraft) : undefined;
const replyContent = plainText?.length === 0 ? getReplyContent(replyDraft) : undefined;
if (replyContent) contents[0]['m.relates_to'] = replyContent;
setReplyDraft(undefined);
}
@@ -414,7 +408,6 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
const submit = useCallback(async () => {
uploadBoardHandlers.current?.handleSend();
if (describedFile !== undefined) return;
const commandName = getBeginCommand(editor);
let plainText = toPlainText(editor.children, isMarkdown).trim();
let customHtml = trimCustomHtml(
@@ -489,7 +482,6 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
setReplyDraft(undefined);
sendTypingStatus(false);
};
if (scheduledTime) {
try {
const delayMs = computeDelayMs(scheduledTime);
@@ -505,7 +497,6 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
setEditingScheduledDelayId(null);
setScheduledTime(null);
resetInput();
setDescribedFile(undefined);
} catch {
// Network/server error — leave editor and scheduled state intact for retry
}
@@ -516,7 +507,6 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
invalidate();
setEditingScheduledDelayId(null);
resetInput();
setDescribedFile(undefined);
} catch {
// Cancel failed — leave state intact for retry
}
@@ -527,22 +517,21 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
});
}
}, [
editor,
isMarkdown,
mx,
roomId,
room,
editor,
replyDraft,
sendTypingStatus,
setReplyDraft,
describedFile,
isMarkdown,
commands,
scheduledTime,
setScheduledTime,
isEncrypted,
queryClient,
editingScheduledDelayId,
commands,
sendTypingStatus,
queryClient,
setReplyDraft,
isEncrypted,
setEditingScheduledDelayId,
setScheduledTime,
room,
]);
const handleKeyDown: KeyboardEventHandler = useCallback(
@@ -682,7 +671,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
fileItem={fileItem}
setMetadata={handleFileMetadata}
onRemove={handleRemoveUpload}
setDescription={handleDescription}
setDesc={setDesc}
/>
))}
</UploadBoardContent>
+28 -4
View File
@@ -59,6 +59,8 @@ export const getImageMsgContent = async (
msgtype: MsgType.Image,
filename: file.name,
body: file.name,
format: 'org.matrix.custom.html',
formatted_body: file.name,
[MATRIX_SPOILER_PROPERTY_NAME]: metadata.markedAsSpoiler,
};
if (imgEl) {
@@ -77,7 +79,11 @@ export const getImageMsgContent = async (
} else {
content.url = mxc;
}
if (item.body?.length && item.body.length > 0) content.body = item.body;
if (item.body && item.body.length > 0) content.body = item.body;
if (item.formatted_body && item.formatted_body.length > 0) {
content.format = 'org.matrix.custom.html';
content.formatted_body = item.formatted_body;
}
return content;
};
@@ -95,6 +101,8 @@ export const getVideoMsgContent = async (
msgtype: MsgType.Video,
filename: file.name,
body: file.name,
format: 'org.matrix.custom.html',
formatted_body: file.name,
[MATRIX_SPOILER_PROPERTY_NAME]: metadata.markedAsSpoiler,
};
if (videoEl) {
@@ -127,7 +135,11 @@ export const getVideoMsgContent = async (
} else {
content.url = mxc;
}
if (item.body?.length && item.body.length > 0) content.body = item.body;
if (item.body && item.body.length > 0) content.body = item.body;
if (item.formatted_body && item.formatted_body.length > 0) {
content.format = 'org.matrix.custom.html';
content.formatted_body = item.formatted_body;
}
return content;
};
@@ -137,6 +149,8 @@ export const getAudioMsgContent = (item: TUploadItem, mxc: string): IContent =>
msgtype: MsgType.Audio,
filename: file.name,
body: file.name,
format: 'org.matrix.custom.html',
formatted_body: file.name,
info: {
mimetype: file.type,
size: file.size,
@@ -150,7 +164,11 @@ export const getAudioMsgContent = (item: TUploadItem, mxc: string): IContent =>
} else {
content.url = mxc;
}
if (item.body?.length && item.body.length > 0) content.body = item.body;
if (item.body && item.body.length > 0) content.body = item.body;
if (item.formatted_body && item.formatted_body.length > 0) {
content.format = 'org.matrix.custom.html';
content.formatted_body = item.formatted_body;
}
return content;
};
@@ -160,6 +178,8 @@ export const getFileMsgContent = (item: TUploadItem, mxc: string): IContent => {
msgtype: MsgType.File,
filename: file.name,
body: file.name,
format: 'org.matrix.custom.html',
formatted_body: file.name,
info: {
mimetype: file.type,
size: file.size,
@@ -173,6 +193,10 @@ export const getFileMsgContent = (item: TUploadItem, mxc: string): IContent => {
} else {
content.url = mxc;
}
if (item.body?.length && item.body.length > 0) content.body = item.body;
if (item.body && item.body.length > 0) content.body = item.body;
if (item.formatted_body && item.formatted_body.length > 0) {
content.format = 'org.matrix.custom.html';
content.formatted_body = item.formatted_body;
}
return content;
};
+2
View File
@@ -17,6 +17,8 @@ export type TUploadItem = {
metadata: TUploadMetadata;
encInfo: EncryptedAttachmentInfo | undefined;
body?: string;
format?: string;
formatted_body?: string;
};
export type TUploadListAtom = ReturnType<typeof createListAtom<TUploadItem>>;