diff --git a/.changeset/feat_adding_basic_file_descriptions.md b/.changeset/feat_adding_basic_file_descriptions.md new file mode 100644 index 00000000..8b6e9951 --- /dev/null +++ b/.changeset/feat_adding_basic_file_descriptions.md @@ -0,0 +1,5 @@ +--- +sable: patch +--- + +Added the ability to add descriptions to uploaded files diff --git a/src/app/components/upload-card/UploadCardRenderer.tsx b/src/app/components/upload-card/UploadCardRenderer.tsx index 8ff54ff0..b15a91c6 100644 --- a/src/app/components/upload-card/UploadCardRenderer.tsx +++ b/src/app/components/upload-card/UploadCardRenderer.tsx @@ -1,5 +1,5 @@ -import { ReactNode, useEffect } from 'react'; -import { Box, Chip, Icon, IconButton, Icons, Text, color, config, toRem } from 'folds'; +import { ReactNode, useEffect, useState } from 'react'; +import { Box, Chip, Icon, IconButton, Icons, Text, Tooltip, color, config, toRem } from 'folds'; import { UploadStatus, UploadSuccess, useBindUploadAtom } from '$state/upload'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { TUploadContent } from '$utils/matrix'; @@ -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,6 +99,7 @@ type UploadCardRendererProps = { isEncrypted?: boolean; fileItem: TUploadItem; setMetadata: (fileItem: TUploadItem, metadata: TUploadMetadata) => void; + setDesc: (fileItem: TUploadItem, body: string, formatted_body: string) => void; onRemove: (file: TUploadContent) => void; onComplete?: (upload: UploadSuccess) => void; }; @@ -105,6 +107,7 @@ export function UploadCardRenderer({ isEncrypted, fileItem, setMetadata, + setDesc, onRemove, onComplete, }: UploadCardRendererProps) { @@ -118,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(); } @@ -136,7 +141,6 @@ export function UploadCardRenderer({ onComplete?.(upload); } }, [upload, onComplete]); - return ( Retry )} + { + setIsDescribed(!isDescribed); + }} + aria-label="Add Upload Description" + variant="SurfaceVariant" + radii="Pill" + size="300" + > + + + )} + {isDescribed && ( + { + setDesc(fileItem, plainText, htmlContent); + setIsDescribed(false); + }} + /> + )} + {!isDescribed && fileItem.body && fileItem.body.length > 0 && ( + + + {fileItem.body} + + + )} } > diff --git a/src/app/components/upload-card/UploadDescriptionEditor.css.tsx b/src/app/components/upload-card/UploadDescriptionEditor.css.tsx new file mode 100644 index 00000000..04037a7b --- /dev/null +++ b/src/app/components/upload-card/UploadDescriptionEditor.css.tsx @@ -0,0 +1,28 @@ +import { style, globalStyle } from '@vanilla-extract/css'; +import { config } from 'folds'; + +export const DescriptionEditorContainer = style({ + backgroundColor: 'var(--sable-bg-container)', + borderRadius: config.radii.R400, + overflow: 'hidden', +}); + +globalStyle(`${DescriptionEditorContainer} div[class*="EditorTextarea"]`, { + backgroundColor: 'var(--sable-bg-container) !important', + border: 'none !important', +}); + +globalStyle(`${DescriptionEditorContainer} [class*="Toolbar"]`, { + backgroundColor: 'var(--sable-bg-container) !important', + padding: 'var(--space-S100) !important', + borderTop: '1px solid var(--sable-outline-variant) !important', +}); + +globalStyle(`${DescriptionEditorContainer} [class*="Toolbar"] button`, { + backgroundColor: 'transparent !important', + boxShadow: 'none !important', +}); + +globalStyle(`${DescriptionEditorContainer} [class*="Toolbar"] button:hover`, { + backgroundColor: 'var(--sable-surface-variant) !important', +}); diff --git a/src/app/components/upload-card/UploadDescriptionEditor.tsx b/src/app/components/upload-card/UploadDescriptionEditor.tsx new file mode 100644 index 00000000..4893ba38 --- /dev/null +++ b/src/app/components/upload-card/UploadDescriptionEditor.tsx @@ -0,0 +1,256 @@ +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 DescriptionEditorProps = { + value?: string | any; + isSaving?: boolean; + imagePackRooms?: any[]; + onSave: (plaintext: string, htmlContent: string) => void; +}; + +export function DescriptionEditor({ + value, + isSaving, + imagePackRooms, + onSave, +}: DescriptionEditorProps) { + const editor = useEditor(); + const [enterForNewline] = useSetting(settingsAtom, 'enterForNewline'); + const [isMarkdown] = useSetting(settingsAtom, 'isMarkdown'); + const [toolbar, setToolbar] = useState(false); + + const [autocompleteQuery, setAutocompleteQuery] = + useState>(); + + 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(plainText, customHtml || plainText); + }, [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; + } + }, [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); + }; + + return ( + + + {autocompleteQuery?.prefix === AutocompletePrefix.Emoticon && ( + + )} + + + + : undefined + } + > + {isSaving ? 'Saving' : 'Save'} + + + + setToolbar(!toolbar)} + > + + + + {(anchor: RectCords | undefined, setAnchor) => ( + + setAnchor((v) => { + if (v) { + if (!mobileOrTablet()) ReactEditor.focus(editor); + return undefined; + } + return v; + }) + } + /> + } + > + setAnchor(evt.currentTarget.getBoundingClientRect())} + > + + + + )} + + + + {toolbar && ( + + + + + )} + + } + /> + + + ); +} diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index f9e2b81d..0395a791 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -354,7 +354,16 @@ export const RoomInput = forwardRef( }, [setSelectedFiles] ); - + const setDesc = useCallback( + (fileItem: TUploadItem, body: string, formatted_body: string) => { + setSelectedFiles({ + type: 'REPLACE', + item: fileItem, + replacement: { ...fileItem, body, formatted_body }, + }); + }, + [setSelectedFiles] + ); const handleRemoveUpload = useCallback( (upload: TUploadContent | TUploadContent[]) => { const uploads = Array.isArray(upload) ? upload : [upload]; @@ -377,7 +386,8 @@ export const RoomInput = forwardRef( }; 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'); @@ -397,7 +407,7 @@ export const RoomInput = forwardRef( 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); } @@ -530,7 +540,6 @@ export const RoomInput = forwardRef( setReplyDraft(undefined); sendTypingStatus(false); }; - if (scheduledTime) { try { const delayMs = computeDelayMs(scheduledTime); @@ -707,6 +716,7 @@ export const RoomInput = forwardRef( fileItem={fileItem} setMetadata={handleFileMetadata} onRemove={handleRemoveUpload} + setDesc={setDesc} /> ))} diff --git a/src/app/features/room/msgContent.ts b/src/app/features/room/msgContent.ts index fa3b94cb..3ecc0771 100644 --- a/src/app/features/room/msgContent.ts +++ b/src/app/features/room/msgContent.ts @@ -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,6 +79,11 @@ export const getImageMsgContent = async ( } else { content.url = mxc; } + 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; }; @@ -94,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) { @@ -126,6 +135,11 @@ export const getVideoMsgContent = async ( } else { content.url = mxc; } + 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; }; @@ -135,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, @@ -148,6 +164,11 @@ export const getAudioMsgContent = (item: TUploadItem, mxc: string): IContent => } else { content.url = mxc; } + 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; }; @@ -155,8 +176,10 @@ export const getFileMsgContent = (item: TUploadItem, mxc: string): IContent => { const { file, encInfo } = item; const content: IContent = { msgtype: MsgType.File, - body: file.name, filename: file.name, + body: file.name, + format: 'org.matrix.custom.html', + formatted_body: file.name, info: { mimetype: file.type, size: file.size, @@ -170,5 +193,10 @@ export const getFileMsgContent = (item: TUploadItem, mxc: string): IContent => { } else { content.url = mxc; } + 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; }; diff --git a/src/app/state/room/roomInputDrafts.ts b/src/app/state/room/roomInputDrafts.ts index f5cdd84a..51c3cfaf 100644 --- a/src/app/state/room/roomInputDrafts.ts +++ b/src/app/state/room/roomInputDrafts.ts @@ -16,6 +16,9 @@ export type TUploadItem = { originalFile: TUploadContent; metadata: TUploadMetadata; encInfo: EncryptedAttachmentInfo | undefined; + body?: string; + format?: string; + formatted_body?: string; }; export type TUploadListAtom = ReturnType>;