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.

fix(email): Email scroll jumping, suspense issues, and refactor (#770)

dev-rb49b1f99c1d5f
diff --git a/js/app/packages/app/component/Soup.tsx b/js/app/packages/app/component/Soup.tsx
index b24900e313..b7a2609979 100644
--- a/js/app/packages/app/component/Soup.tsx
+++ b/js/app/packages/app/component/Soup.tsx
@@ -163,8 +163,8 @@ const PreviewPanelContent: Component<{
class="size-full"
onFocusIn={(event) => {
if (interactedWith()) return;
- const relatedTarget = event.relatedTarget as HTMLElement;
- const currentTarget = event.currentTarget as HTMLElement;
+ const relatedTarget = event.relatedTarget;
+ const currentTarget = event.currentTarget;
// TODO: use state instead to determine when preview block can recieve focus
if (event.target.hasAttribute('data-allow-focus-in-preview')) {
@@ -172,8 +172,10 @@ const PreviewPanelContent: Component<{
return;
}
- if (!currentTarget.contains(relatedTarget)) {
- relatedTarget.focus();
+ if (relatedTarget instanceof HTMLElement) {
+ if (!currentTarget.contains(relatedTarget)) {
+ relatedTarget.focus();
+ }
}
}}
onPointerDown={() => {
diff --git a/js/app/packages/block-email/component/BaseInput.tsx b/js/app/packages/block-email/component/BaseInput.tsx
index dc73583719..0f48b55479 100644
--- a/js/app/packages/block-email/component/BaseInput.tsx
+++ b/js/app/packages/block-email/component/BaseInput.tsx
@@ -73,7 +73,7 @@ import {
Show,
untrack,
} from 'solid-js';
-import { createStore, produce } from 'solid-js/store';
+import { createStore } from 'solid-js/store';
import { deleteEmailDraft, saveEmailDraft } from '../signal/emailDraft';
import { handleFileUpload } from '../util/handleFileUpload';
import { makeAttachmentPublic } from '../util/makeAttachmentPublic';
@@ -281,7 +281,7 @@ export function BaseInput(props: {
setSavedDraftId(undefined);
return;
}
- const currentThread = ctx.threadData();
+ const currentThread = ctx.thread();
const newMessage = props.newMessage ?? false;
if (!currentThread && !newMessage) {
@@ -412,7 +412,7 @@ export function BaseInput(props: {
return;
}
- const currentThread = ctx.threadData();
+ const currentThread = ctx.thread();
const newMessage = props.newMessage ?? false;
if (!currentThread && !newMessage) {
@@ -506,11 +506,7 @@ export function BaseInput(props: {
}
const replyingToId = props.replyingTo()?.db_id;
if (replyingToId) {
- ctx.setMessageDbIdToDraftChildren(
- produce((state) => {
- delete state[replyingToId];
- })
- );
+ ctx.drafts.deleteDraftForMessage(replyingToId);
}
resetState();
props.setShowReply?.(false);
diff --git a/js/app/packages/block-email/component/Block.tsx b/js/app/packages/block-email/component/Block.tsx
index 7f9961acfd..8d567e1496 100644
--- a/js/app/packages/block-email/component/Block.tsx
+++ b/js/app/packages/block-email/component/Block.tsx
@@ -4,7 +4,7 @@ import { DocumentBlockContainer } from '@core/component/DocumentBlockContainer';
import { EmailDebouncedReadMarker } from '@notifications';
import { createMemo, onMount, Show, Suspense } from 'solid-js';
import { blockDataSignal } from '../signal/emailBlockData';
-import { Email } from './Email';
+import { EmailView } from './Email';
const { track, TrackingEvents } = withAnalytics();
@@ -37,7 +37,7 @@ export default function BlockEmail() {
threadId={id()}
/>
<Suspense>
- <Email title={title} threadId={id} />
+ <EmailView title={title} threadId={id} />
</Suspense>
</>
)}
diff --git a/js/app/packages/block-email/component/Email.tsx b/js/app/packages/block-email/component/Email.tsx
index 4f2944a474..e34a76c9df 100644
--- a/js/app/packages/block-email/component/Email.tsx
+++ b/js/app/packages/block-email/component/Email.tsx
@@ -1,253 +1,51 @@
-import { useGlobalNotificationSource } from '@app/component/GlobalAppState';
-import { useSplitPanelOrThrow } from '@app/component/split-layout/layoutUtils';
-import { toast } from '@core/component/Toast/Toast';
+import {
+ EmailProvider,
+ useEmailContext,
+} from '@block-email/component/EmailContext';
import { TOKENS } from '@core/hotkey/tokens';
import { registerScopeSignalHotkey } from '@core/hotkey/utils';
-import { createMethodRegistration } from '@core/orchestrator';
import {
blockElementSignal,
blockHotkeyScopeSignal,
} from '@core/signal/blockElement';
-import { blockHandleSignal } from '@core/signal/load';
-import {
- type ContactInfo,
- recipientEntityMapper,
- useContacts,
-} from '@core/user';
-import { whenSettled } from '@core/util/whenSettled';
-import {
- createEffectOnEntityTypeNotification,
- isNewEmail,
-} from '@notifications';
-import {
- useArchiveThreadMutation,
- useThreadQuery,
-} from '@queries/email/thread';
import type { MessageWithBodyReplyless } from '@service-email/generated/schemas';
import { createCallback } from '@solid-primitives/rootless';
-import { useSearchParams } from '@solidjs/router';
import {
type Accessor,
createEffect,
createMemo,
- createSignal,
onMount,
Show,
untrack,
} from 'solid-js';
-import { createStore } from 'solid-js/store';
-import { URL_PARAMS } from '../constants';
import { isScrollingToMessage } from '../signal/scrollState';
import { registerEmailHotkeys } from '../util/emailHotkeys';
-import {
- getLastMessageId,
- scrollToLastMessage,
- scrollToMessage,
-} from '../util/scrollToMessage';
-import { EmailProvider, type EmailRecipient } from './EmailContext';
+import { scrollToMessage } from '../util/scrollToMessage';
import { EmailFormContextProvider } from './EmailFormContext';
import { EmailInput } from './EmailInput';
import { MessageList } from './MessageList';
import { TopBar } from './TopBar';
-type EmailProps = {
+type EmailViewProps = {
title: Accessor<string>;
threadId: Accessor<string>;
};
-export function Email(props: EmailProps) {
+export function EmailView(props: EmailViewProps) {
+ return (
+ <EmailProvider threadID={props.threadId()}>
+ <EmailContent {...props} />
+ </EmailProvider>
+ );
+}
+
+function EmailContent(props: EmailViewProps) {
const scopeId = blockHotkeyScopeSignal.get;
const setIsScrollingToMessage = isScrollingToMessage.set;
const blockElement = blockElementSignal.get;
- const {
- unifiedListContext: {
- entitiesSignal: [entities],
- actionRegistry,
- },
- } = useSplitPanelOrThrow();
-
- const threadQuery = useThreadQuery(props.threadId);
- const threadData = () => threadQuery.data?.thread;
- const hasMore = () => threadQuery.data?.hasMore ?? false;
- const isFetching = () => threadQuery.isFetching;
- const fetchNextPage = () => threadQuery.fetchNextPage();
-
- const { mutate: archiveThreadMutate } = useArchiveThreadMutation({
- onError: () => {
- toast.failure('Failed to archive thread');
- },
- });
-
- const [searchParams] = useSearchParams();
- const searchParamsMessageId = () => {
- const messageID = searchParams[URL_PARAMS.messageId];
- if (typeof messageID === 'string') {
- return messageID;
- } else if (Array.isArray(messageID)) {
- return messageID[0];
- }
- return undefined;
- };
- const [targetMessageId, setTargetMessageId] = createSignal<
- string | undefined
- >(searchParamsMessageId());
-
- const filteredMessages = createMemo(() => {
- return (
- threadData()
- ?.messages.filter((message) => !message.is_draft)
- .sort((a, b) => {
- if (a.internal_date_ts && b.internal_date_ts) {
- return (
- new Date(a.internal_date_ts).getTime() -
- new Date(b.internal_date_ts).getTime()
- );
- }
- // Below is fallback for when internal_date_ts is not set
- else if (a.sent_at && b.sent_at) {
- return (
- new Date(a.sent_at).getTime() - new Date(b.sent_at).getTime()
- );
- }
- return 0;
- }) ?? []
- );
- });
-
- // ============================================
- // Map Parent Messages to Draft Children
- // ============================================
-
- const [messageDbIdToDraftChildren, setMessageDbIdToDraftChildren] =
- createStore<Record<string, MessageWithBodyReplyless>>({});
- const [draftsSettled, setDraftsSettled] = createSignal(false);
-
- whenSettled(
- threadQuery,
- (data) => {
- const t = data.thread;
- if (!t) return;
- const map: Record<string, MessageWithBodyReplyless> = {};
- for (const message of t.messages) {
- if (!message.is_draft || message.body_text?.trim().length === 0)
- continue;
- const replyingToId = message.replying_to_id;
- if (replyingToId) {
- map[replyingToId] = message;
- }
- }
- setMessageDbIdToDraftChildren(map);
- setDraftsSettled(true);
- },
- (error) => {
- console.error('Failed to load thread data:', error);
- toast.failure('Failed to load email thread. Please try again.');
- }
- );
-
- // ============================================
- // SHARED RECIPIENT OPTIONS
- // ============================================
- const contacts = useContacts();
-
- const [augmentedRecipients, setAugmentedRecipients] = createSignal<
- EmailRecipient[]
- >([]);
-
- function onRecipientsAugment(items: EmailRecipient[]) {
- const existing = augmentedRecipients();
- const existingEmails = new Set(
- existing.map((r) => r.data.email).filter((e) => e.length > 0)
- );
-
- const uniques: EmailRecipient[] = [];
- for (const r of items) {
- const email = r.data.email;
- if (email && !existingEmails.has(email)) {
- existingEmails.add(email);
- uniques.push(r);
- }
- }
-
- if (uniques.length === 0) return;
- setAugmentedRecipients([...existing, ...uniques]);
- }
-
- const recipientOptions = createMemo<EmailRecipient[]>(() => {
- const optionsMap = new Map<string, EmailRecipient>();
-
- contacts()
- .map(recipientEntityMapper('user'))
- .forEach((u) => optionsMap.set(u.data.email, u));
-
- const t = threadData();
- if (t) {
- const seen = new Map<string, ContactInfo>();
-
- const add = (c: ContactInfo) => {
- const existing = seen.get(c.email);
- if (!existing || (!existing.name && c.name)) seen.set(c.email, c);
- };
-
- t.messages.forEach((m) => {
- m.to.forEach(add);
- m.cc.forEach(add);
- m.bcc.forEach(add);
- if (m.from?.email)
- add({
- email: m.from.email,
- name: m.from.name ?? undefined,
- });
- });
- seen
- .values()
- .map(recipientEntityMapper('contact'))
- .forEach((c) => {
- optionsMap.set(c.data.email, c);
- });
- }
-
- augmentedRecipients().forEach((r) => {
- const email = r.data.email;
- if (email && !optionsMap.has(email)) optionsMap.set(email, r);
- });
-
- return Array.from(optionsMap.values());
- });
-
- const [messagesRef, setmessagesRef] = createSignal<
- HTMLDivElement | undefined
- >(undefined);
- const [messagesContainerRef, setMessagesContainerRef] = createSignal<
- HTMLDivElement | undefined
- >(undefined);
- const [focusedMessageId, setFocusedMessageId] = createSignal<string>();
- const [isContainerFilled, setIsContainerFilled] = createSignal(false);
- const [hasHandledTarget, setHasHandledTarget] = createSignal(false);
- const [targetMessageActive, setTargetMessageActive] = createSignal(false);
-
- const activeTargetMessageId = createMemo(() => {
- if (!targetMessageActive()) return undefined;
- return untrack(targetMessageId);
- });
- const blockHandle = blockHandleSignal.get;
- createMethodRegistration(blockHandle, {
- goToLocationFromParams: (params: Record<string, any>) => {
- if (params[URL_PARAMS.messageId]) {
- setTargetMessageId(undefined);
- setTimeout(() => {
- setTargetMessageId(params[URL_PARAMS.messageId]);
- setHasHandledTarget(false);
- }, 0);
- }
- },
- });
-
- // ============================================
- // SCROLLING LOGIC HELPER FUNCTIONS
- // ============================================
+ const context = useEmailContext();
/**
* Waits for the query to finish fetching
@@ -255,7 +53,7 @@ export function Email(props: EmailProps) {
const waitForQueryLoad = (): Promise<void> => {
return new Promise((resolve) => {
const checkInterval = setInterval(() => {
- if (!threadQuery.isFetching) {
+ if (!context.query.isFetching()) {
clearInterval(checkInterval);
resolve();
}
@@ -270,90 +68,94 @@ export function Email(props: EmailProps) {
targetMessageId: string
): Promise<boolean> => {
while (true) {
- const data = threadQuery.data;
+ const messages = context.messages.unfiltered();
// Check if message exists in current batch
- const messageExists = data?.thread.messages.some(
+ const messageExists = messages.some(
(m: MessageWithBodyReplyless) => m.db_id === targetMessageId
);
if (messageExists) return true;
// No more messages to load
- if (!data?.hasMore) return false;
+ if (!context.query.hasMore()) return false;
// Load next batch and wait
- threadQuery.fetchNextPage();
+ context.query.fetchNextPage();
await waitForQueryLoad();
}
};
/**
- * Loads one more batch of messages for better scroll context
- * (useful when target message is at the edge of loaded messages)
+ * Loads the next page only when there is more data to load and
+ * it's not already fetching
*/
- const loadContextBatch = async (): Promise<void> => {
- if (hasMore() && !isFetching()) {
- fetchNextPage();
- await waitForQueryLoad();
+ const fetchNextPage = () => {
+ if (context.query.hasMore() && !context.query.isFetching()) {
+ context.query.fetchNextPage();
}
};
/**
- * Performs the actual scroll to a message and updates focus
+ * Performs scrolling to a message and updates focus.
*/
const performScrollToMessage = (
messageId: string,
- behavior: ScrollBehavior = 'smooth'
+ opts: { behavior?: ScrollBehavior; focus?: boolean } = {
+ behavior: 'smooth',
+ focus: true,
+ }
) => {
- const messages = untrack(() => filteredMessages());
- const container = untrack(() => messagesRef());
+ opts = { focus: true, behavior: 'smooth', ...opts };
+ const messages = untrack(context.messages.list);
+ const container = untrack(context.messagesListRef);
if (!messages || !container) return false;
+ if (opts.focus) {
+ context.messages.setFocused(messageId);
+ }
+
setIsScrollingToMessage(true);
- const success = scrollToMessage(messageId, messages, container, behavior);
- if (success) {
- setFocusedMessageId(messageId);
- // Flash the message after scroll completes
- setTargetMessageActive(true);
+ const success = scrollToMessage(messageId, messages, container, {
+ behavior: opts.behavior,
+ reversed: true,
+ });
+
+ if (!success) {
+ setIsScrollingToMessage(false);
+ return false;
+ }
+
+ if (context.messages.targetMessageID() === messageId) {
setTimeout(() => {
- setTargetMessageActive(false);
+ context.messages.setTargetMessageID(undefined);
}, 800);
- // Clear scrolling flag after animation
- setTimeout(() => setIsScrollingToMessage(false), 1000);
- } else {
- setIsScrollingToMessage(false);
}
- return success;
+ // Clear scrolling flag after animation
+ setTimeout(() => setIsScrollingToMessage(false), 1000);
+
+ return true;
};
- /**
- * Scrolls to the last message in the thread
- */
- const scrollToLastMessageAndFocus = (
- behavior: ScrollBehavior = 'instant'
+ const scrollToLastMessage = (
+ behavior: ScrollBehavior = 'instant',
+ focus = false
) => {
- const container = untrack(() => messagesRef());
- const messages = untrack(() => filteredMessages());
- if (!messages) return;
- if (container && messages.length > 0) {
- // We need to scroll after focus because the scroll needs to account
- // for the size of the message with the focused styling applied
- const lastMessageId = getLastMessageId(messages);
- if (lastMessageId) {
- setFocusedMessageId(lastMessageId);
- }
- queueMicrotask(() => {
- scrollToLastMessage(container, behavior);
- });
- }
+ const messages = context.messages.list();
+ if (!messages?.length) return;
+
+ const lastMessage = messages[messages.length - 1];
+
+ if (!lastMessage.db_id) return;
+
+ performScrollToMessage(lastMessage.db_id, { behavior, focus });
};
const firstUnreadMessageId = createMemo(() => {
- const messages = filteredMessages()?.sort((a, b) => {
+ const messages = context.messages.list().toSorted((a, b) => {
if (a.internal_date_ts && b.internal_date_ts) {
return (
new Date(a.internal_date_ts).getTime() -
@@ -369,65 +171,16 @@ export function Email(props: EmailProps) {
)?.db_id;
});
- // ============================================
- // PHASE 1: ENSURE CONTAINER IS FILLED
- // ============================================
- // This effect ensures we have enough messages to fill the viewport
- // to avoid a sparse UI on initial load
- createEffect(() => {
- const messageList = messagesRef();
- const containerRef = messagesContainerRef();
-
- // Skip if dependencies not ready
- if (!messageList || !containerRef || !untrack(threadData)?.db_id) {
- return;
- }
-
- // Skip if still loading or already filled
- if (isFetching() || untrack(isContainerFilled)) {
- return;
- }
-
- const messageListHeight = messageList.getBoundingClientRect().height;
- const containerHeight = containerRef.getBoundingClientRect().height;
-
- // Load more if container isn't filled
- if (messageListHeight < containerHeight && hasMore()) {
- fetchNextPage();
- } else {
- setIsContainerFilled(true);
- }
- });
-
// ============================================
// PHASE 2: HANDLE TARGET MESSAGE SCROLLING
// ============================================
// This effect handles scrolling to a specific message (if provided via URL) or scrolling to the last message by default
// This effect should only run once.
- createEffect(() => {
- if (hasHandledTarget()) return;
- const data = threadQuery.data;
- if (!data) return;
- // Check if initial loading is complete
- const isInitialLoadComplete =
- (isContainerFilled() || data.hasMore === false) && !isFetching();
-
- // Skip if not ready
- if (!isInitialLoadComplete) {
- return;
- }
-
- // Skip if basic requirements not met
- if (!untrack(threadData) || !untrack(() => messagesRef())) {
- return;
- }
-
- // Mark as handled to prevent re-running
- setHasHandledTarget(true);
-
+ context.onInitialDataLoad(() => {
// Check for target message
- const targetMessageId_ = targetMessageId();
- if (targetMessageId_ && typeof targetMessageId_ !== 'string') return;
+ const targetMessageId_ = context.messages.targetMessageID();
+
+ if (targetMessageId_ && typeof targetMessageId_ !== 'string') return true;
if (targetMessageId_) {
handleTargetMessage(targetMessageId_);
@@ -436,21 +189,23 @@ export function Email(props: EmailProps) {
// Check if there is an unread message
if (lastUnreadMessageId_) {
setTimeout(() =>
- performScrollToMessage(lastUnreadMessageId_!, 'instant')
+ performScrollToMessage(lastUnreadMessageId_!, { behavior: 'instant' })
);
- setFocusedMessageId(lastUnreadMessageId_!);
+ context.messages.setFocused(lastUnreadMessageId_!);
} else {
// No unread message, scroll to last message
- setTimeout(() => scrollToLastMessageAndFocus('instant'));
+ scrollToLastMessage('instant', true);
}
}
+
+ return true;
});
/**
* Handles scrolling to a specific message ID from URL
*/
async function handleTargetMessage(messageId: string) {
- const messages = untrack(() => filteredMessages());
+ const messages = untrack(context.messages.list);
if (!messages) return;
const targetIndex = messages.findIndex((m) => m.db_id === messageId);
@@ -460,59 +215,41 @@ export function Email(props: EmailProps) {
const found = await loadMessagesUntilFound(messageId);
if (found) {
// Load one more batch for scroll context
- await loadContextBatch();
+ fetchNextPage();
+ await waitForQueryLoad();
// Scroll to the message after DOM updates
- setTimeout(() => performScrollToMessage(messageId, 'instant'));
+ setTimeout(() =>
+ performScrollToMessage(messageId, { behavior: 'instant' })
+ );
} else {
// Message not found, fallback to last message
- setTimeout(() => scrollToLastMessageAndFocus('instant'));
+ setTimeout(() => scrollToLastMessage('instant', true));
}
} catch (error) {
console.error('Error loading target message:', error);
- setTimeout(() => scrollToLastMessageAndFocus('instant'));
+ setTimeout(() => scrollToLastMessage('instant', true));
}
}
// Case 2: Message is first in current batch - load more for context
else if (targetIndex === 0) {
- await loadContextBatch();
- setTimeout(() => performScrollToMessage(messageId, 'instant'));
- }
- // Case 3: Message is in current batch with sufficient context
- else {
- setTimeout(() => performScrollToMessage(messageId, 'instant'));
+ fetchNextPage();
+ await waitForQueryLoad();
+ setTimeout(() =>
+ performScrollToMessage(messageId, { behavior: 'instant' })
+ );
}
- }
- const archiveThread = createCallback(() => {
- const thread = threadData();
- if (!thread?.db_id) return false;
- archiveThreadMutate({
- threadId: thread.db_id,
- archive: thread.inbox_visible,
- });
-
- if (!props) return false;
-
- const selectedEntity = entities()?.find(
- (entity) => entity.id === threadData()!.db_id
+ // Case 3: Message is in current batch with sufficient context
+ setTimeout(() =>
+ performScrollToMessage(messageId, { behavior: 'instant' })
);
-
- if (selectedEntity) {
- actionRegistry.execute('mark_as_done', selectedEntity);
- } else {
- archiveThreadMutate({
- threadId: thread.db_id,
- archive: thread.inbox_visible,
- });
- }
-
- return true;
- });
+ }
// If there is a focused message id, but it does not currently exist in the message list, it is because the user has just sent a message. When it does come into existence, we want to scroll to the bottom.
createEffect((prev: boolean | undefined) => {
- const currentFocusedId = focusedMessageId();
- const messages = filteredMessages();
+ const currentFocusedId = context.messages.focusedID();
+ const messages = context.messages.list();
+
if (!currentFocusedId || !messages) return true;
const currentIndex = messages.findIndex(
@@ -522,19 +259,16 @@ export function Email(props: EmailProps) {
if (prev === false) {
setTimeout(() => {
- const container = messagesRef();
- if (container) {
- scrollToLastMessage(container, 'smooth');
- }
+ scrollToLastMessage('smooth');
}, 100);
}
return true;
});
const navigateMessage = createCallback((dir: 'prev' | 'next') => {
- const currentFocusedId = focusedMessageId();
- const messages = filteredMessages();
- const list = messagesRef();
+ const currentFocusedId = context.messages.focusedID();
+ const messages = context.messages.list();
+ const list = context.messagesListRef();
if (!currentFocusedId || !messages || !list) return false;
const currentIndex = messages.findIndex(
@@ -543,27 +277,29 @@ export function Email(props: EmailProps) {
if (currentIndex < 0) return false;
const delta = dir === 'prev' ? -1 : 1;
+
const targetIndex = currentIndex + delta;
+
if (targetIndex < 0 || targetIndex >= messages.length) return false;
const targetMsg = messages[targetIndex];
+
if (!targetMsg?.db_id) return false;
- const targetEl = list.children.item(targetIndex) as HTMLDivElement | null;
- targetEl?.scrollIntoView({ behavior: 'smooth', block: 'start' });
- targetEl?.focus();
- setFocusedMessageId(targetMsg.db_id);
+ performScrollToMessage(targetMsg.db_id, {
+ behavior: 'smooth',
+ focus: true,
+ });
+
return true;
});
- const navigateToPreviousMessage = createCallback(() =>
- navigateMessage('prev')
- );
- const navigateToNextMessage = createCallback(() => navigateMessage('next'));
+ const navigateToPreviousMessage = () => navigateMessage('prev');
+ const navigateToNextMessage = () => navigateMessage('next');
onMount(() => {
- registerEmailHotkeys(scopeId(), threadData, {
- archiveThread,
+ registerEmailHotkeys(scopeId(), context.thread, {
+ archiveThread: context.archiveThread,
navigateToPreviousMessage,
navigateToNextMessage,
});
@@ -579,20 +315,6 @@ export function Email(props: EmailProps) {
hasRun = true;
});
- const notificationSource = useGlobalNotificationSource();
-
- createEffectOnEntityTypeNotification(
- notificationSource,
- 'email',
- (notification) => {
- if (!isNewEmail(notification)) return;
- const notificationThreadId = notification.notificationMetadata.threadId;
- if (notificationThreadId === threadData()?.db_id) {
- threadQuery.refetch();
- }
- }
- );
-
let markdownDomRef!: HTMLDivElement;
registerScopeSignalHotkey(scopeId, {
@@ -609,49 +331,34 @@ export function Email(props: EmailProps) {
hide: true,
});
- const refetch = () => threadQuery.refetch();
-
return (
- <EmailProvider
- value={{
- recipientOptions,
- onRecipientsAugment: onRecipientsAugment,
- messageDbIdToDraftChildren,
- setMessageDbIdToDraftChildren,
- messagesRef,
- setMessagesRef: setmessagesRef,
- threadId: props.threadId,
- focusedMessageId,
- setFocusedMessageId,
- filteredMessages,
- threadData,
- hasMore,
- isFetching,
- fetchNextPage,
- refetch,
- archiveThread,
- activeTargetMessageId,
- draftsSettled,
- }}
- >
- <EmailFormContextProvider>
- <div class="w-full h-full bg-panel select-none overscroll-none overflow-hidden flex flex-col">
- <TopBar title={props.title()} />
- <div
- class="w-full flex-1 flex flex-col items-center justify-center overflow-hidden"
- ref={setMessagesContainerRef}
- >
- <MessageList initialLoadComplete={hasHandledTarget()} />
- </div>
- {/* <div class="z-4 absolute left-[44px] bottom-[92px] w-[21px] rounded-bl-xl min-h-[84px] border-l border-b border-edge" /> */}
- <Show when={draftsSettled() && filteredMessages()?.at(-1)}>
- {(lastMessage) => (
+ <EmailFormContextProvider>
+ <div class="w-full h-full bg-panel select-none overscroll-none overflow-hidden flex flex-col">
+ <TopBar title={props.title()} />
+ <div
+ class="w-full flex-1 flex flex-col items-center overflow-hidden"
+ ref={context.registerMessagesContainer}
+ >
+ <MessageList initialLoadComplete={context.initialLoadComplete()} />
+ </div>
+ <Show
+ when={
+ context.drafts.initialDraftsSettled() &&
+ context.messages.list().at(-1)
+ }
+ >
+ {(lastMessage) => {
+ return (
<div class="shrink-0 w-full px-4 pb-2">
<div class="w-full flex flex-row justify-center bg-panel macro-message-width mx-auto">
<EmailInput
replyingTo={lastMessage}
draft={
- messageDbIdToDraftChildren[lastMessage().db_id ?? '']
+ lastMessage().db_id
+ ? context.drafts.getDraftForMessage(
+ lastMessage().db_id!
+ )
+ : undefined
}
markdownDomRef={(el) => {
markdownDomRef = el;
@@ -659,10 +366,10 @@ export function Email(props: EmailProps) {
/>
</div>
</div>
- )}
- </Show>
- </div>
- </EmailFormContextProvider>
- </EmailProvider>
+ );
+ }}
+ </Show>
+ </div>
+ </EmailFormContextProvider>
);
}
diff --git a/js/app/packages/block-email/component/EmailContext.tsx b/js/app/packages/block-email/component/EmailContext.tsx
index 1719475a04..63da53ac62 100644
--- a/js/app/packages/block-email/component/EmailContext.tsx
+++ b/js/app/packages/block-email/component/EmailContext.tsx
@@ -1,55 +1,427 @@
-import type { WithCustomUserInput } from '@core/user';
+import { useGlobalNotificationSource } from '@app/component/GlobalAppState';
+import { useSplitPanelOrThrow } from '@app/component/split-layout/layoutUtils';
+import { URL_PARAMS } from '@block-email/constants';
+import { toast } from '@core/component/Toast/Toast';
+import { createMethodRegistration } from '@core/orchestrator';
+import { blockHandleSignal } from '@core/signal/load';
+import {
+ recipientEntityMapper,
+ useContacts,
+ type WithCustomUserInput,
+} from '@core/user';
+import { whenSettled } from '@core/util/whenSettled';
+import {
+ createEffectOnEntityTypeNotification,
+ isNewEmail,
+} from '@notifications';
+import {
+ useArchiveThreadMutation,
+ useThreadQuery,
+} from '@queries/email/thread';
import type {
+ ContactInfo,
MessageWithBodyReplyless,
Thread,
} from '@service-email/generated/schemas';
+import { useSearchParams } from '@solidjs/router';
import {
type Accessor,
createContext,
- type Setter,
+ createEffect,
+ createMemo,
+ createSignal,
+ type FlowProps,
+ Suspense,
+ untrack,
useContext,
} from 'solid-js';
-import type { SetStoreFunction } from 'solid-js/store';
+import { createStore } from 'solid-js/store';
export type EmailRecipient = WithCustomUserInput<'user' | 'contact'>;
-export type EmailContextValue = {
+export type EmailContextValues = {
+ registerMessagesList: (list: HTMLElement) => void;
+ messagesListRef: Accessor<HTMLElement | undefined>;
+ registerMessagesContainer: (container: HTMLElement) => void;
+ messagesContainerRef: Accessor<HTMLElement | undefined>;
+
recipientOptions: Accessor<EmailRecipient[]>;
- onRecipientsAugment: (items: EmailRecipient[]) => void;
- messageDbIdToDraftChildren: Record<string, MessageWithBodyReplyless>;
- setMessageDbIdToDraftChildren: SetStoreFunction<
- Record<string, MessageWithBodyReplyless>
- >;
- messagesRef: Accessor<HTMLDivElement | undefined>;
- setMessagesRef: Setter<HTMLDivElement | undefined>;
- threadId: Accessor<string>;
- focusedMessageId: Accessor<string | undefined>;
- setFocusedMessageId: Setter<string | undefined>;
- filteredMessages: Accessor<MessageWithBodyReplyless[]>;
- threadData: Accessor<Thread | undefined>;
- hasMore: Accessor<boolean>;
- isFetching: Accessor<boolean>;
- fetchNextPage: () => void;
- refetch: () => void;
- archiveThread: Accessor<boolean>;
- activeTargetMessageId: Accessor<string | undefined>;
- draftsSettled: Accessor<boolean>;
+ onRecipientsChange: (items: EmailRecipient[]) => void;
+
+ drafts: {
+ getDraftForMessage: (
+ messageDbID: string
+ ) => MessageWithBodyReplyless | undefined;
+ deleteDraftForMessage: (messageDbID: string) => void;
+ initialDraftsSettled: Accessor<boolean>;
+ };
+
+ messages: {
+ unfiltered: Accessor<MessageWithBodyReplyless[]>;
+ list: Accessor<MessageWithBodyReplyless[]>;
+ targetMessageID: Accessor<string | undefined>;
+ setTargetMessageID: (id: string | undefined) => void;
+ focusedID: Accessor<string | undefined>;
+ setFocused: (messageID: string | undefined) => void;
+ };
+ thread: Accessor<Thread | undefined>;
+
+ query: {
+ hasMore: Accessor<boolean>;
+ isFetching: Accessor<boolean>;
+ fetchNextPage: () => void;
+ refetch: () => void;
+ };
+
+ archiveThread: () => boolean;
+ initialLoadComplete: Accessor<boolean>;
+ onInitialDataLoad: (callback: () => boolean) => void;
};
-const EmailContext = createContext<EmailContextValue>();
+const EmailContext = createContext<EmailContextValues>();
+
+export function EmailProvider(props: FlowProps<{ threadID: string }>) {
+ const threadQuery = useThreadQuery(
+ () => props.threadID,
+ () => ({
+ select(data) {
+ const messages = data.pages.flatMap((t) => t.messages);
+
+ const filtered = [];
+ const messageDraftMap: Record<string, MessageWithBodyReplyless> = {};
+
+ for (const message of messages) {
+ if (!message.is_draft) {
+ filtered.push(message);
+ continue;
+ }
+
+ if (message.body_html_sanitized?.trim().length === 0) {
+ continue;
+ }
+
+ const replyingToId = message.replying_to_id;
+
+ if (!replyingToId) continue;
+
+ messageDraftMap[replyingToId] = message;
+ }
+
+ filtered.sort((a, b) => {
+ if (a.internal_date_ts && b.internal_date_ts) {
+ return (
+ new Date(a.internal_date_ts).getTime() -
+ new Date(b.internal_date_ts).getTime()
+ );
+ }
+ // Below is fallback for when internal_date_ts is not set
+ else if (a.sent_at && b.sent_at) {
+ return (
+ new Date(a.sent_at).getTime() - new Date(b.sent_at).getTime()
+ );
+ }
+ return 0;
+ });
+
+ return {
+ ...data.pages[0],
+ messages: messages,
+ filtered: filtered,
+ draftMap: messageDraftMap,
+ };
+ },
+ })
+ );
+
+ const notificationSource = useGlobalNotificationSource();
+
+ createEffectOnEntityTypeNotification(
+ notificationSource,
+ 'email',
+ (notification) => {
+ if (!isNewEmail(notification)) return;
+ const notificationThreadId = notification.notificationMetadata.threadId;
+ if (notificationThreadId === threadQuery.data?.db_id) {
+ threadQuery.refetch();
+ }
+ }
+ );
+
+ const [focusedMessageId, setFocusedMessageId] = createSignal<string>();
+ const [searchParams] = useSearchParams();
+ const searchParamsMessageId = () => {
+ const messageID = searchParams[URL_PARAMS.messageId];
+ if (typeof messageID === 'string') {
+ return messageID;
+ } else if (Array.isArray(messageID)) {
+ return messageID[0];
+ }
+ return undefined;
+ };
+ const [targetMessageId, setTargetMessageId] = createSignal<
+ string | undefined
+ >(searchParamsMessageId());
+
+ const [hasHandledTarget, setHasHandledTarget] = createSignal(false);
+
+ const blockHandle = blockHandleSignal.get;
+ createMethodRegistration(blockHandle, {
+ goToLocationFromParams: (params: Record<string, any>) => {
+ if (params[URL_PARAMS.messageId]) {
+ setTargetMessageId(undefined);
+ setTimeout(() => {
+ setTargetMessageId(params[URL_PARAMS.messageId]);
+ setHasHandledTarget(false);
+ }, 0);
+ }
+ },
+ });
+
+ const [messageDraftMap, setMessageDraftMap] = createStore<
+ Record<string, MessageWithBodyReplyless | undefined>
+ >({});
+
+ const deleteDraftForMessage = (messageID: string) => {
+ setMessageDraftMap(messageID, undefined!);
+ };
+
+ const getDraftForMessage = (messageID: string) => {
+ return messageDraftMap[messageID];
+ };
+
+ const [draftsSettled, setDraftsSettled] = createSignal(false);
+
+ whenSettled(
+ threadQuery,
+ (data) => {
+ setMessageDraftMap(data.draftMap);
+ setDraftsSettled(true);
+ },
+ (error) => {
+ console.error('Failed to load thread data:', error);
+ toast.failure('Failed to load email thread. Please try again.');
+ }
+ );
+
+ const contacts = useContacts();
+
+ const [augmentedRecipients, setAugmentedRecipients] = createSignal<
+ EmailRecipient[]
+ >([]);
+
+ function onRecipientsChange(items: EmailRecipient[]) {
+ const existing = augmentedRecipients();
+ const existingEmails = new Set(
+ existing.map((r) => r.data.email).filter((e) => e.length > 0)
+ );
+
+ const uniques: EmailRecipient[] = [];
+ for (const r of items) {
+ const email = r.data.email;
+ if (email && !existingEmails.has(email)) {
+ existingEmails.add(email);
+ uniques.push(r);
+ }
+ }
+
+ if (uniques.length === 0) return;
+ setAugmentedRecipients([...existing, ...uniques]);
+ }
+
+ const getRecipientOptions = () => {
+ const optionsMap = new Map<string, EmailRecipient>();
+
+ for (const contact of contacts()) {
+ const mapped = recipientEntityMapper('user')(contact);
+ optionsMap.set(mapped.data.email, mapped);
+ }
+
+ const thread = threadQuery.data;
+ if (thread) {
+ const seen = new Map<string, ContactInfo>();
+
+ const add = (c: ContactInfo) => {
+ const existing = seen.get(c.email);
+ if (!existing || (!existing.name && c.name)) seen.set(c.email, c);
+ };
+
+ thread.messages.forEach((m) => {
+ m.to.forEach(add);
+ m.cc.forEach(add);
+ m.bcc.forEach(add);
+ if (m.from?.email)
+ add({
+ email: m.from.email,
+ name: m.from.name ?? undefined,
+ });
+ });
+
+ for (const value of seen.values()) {
+ const mapped = recipientEntityMapper('contact')({
+ ...value,
+ type: 'extracted',
+ id: value.email,
+ });
+ optionsMap.set(mapped.data.email, mapped);
+ }
+ }
+
+ augmentedRecipients().forEach((r) => {
+ const email = r.data.email;
+ if (email && !optionsMap.has(email)) optionsMap.set(email, r);
+ });
+
+ return Array.from(optionsMap.values());
+ };
+
+ const {
+ unifiedListContext: {
+ entitiesSignal: [entities],
+ actionRegistry,
+ },
+ } = useSplitPanelOrThrow();
+
+ const archiveMutation = useArchiveThreadMutation({
+ onError: () => {
+ toast.failure('Failed to archive thread');
+ },
+ });
+
+ const archiveThread = () => {
+ const thread = threadQuery.data;
+
+ if (!thread?.db_id) return false;
+
+ archiveMutation.mutate({
+ threadId: thread.db_id,
+ archive: thread.inbox_visible,
+ });
+
+ if (!props) return false;
+
+ const selectedEntity = entities()?.find(
+ (entity) => entity.id === thread.db_id
+ );
+
+ if (selectedEntity) {
+ actionRegistry.execute('mark_as_done', selectedEntity);
+ } else {
+ archiveMutation.mutate({
+ threadId: thread.db_id,
+ archive: thread.inbox_visible,
+ });
+ }
+
+ return true;
+ };
+
+ const [messagesListRef, setMessagesListRef] = createSignal<
+ HTMLDivElement | undefined
+ >(undefined);
+ const [messagesContainerRef, setMessagesContainerRef] = createSignal<
+ HTMLDivElement | undefined
+ >(undefined);
+
+ let containerFilled = false;
+ const isContainerFilled = () => {
+ const messageList = messagesListRef();
+ const containerRef = messagesContainerRef();
+
+ // Skip if dependencies not ready
+ if (
+ !messageList ||
+ !containerRef ||
+ !untrack(() => threadQuery.data)?.db_id
+ ) {
+ containerFilled = false;
+ return false;
+ }
+
+ // Skip if still loading or already filled
+ if (threadQuery.isFetching || containerFilled) {
+ return containerFilled;
+ }
+
+ const messageListHeight = messageList.getBoundingClientRect().height;
+ const containerHeight = containerRef.getBoundingClientRect().height;
+
+ // Load more if container isn't filled
+ if (
+ messageListHeight < containerHeight &&
+ threadQuery.hasNextPage &&
+ !threadQuery.isFetching
+ ) {
+ threadQuery.fetchNextPage();
+ containerFilled = false;
+ return false;
+ }
+ containerFilled = true;
+ return true;
+ };
+
+ const onInitialDataLoad = (callback: () => boolean) => {
+ createEffect(() => {
+ if (hasHandledTarget()) return;
+ const fetching = threadQuery.isFetching;
+ if (fetching) return;
+ // Check if initial loading is complete
+ const isInitialLoadComplete =
+ (isContainerFilled() || threadQuery.hasNextPage === false) &&
+ !threadQuery.isFetching;
+
+ if (!isInitialLoadComplete) return;
+
+ // Skip if basic requirements not met
+ if (!untrack(messagesListRef)) {
+ return;
+ }
+
+ setHasHandledTarget(callback());
+ });
+ };
-export function EmailProvider(props: {
- value: EmailContextValue;
- children: any;
-}) {
return (
- <EmailContext.Provider value={props.value}>
- {props.children}
- </EmailContext.Provider>
+ <Suspense>
+ <EmailContext.Provider
+ value={{
+ registerMessagesList: setMessagesListRef,
+ registerMessagesContainer: setMessagesContainerRef,
+ thread: createMemo(() => threadQuery.data),
+ recipientOptions: createMemo(getRecipientOptions),
+ onRecipientsChange,
+ archiveThread,
+ messagesContainerRef,
+ messagesListRef,
+ query: {
+ hasMore: () => threadQuery.hasNextPage ?? false,
+ fetchNextPage: threadQuery.fetchNextPage,
+ isFetching: () => threadQuery.isFetching,
+ refetch: threadQuery.refetch,
+ },
+ drafts: {
+ deleteDraftForMessage,
+ getDraftForMessage,
+ initialDraftsSettled: draftsSettled,
+ },
+ messages: {
+ focusedID: focusedMessageId,
+ setFocused: setFocusedMessageId,
+ targetMessageID: targetMessageId,
+ setTargetMessageID: setTargetMessageId,
+ list: createMemo(() => threadQuery.data?.filtered ?? []),
+ unfiltered: createMemo(() => threadQuery.data?.messages ?? []),
+ },
+ initialLoadComplete: hasHandledTarget,
+ onInitialDataLoad,
+ }}
+ >
+ {props.children}
+ </EmailContext.Provider>
+ </Suspense>
);
}
-export function useEmailContext(): EmailContextValue {
+export function useEmailContext() {
const ctx = useContext(EmailContext);
if (!ctx) {
throw new Error('useEmailContext must be used within an EmailProvider');
diff --git a/js/app/packages/block-email/component/EmailInput.tsx b/js/app/packages/block-email/component/EmailInput.tsx
index 9ca3e93cac..128fe759da 100644
--- a/js/app/packages/block-email/component/EmailInput.tsx
+++ b/js/app/packages/block-email/component/EmailInput.tsx
@@ -1,3 +1,4 @@
+import { useEmailContext } from '@block-email/component/EmailContext';
import type {
MessageToSendDbId,
MessageWithBodyReplyless,
@@ -5,7 +6,6 @@ import type {
import { type Accessor, createMemo, type Setter, Show } from 'solid-js';
import { decodeBase64Utf8 } from '../util/decodeBase64';
import { BaseInput } from './BaseInput';
-import { useEmailContext } from './EmailContext';
interface EmailInputProps {
replyingTo: Accessor<MessageWithBodyReplyless>;
@@ -26,14 +26,14 @@ export function EmailInput(props: EmailInputProps) {
function afterSend(newMessageId: MessageToSendDbId | null) {
// Refresh to get the new message
- ctx.refetch();
+ ctx.query.refetch();
// Set focus to new message if provided
- if (newMessageId) ctx.setFocusedMessageId(newMessageId);
+ if (newMessageId) ctx.messages.setFocused(newMessageId);
}
return (
- <Show when={props.replyingTo() && ctx.draftsSettled()}>
+ <Show when={props.replyingTo() && ctx.drafts.initialDraftsSettled()}>
<BaseInput
replyingTo={props.replyingTo}
draft={props.draft}
diff --git a/js/app/packages/block-email/component/EmailMessageBody.tsx b/js/app/packages/block-email/component/EmailMessageBody.tsx
index 87245843d6..2a11826912 100644
--- a/js/app/packages/block-email/component/EmailMessageBody.tsx
+++ b/js/app/packages/block-email/component/EmailMessageBody.tsx
@@ -12,7 +12,6 @@ import {
createMemo,
createSignal,
Match,
- type Setter,
Show,
Switch,
untrack,
@@ -26,8 +25,8 @@ interface EmailMessageBodyProps {
message: MessageWithBodyReplyless;
isBodyExpanded: Accessor<boolean>;
setExpandedMessageBody: (id: string) => void;
- setFocusedMessageId: Setter<string | undefined>;
- threadMessageIndex: number;
+ setFocusedMessageId: (messageID: string | undefined) => void;
+ isFirstMessageInThread: boolean;
}
export function EmailMessageBody(props: EmailMessageBodyProps) {
@@ -84,7 +83,7 @@ export function EmailMessageBody(props: EmailMessageBodyProps) {
});
const source = () => {
- return showFullHTML() || props.threadMessageIndex === 0
+ return showFullHTML() || props.isFirstMessageInThread
? parsedBodyHtml()
: parsedBodyReplyless();
};
diff --git a/js/app/packages/block-email/component/EmailMessageTopBar.tsx b/js/app/packages/block-email/component/EmailMessageTopBar.tsx
index a297fc570a..ff893d681a 100644
--- a/js/app/packages/block-email/component/EmailMessageTopBar.tsx
+++ b/js/app/packages/block-email/component/EmailMessageTopBar.tsx
@@ -16,7 +16,7 @@ interface EmailMessageTopBarProps {
isBodyExpanded: Accessor<boolean>;
expandedHeader: Accessor<boolean>;
setExpandedHeader: Setter<boolean>;
- setFocusedMessageId: Setter<string | undefined>;
+ setFocusedMessageId: (messageId: string | undefined) => void;
setShowReply: Setter<boolean>;
isLastMessage?: boolean;
}
diff --git a/js/app/packages/block-email/component/MessageContainer.tsx b/js/app/packages/block-email/component/MessageContainer.tsx
index 4b0f95ad8c..f7d3806b16 100644
--- a/js/app/packages/block-email/component/MessageContainer.tsx
+++ b/js/app/packages/block-email/component/MessageContainer.tsx
@@ -1,4 +1,9 @@
import { useSplitLayout } from '@app/component/split-layout/layout';
+import { EmailAttachmentPill } from '@block-email/component/AttachmentPill';
+import { useEmailContext } from '@block-email/component/EmailContext';
+import { EmailInput } from '@block-email/component/EmailInput';
+import { EmailMessageBody } from '@block-email/component/EmailMessageBody';
+import { EmailMessageTopBar } from '@block-email/component/EmailMessageTopBar';
import { ImageGalleryPreview } from '@core/component/ImageGalleryPreview';
import { ImagePreview } from '@core/component/ImagePreview';
import { Message } from '@core/component/Message';
@@ -28,11 +33,6 @@ import {
} from 'solid-js';
import type { SetStoreFunction } from 'solid-js/store';
import { Portal } from 'solid-js/web';
-import { EmailAttachmentPill } from './AttachmentPill';
-import { useEmailContext } from './EmailContext';
-import { EmailInput } from './EmailInput';
-import { EmailMessageBody } from './EmailMessageBody';
-import { EmailMessageTopBar } from './EmailMessageTopBar';
interface MessageContainerProps {
message: MessageWithBodyReplyless;
@@ -42,14 +42,13 @@ interface MessageContainerProps {
isLastMessage: boolean;
isFocused: boolean;
isTarget: boolean;
- threadMessageIndex: number;
}
export function MessageContainer(props: MessageContainerProps) {
const context = useEmailContext();
const draftChild = createMemo(() => {
if (!props.message.db_id) return undefined;
- const draft = context.messageDbIdToDraftChildren[props.message.db_id];
+ const draft = context.drafts.getDraftForMessage(props.message.db_id);
if (!draft) return undefined;
return draft;
});
@@ -203,7 +202,7 @@ export function MessageContainer(props: MessageContainerProps) {
isBodyExpanded={isBodyExpanded}
expandedHeader={expandedHeader}
setExpandedHeader={setExpandedHeader}
- setFocusedMessageId={context.setFocusedMessageId}
+ setFocusedMessageId={context.messages.setFocused}
setShowReply={setShowReply}
isLastMessage={props.isLastMessage}
/>
@@ -215,8 +214,8 @@ export function MessageContainer(props: MessageContainerProps) {
setExpandedMessageBody={(id) =>
props.setExpandedMessageBodyIds(id, true)
}
- setFocusedMessageId={context.setFocusedMessageId}
- threadMessageIndex={props.threadMessageIndex}
+ setFocusedMessageId={context.messages.setFocused}
+ isFirstMessageInThread={props.isFirstMessage}
/>
</Message.Body>
{/* Image attachments */}
diff --git a/js/app/packages/block-email/component/MessageList.tsx b/js/app/packages/block-email/component/MessageList.tsx
index 691c95dc46..acbca80526 100644
--- a/js/app/packages/block-email/component/MessageList.tsx
+++ b/js/app/packages/block-email/component/MessageList.tsx
@@ -1,8 +1,8 @@
+import { useEmailContext } from '@block-email/component/EmailContext';
import { isScrollingToMessage } from '@block-email/signal/scrollState';
import { CircleSpinner } from '@core/component/CircleSpinner';
-import { createSelector, For, Show } from 'solid-js';
+import { createMemo, createSelector, For, Show } from 'solid-js';
import { createStore } from 'solid-js/store';
-import { useEmailContext } from './EmailContext';
import { MessageContainer } from './MessageContainer';
interface MessageListProps {
@@ -16,53 +16,82 @@ export function MessageList(props: MessageListProps) {
Record<string, boolean>
>({});
const isFocusedSelector = createSelector(
- context.focusedMessageId,
+ context.messages.focusedID,
(a, b) => !!a && !!b && a === b
);
const isTargetSelector = createSelector(
- context.activeTargetMessageId,
- (a, b) => !!a && !!b && a === b
+ context.messages.targetMessageID,
+ (a, b) => a === b
);
return (
<div
- class="pt-3 w-full flex-1 flex flex-col items-center overflow-y-scroll overflow-x-hidden suppress-css-brackets"
- ref={context.setMessagesRef}
+ class="pt-3 w-full flex flex-col-reverse items-center overflow-y-scroll overflow-x-hidden suppress-css-brackets"
+ ref={context.registerMessagesList}
onscroll={(e) => {
// Don't load more if we're programmatically scrolling to a message
if (getIsScrollingToMessage() || !props.initialLoadComplete) return;
const threshold = 300;
- const isNearBeginning = e.currentTarget.scrollTop <= threshold;
- if (isNearBeginning && !context.isFetching() && context.hasMore()) {
- context.fetchNextPage();
+ // Since the list is reversed, the scrollTop is negative. So we get the scroll position
+ // from the bottom up using the scrollHeight and clientHeight
+ const currentScrollPosition =
+ e.currentTarget.scrollHeight +
+ e.currentTarget.scrollTop -
+ e.currentTarget.clientHeight;
+
+ const isNearBeginning = currentScrollPosition <= threshold;
+
+ if (
+ isNearBeginning &&
+ !context.query.isFetching() &&
+ context.query.hasMore()
+ ) {
+ context.query.fetchNextPage();
}
}}
>
- <Show when={context.isFetching()}>
- <div class="flex items-center justify-center h-16">
- <CircleSpinner />
- </div>
- </Show>
- <For each={context.filteredMessages()}>
+ <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();
+
+ // 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 (
<MessageContainer
- isFirstMessage={index() === 0}
+ isFirstMessage={normalizedIndex() === 0}
isLastMessage={
- index() === (context.filteredMessages().length ?? 0) - 1
+ 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}
- threadMessageIndex={index()}
/>
);
}}
</For>
+
+ <Show when={context.query.isFetching()}>
+ <div class="flex items-center justify-center h-16">
+ <CircleSpinner />
+ </div>
+ </Show>
</div>
);
}
diff --git a/js/app/packages/block-email/component/createEmailFormState.ts b/js/app/packages/block-email/component/createEmailFormState.ts
index af59291440..001ee0771a 100644
--- a/js/app/packages/block-email/component/createEmailFormState.ts
+++ b/js/app/packages/block-email/component/createEmailFormState.ts
@@ -28,8 +28,8 @@ export function createEmailFormState(key: string) {
const emailCtx = useEmailContext();
const userEmail = useEmail();
- const replyingTo = emailCtx.filteredMessages().find((m) => m.db_id === key);
- const draft = emailCtx.messageDbIdToDraftChildren[key];
+ const replyingTo = emailCtx.messages.list().find((m) => m.db_id === key);
+ const draft = emailCtx.drafts.getDraftForMessage(key);
const draftContainsAppendedReply = () => {
const encoded = draft?.body_html_sanitized;
@@ -94,7 +94,7 @@ export function createEmailFormState(key: string) {
setRecipientsInner(field, next);
callDirty();
const all = [...recipients.to, ...recipients.cc, ...recipients.bcc];
- emailCtx.onRecipientsAugment(all);
+ emailCtx.onRecipientsChange(all);
};
const initialSubject =
@@ -177,7 +177,7 @@ export function createEmailFormState(key: string) {
...initialRecipients.cc,
...initialRecipients.bcc,
];
- emailCtx.onRecipientsAugment(all);
+ emailCtx.onRecipientsChange(all);
// Restore subject and input focus
setSubjectInner(initialSubject);
diff --git a/js/app/packages/block-email/util/scrollToMessage.ts b/js/app/packages/block-email/util/scrollToMessage.ts
index ba8be9b1cc..dae04d1769 100644
--- a/js/app/packages/block-email/util/scrollToMessage.ts
+++ b/js/app/packages/block-email/util/scrollToMessage.ts
@@ -11,10 +11,17 @@ import type { MessageWithBodyReplyless } from '@service-email/generated/schemas'
export function scrollToMessage(
messageId: string,
messages: MessageWithBodyReplyless[],
- messagesContainer: HTMLDivElement,
- behavior: ScrollBehavior = 'smooth'
+ messagesContainer: HTMLElement,
+ {
+ behavior = 'smooth',
+ reversed = false,
+ }: { behavior?: ScrollBehavior; reversed?: boolean }
): boolean {
- const messageIndex = messages.findIndex((m) => m.db_id === messageId);
+ let messageIndex = messages.findIndex((m) => m.db_id === messageId);
+
+ if (reversed) {
+ messageIndex = messages.length - 1 - messageIndex;
+ }
if (messageIndex < 0) {
return false;
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 82e118e133..29d2e51e63 100644
--- a/js/app/packages/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx
+++ b/js/app/packages/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx
@@ -15,6 +15,7 @@ import {
createEffect,
createSignal,
type JSX,
+ on,
onCleanup,
Show,
} from 'solid-js';
@@ -112,6 +113,8 @@ export function MarkdownTextarea(props: MarkdownTextareaProps) {
const [markdownState, setMarkdownState] = createSignal<string>('');
+ let didInitializeContent = false;
+
const onConnect = () => {
if (props.focusOnMount) {
setTimeout(() => {
@@ -124,15 +127,30 @@ export function MarkdownTextarea(props: MarkdownTextareaProps) {
} else if (props.initialValue) {
setEditorStateFromMarkdown(editor, props.initialValue);
}
+
+ if (props.initialHtml || props.initialValue) {
+ // We do this to make sure anything relying on the markdownState existing initially
+ // has the content
+ props.onChange?.(markdownState());
+ }
+
+ didInitializeContent = true;
};
createEffect(() => {
editor.setEditable(props.editable());
});
- createEffect(() => {
- props.onChange?.(markdownState(), editor);
- });
+ createEffect(
+ on(
+ markdownState,
+ () => {
+ if (!didInitializeContent) return;
+ props.onChange?.(markdownState(), editor);
+ },
+ { defer: true }
+ )
+ );
if (props.initialHtml) {
setEditorStateFromHtml(editor, props.initialHtml);
@@ -273,6 +291,8 @@ export function MarkdownTextarea(props: MarkdownTextareaProps) {
ref={(el) => {
onElementConnect(el, () => {
editor.setRootElement(el);
+ props.domRef?.(el);
+ mountRef = el;
onConnect();
});
}}
diff --git a/js/app/packages/notifications/components/DebouncedNotificationReadMarker.tsx b/js/app/packages/notifications/components/DebouncedNotificationReadMarker.tsx
index 5f72c93782..71ad199d48 100644
--- a/js/app/packages/notifications/components/DebouncedNotificationReadMarker.tsx
+++ b/js/app/packages/notifications/components/DebouncedNotificationReadMarker.tsx
@@ -115,7 +115,14 @@ export function EmailDebouncedReadMarker(props: {
return (
<DebouncedMarker
debounceTime={props.debounceTime}
- debouncedFn={() => markSeenMutation.mutate({ threadId: props.threadId })}
+ debouncedFn={() => {
+ const hasUnreadNotification = props.notificationSource
+ .notifications()
+ .find((e) => e.entity_id === props.threadId);
+ if (!hasUnreadNotification) return;
+
+ markSeenMutation.mutate({ threadId: props.threadId });
+ }}
/>
);
}
diff --git a/js/app/packages/queries/email/thread.ts b/js/app/packages/queries/email/thread.ts
index 26f2840895..0e437917b7 100644
--- a/js/app/packages/queries/email/thread.ts
+++ b/js/app/packages/queries/email/thread.ts
@@ -8,6 +8,8 @@ import type {
} from '@service-email/generated/schemas';
import {
type InfiniteData,
+ type SolidInfiniteQueryOptions,
+ type UseInfiniteQueryResult,
useInfiniteQuery,
useMutation,
} from '@tanstack/solid-query';
@@ -18,6 +20,23 @@ import { emailKeys } from './keys';
const THREAD_STALE_TIME = 5 * 60 * 1000;
+type ThreadQueryOptions = SolidInfiniteQueryOptions<
+ Thread,
+ Error,
+ any,
+ ReturnType<typeof emailKeys.threadMessages>['queryKey'],
+ number
+>;
+
+type UseThreadQueryOptions = Omit<
+ ThreadQueryOptions,
+ | 'queryFn'
+ | 'queryKey'
+ | 'initialData'
+ | 'getNextPageParam'
+ | 'initialPageParam'
+>;
+
/**
* Shared infinite query options for thread fetching.
*/
@@ -96,7 +115,22 @@ export type ThreadQueryData = {
/**
* Query hook for fetching a thread with paginated messages.
*/
-export function useThreadQuery(threadId: Accessor<string>) {
+export function useThreadQuery(
+ threadId: Accessor<string>
+): UseInfiniteQueryResult<ThreadQueryData, Error>;
+export function useThreadQuery<Options extends UseThreadQueryOptions>(
+ threadId: Accessor<string>,
+ options: Accessor<Options>
+): UseInfiniteQueryResult<
+ Options['select'] extends undefined
+ ? ThreadQueryData
+ : ReturnType<NonNullable<Options['select']>>,
+ Error
+>;
+export function useThreadQuery<Options extends UseThreadQueryOptions>(
+ threadId: Accessor<string>,
+ options?: Accessor<Options>
+): UseInfiniteQueryResult<ThreadQueryData, Error> {
return useInfiniteQuery(() => ({
...threadQueryOptions(threadId()),
select: (data: InfiniteData<Thread, number>): ThreadQueryData => {
@@ -106,6 +140,7 @@ export function useThreadQuery(threadId: Accessor<string>) {
hasMore: lastPage.messages.length === DEFAULT_THREAD_MESSAGES_LIMIT,
};
},
+ ...(options?.() ?? {}),
}));
}