Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat: images in emails (#789)

Peter Chinman40d7639c232b
diff --git a/js/app/packages/block-email/component/BaseInput.tsx b/js/app/packages/block-email/component/BaseInput.tsx
index 83b7645f49..a67c0752cc 100644
--- a/js/app/packages/block-email/component/BaseInput.tsx
+++ b/js/app/packages/block-email/component/BaseInput.tsx
@@ -6,16 +6,21 @@ import { useBlockId } from '@core/block';
import { BrightJoins } from '@core/component/BrightJoins';
import { FileDropOverlay } from '@core/component/FileDropOverlay';
import { MarkdownTextarea } from '@core/component/LexicalMarkdown/component/core/MarkdownTextarea';
-import type { UserMentionRecord } from '@core/component/LexicalMarkdown/component/menu/MentionsMenu';
+import {
+ createFilesReadyHandler,
+ getDragDropPosition,
+} from '@core/component/LexicalMarkdown/utils/fileUploadUtils';
+import type { UserMentionRecord } from '@core/component/LexicalMarkdown/utils/mentionsUtils';
import { DropdownMenuContent, MenuItem } from '@core/component/Menu';
import { RecipientSelector } from '@core/component/RecipientSelector';
import { toast } from '@core/component/Toast/Toast';
import { Tooltip } from '@core/component/Tooltip';
-import { fileDrop } from '@core/directive/fileDrop';
+import { fileFolderDrop } from '@core/directive/fileFolderDrop';
import { TOKENS } from '@core/hotkey/tokens';
import { isMobileWidth } from '@core/mobile/mobileWidth';
import { trackMention } from '@core/signal/mention';
import { useDisplayName } from '@core/user';
+import { handleFileFolderDrop } from '@core/util/upload';
import ArrowUp from '@icon/bold/arrow-up-bold.svg';
import Spinner from '@icon/bold/spinner-gap-bold.svg';
import ReplyAll from '@icon/regular/arrow-bend-double-up-left.svg';
@@ -75,7 +80,6 @@ import {
} from 'solid-js';
import { createStore } from 'solid-js/store';
import { deleteEmailDraft, saveEmailDraft } from '../signal/emailDraft';
-import { handleFileUpload } from '../util/handleFileUpload';
import { makeAttachmentPublic } from '../util/makeAttachmentPublic';
import { getFirstName } from '../util/name';
import {
@@ -92,7 +96,7 @@ import { AttachMenu } from './AttachMenu';
import { type EmailRecipient, useEmailContext } from './EmailContext';
import { getOrInitEmailFormContext } from './EmailFormContext';
-false && fileDrop;
+false && fileFolderDrop;
const getRecipientDisplayName = (item: EmailRecipient): string => {
switch (item.kind) {
@@ -814,18 +818,30 @@ export function BaseInput(props: {
onclick={() => {
editor()?.focus();
}}
- use:fileDrop={{
+ use:fileFolderDrop={{
onDragStart: () => setIsDragging(true),
onDragEnd: () => setIsDragging(false),
- onDrop: async (files) => {
- handleFileUpload(files, setIsPendingUpload, (items) => {
- setIsDragging(false);
- appendItemsAsMacroMentions(editor(), items);
- items.forEach((item) => {
- makeAttachmentPublic(item.documentId);
- });
- scheduleDraftSave();
- });
+ onDrop: (fileEntries, folderEntries, e) => {
+ const editor_ = editor();
+ if (!editor_ || !e) return;
+ handleFileFolderDrop(
+ fileEntries,
+ folderEntries,
+ createFilesReadyHandler(
+ editor_,
+ blockId,
+ 'email',
+ () => getDragDropPosition(editor_, e, true),
+ (uploadedItemIds) => {
+ setIsDragging(false);
+ uploadedItemIds.forEach((itemId) => {
+ makeAttachmentPublic(itemId);
+ });
+ scheduleDraftSave();
+ },
+ { width: 542, height: 542 }
+ )
+ );
},
}}
>
@@ -848,12 +864,34 @@ export function BaseInput(props: {
onChange={handleChange}
onDocumentMention={(item) => {
makeAttachmentPublic(item.id);
+ scheduleDraftSave();
}}
onUserMention={handleUserMention}
portalScope="local"
formatState={formatState}
setFormatState={setFormatState}
domRef={props.markdownDomRef}
+ onPasteFilesAndDirs={(files, directories) => {
+ const editor_ = editor();
+ if (!editor_) return;
+ handleFileFolderDrop(
+ files,
+ directories,
+ createFilesReadyHandler(
+ editor_,
+ blockId,
+ 'email',
+ undefined,
+ (uploadedItemIds) => {
+ uploadedItemIds.forEach((itemId) => {
+ makeAttachmentPublic(itemId);
+ });
+ scheduleDraftSave();
+ },
+ { width: 542, height: 542 }
+ )
+ );
+ }}
/>
</div>
<div class="flex flex-row w-full h-8 justify-between items-center py-2 px-2 mb-2 space-x-2 allow-css-brackets">
diff --git a/js/app/packages/block-email/component/ComposeEmailInput.tsx b/js/app/packages/block-email/component/ComposeEmailInput.tsx
index 5166b7caf4..d886d0f442 100644
--- a/js/app/packages/block-email/component/ComposeEmailInput.tsx
+++ b/js/app/packages/block-email/component/ComposeEmailInput.tsx
@@ -6,7 +6,12 @@ import { useHasPaidAccess } from '@core/auth';
import { DeprecatedIconButton } from '@core/component/DeprecatedIconButton';
import { FileDropOverlay } from '@core/component/FileDropOverlay';
import { MarkdownTextarea } from '@core/component/LexicalMarkdown/component/core/MarkdownTextarea';
-import { fileDrop } from '@core/directive/fileDrop';
+import {
+ createFilesReadyHandler,
+ getDragDropPosition,
+} from '@core/component/LexicalMarkdown/utils/fileUploadUtils';
+import { fileFolderDrop } from '@core/directive/fileFolderDrop';
+import { handleFileFolderDrop } from '@core/util/upload';
import TextAa from '@icon/regular/text-aa.svg';
import {
$appendWatermarkNodeToLast,
@@ -31,7 +36,6 @@ import {
} from 'lexical';
import { createSignal, onMount, Show } from 'solid-js';
import { type FocusableElement, tabbable } from 'tabbable';
-import { handleFileUpload } from '../util/handleFileUpload';
import { makeAttachmentPublic } from '../util/makeAttachmentPublic';
import {
appendItemsAsMacroMentions,
@@ -39,7 +43,7 @@ import {
} from '../util/prepareEmailBody';
import { AttachMenu } from './AttachMenu';
-false && fileDrop;
+false && fileFolderDrop;
export type ComposeInputData = {
body: {
@@ -109,13 +113,10 @@ export function ComposeEmailInput(props: ComposeEmailInputProps) {
}
function onAttachDocuments(items: DocumentMentionInfo[]) {
- console.log('ComposeEmailInput: onAttachDocuments called with', items);
- console.log('ComposeEmailInput: Current editor state:', editor());
appendItemsAsMacroMentions(editor(), items);
items.forEach((item) => {
makeAttachmentPublic(item.documentId);
});
- console.log('ComposeEmailInput: Document attachments processed');
}
// Set up hotkey scope for the compose message component
@@ -196,17 +197,30 @@ export function ComposeEmailInput(props: ComposeEmailInputProps) {
onclick={() => {
editor()?.focus();
}}
- use:fileDrop={{
+ use:fileFolderDrop={{
onDragStart: () => setIsDragging(true),
onDragEnd: () => setIsDragging(false),
- onDrop: async (files) => {
- handleFileUpload(files, setIsPendingUpload, (items) => {
- setIsDragging(false);
- appendItemsAsMacroMentions(editor(), items);
- items.forEach((item) => {
- makeAttachmentPublic(item.documentId);
- });
- });
+ onDrop: (fileEntries, folderEntries, e) => {
+ const editor_ = editor();
+ if (!editor_ || !e) return;
+ handleFileFolderDrop(
+ fileEntries,
+ folderEntries,
+ createFilesReadyHandler(
+ editor_,
+ undefined,
+ undefined,
+ () => getDragDropPosition(editor_, e, true),
+ (uploadedItemIds) => {
+ setIsDragging(false);
+ uploadedItemIds.forEach((itemId) => {
+ makeAttachmentPublic(itemId);
+ });
+ // TODO: schedule draft save, when implemented
+ },
+ { width: 542, height: 542 }
+ )
+ );
},
}}
>
@@ -230,6 +244,26 @@ export function ComposeEmailInput(props: ComposeEmailInputProps) {
focusSibling('next');
}}
portalScope="local"
+ onPasteFilesAndDirs={(files, directories) => {
+ const editor_ = editor();
+ if (!editor_) return;
+ handleFileFolderDrop(
+ files,
+ directories,
+ createFilesReadyHandler(
+ editor_,
+ undefined,
+ undefined,
+ undefined,
+ (uploadedItemIds) => {
+ uploadedItemIds.forEach((itemId) => {
+ makeAttachmentPublic(itemId);
+ });
+ },
+ { width: 542, height: 542 }
+ )
+ );
+ }}
/>
</div>
</div>
diff --git a/js/app/packages/block-email/component/MessageList.tsx b/js/app/packages/block-email/component/MessageList.tsx
index acbca80526..78533f0a2f 100644
--- a/js/app/packages/block-email/component/MessageList.tsx
+++ b/js/app/packages/block-email/component/MessageList.tsx
@@ -1,6 +1,7 @@
import { useEmailContext } from '@block-email/component/EmailContext';
import { isScrollingToMessage } from '@block-email/signal/scrollState';
import { CircleSpinner } from '@core/component/CircleSpinner';
+import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
import { createMemo, createSelector, For, Show } from 'solid-js';
import { createStore } from 'solid-js/store';
import { MessageContainer } from './MessageContainer';
@@ -52,46 +53,49 @@ export function MessageList(props: MessageListProps) {
}
}}
>
- <For each={context.messages.list().toReversed()}>
- {(message, index) => {
- // We need the index as if the list was not reversed
- const normalizedIndex = createMemo(() => {
- const listLength = context.messages.list().length;
+ <StaticMarkdownContext>
+ <For each={context.messages.list().toReversed()}>
+ {(message, index) => {
+ // We need the index as if the list was not reversed
+ const normalizedIndex = createMemo(() => {
+ const listLength = context.messages.list().length;
- const normalized = listLength - 1 - index();
+ const normalized = listLength - 1 - index();
- // The element at the 0th index isn't actually the first message
- // if there is more data to load so we return -1 so that `isFirstMessage`
- // evaluates to false. This fixes an issue with the "first" message' full
- // html to show in `EmailMessageBody`
- if (normalized === 0 && context.query.hasMore()) {
- return -1;
- }
+ // The element at the 0th index isn't actually the first message
+ // if there is more data to load so we return -1 so that `isFirstMessage`
+ // evaluates to false. This fixes an issue with the "first" message' full
+ // html to show in `EmailMessageBody`
+ if (normalized === 0 && context.query.hasMore()) {
+ return -1;
+ }
- return normalized;
- });
+ return normalized;
+ });
- return (
- <MessageContainer
- isFirstMessage={normalizedIndex() === 0}
- isLastMessage={
- normalizedIndex() === (context.messages.list().length ?? 0) - 1
- }
- isFocused={isFocusedSelector(message.db_id ?? undefined)}
- isTarget={isTargetSelector(message.db_id ?? undefined)}
- message={message}
- expandedMessageBodyIds={expandedMessageBodyIds}
- setExpandedMessageBodyIds={setExpandedMessageBodyIds}
- />
- );
- }}
- </For>
+ return (
+ <MessageContainer
+ isFirstMessage={normalizedIndex() === 0}
+ isLastMessage={
+ normalizedIndex() ===
+ (context.messages.list().length ?? 0) - 1
+ }
+ isFocused={isFocusedSelector(message.db_id ?? undefined)}
+ isTarget={isTargetSelector(message.db_id ?? undefined)}
+ message={message}
+ expandedMessageBodyIds={expandedMessageBodyIds}
+ setExpandedMessageBodyIds={setExpandedMessageBodyIds}
+ />
+ );
+ }}
+ </For>
- <Show when={context.query.isFetching()}>
- <div class="flex items-center justify-center h-16">
- <CircleSpinner />
- </div>
- </Show>
+ <Show when={context.query.isFetching()}>
+ <div class="flex items-center justify-center h-16">
+ <CircleSpinner />
+ </div>
+ </Show>
+ </StaticMarkdownContext>
</div>
);
}
diff --git a/js/app/packages/block-email/tsconfig.json b/js/app/packages/block-email/tsconfig.json
new file mode 100644
index 0000000000..1356b3adde
--- /dev/null
+++ b/js/app/packages/block-email/tsconfig.json
@@ -0,0 +1,12 @@
+{
+ "extends": "../../tsconfig.json",
+ "compilerOptions": {
+ "jsx": "preserve",
+ "jsxImportSource": "solid-js",
+ "verbatimModuleSyntax": true,
+ "declaration": true,
+ "composite": true,
+ "moduleResolution": "bundler"
+ }
+}
+
diff --git a/js/app/packages/block-md/component/MarkdownEditor.tsx b/js/app/packages/block-md/component/MarkdownEditor.tsx
index c23b8d9dcd..691b809eb8 100644
--- a/js/app/packages/block-md/component/MarkdownEditor.tsx
+++ b/js/app/packages/block-md/component/MarkdownEditor.tsx
@@ -38,7 +38,6 @@ import {
} from '@core/component/LexicalMarkdown/context/LexicalWrapperContext';
import {
CLOSE_INLINE_SEARCH_COMMAND,
- calculateInsertPoint,
createDragInsertStore,
createWordcountStatsStore,
DefaultShortcuts,
@@ -52,7 +51,6 @@ import {
markdownPastePlugin,
mentionsPlugin,
pinnedPropertiesPlugin,
- SET_SELECTION_AT_INSERTION,
selectionDataPlugin,
tabIndentationPlugin,
tableActionMenuPlugin,
@@ -79,7 +77,6 @@ import {
parsePersistentLocation,
} from '@core/component/LexicalMarkdown/plugins/location';
import {
- addMediaFromFile,
INSERT_MEDIA_COMMAND,
mediaPlugin,
} from '@core/component/LexicalMarkdown/plugins/media';
@@ -96,12 +93,13 @@ import {
initializeEditorWithState,
setEditorStateFromMarkdown,
} from '@core/component/LexicalMarkdown/utils';
+import {
+ createFilesReadyHandler,
+ getDragDropPosition,
+} from '@core/component/LexicalMarkdown/utils/fileUploadUtils';
import { ScopedPortal } from '@core/component/ScopedPortal';
import { toast } from '@core/component/Toast/Toast';
-import {
- blockNameToFileExtensions,
- fileTypeToBlockName,
-} from '@core/constant/allBlocks';
+import { fileTypeToBlockName } from '@core/constant/allBlocks';
import {
ENABLE_MARKDOWN_COMMENTS,
ENABLE_MARKDOWN_DIFF,
@@ -109,7 +107,6 @@ import {
LOCAL_ONLY,
} from '@core/constant/featureFlags';
import { fileFolderDrop } from '@core/directive/fileFolderDrop';
-import { HEIC_EXTENSIONS } from '@core/heic/constants';
import { blockElementSignal } from '@core/signal/blockElement';
import {
blockFileSignal,
@@ -122,13 +119,7 @@ import { useCanComment, useCanEdit } from '@core/signal/permissions';
import { useBlockDocumentName } from '@core/util/currentBlockDocumentName';
import { isSourceDSS, isSourceSyncService } from '@core/util/source';
import { bufToString } from '@core/util/string';
-import {
- forceDssRuleset,
- handleFileFolderDrop,
- isFileUploadEntry,
- type UploadInput,
- uploadFiles,
-} from '@core/util/upload';
+import { handleFileFolderDrop } from '@core/util/upload';
import WarningIcon from '@icon/regular/warning.svg';
import {
$createDocumentMentionNode,
@@ -139,8 +130,6 @@ import {
type PeerIdValidator,
peerIdPlugin,
} from '@lexical-core';
-import { waitBulkUploadStatus } from '@service-connection/bulkUpload';
-import { fileExtension } from '@service-storage/util/filename';
import { onElementConnect } from '@solid-primitives/lifecycle';
import { createCallback } from '@solid-primitives/rootless';
import { debounce, throttle } from '@solid-primitives/scheduled';
@@ -153,12 +142,7 @@ import {
registerInternalLayoutShiftListener,
} from 'core/component/LexicalMarkdown/plugins/shared/utils';
import { createMethodRegistration } from 'core/orchestrator';
-import {
- $getRoot,
- $getSelection,
- $isElementNode,
- type EditorState,
-} from 'lexical';
+import { $getRoot, $isElementNode, type EditorState } from 'lexical';
import {
type Accessor,
createEffect,
@@ -191,8 +175,6 @@ const DEBUG = LOCAL_ONLY;
// once the editor has at least one full page of content.
const EDITOR_PADDING_BOTTOM = 200;
-const DRAG_EVENT_PADDING = 8;
-
export function MarkdownEditor(props: { autoFocusOnMount?: boolean } = {}) {
const blockData = blockDataSignal.get;
const blockId = useBlockId();
@@ -210,12 +192,6 @@ export function MarkdownEditor(props: { autoFocusOnMount?: boolean } = {}) {
const [findAndReplaceStore, setFindAndReplaceStore] = FindAndReplaceStore;
const docSource = blockSourceSignal.get;
- const IMAGE_EXTENSIONS_HEIC = [
- ...blockNameToFileExtensions.image,
- ...HEIC_EXTENSIONS,
- ];
- const VIDEO_EXTENSIONS = blockNameToFileExtensions.video;
-
const blockHandle = blockHandleSignal.get;
createMethodRegistration(blockHandle, {
goToLocationFromParams: (params: Record<string, any>) => {
@@ -295,153 +271,6 @@ export function MarkdownEditor(props: { autoFocusOnMount?: boolean } = {}) {
const emojiMenuOperations = createMenuOperations();
const actionsMenuOperations = createMenuOperations();
- const getDragDropPosition = (
- e: DragEvent | { clientX: number; clientY: number },
- setSelection = false
- ) => {
- const { key, position } = calculateInsertPoint(
- editor,
- e,
- DRAG_EVENT_PADDING
- );
- if (setSelection && key !== null && position !== null) {
- editor.dispatchCommand(SET_SELECTION_AT_INSERTION, [key, position]);
- }
- return { key, position };
- };
-
- async function processInlineMediaFiles(files: File[]) {
- let success = false;
- for (const file of files) {
- const ext = fileExtension(file.name);
- if (ext != null && IMAGE_EXTENSIONS_HEIC.includes(ext)) {
- const res = await addMediaFromFile(editor, file, 'image');
- success = success && res.success;
- } else if (ext != null && VIDEO_EXTENSIONS.includes(ext)) {
- const res = await addMediaFromFile(editor, file, 'video');
- success = success && res.success;
- }
- }
- return success;
- }
-
- async function insertMention(
- documentId: string,
- documentName: string,
- blockName: string,
- position?: ReturnType<typeof getDragDropPosition>
- ) {
- const mentionId = await trackMention(blockId, 'document', documentId);
- editor.update(() => {
- const mention = $createDocumentMentionNode({
- documentId,
- documentName,
- blockName: blockName,
- mentionUuid: mentionId,
- });
- if (position && position.key) {
- if (position.position === 'before') {
- $insertWrappedBefore(position.key, mention);
- } else {
- $insertWrappedAfter(position.key, mention);
- }
- } else {
- $getSelection()?.insertNodes([mention]);
- }
- mention.selectEnd();
- });
- }
-
- async function handleUploadEntriesForEditor(
- uploadEntries: UploadInput[],
- position?: ReturnType<typeof getDragDropPosition>
- ): Promise<void> {
- const mediaFiles: File[] = [];
- const filesToUpload: UploadInput[] = [];
-
- for (const entry of uploadEntries) {
- if (isFileUploadEntry(entry) && entry.isFolder) {
- filesToUpload.push(entry);
- } else {
- const file = isFileUploadEntry(entry) ? entry.file : entry;
- const ext = fileExtension(file.name);
- if (
- ext != null &&
- (IMAGE_EXTENSIONS_HEIC.includes(ext) ||
- VIDEO_EXTENSIONS.includes(ext))
- ) {
- mediaFiles.push(file);
- } else {
- filesToUpload.push(entry);
- }
- }
- }
-
- const processInlineMediaFilesSuccess =
- await processInlineMediaFiles(mediaFiles);
-
- // exit early if we can't process media files
- if (!processInlineMediaFilesSuccess) {
- toast.failure('Invalid media attachment file(s)');
- return;
- }
-
- if (filesToUpload.length === 0) {
- return;
- }
-
- const results = await uploadFiles(filesToUpload, forceDssRuleset);
-
- const failedUploads: string[] = [];
- const failedFolders: string[] = [];
-
- for (const result of results) {
- if (result.failed) {
- failedUploads.push(result.name);
- continue;
- }
-
- if (result.destination !== 'dss') {
- continue;
- }
-
- if (result.type === 'document') {
- const blockName = fileTypeToBlockName(result.fileType, true);
- if (blockName) {
- await insertMention(
- result.documentId,
- result.name,
- blockName,
- position
- );
- }
- } else if (result.type === 'folder') {
- const projectId = await waitBulkUploadStatus(result.requestId);
- if (projectId) {
- await insertMention(projectId, result.name, 'project', position);
- } else {
- failedFolders.push(result.name);
- }
- }
- }
-
- // Aggregate and show failure toasts
- if (failedUploads.length > 0 || failedFolders.length > 0) {
- const failures: string[] = [];
- if (failedUploads.length > 0) {
- failures.push(
- `${failedUploads.length} file${failedUploads.length > 1 ? 's' : ''} failed to upload`
- );
- }
- if (failedFolders.length > 0) {
- failures.push(
- `${failedFolders.length} folder${failedFolders.length > 1 ? 's' : ''} failed to upload`
- );
- }
- toast.failure(failures.join('. '));
- }
- }
-
// store for the drag insert pluign.
const [dragInsertStore, setDragInsertStore] = createDragInsertStore();
@@ -484,7 +313,7 @@ export function MarkdownEditor(props: { autoFocusOnMount?: boolean } = {}) {
const res = wrapDndEvent(event);
if (!res) return;
- const { key, position } = getDragDropPosition(res.mousePos, true);
+ const { key, position } = getDragDropPosition(editor, res.mousePos, true);
if (res.blockName === 'image' || res.blockName === 'video') {
editor.dispatchCommand(INSERT_MEDIA_COMMAND, {
@@ -524,7 +353,7 @@ export function MarkdownEditor(props: { autoFocusOnMount?: boolean } = {}) {
const res = wrapDndEvent(event);
if (!res) return;
const { mousePos } = res;
- const { key, position } = getDragDropPosition(mousePos, false);
+ const { key, position } = getDragDropPosition(editor, mousePos, false);
if (key !== null && position !== null) {
setDragInsertStore({ nodeKey: key, position, visible: true });
}
@@ -686,7 +515,7 @@ export function MarkdownEditor(props: { autoFocusOnMount?: boolean } = {}) {
handleFileFolderDrop(
fileEntries,
directories,
- handleUploadEntriesForEditor
+ createFilesReadyHandler(editor, blockId)
),
})
)
@@ -1014,10 +843,14 @@ export function MarkdownEditor(props: { autoFocusOnMount?: boolean } = {}) {
ref={editorContainerRef}
use:fileFolderDrop={{
onDrop: (fileEntries, folderEntries, e) => {
- handleFileFolderDrop(fileEntries, folderEntries, (entries) => {
- const position = e ? getDragDropPosition(e, true) : undefined;
- handleUploadEntriesForEditor(entries, position);
- });
+ if (!e) return;
+ handleFileFolderDrop(
+ fileEntries,
+ folderEntries,
+ createFilesReadyHandler(editor, blockId, 'md', () =>
+ getDragDropPosition(editor, e, true)
+ )
+ );
},
}}
use:droppable
diff --git a/js/app/packages/core/collab/comments/Thread.tsx b/js/app/packages/core/collab/comments/Thread.tsx
index 6c83417a35..bbe1de2179 100644
--- a/js/app/packages/core/collab/comments/Thread.tsx
+++ b/js/app/packages/core/collab/comments/Thread.tsx
@@ -1,7 +1,7 @@
import { BozzyBracketInnerSibling } from '@core/component/BozzyBracket';
import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
-import type { UserMentionRecord } from '@core/component/LexicalMarkdown/component/menu/MentionsMenu';
import { createTheme } from '@core/component/LexicalMarkdown/theme';
+import type { UserMentionRecord } from '@core/component/LexicalMarkdown/utils/mentionsUtils';
import type { DocumentMentionLocation } from '@service-notification/client';
import { storageServiceClient } from '@service-storage/client';
import type { EditorThemeClasses } from 'lexical';
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx b/js/app/packages/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx
index 29d2e51e63..659b84c17c 100644
--- a/js/app/packages/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx
+++ b/js/app/packages/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx
@@ -31,8 +31,10 @@ import {
createAccessoryStore,
customSelectionDataPlugin,
emojisPlugin,
+ filePastePlugin,
type ItemMention,
keyboardFocusPlugin,
+ mediaPlugin,
mentionsPlugin,
type SelectionData,
selectionDataPlugin,
@@ -46,9 +48,10 @@ import {
setEditorStateFromHtml,
setEditorStateFromMarkdown,
} from '../../utils';
+import type { UserMentionRecord } from '../../utils/mentionsUtils';
import { EmojiMenu } from '../menu/EmojiMenu';
import { FloatingLinkMenu } from '../menu/FloatingLinkMenu';
-import { MentionsMenu, type UserMentionRecord } from '../menu/MentionsMenu';
+import { MentionsMenu } from '../menu/MentionsMenu';
import { DecoratorRenderer } from './DecoratorRenderer';
import { NodeAccessoryRenderer } from './NodeAccessoryRenderer';
@@ -90,6 +93,10 @@ export interface MarkdownTextareaProps {
formatState?: SelectionData;
setFormatState?: SetStoreFunction<SelectionData>;
domRef?: (ref: HTMLDivElement) => void | HTMLDivElement;
+ onPasteFilesAndDirs?: (
+ files: FileSystemFileEntry[],
+ directories: FileSystemDirectoryEntry[]
+ ) => void;
}
export function MarkdownTextarea(props: MarkdownTextareaProps) {
@@ -173,6 +180,7 @@ export function MarkdownTextarea(props: MarkdownTextareaProps) {
.state<string>(setMarkdownState, 'markdown')
.history(400)
.use(restoreFocusPlugin())
+ .use(mediaPlugin())
.use(
props.formatState && props.setFormatState
? customSelectionDataPlugin(
@@ -191,6 +199,14 @@ export function MarkdownTextarea(props: MarkdownTextareaProps) {
)
.use(emojisPlugin({ menu: emojisMenuOperations }));
+ if (props.onPasteFilesAndDirs) {
+ plugins.use(
+ filePastePlugin({
+ onPasteFilesAndDirs: props.onPasteFilesAndDirs,
+ })
+ );
+ }
+
const [accessoryStore, setAccessoryStore] = createAccessoryStore();
plugins.use(
codePlugin({
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx b/js/app/packages/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx
index e7719252c1..0976fee23e 100644
--- a/js/app/packages/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx
+++ b/js/app/packages/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx
@@ -18,10 +18,12 @@ import {
type DocumentMentionNode,
type EquationNode,
type HorizontalRuleNode,
+ type ImageNode,
isSupportedLanguage,
normalizedLanguage,
SupportedNodeTypes,
type UserMentionNode,
+ type VideoNode,
type WatermarkNode,
} from '@lexical-core';
import {
@@ -61,6 +63,8 @@ import { ContactMention as ContactMentionDecorator } from '../decorator/ContactM
import { DateMention as DateMentionDecorator } from '../decorator/DateMention';
import { DocumentMention as DocumentMentionDecorator } from '../decorator/DocumentMention';
import { Equation as EquationDecorator } from '../decorator/Equation';
+import { MarkdownImage as ImageDecorator } from '../decorator/MarkdownImage';
+import { MarkdownVideo as VideoDecorator } from '../decorator/MarkdownVideo';
import { UserMention as UserMentionDecorator } from '../decorator/UserMention';
import { Watermark as WatermarkDecorator } from '../decorator/Watermark';
import { LinkWithPreview } from './LinkWithPreview';
@@ -306,6 +310,16 @@ const DateMention: RenderableEntity<DateMentionNode> = {
),
};
+const Image: RenderableEntity<ImageNode> = {
+ guard: (node: LexicalNode): node is ImageNode => node.__type === 'image',
+ render: (props) => ImageDecorator(props.node.exportComponentProps()),
+};
+
+const Video: RenderableEntity<VideoNode> = {
+ guard: (node: LexicalNode): node is VideoNode => node.__type === 'video',
+ render: (props) => VideoDecorator(props.node.exportComponentProps()),
+};
+
const Paragraph: RenderableElement<ParagraphNode> = {
guard: (node: LexicalNode): node is ParagraphNode =>
node.__type === 'paragraph',
@@ -582,6 +596,8 @@ const InlineEntities: Array<RenderableEntity> = [
DocumentMention,
ContactMention,
DateMention,
+ Image,
+ Video,
HorizontalRule,
Equation,
Watermark,
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/decorator/MarkdownImage.tsx b/js/app/packages/core/component/LexicalMarkdown/component/decorator/MarkdownImage.tsx
index 21ed1a2552..6f0c4d3b14 100644
--- a/js/app/packages/core/component/LexicalMarkdown/component/decorator/MarkdownImage.tsx
+++ b/js/app/packages/core/component/LexicalMarkdown/component/decorator/MarkdownImage.tsx
@@ -8,6 +8,7 @@ import XIcon from '@icon/regular/x.svg';
import { Dialog } from '@kobalte/core/dialog';
import { mergeRegister } from '@lexical/utils';
import { $isImageNode, type ImageDecoratorProps } from '@lexical-core';
+import { calculateEffectiveDimensions } from '@lexical-core/utils/media';
import { debounce } from '@solid-primitives/scheduled';
import {
$createNodeSelection,
@@ -18,6 +19,7 @@ import {
} from 'lexical';
import {
createEffect,
+ createMemo,
createSignal,
onCleanup,
onMount,
@@ -77,6 +79,17 @@ export function MarkdownImage(props: ImageDecoratorProps) {
const [scale, setScale] = createSignal(props.scale);
+ // Calculate effective dimensions from props
+ const effectiveDims = createMemo(() => {
+ const dims = calculateEffectiveDimensions(
+ imageDims()[0],
+ imageDims()[1],
+ props.constrainedWidth,
+ props.constrainedHeight
+ );
+ return [dims.width, dims.height] as [number, number];
+ });
+
createEffect(() => {
if (props.srcType === 'local') {
setImageUrl(props.url);
@@ -248,16 +261,18 @@ export function MarkdownImage(props: ImageDecoratorProps) {
<Dialog open={viewerOpen()} onOpenChange={setViewerOpen}>
<div
ref={containerRef}
- class="relative max-w-full my-4 grid place-items-center mx-auto"
+ class="relative max-w-full my-4 grid place-items-center"
classList={{
'bracket-offset-4 bracket': isSelectedAsNode(),
'media-error min-h-44': state() === 'error',
+ // If there are no constrained dimensions, center the image
+ 'mx-auto': !props.constrainedWidth && !props.constrainedHeight,
}}
style={{
- 'max-height': `${imageDims() ? imageDims()[1] * scale() : 640}px`,
+ 'max-width': `${effectiveDims()[0] ? effectiveDims()[0] * scale() : 640}px`,
'aspect-ratio':
- imageDims()[0] && imageDims()[1]
- ? `${imageDims()[0] / imageDims()[1]}`
+ effectiveDims()[0] && effectiveDims()[1]
+ ? `${effectiveDims()[0] / effectiveDims()[1]}`
: 'auto',
}}
onClick={(e: MouseEvent) => {
@@ -276,7 +291,14 @@ export function MarkdownImage(props: ImageDecoratorProps) {
setImageHover(false);
}}
>
- <Show when={state() === 'ok' && editor()?.isEditable()}>
+ <Show
+ when={
+ state() === 'ok' &&
+ editor()?.isEditable() &&
+ !props.constrainedWidth &&
+ !props.constrainedHeight
+ }
+ >
<ResizeHandle
scale={scale}
setScale={setScale}
@@ -302,7 +324,9 @@ export function MarkdownImage(props: ImageDecoratorProps) {
ref={imageRef}
src={imageUrl()}
style={{
- width: `${imageDims()[0] ? imageDims()[0] * scale() : 'auto'}px`,
+ width: effectiveDims()[0]
+ ? `${effectiveDims()[0] * scale()}px`
+ : 'auto',
}}
/>
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu.tsx b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu.tsx
index 8ac0f03742..8176c6847a 100644
--- a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu.tsx
+++ b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu.tsx
@@ -1,5 +1,4 @@
import {
- type BlockAlias,
type BlockName,
useMaybeBlockId,
useMaybeBlockName,
@@ -10,16 +9,14 @@ import { useChannelsContext } from '@core/component/ChannelsProvider';
import { EntityIcon } from '@core/component/EntityIcon';
import { type PortalScope, ScopedPortal } from '@core/component/ScopedPortal';
import { UserIcon } from '@core/component/UserIcon';
-import { fileTypeToBlockName } from '@core/constant/allBlocks';
import { ENABLE_CHAT_CHANNEL_ATTACHMENT } from '@core/constant/featureFlags';
import clickOutside from '@core/directive/clickOutside';
-import { trackMention } from '@core/signal/mention';
import {
type ChannelWithParticipants,
type IUser,
useContacts,
} from '@core/user';
-import { getDateSuggestions, type ParsedDate } from '@core/util/dateParser';
+import { getDateSuggestions } from '@core/util/dateParser';
import { createFreshSearch } from '@core/util/freshSort';
import ClockIcon from '@icon/regular/clock.svg';
import EmailIcon from '@icon/regular/envelope.svg';
@@ -29,9 +26,7 @@ import {
type EmailEntity,
useEmails,
} from '@macro-entity';
-import type { DocumentMentionMetadata } from '@service-notification/client';
import type { PaginatedSearchArgs } from '@service-search/client';
-import { storageServiceClient } from '@service-storage/client';
import type { Item } from '@service-storage/generated/schemas/item';
import { useHistory } from '@service-storage/history';
import { debounce } from '@solid-primitives/scheduled';
@@ -51,17 +46,28 @@ import {
Show,
untrack,
} from 'solid-js';
-import { v7 } from 'uuid';
import { floatWithElement } from '../../directive/floatWithElement';
import { floatWithSelection } from '../../directive/floatWithSelection';
import {
CLOSE_INLINE_SEARCH_COMMAND,
- INSERT_DATE_MENTION_COMMAND,
- INSERT_DOCUMENT_MENTION_COMMAND,
- INSERT_USER_MENTION_COMMAND,
REMOVE_INLINE_SEARCH_COMMAND,
} from '../../plugins';
import type { MenuOperations } from '../../shared/inlineMenu';
+import {
+ type CombinedEntity,
+ type Entity,
+ type EntityMap,
+ entityMapper,
+ getCombinedEntityBlockName,
+ getItemName,
+ type HandlerDependencies,
+ handleBasicMention,
+ handleChannelMention,
+ handleDateMention,
+ handleEmailMention,
+ handleUserMention,
+ type UserMentionRecord,
+} from '../../utils/mentionsUtils';
false && clickOutside;
false && floatWithSelection;
@@ -73,52 +79,6 @@ const MAX_ITEMS = 8;
/** Whether to filter sidebar non-persistent-chats */
const ONLY_REAL_CHATS = false;
-export type UserMentionRecord = {
- documentId: string;
- mentions: string[];
- metadata: DocumentMentionMetadata;
-};
-
-type DateItem = ParsedDate & {
- id: string;
-};
-
-type EntityMap = {
- item: Item;
- user: IUser;
- channel: ChannelWithParticipants;
- date: DateItem;
- email: EmailEntity;
-};
-
-type Entity<T extends keyof EntityMap> = {
- kind: T;
- id: EntityMap[T]['id'];
- data: EntityMap[T];
-};
-
-type PickEntity<K extends keyof EntityMap> = {
- [P in K]: Entity<P>;
-}[K];
-
-type CombinedEntity<K extends keyof EntityMap = keyof EntityMap> =
- PickEntity<K>;
-
-// mapper fn that converts entity data to its entity type
-type EntityMapper<K extends keyof EntityMap> = (
- data: EntityMap[K]
-) => PickEntity<K>;
-
-function entityMapper<K extends keyof EntityMap>(kind: K): EntityMapper<K> {
- return (data: EntityMap[K]) => ({ kind, data, id: data.id });
-}
-
-const getUserName = (item: IUser): string => {
- const { email, name } = item;
- if (name === email) return email;
- return `${name} | ${email}`;
-};
-
const getUserSearchText = (item: IUser): string => {
const { email, name } = item;
// Note: we return the email twice to make users with a display name
@@ -127,42 +87,6 @@ const getUserSearchText = (item: IUser): string => {
return `${name} | ${email}`;
};
-const getCombinedEntityBlockName = (
- item: CombinedEntity<'item' | 'channel' | 'email'>,
- icon?: boolean
-): BlockName | BlockAlias => {
- switch (item.kind) {
- case 'item':
- if (item.data.type === 'document')
- return fileTypeToBlockName(
- item.data.subType || item.data.fileType,
- icon
- );
- if (item.data.type === 'chat') return 'chat';
- if (item.data.type === 'project') return 'project';
- return 'unknown';
- case 'email':
- return 'email';
- case 'channel':
- return 'channel';
- }
-};
-
-const getItemName = (item: CombinedEntity): string => {
- switch (item.kind) {
- case 'item':
- return item.data.name;
- case 'user':
- return getUserName(item.data);
- case 'channel':
- return item.data.name ?? '';
- case 'email':
- return item.data.name ?? 'No Subject';
- case 'date':
- return item.data.displayFormat;
- }
-};
-
const getItemSearchText = (item: CombinedEntity): string => {
switch (item.kind) {
case 'item':
@@ -199,189 +123,6 @@ function allItemFilter(item: CombinedEntity): boolean {
return true;
}
-/**
- * These are the stateful utils needed to handle an item of a given type. I have opted
- * to implement the handlers as smaller helpers rather than 1 giant function. So these
- * dependencies have to be injected via the component.
- */
-type HandlerDependencies = {
- editor: LexicalEditor;
- blockName?: BlockName;
- blockId?: string;
- onUserMention?: (record: UserMentionRecord) => void;
- onDocumentMention?: (item: Item | ChannelWithParticipants) => void;
- disableMentionTracking?: boolean;
- onEmailMention?: (item: EmailEntity) => void;
-};
-
-/**
- * Handles user mentions by lexical inserting and potentially up-serting to the notification service.
- * @param user The user to mention.
- * @param dependencies The dependencies required to handle the user mention.
- */
-async function handleUserMention(
- user: IUser,
- dependencies: HandlerDependencies
-) {
- const { editor, blockName, blockId, onUserMention, disableMentionTracking } =
- dependencies;
- let mentionId: string | undefined;
-
- console.log({ blockName, blockId });
- if (blockName !== 'channel') {
- if (blockId) {
- const record: UserMentionRecord = {
- documentId: blockId,
- mentions: [user.id],
- metadata: {
- mention_id: v7(),
- },
- };
- if (onUserMention) {
- onUserMention(record);
- } else {
- storageServiceClient.upsertUserMentions(record);
- }
- if (!disableMentionTracking) {
- mentionId = await trackMention(blockId, 'user', user.id);
- }
- }
- }
-
- editor.dispatchCommand(INSERT_USER_MENTION_COMMAND, {
- userId: user.id,
- email: user.email,
- mentionUuid: mentionId,
- });
-}
-
-/**
- * Inserts a date mention.
- * @param date
- * @param dependencies
- */
-async function handleDateMention(
- date: DateItem,
- dependencies: HandlerDependencies
-) {
- const { editor } = dependencies;
- editor.dispatchCommand(INSERT_DATE_MENTION_COMMAND, {
- date: date.date.toISOString(),
- displayFormat: date.displayFormat,
- });
-}
-
-async function handleEmailMention(
- email: EmailEntity,
- dependencies: HandlerDependencies
-) {
- const {
- editor,
- blockName: parentBlockName,
- blockId,
- onEmailMention,
- disableMentionTracking,
- } = dependencies;
- let mentionId: string | undefined;
- if (
- blockId &&
- parentBlockName !== 'channel' &&
- parentBlockName !== 'chat' &&
- !disableMentionTracking
- ) {
- mentionId = await trackMention(blockId, 'document', email.id);
- }
- const itemName = email.name ?? 'No Subject';
-
- onEmailMention?.(email);
-
- editor.dispatchCommand(INSERT_DOCUMENT_MENTION_COMMAND, {
- documentId: email.id,
- documentName: itemName,
- blockName: 'email',
- mentionUuid: mentionId,
- });
-}
-
-/**
- * Insert a document mentions and track it.
- * @param item
- * @param dependencies
- */
-async function handleBasicMention(
- item: Item,
- dependencies: HandlerDependencies
-) {
- const {
- editor,
- blockName: parentBlockName,
- blockId,
- onDocumentMention,
- disableMentionTracking,
- } = dependencies;
- let mentionId: string | undefined;
- if (
- blockId &&
- parentBlockName !== 'channel' &&
- parentBlockName !== 'chat' &&
- !disableMentionTracking
- ) {
- mentionId = await trackMention(blockId, 'document', item.id);
- }
- const itemEntity = entityMapper('item')(item);
- const itemBlock = getCombinedEntityBlockName(itemEntity);
- const itemName = getItemName(itemEntity);
-
- onDocumentMention?.(item);
-
- editor.dispatchCommand(INSERT_DOCUMENT_MENTION_COMMAND, {
- documentId: item.id,
- documentName: itemName,
- blockName: itemBlock,
- mentionUuid: mentionId,
- });
-}
-
-/**
- * Insert a channel mention and track it.
- * @param channel
- * @param dependencies
- */
-async function handleChannelMention(
- channel: ChannelWithParticipants,
- dependencies: HandlerDependencies
-) {
- const {
- editor,
- blockName: parentBlockName,
- blockId,
- onDocumentMention,
- disableMentionTracking,
- } = dependencies;
- let mentionId: string | undefined;
- if (
- blockId &&
- parentBlockName !== 'channel' &&
- parentBlockName !== 'chat' &&
- !disableMentionTracking
- ) {
- mentionId = await trackMention(blockId, 'channel', channel.id);
- }
- const channelEntity = entityMapper('channel')(channel);
- const itemBlock = getCombinedEntityBlockName(channelEntity);
- const itemName = getItemName(channelEntity);
-
- onDocumentMention?.(channel);
-
- editor.dispatchCommand(INSERT_DOCUMENT_MENTION_COMMAND, {
- documentId: channel.id,
- documentName: itemName,
- blockName: itemBlock,
- mentionUuid: mentionId,
- channelType: channel.channel_type,
- });
-}
-
/**
* Create the universal item handler.
* @param dependencies
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/misc/MentionsTextarea.tsx b/js/app/packages/core/component/LexicalMarkdown/component/misc/MentionsTextarea.tsx
index 43ab5b375d..eabfa34080 100644
--- a/js/app/packages/core/component/LexicalMarkdown/component/misc/MentionsTextarea.tsx
+++ b/js/app/packages/core/component/LexicalMarkdown/component/misc/MentionsTextarea.tsx
@@ -31,8 +31,9 @@ import {
initializeEditorEmpty,
setEditorStateFromMarkdown,
} from '../../utils';
+import type { UserMentionRecord } from '../../utils/mentionsUtils';
import { DecoratorRenderer } from '../core/DecoratorRenderer';
-import { MentionsMenu, type UserMentionRecord } from '../menu/MentionsMenu';
+import { MentionsMenu } from '../menu/MentionsMenu';
// Version of MarkdownTextArea modified for email to/cc/bcc input fields
diff --git a/js/app/packages/core/component/LexicalMarkdown/plugins/media/mediaPlugin.ts b/js/app/packages/core/component/LexicalMarkdown/plugins/media/mediaPlugin.ts
index 8d4fcb8c4e..bf6843a84a 100644
--- a/js/app/packages/core/component/LexicalMarkdown/plugins/media/mediaPlugin.ts
+++ b/js/app/packages/core/component/LexicalMarkdown/plugins/media/mediaPlugin.ts
@@ -63,6 +63,7 @@ export type MediaSourceType = MediaSource['type'];
export type MediaCreationPayload = Exclude<MediaSource, 'file'> & {
alt?: string;
mediaType: MediaType;
+ constrainedMediaDimensions?: { width: number; height: number };
};
export const INSERT_MEDIA_COMMAND: LexicalCommand<MediaCreationPayload> =
@@ -95,7 +96,8 @@ export function validateMediaFile(file: File, mediaType: MediaType): boolean {
export async function addMediaFromFile(
editor: LexicalEditor,
file: File,
- mediaType: MediaType
+ mediaType: MediaType,
+ constrainedMediaDimensions?: { width: number; height: number }
) {
const processedFile = await processFile(file);
if (!validateMediaFile(processedFile, mediaType)) return { success: false };
@@ -104,6 +106,7 @@ export async function addMediaFromFile(
url: URL.createObjectURL(processedFile),
file: processedFile,
mediaType,
+ constrainedMediaDimensions,
});
return { success: true };
}
@@ -361,10 +364,14 @@ function registerMediaPlugin(editor: LexicalEditor) {
srcType: payload.type,
url: payload.url,
alt: payload.alt,
+ constrainedWidth: payload.constrainedMediaDimensions?.width,
+ constrainedHeight: payload.constrainedMediaDimensions?.height,
})
: $createVideoNode({
srcType: payload.type,
url: payload.url,
+ constrainedWidth: payload.constrainedMediaDimensions?.width,
+ constrainedHeight: payload.constrainedMediaDimensions?.height,
});
$safeInsertMediaNode(node);
return true;
@@ -377,10 +384,14 @@ function registerMediaPlugin(editor: LexicalEditor) {
srcType: payload.type,
url: payload.url,
alt: payload.alt,
+ constrainedWidth: payload.constrainedMediaDimensions?.width,
+ constrainedHeight: payload.constrainedMediaDimensions?.height,
})
: $createVideoNode({
srcType: payload.type,
url: payload.url,
+ constrainedWidth: payload.constrainedMediaDimensions?.width,
+ constrainedHeight: payload.constrainedMediaDimensions?.height,
});
$safeInsertMediaNode(node);
@@ -396,10 +407,14 @@ function registerMediaPlugin(editor: LexicalEditor) {
srcType: payload.type,
id: payload.id,
alt: payload.alt,
+ constrainedWidth: payload.constrainedMediaDimensions?.width,
+ constrainedHeight: payload.constrainedMediaDimensions?.height,
})
: $createVideoNode({
srcType: payload.type,
id: payload.id,
+ constrainedWidth: payload.constrainedMediaDimensions?.width,
+ constrainedHeight: payload.constrainedMediaDimensions?.height,
});
$safeInsertMediaNode(node);
}
diff --git a/js/app/packages/core/component/LexicalMarkdown/utils/fileUploadUtils.ts b/js/app/packages/core/component/LexicalMarkdown/utils/fileUploadUtils.ts
new file mode 100644
index 0000000000..254618737f
--- /dev/null
+++ b/js/app/packages/core/component/LexicalMarkdown/utils/fileUploadUtils.ts
@@ -0,0 +1,199 @@
+import type { BlockName } from '@core/block';
+import { toast } from '@core/component/Toast/Toast';
+import {
+ blockNameToFileExtensions,
+ fileTypeToBlockName,
+} from '@core/constant/allBlocks';
+import { HEIC_EXTENSIONS } from '@core/heic';
+import {
+ forceDssRuleset,
+ isFileUploadEntry,
+ type UploadInput,
+ uploadFiles,
+} from '@core/util/upload';
+import { logger } from '@observability';
+import { fileExtension } from '@service-storage/util/filename';
+import type { LexicalEditor } from 'lexical';
+import {
+ calculateInsertPoint,
+ SET_SELECTION_AT_INSERTION,
+} from '../plugins/drag-insert/dragInsertPlugin';
+import { addMediaFromFile } from '../plugins/media';
+import { documentUploadToItem, handleBasicMention } from './mentionsUtils';
+
+const getImageExtensionsHeic = () => [
+ ...blockNameToFileExtensions.image,
+ ...HEIC_EXTENSIONS,
+];
+const getVideoExtensions = () => blockNameToFileExtensions.video;
+
+async function processInlineMediaFiles(
+ editor: LexicalEditor,
+ files: File[],
+ constrainedMediaDimensions?: { width: number; height: number }
+) {
+ const IMAGE_EXTENSIONS_HEIC = getImageExtensionsHeic();
+ const VIDEO_EXTENSIONS = getVideoExtensions();
+ for (const file of files) {
+ const ext = fileExtension(file.name);
+ if (ext != null && IMAGE_EXTENSIONS_HEIC.includes(ext)) {
+ const res = await addMediaFromFile(
+ editor,
+ file,
+ 'image',
+ constrainedMediaDimensions
+ );
+ if (!res.success) {
+ toast.failure('Invalid media attachment file(s)');
+ }
+ } else if (ext != null && VIDEO_EXTENSIONS.includes(ext)) {
+ const res = await addMediaFromFile(
+ editor,
+ file,
+ 'video',
+ constrainedMediaDimensions
+ );
+ if (!res.success) {
+ toast.failure('Invalid media attachment file(s)');
+ }
+ }
+ }
+}
+
+const DRAG_EVENT_PADDING = 8;
+
+export const getDragDropPosition = (
+ editor: LexicalEditor,
+ e: DragEvent | { clientX: number; clientY: number },
+ setSelection = false
+) => {
+ const { key, position } = calculateInsertPoint(editor, e, DRAG_EVENT_PADDING);
+ if (setSelection && key !== null && position !== null) {
+ editor.dispatchCommand(SET_SELECTION_AT_INSERTION, [key, position]);
+ }
+ return { key, position };
+};
+
+export async function onFilesReady(
+ editor: LexicalEditor,
+ uploadEntries: UploadInput[],
+ blockId?: string,
+ parentBlockName?: BlockName,
+ position?: ReturnType<typeof getDragDropPosition>,
+ afterFileUpload?: (uploadedItemIds: string[]) => void,
+ constrainedMediaDimensions?: { width: number; height: number }
+): Promise<void> {
+ const IMAGE_EXTENSIONS_HEIC = getImageExtensionsHeic();
+ const VIDEO_EXTENSIONS = getVideoExtensions();
+ const mediaFiles: File[] = [];
+ const filesToUpload: UploadInput[] = [];
+
+ for (const entry of uploadEntries) {
+ if (isFileUploadEntry(entry) && entry.isFolder) {
+ filesToUpload.push(entry);
+ } else {
+ const file = isFileUploadEntry(entry) ? entry.file : entry;
+ const ext = fileExtension(file.name);
+ if (
+ ext != null &&
+ (IMAGE_EXTENSIONS_HEIC.includes(ext) || VIDEO_EXTENSIONS.includes(ext))
+ ) {
+ mediaFiles.push(file);
+ } else {
+ filesToUpload.push(entry);
+ }
+ }
+ }
+
+ if (position) {
+ const { key, position: position_ } = position;
+ if (key !== null && position_ !== null) {
+ editor.dispatchCommand(SET_SELECTION_AT_INSERTION, [key, position_]);
+ }
+ }
+
+ await processInlineMediaFiles(editor, mediaFiles, constrainedMediaDimensions);
+
+ if (filesToUpload.length === 0) return;
+
+ const results = await uploadFiles(filesToUpload, forceDssRuleset);
+
+ let uploadedItemIds: string[] = [];
+
+ for (const result of results) {
+ if (result.failed) continue;
+
+ if (result.destination !== 'dss') continue;
+
+ if (result.type === 'document') {
+ const blockName = fileTypeToBlockName(result.fileType, true);
+ if (blockName) {
+ const item = await documentUploadToItem(result);
+ if (!item) {
+ toast.failure('Document upload failed or timed out');
+ logger.error('Document upload failed or timed out', {
+ cause: new Error(),
+ });
+ continue;
+ }
+ uploadedItemIds.push(item.id);
+ handleBasicMention(item, {
+ editor,
+ blockName: parentBlockName,
+ blockId,
+ onDocumentMention: () => {},
+ disableMentionTracking: false,
+ });
+ }
+ } else if (result.type === 'folder') {
+ const item = await documentUploadToItem(result);
+ if (!item) {
+ toast.failure('Folder upload failed or timed out');
+ logger.error('Folder upload failed or timed out', {
+ cause: new Error(),
+ });
+ continue;
+ }
+ uploadedItemIds.push(item.id);
+ handleBasicMention(item, {
+ editor,
+ blockName: parentBlockName,
+ blockId,
+ onDocumentMention: () => {},
+ disableMentionTracking: false,
+ });
+ }
+ }
+
+ afterFileUpload?.(uploadedItemIds);
+}
+
+/**
+ * Creates a handler for files ready event.
+ * @param editor - The editor instance
+ * @param blockId - The block ID.
+ * @param getPosition - An optionalfunction to get the position of the files.
+ * @returns A function to handle files ready event.
+ */
+export function createFilesReadyHandler(
+ editor: LexicalEditor,
+ blockId?: string,
+ parentBlockName?: BlockName,
+ getPosition?: () => ReturnType<typeof getDragDropPosition>,
+ afterFileUpload?: (uploadedItemIds: string[]) => void,
+ constrainedMediaDimensions?: { width: number; height: number }
+) {
+ return async (uploadEntries: UploadInput[]) => {
+ if (!editor) return;
+ const position = getPosition?.();
+ await onFilesReady(
+ editor,
+ uploadEntries,
+ blockId,
+ parentBlockName,
+ position,
+ afterFileUpload,
+ constrainedMediaDimensions
+ );
+ };
+}
diff --git a/js/app/packages/core/component/LexicalMarkdown/utils/mentionsUtils.ts b/js/app/packages/core/component/LexicalMarkdown/utils/mentionsUtils.ts
new file mode 100644
index 0000000000..26dc8e750f
--- /dev/null
+++ b/js/app/packages/core/component/LexicalMarkdown/utils/mentionsUtils.ts
@@ -0,0 +1,320 @@
+import type { BlockAlias, BlockName } from '@core/block';
+import { fileTypeToBlockName } from '@core/constant/allBlocks';
+import { trackMention } from '@core/signal/mention';
+import type { ChannelWithParticipants, IUser } from '@core/user';
+import type { ParsedDate } from '@core/util/dateParser';
+import type { EmailEntity } from '@macro-entity';
+import { waitBulkUploadStatus } from '@service-connection/bulkUpload';
+import type { DocumentMentionMetadata } from '@service-notification/client';
+import { storageServiceClient } from '@service-storage/client';
+import type { BasicDocument } from '@service-storage/generated/schemas/basicDocument';
+import type { Item } from '@service-storage/generated/schemas/item';
+import type { Project } from '@service-storage/generated/schemas/project';
+import type { UploadSuccess } from '@service-storage/util/upload';
+import type { LexicalEditor } from 'lexical';
+import { v7 } from 'uuid';
+import {
+ INSERT_DATE_MENTION_COMMAND,
+ INSERT_DOCUMENT_MENTION_COMMAND,
+ INSERT_USER_MENTION_COMMAND,
+} from '../plugins/mentions';
+
+export type EntityMap = {
+ item: Item;
+ user: IUser;
+ channel: ChannelWithParticipants;
+ date: DateItem;
+ email: EmailEntity;
+};
+
+export type Entity<T extends keyof EntityMap> = {
+ kind: T;
+ id: EntityMap[T]['id'];
+ data: EntityMap[T];
+};
+
+type PickEntity<K extends keyof EntityMap> = {
+ [P in K]: Entity<P>;
+}[K];
+
+export type CombinedEntity<K extends keyof EntityMap = keyof EntityMap> =
+ PickEntity<K>;
+
+// mapper fn that converts entity data to its entity type
+type EntityMapper<K extends keyof EntityMap> = (
+ data: EntityMap[K]
+) => PickEntity<K>;
+
+export function entityMapper<K extends keyof EntityMap>(
+ kind: K
+): EntityMapper<K> {
+ return (data: EntityMap[K]) => ({ kind, data, id: data.id });
+}
+
+export type DateItem = ParsedDate & {
+ id: string;
+};
+
+export type UserMentionRecord = {
+ documentId: string;
+ mentions: string[];
+ metadata: DocumentMentionMetadata;
+};
+
+export const getCombinedEntityBlockName = (
+ item: CombinedEntity<'item' | 'channel' | 'email'>,
+ icon?: boolean
+): BlockName | BlockAlias => {
+ switch (item.kind) {
+ case 'item':
+ if (item.data.type === 'document')
+ return fileTypeToBlockName(
+ item.data.subType || item.data.fileType,
+ icon
+ );
+ if (item.data.type === 'chat') return 'chat';
+ if (item.data.type === 'project') return 'project';
+ return 'unknown';
+ case 'email':
+ return 'email';
+ case 'channel':
+ return 'channel';
+ }
+};
+
+const getUserName = (item: IUser): string => {
+ const { email, name } = item;
+ if (name === email) return email;
+ return `${name} | ${email}`;
+};
+
+export const getItemName = (item: CombinedEntity): string => {
+ switch (item.kind) {
+ case 'item':
+ return item.data.name;
+ case 'user':
+ return getUserName(item.data);
+ case 'channel':
+ return item.data.name ?? '';
+ case 'email':
+ return item.data.name ?? 'No Subject';
+ case 'date':
+ return item.data.displayFormat;
+ }
+};
+
+/**
+ * These are the stateful utils needed to handle an item of a given type. I have opted
+ * to implement the handlers as smaller helpers rather than 1 giant function. So these
+ * dependencies have to be injected via the component.
+ */
+export type HandlerDependencies = {
+ editor: LexicalEditor;
+ blockName?: BlockName;
+ blockId?: string;
+ onUserMention?: (record: UserMentionRecord) => void;
+ onDocumentMention?: (item: Item | ChannelWithParticipants) => void;
+ disableMentionTracking?: boolean;
+ onEmailMention?: (item: EmailEntity) => void;
+};
+
+/**
+ * Handles user mentions by lexical inserting and potentially up-serting to the notification service.
+ * @param user The user to mention.
+ * @param dependencies The dependencies required to handle the user mention.
+ */
+export async function handleUserMention(
+ user: IUser,
+ dependencies: HandlerDependencies
+) {
+ const { editor, blockName, blockId, onUserMention, disableMentionTracking } =
+ dependencies;
+ let mentionId: string | undefined;
+
+ if (blockName !== 'channel') {
+ if (blockId) {
+ const record: UserMentionRecord = {
+ documentId: blockId,
+ mentions: [user.id],
+ metadata: {
+ mention_id: v7(),
+ },
+ };
+ if (onUserMention) {
+ onUserMention(record);
+ } else {
+ storageServiceClient.upsertUserMentions(record);
+ }
+ if (!disableMentionTracking) {
+ mentionId = await trackMention(blockId, 'user', user.id);
+ }
+ }
+ }
+
+ editor.dispatchCommand(INSERT_USER_MENTION_COMMAND, {
+ userId: user.id,
+ email: user.email,
+ mentionUuid: mentionId,
+ });
+}
+
+/**
+ * Inserts a date mention.
+ * @param date
+ * @param dependencies
+ */
+export async function handleDateMention(
+ date: DateItem,
+ dependencies: HandlerDependencies
+) {
+ const { editor } = dependencies;
+ editor.dispatchCommand(INSERT_DATE_MENTION_COMMAND, {
+ date: date.date.toISOString(),
+ displayFormat: date.displayFormat,
+ });
+}
+
+export async function handleEmailMention(
+ email: EmailEntity,
+ dependencies: HandlerDependencies
+) {
+ const {
+ editor,
+ blockName: parentBlockName,
+ blockId,
+ onEmailMention,
+ disableMentionTracking,
+ } = dependencies;
+ let mentionId: string | undefined;
+ if (
+ blockId &&
+ parentBlockName !== 'channel' &&
+ parentBlockName !== 'chat' &&
+ !disableMentionTracking
+ ) {
+ mentionId = await trackMention(blockId, 'document', email.id);
+ }
+ const itemName = email.name ?? 'No Subject';
+
+ onEmailMention?.(email);
+
+ editor.dispatchCommand(INSERT_DOCUMENT_MENTION_COMMAND, {
+ documentId: email.id,
+ documentName: itemName,
+ blockName: 'email',
+ mentionUuid: mentionId,
+ });
+}
+
+/**
+ * Converts a UploadSuccess to an Item. Folder UploadSuccesses contain a promise for the projectId, so we need to wait for that to resolve.
+ */
+export async function documentUploadToItem(upload: UploadSuccess) {
+ const now = Date.now();
+
+ if (upload.type === 'document') {
+ return {
+ id: upload.documentId,
+ name: upload.name,
+ type: 'document',
+ fileType: upload.fileType,
+ createdAt: now,
+ updatedAt: now,
+ deletedAt: null,
+ documentVersionId: 0,
+ owner: '',
+ } satisfies BasicDocument;
+ }
+
+ const projectId = await waitBulkUploadStatus(upload.requestId);
+ if (!projectId) return;
+
+ return {
+ id: projectId,
+ name: upload.name,
+ type: 'project',
+ createdAt: now,
+ updatedAt: now,
+ deletedAt: null,
+ userId: '',
+ } satisfies Project;
+}
+
+/**
+ * Insert a document mentions and track it.
+ * @param item
+ * @param dependencies
+ */
+export async function handleBasicMention(
+ item: Item,
+ dependencies: HandlerDependencies
+) {
+ const {
+ editor,
+ blockName: parentBlockName,
+ blockId,
+ onDocumentMention,
+ disableMentionTracking,
+ } = dependencies;
+ let mentionId: string | undefined;
+ if (
+ blockId &&
+ parentBlockName !== 'channel' &&
+ parentBlockName !== 'chat' &&
+ !disableMentionTracking
+ ) {
+ mentionId = await trackMention(blockId, 'document', item.id);
+ }
+ const itemEntity = entityMapper('item')(item);
+ const itemBlock = getCombinedEntityBlockName(itemEntity);
+ const itemName = getItemName(itemEntity);
+
+ onDocumentMention?.(item);
+
+ editor.dispatchCommand(INSERT_DOCUMENT_MENTION_COMMAND, {
+ documentId: item.id,
+ documentName: itemName,
+ blockName: itemBlock,
+ mentionUuid: mentionId,
+ });
+}
+
+/**
+ * Insert a channel mention and track it.
+ * @param channel
+ * @param dependencies
+ */
+export async function handleChannelMention(
+ channel: ChannelWithParticipants,
+ dependencies: HandlerDependencies
+) {
+ const {
+ editor,
+ blockName: parentBlockName,
+ blockId,
+ onDocumentMention,
+ disableMentionTracking,
+ } = dependencies;
+ let mentionId: string | undefined;
+ if (
+ blockId &&
+ parentBlockName !== 'channel' &&
+ parentBlockName !== 'chat' &&
+ !disableMentionTracking
+ ) {
+ mentionId = await trackMention(blockId, 'channel', channel.id);
+ }
+ const channelEntity = entityMapper('channel')(channel);
+ const itemBlock = getCombinedEntityBlockName(channelEntity);
+ const itemName = getItemName(channelEntity);
+
+ onDocumentMention?.(channel);
+
+ editor.dispatchCommand(INSERT_DOCUMENT_MENTION_COMMAND, {
+ documentId: channel.id,
+ documentName: itemName,
+ blockName: itemBlock,
+ mentionUuid: mentionId,
+ channelType: channel.channel_type,
+ });
+}
diff --git a/js/app/packages/core/component/Toast/Toast.tsx b/js/app/packages/core/component/Toast/Toast.tsx
index 325fe3dfda..cfc1bf6584 100644
--- a/js/app/packages/core/component/Toast/Toast.tsx
+++ b/js/app/packages/core/component/Toast/Toast.tsx
@@ -326,17 +326,17 @@ export function createUploadToast(message: string) {
<Toast
toastId={props.toastId}
persistent={true}
- class={`flex flex-col items-center justify-between gap-2 border rounded-md p-3 shadow-lg bg-amber-50 border-amber-300 text-amber-700 pointer-events-auto
+ class={`flex flex-col items-center justify-between gap-2 border rounded-md p-3 shadow-lg bg-menu border-edge-muted pointer-events-auto
ui-opened:animate-slide-in ui-closed:animate-hide transition-transform ui-swipe-move:translate-x-[var(--kb-toast-swipe-move-x)]
ui-swipe-cancel:translate-x-0 ui-swipe-cancel:ease-out ui-swipe-cancel:duration-200 ui-swipe-end:animate-swipe-out`}
>
<div class="flex items-center w-full">
- <Spinner class="fill-amber-700 mr-3 h-7 animate-spin shrink-0" />
+ <Spinner class="mr-3 h-7 animate-spin shrink-0" />
<div>
<Toast.Title>{message}</Toast.Title>
</div>
<Toast.CloseButton class="ml-auto">
- <XIcon class={`h-5 ml-4 fill-amber-700`} />
+ <XIcon class={`h-5 ml-4`} />
</Toast.CloseButton>
</div>
</Toast>
diff --git a/js/app/packages/core/component/Toast/ToastRegion.tsx b/js/app/packages/core/component/Toast/ToastRegion.tsx
index 3a9f1c761f..f9c43fa20b 100644
--- a/js/app/packages/core/component/Toast/ToastRegion.tsx
+++ b/js/app/packages/core/component/Toast/ToastRegion.tsx
@@ -4,12 +4,12 @@ import { Portal } from 'solid-js/web';
export function ToastRegion() {
return (
<Portal>
- <div class="fixed bottom-[40px] sm:bottom-0 right-0 w-[90%] sm:w-108 m-0 list-none outline-none pointer-events-none z-toast-region">
+ <div class="fixed bottom-[40px] sm:bottom-12 right-0 w-[90%] sm:w-108 m-0 list-none outline-none pointer-events-none z-toast-region">
<Toast.Region regionId="toast-region" duration={6000}>
- <Toast.List class="flex flex-col p-4 gap-2" />
+ <Toast.List class="absolute bottom-0 right-0 flex-col p-4 gap-2" />
</Toast.Region>
<Toast.Region regionId="stable-toast" duration={Infinity}>
- <Toast.List class="flex flex-col p-4 gap-2" />
+ <Toast.List class="absolute bottom-0 right-0 flex flex-col p-4 gap-2" />
</Toast.Region>
</div>
</Portal>
diff --git a/js/app/packages/lexical-core/nodes/ImageNode.ts b/js/app/packages/lexical-core/nodes/ImageNode.ts
index 58f40bf462..e4a85c8cd7 100644
--- a/js/app/packages/lexical-core/nodes/ImageNode.ts
+++ b/js/app/packages/lexical-core/nodes/ImageNode.ts
@@ -35,10 +35,22 @@ export class ImageNode extends MediaNode<{ alt: string }> {
alt: string,
width: number,
height: number,
+ constrainedWidth?: number,
+ constrainedHeight?: number,
scale?: number,
key?: NodeKey
) {
- super(srcType, id, url, width, height, scale, key);
+ super(
+ srcType,
+ id,
+ url,
+ width,
+ height,
+ constrainedWidth,
+ constrainedHeight,
+ scale,
+ key
+ );
this.__alt = alt;
}
@@ -85,6 +97,8 @@ export class ImageNode extends MediaNode<{ alt: string }> {
node.__alt,
node.__width,
node.__height,
+ node.__constrainedWidth,
+ node.__constrainedHeight,
node.__scale,
node.__key
);
@@ -117,7 +131,7 @@ export class ImageNode extends MediaNode<{ alt: string }> {
exportDOM() {
const result = super.exportDOM();
if (result && result.element) {
- (result.element as HTMLImageElement).setAttribute('alt', this.__alt);
+ result.element.querySelector('img')?.setAttribute('alt', this.__alt);
}
return result;
}
@@ -132,6 +146,10 @@ export class ImageNode extends MediaNode<{ alt: string }> {
const scale = domNode.getAttribute('data-scale');
const srcType = domNode.getAttribute('data-src-type');
const id = domNode.getAttribute('data-image-id');
+ const constrainedWidth = domNode.getAttribute('data-constrained-width');
+ const constrainedHeight = domNode.getAttribute(
+ 'data-constrained-height'
+ );
if (src && id && srcType) {
return {
@@ -144,6 +162,12 @@ export class ImageNode extends MediaNode<{ alt: string }> {
width: width ? parseInt(width, 10) : 0,
height: height ? parseInt(height, 10) : 0,
scale: scale ? parseFloat(scale) : 1,
+ constrainedWidth: constrainedWidth
+ ? parseInt(constrainedWidth, 10)
+ : undefined,
+ constrainedHeight: constrainedHeight
+ ? parseInt(constrainedHeight, 10)
+ : undefined,
});
return { node };
},
@@ -152,6 +176,45 @@ export class ImageNode extends MediaNode<{ alt: string }> {
}
return null;
},
+ div: (domNode: HTMLDivElement) => {
+ const img = domNode.querySelector('img');
+ if (!img) return null;
+
+ const src = img.getAttribute('src');
+ const alt = img.getAttribute('alt');
+ const width = img.getAttribute('width');
+ const height = img.getAttribute('height');
+ const scale = img.getAttribute('data-scale');
+ const srcType = img.getAttribute('data-src-type');
+ const id = img.getAttribute('data-image-id');
+ const constrainedWidth = img.getAttribute('data-constrained-width');
+ const constrainedHeight = img.getAttribute('data-constrained-height');
+
+ if (src && id && srcType) {
+ return {
+ conversion: () => {
+ const node = $createImageNode({
+ srcType: srcType,
+ id,
+ url: src,
+ alt: alt || '',
+ width: width ? parseInt(width, 10) : 0,
+ height: height ? parseInt(height, 10) : 0,
+ scale: scale ? parseFloat(scale) : 1,
+ constrainedWidth: constrainedWidth
+ ? parseInt(constrainedWidth, 10)
+ : undefined,
+ constrainedHeight: constrainedHeight
+ ? parseInt(constrainedHeight, 10)
+ : undefined,
+ });
+ return { node };
+ },
+ priority: 2, // Higher priority for our wrapped format
+ };
+ }
+ return null;
+ },
};
}
@@ -189,6 +252,8 @@ export class ImageNode extends MediaNode<{ alt: string }> {
alt: this.__alt,
key: this.__key,
scale: this.__scale,
+ constrainedWidth: this.__constrainedWidth,
+ constrainedHeight: this.__constrainedHeight,
};
}
}
@@ -200,6 +265,8 @@ export function $createImageNode(params: {
alt?: string;
width?: number;
height?: number;
+ constrainedWidth?: number;
+ constrainedHeight?: number;
scale?: number;
}) {
return $applyNodeReplacement(
@@ -210,6 +277,8 @@ export function $createImageNode(params: {
params.alt ?? '',
params.width ?? 0,
params.height ?? 0,
+ params.constrainedWidth,
+ params.constrainedHeight,
params.scale ?? 1
)
);
diff --git a/js/app/packages/lexical-core/nodes/MediaNode.ts b/js/app/packages/lexical-core/nodes/MediaNode.ts
index c3cdfd3e83..a02bb66246 100644
--- a/js/app/packages/lexical-core/nodes/MediaNode.ts
+++ b/js/app/packages/lexical-core/nodes/MediaNode.ts
@@ -6,6 +6,7 @@ import type {
} from 'lexical';
import type { DecoratorComponent } from '../decoratorRegistry';
import { $applyIdFromSerialized } from '../plugins/nodeIdPlugin';
+import { calculateEffectiveDimensions } from '../utils/media';
import { DecoratorBlockNode } from './DecoratorBlockNode';
export type MediaType = 'image' | 'video';
@@ -17,6 +18,8 @@ export type MediaInfo = {
width: number;
height: number;
scale: number;
+ constrainedWidth?: number;
+ constrainedHeight?: number;
};
export type SerializedMediaNode<T = {}> = Spread<
@@ -32,6 +35,8 @@ export abstract class MediaNode<
__url: string;
__width: number;
__height: number;
+ __constrainedWidth?: number;
+ __constrainedHeight?: number;
__componentDirty: boolean;
__scale: number;
__cachedDecoratorComponent: DecoratorComponent<MediaInfo & T> | null;
@@ -42,6 +47,8 @@ export abstract class MediaNode<
url: string,
width: number,
height: number,
+ constrainedWidth?: number,
+ constrainedHeight?: number,
scale?: number,
key?: NodeKey
) {
@@ -51,6 +58,8 @@ export abstract class MediaNode<
this.__url = url;
this.__width = width;
this.__height = height;
+ this.__constrainedWidth = constrainedWidth;
+ this.__constrainedHeight = constrainedHeight;
this.__scale = scale || 1;
this.__componentDirty = true;
this.__cachedDecoratorComponent = null;
@@ -125,6 +134,39 @@ export abstract class MediaNode<
return writable;
}
+ getConstrainedWidth() {
+ return this.__constrainedWidth;
+ }
+ setConstrainedWidth(width: number | undefined, rerender = true): this {
+ const writable = this.getWritable();
+ writable.__constrainedWidth = width;
+ if (rerender) writable.__componentDirty = true;
+ return writable;
+ }
+
+ getConstrainedHeight() {
+ return this.__constrainedHeight;
+ }
+ setConstrainedHeight(height: number | undefined, rerender = true): this {
+ const writable = this.getWritable();
+ writable.__constrainedHeight = height;
+ if (rerender) writable.__componentDirty = true;
+ return writable;
+ }
+
+ /**
+ * Calculates the effective width and height based on the more constrained dimension.
+ * Returns the width/height that should be used, respecting aspect ratio.
+ */
+ getEffectiveDimensions(): { width: number; height: number } {
+ return calculateEffectiveDimensions(
+ this.__width,
+ this.__height,
+ this.__constrainedWidth,
+ this.__constrainedHeight
+ );
+ }
+
createDOM(): HTMLElement {
return document.createElement('div');
}
@@ -134,14 +176,29 @@ export abstract class MediaNode<
}
exportDOM() {
+ const wrapper = document.createElement('div');
const element = this.getDOMElement();
+ const { width, height } = this.getEffectiveDimensions();
element.setAttribute('src', this.__url);
- element.setAttribute('width', this.__width.toString());
- element.setAttribute('height', this.__height.toString());
+ element.setAttribute('width', width.toString());
+ element.setAttribute('height', height.toString());
element.setAttribute('data-src-type', this.__srcType);
element.setAttribute(`data-${this.getMediaType()}-id`, this.__id);
element.setAttribute('data-scale', this.__scale.toString());
- return { element };
+ if (this.__constrainedWidth !== undefined) {
+ element.setAttribute(
+ 'data-constrained-width',
+ this.__constrainedWidth.toString()
+ );
+ }
+ if (this.__constrainedHeight !== undefined) {
+ element.setAttribute(
+ 'data-constrained-height',
+ this.__constrainedHeight.toString()
+ );
+ }
+ wrapper.appendChild(element);
+ return { element: wrapper };
}
decorate(): DecoratorComponent<MediaInfo & T> | undefined {
@@ -156,7 +213,9 @@ export abstract class MediaNode<
.setUrl(serializedNode.url)
.setWidth(serializedNode.width)
.setHeight(serializedNode.height)
- .setScale(serializedNode.scale || 1);
+ .setScale(serializedNode.scale || 1)
+ .setConstrainedWidth(serializedNode.constrainedWidth, false)
+ .setConstrainedHeight(serializedNode.constrainedHeight, false);
$applyIdFromSerialized(self, serializedNode);
return self;
@@ -171,6 +230,8 @@ export abstract class MediaNode<
width: this.__width,
height: this.__height,
scale: this.__scale,
+ constrainedWidth: this.__constrainedWidth,
+ constrainedHeight: this.__constrainedHeight,
} as SerializedMediaNode<{}>;
}
}
diff --git a/js/app/packages/lexical-core/nodes/VideoNode.ts b/js/app/packages/lexical-core/nodes/VideoNode.ts
index fa08b2ffd2..9e7cae48ff 100644
--- a/js/app/packages/lexical-core/nodes/VideoNode.ts
+++ b/js/app/packages/lexical-core/nodes/VideoNode.ts
@@ -35,10 +35,22 @@ export class VideoNode extends MediaNode<{ controls: boolean }> {
controls: boolean,
width: number,
height: number,
+ constrainedWidth?: number,
+ constrainedHeight?: number,
scale?: number,
key?: NodeKey
) {
- super(srcType, id, url, width, height, scale, key);
+ super(
+ srcType,
+ id,
+ url,
+ width,
+ height,
+ constrainedWidth,
+ constrainedHeight,
+ scale,
+ key
+ );
this.__controls = controls;
}
@@ -87,6 +99,8 @@ export class VideoNode extends MediaNode<{ controls: boolean }> {
node.__controls,
node.__width,
node.__height,
+ node.__constrainedWidth,
+ node.__constrainedHeight,
node.__scale,
node.__key
);
@@ -119,10 +133,9 @@ export class VideoNode extends MediaNode<{ controls: boolean }> {
exportDOM() {
const result = super.exportDOM();
if (result && result.element) {
- (result.element as HTMLVideoElement).setAttribute(
- 'controls',
- this.__controls.toString()
- );
+ result.element
+ .querySelector('video')
+ ?.setAttribute('controls', this.__controls.toString());
}
return result;
}
@@ -137,6 +150,10 @@ export class VideoNode extends MediaNode<{ controls: boolean }> {
const scale = domNode.getAttribute('data-scale');
const srcType = domNode.getAttribute('data-src-type');
const id = domNode.getAttribute('data-video-id');
+ const constrainedWidth = domNode.getAttribute('data-constrained-width');
+ const constrainedHeight = domNode.getAttribute(
+ 'data-constrained-height'
+ );
if (src && id && srcType) {
return {
@@ -149,6 +166,12 @@ export class VideoNode extends MediaNode<{ controls: boolean }> {
width: width ? parseInt(width, 10) : 0,
height: height ? parseInt(height, 10) : 0,
scale: scale ? parseFloat(scale) : 1,
+ constrainedWidth: constrainedWidth
+ ? parseInt(constrainedWidth, 10)
+ : undefined,
+ constrainedHeight: constrainedHeight
+ ? parseInt(constrainedHeight, 10)
+ : undefined,
});
return { node };
},
@@ -157,6 +180,45 @@ export class VideoNode extends MediaNode<{ controls: boolean }> {
}
return null;
},
+ div: (domNode: HTMLDivElement) => {
+ const video = domNode.querySelector('video');
+ if (!video) return null;
+
+ const src = video.getAttribute('src');
+ const controls = video.hasAttribute('controls');
+ const width = video.getAttribute('width');
+ const height = video.getAttribute('height');
+ const scale = video.getAttribute('data-scale');
+ const srcType = video.getAttribute('data-src-type');
+ const id = video.getAttribute('data-video-id');
+ const constrainedWidth = video.getAttribute('data-constrained-width');
+ const constrainedHeight = video.getAttribute('data-constrained-height');
+
+ if (src && id && srcType) {
+ return {
+ conversion: () => {
+ const node = $createVideoNode({
+ srcType: srcType,
+ id,
+ url: src,
+ controls: controls,
+ width: width ? parseInt(width, 10) : 0,
+ height: height ? parseInt(height, 10) : 0,
+ scale: scale ? parseFloat(scale) : 1,
+ constrainedWidth: constrainedWidth
+ ? parseInt(constrainedWidth, 10)
+ : undefined,
+ constrainedHeight: constrainedHeight
+ ? parseInt(constrainedHeight, 10)
+ : undefined,
+ });
+ return { node };
+ },
+ priority: 2, // Higher priority for our wrapped format
+ };
+ }
+ return null;
+ },
};
}
@@ -198,6 +260,8 @@ export class VideoNode extends MediaNode<{ controls: boolean }> {
controls: this.__controls,
scale: this.__scale || 1,
key: this.__key,
+ constrainedWidth: this.__constrainedWidth,
+ constrainedHeight: this.__constrainedHeight,
};
}
}
@@ -209,6 +273,8 @@ export function $createVideoNode(params: {
controls?: boolean;
width?: number;
height?: number;
+ constrainedWidth?: number;
+ constrainedHeight?: number;
scale?: number;
}) {
return $applyNodeReplacement(
@@ -219,6 +285,8 @@ export function $createVideoNode(params: {
params.controls ?? true,
params.width ?? 0,
params.height ?? 0,
+ params.constrainedWidth,
+ params.constrainedHeight,
params.scale ?? 1
)
);
diff --git a/js/app/packages/lexical-core/transformers/image.ts b/js/app/packages/lexical-core/transformers/image.ts
index f882a51f9d..93470a7c5b 100644
--- a/js/app/packages/lexical-core/transformers/image.ts
+++ b/js/app/packages/lexical-core/transformers/image.ts
@@ -1,7 +1,61 @@
import type { ElementTransformer } from '@lexical/markdown';
-import type { LexicalNode } from 'lexical';
+import type { ElementNode, LexicalNode } from 'lexical';
import { $createImageNode, $isImageNode, ImageNode } from '../nodes/ImageNode';
+// Internal transformer for images with constrained dimensions
+export const I_IMAGE_CONSTRAINED: ElementTransformer = {
+ dependencies: [ImageNode],
+ type: 'element',
+ regExp: /<m-image>(.*?)<\/m-image>/,
+ export: (node: LexicalNode) => {
+ if (!$isImageNode(node)) return null;
+ if (node.getSrcType() === 'local') return null;
+ if (!node.getUrl()) return null;
+
+ const constrainedWidth = node.getConstrainedWidth();
+ const constrainedHeight = node.getConstrainedHeight();
+ if (constrainedWidth === undefined && constrainedHeight === undefined) {
+ return null;
+ }
+
+ const data = JSON.stringify({
+ url: node.getUrl(),
+ alt: node.getAlt() || '',
+ srcType: node.getSrcType(),
+ id: node.getId(),
+ width: node.getWidth(),
+ height: node.getHeight(),
+ scale: node.getScale(),
+ constrainedWidth,
+ constrainedHeight,
+ });
+
+ return `<m-image>${data}</m-image>`;
+ },
+ replace: (parent: ElementNode, _, match: RegExpMatchArray) => {
+ try {
+ const data = JSON.parse(match[1]);
+ if (!data.url) throw new Error('Missing url field');
+
+ const imageNode = $createImageNode({
+ srcType: data.srcType || 'url',
+ url: data.url,
+ alt: data.alt || '',
+ id: data.id || '',
+ width: data.width || 0,
+ height: data.height || 0,
+ scale: data.scale || 1,
+ constrainedWidth: data.constrainedWidth,
+ constrainedHeight: data.constrainedHeight,
+ });
+ parent.append(imageNode);
+ } catch (e) {
+ console.error('Failed to parse m-image:', e);
+ }
+ },
+};
+
+// Standard markdown image transformer (for simple images without constraints)
export const IMAGE: ElementTransformer = {
dependencies: [ImageNode],
type: 'element',
diff --git a/js/app/packages/lexical-core/transformers/index.ts b/js/app/packages/lexical-core/transformers/index.ts
index 84a0301c20..b87e897c2a 100644
--- a/js/app/packages/lexical-core/transformers/index.ts
+++ b/js/app/packages/lexical-core/transformers/index.ts
@@ -1,7 +1,7 @@
import type { Transformer } from '@lexical/markdown';
import { I_MACRO_QUOTE } from './classedBlock';
import { CUSTOM_TRANSFORMERS } from './customTransformers';
-import { IMAGE } from './image';
+import { I_IMAGE_CONSTRAINED, IMAGE } from './image';
import {
E_BLOCK_EQUATION_NODE,
E_INLINE_EQUATION_NODE,
@@ -41,7 +41,8 @@ export const INTERNAL_TRANSFORMERS: Transformer[] = [
MARK_XML,
SEARCH_MATCH,
HR,
- IMAGE,
+ I_IMAGE_CONSTRAINED,
+ IMAGE, // Standard markdown images (fallback)
I_USER_MENTION,
I_DOCUMENT_MENTION,
I_CONTACT_MENTION,
@@ -85,6 +86,7 @@ export const ALL_TRANSFORMERS: Transformer[] = [
MARK_XML,
SEARCH_MATCH,
HR,
+ I_IMAGE_CONSTRAINED,
IMAGE,
BR_TAG_TO_LINE_BREAK,
I_TABLE_NODE,
diff --git a/js/app/packages/lexical-core/utils/index.ts b/js/app/packages/lexical-core/utils/index.ts
index 1a53d126d6..03ef00f7af 100644
--- a/js/app/packages/lexical-core/utils/index.ts
+++ b/js/app/packages/lexical-core/utils/index.ts
@@ -4,6 +4,7 @@ import type { LexicalNode, SerializedLexicalNode } from 'lexical';
export * from './document';
export * from './languageSupport';
+export * from './media';
export * from './mentions';
export function $isSerializedNode(
diff --git a/js/app/packages/lexical-core/utils/media.ts b/js/app/packages/lexical-core/utils/media.ts
new file mode 100644
index 0000000000..297bdfd757
--- /dev/null
+++ b/js/app/packages/lexical-core/utils/media.ts
@@ -0,0 +1,31 @@
+/**
+ * Calculates the effective dimensions based on constrained width and height.
+ * Uses the more constrained dimension to maintain aspect ratio.
+ */
+export function calculateEffectiveDimensions(
+ width: number,
+ height: number,
+ constrainedWidth?: number,
+ constrainedHeight?: number
+): { width: number; height: number } {
+ if (!constrainedWidth && !constrainedHeight) {
+ return { width, height };
+ }
+
+ if (width <= 0 || height <= 0) {
+ return { width, height };
+ }
+
+ const widthScale = constrainedWidth ? constrainedWidth / width : Infinity;
+ const heightScale = constrainedHeight ? constrainedHeight / height : Infinity;
+ const effectiveScale = Math.min(widthScale, heightScale);
+
+ if (effectiveScale === Infinity || effectiveScale >= 1) {
+ return { width, height };
+ }
+
+ return {
+ width: Math.round(width * effectiveScale),
+ height: Math.round(height * effectiveScale),
+ };
+}