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[channels]: new thread reply updates gated by typing (#429)

Peter Chinman8e371a49bf5a
diff --git a/js/app/packages/block-channel/component/BaseInput.tsx b/js/app/packages/block-channel/component/BaseInput.tsx
index b3e2ec68cc..ea90475920 100644
--- a/js/app/packages/block-channel/component/BaseInput.tsx
+++ b/js/app/packages/block-channel/component/BaseInput.tsx
@@ -67,10 +67,6 @@ type BaseInputProps = {
onSend: (args: Parameters<typeof sendMessage>[0]) => Promise<void>;
/** callback to be executed when the user changes the input */
onChange: (content: string) => void;
- /** callback to be executed when the user clears the input */
- onEmpty: () => void;
- /** callback to be executed when the user presses escape */
- escHandler?: () => void;
/** initial value of the input */
initialValue?: Accessor<string>;
/** placeholder text to be displayed */
@@ -95,14 +91,15 @@ type BaseInputProps = {
/** the list of users in the channel */
channelUsers?: () => IUser[];
domRef?: (ref: HTMLDivElement) => void | HTMLDivElement;
- /** callback to delete draft */
- onDeleteDraft?: () => void;
+ /** callback to be called to "clear the input" */
+ onEmptyBlur?: () => void;
/** whether this input is for a reply (affects styling) */
isReplyInput?: boolean;
};
-/** the time after a user stops typing before we consider them idle */
-const ACTIVITY_TIMEOUT_MS = 2000;
+/** the time after a user stops typing before we consider them idle. we want smooth remote changes, but local changes should happen more immediately. */
+const REMOTE_ACTIVITY_TIMEOUT_MS = 2000;
+const LOCAL_ACTIVITY_TIMEOUT_MS = 500;
export function BaseInput(props: BaseInputProps) {
let containerRef!: HTMLDivElement;
@@ -125,8 +122,8 @@ export function BaseInput(props: BaseInputProps) {
);
const [typing, setTyping] = createSignal(false);
- let inactivityTimeout: ReturnType<typeof setTimeout> | undefined;
- let localTypingTimeout: ReturnType<typeof setTimeout> | undefined;
+ let remoteInactivityTimeout: ReturnType<typeof setTimeout> | undefined;
+ let localInactivityTimeout: ReturnType<typeof setTimeout> | undefined;
let viewportObserver: IntersectionObserver | undefined;
const [showAttachMenu, setShowAttachMenu] = createSignal(false);
@@ -134,21 +131,38 @@ export function BaseInput(props: BaseInputProps) {
createSignal<HTMLDivElement>();
function resetInactivityTimeout() {
- if (inactivityTimeout) {
- clearTimeout(inactivityTimeout);
+ if (remoteInactivityTimeout) {
+ clearTimeout(remoteInactivityTimeout);
}
- inactivityTimeout = setTimeout(() => stopTyping(), ACTIVITY_TIMEOUT_MS);
+ if (localInactivityTimeout) {
+ clearTimeout(localInactivityTimeout);
+ }
+ remoteInactivityTimeout = setTimeout(
+ () => stopRemoteTyping(),
+ REMOTE_ACTIVITY_TIMEOUT_MS
+ );
+ localInactivityTimeout = setTimeout(
+ () => stopLocalTyping(),
+ LOCAL_ACTIVITY_TIMEOUT_MS
+ );
}
- function stopTyping() {
+ function stopRemoteTyping() {
if (typing()) {
setTyping(false);
props.onStopTyping();
- if (localTypingTimeout) clearTimeout(localTypingTimeout);
- props.setLocalTyping?.(false);
}
}
+ function stopLocalTyping() {
+ props.setLocalTyping?.(false);
+ }
+
+ function stopTyping() {
+ stopRemoteTyping();
+ stopLocalTyping();
+ }
+
const startTyping = leading(
throttle,
createCallback(() => {
@@ -156,6 +170,7 @@ export function BaseInput(props: BaseInputProps) {
setTyping(true);
props.onStartTyping();
}
+ props.setLocalTyping?.(true);
}),
1000
);
@@ -254,15 +269,13 @@ export function BaseInput(props: BaseInputProps) {
});
onCleanup(() => {
- if (inactivityTimeout) {
- clearTimeout(inactivityTimeout);
+ if (remoteInactivityTimeout) {
+ clearTimeout(remoteInactivityTimeout);
}
stopTyping();
- if (localTypingTimeout) clearTimeout(localTypingTimeout);
- props.setLocalTyping?.(false);
viewportObserver?.disconnect();
if (markdownState().trim() === '') {
- props.onEmpty();
+ props.onEmptyBlur?.();
}
});
@@ -338,17 +351,9 @@ export function BaseInput(props: BaseInputProps) {
function handleChange(input: string) {
if (input.trim() === '') {
stopTyping();
- if (localTypingTimeout) clearTimeout(localTypingTimeout);
- props.setLocalTyping?.(false);
- props.onEmpty();
} else {
startTyping();
resetInactivityTimeout();
- props.setLocalTyping?.(true);
- if (localTypingTimeout) clearTimeout(localTypingTimeout);
- localTypingTimeout = setTimeout(() => {
- props.setLocalTyping?.(false);
- }, 500);
props.onChange(input);
}
}
@@ -372,11 +377,11 @@ export function BaseInput(props: BaseInputProps) {
const documentAttachments = () =>
attachments().filter((a) => !isStaticAttachmentType(a.blockName));
- const onEscape = () => {
+ const handleBlur = () => {
+ blurMarkdownArea();
if (markdownState().trim() === '') {
- props.escHandler?.();
+ props.onEmptyBlur?.();
}
- blurMarkdownArea();
return true;
};
@@ -445,14 +450,14 @@ export function BaseInput(props: BaseInputProps) {
}
onBlur={() => {
stopTyping();
- onEscape();
+ handleBlur();
}}
users={props.channelUsers}
onChange={handleChange}
onPasteFile={onMarkdownAreaPaste}
initialValue={props.initialValue?.()}
useBlockBoundary={true}
- onEscape={onEscape}
+ onEscape={handleBlur}
dontFocusOnMount
onFocusLeaveStart={props.onFocusLeaveStart}
onFocusLeaveEnd={onFocusLeaveEnd}
@@ -514,12 +519,12 @@ export function BaseInput(props: BaseInputProps) {
>
<FormatIcon width={20} height={20} />
</ActionButton>
- <Show when={props.onDeleteDraft}>
+ <Show when={props.onEmptyBlur}>
<ActionButton
tooltip="Delete reply"
onClick={(e) => {
e.preventDefault();
- props.onDeleteDraft?.();
+ props.onEmptyBlur?.();
}}
>
<Trash width={20} height={20} />
diff --git a/js/app/packages/block-channel/component/ChannelInput.tsx b/js/app/packages/block-channel/component/ChannelInput.tsx
index 6c0f373261..3cc0d0183c 100644
--- a/js/app/packages/block-channel/component/ChannelInput.tsx
+++ b/js/app/packages/block-channel/component/ChannelInput.tsx
@@ -75,7 +75,6 @@ export function ChannelInput(props: ChannelInputProps) {
onSend={sendMessage_}
afterSend={() => clearDraftMessage(channelId)}
onChange={handleChange}
- onEmpty={() => clearDraftMessage(channelId)}
initialValue={() => draftMessage()?.content ?? ''}
inputAttachments={{
store: props.inputAttachmentsStore,
@@ -83,6 +82,7 @@ export function ChannelInput(props: ChannelInputProps) {
key: props.inputAttachmentsKey,
}}
onFocusLeaveStart={props.onFocusLeaveStart}
+ onEmptyBlur={() => clearDraftMessage(channelId)}
channelUsers={channelUsers}
autoFocusOnMount={props.autoFocusOnMount}
domRef={props.domRef}
diff --git a/js/app/packages/block-channel/component/DraftChannelInput.tsx b/js/app/packages/block-channel/component/DraftChannelInput.tsx
index 2c7e40b02e..0daf48f09b 100644
--- a/js/app/packages/block-channel/component/DraftChannelInput.tsx
+++ b/js/app/packages/block-channel/component/DraftChannelInput.tsx
@@ -117,7 +117,7 @@ export function DraftChannelInput(props: {
onStopTyping={() => {}}
onSend={handleSend}
onChange={setContent}
- onEmpty={() => setContent('')}
+ onEmptyBlur={() => setContent('')}
initialValue={() => content()}
inputAttachments={
props.inputAttachments || {
diff --git a/js/app/packages/block-channel/component/MessageList/MessageList.tsx b/js/app/packages/block-channel/component/MessageList/MessageList.tsx
index 716d3712ac..9748e590c2 100644
--- a/js/app/packages/block-channel/component/MessageList/MessageList.tsx
+++ b/js/app/packages/block-channel/component/MessageList/MessageList.tsx
@@ -4,7 +4,10 @@ import {
} from '@block-channel/constants';
import { openedChannelSignal } from '@block-channel/signal/activity';
import { messageToReactionStore } from '@block-channel/signal/reactions';
-import { threadsStore } from '@block-channel/signal/threads';
+import {
+ type ThreadStoreData,
+ threadsStore,
+} from '@block-channel/signal/threads';
import { usersTypingSignal } from '@block-channel/signal/typing';
import type { ThreadViewData } from '@block-channel/type/threadView';
import { loadDraftMessage } from '@block-channel/utils/draftMessages';
@@ -105,6 +108,7 @@ export function MessageList(props: MessageListProps) {
const userId = useUserId();
const threads = threadsStore.get;
+ const [viewThreads, setViewThreads] = createStore<ThreadStoreData>({});
const [threadInputAttachmentsStore, setThreadInputAttachmentsStore] =
createStore<Record<string, InputAttachment[]>>({});
@@ -268,9 +272,8 @@ export function MessageList(props: MessageListProps) {
// Keep the message if:
// 1. It's not deleted, OR
// 2. It's deleted but is a parent message
- const messageFilterFn = (message: Message) => {
- return !message.deleted_at || threads[message.id]?.length > 0;
- };
+ const messageFilterFn = (message: Message) =>
+ !message.deleted_at || viewThreads[message.id]?.length > 0;
const filteredTopLevelMessages = createMemo(() =>
props.messages.filter(messageFilterFn)
@@ -280,7 +283,7 @@ export function MessageList(props: MessageListProps) {
// mapFn is not tracking, so wrap thread-dependent logic in a memo per parent.
const segments = mapArray(filteredTopLevelMessages, (message) =>
createMemo(() => {
- const children = threads[message.id] ?? [];
+ const children = viewThreads[message.id] ?? [];
const filteredChildren = children.filter(messageFilterFn);
return filteredChildren.length
? [message, ...filteredChildren]
@@ -295,24 +298,66 @@ export function MessageList(props: MessageListProps) {
return out;
});
- // Thread reply inputs are portaled to the correct message container. This keeps them in the right place, but if they are portaled while a user is typing, the user can lose input. To address this, we do not update the threaded messages until the user stops typing.
- const [localTyping, setLocalTyping] = createSignal(false);
- let updateDelayedByTyping = false;
-
- // TODO something wrong with localTyping signal. When a message from another user comes in, on a thread that a user is typing a reply to, localTyping gets set to false. Investigate why.
createEffect(
- on([flattenedThreaded, localTyping], ([flat, typing], prev) => {
- const oldFlat = prev?.[0];
- if (!typing && (oldFlat !== flat || updateDelayedByTyping)) {
+ on(flattenedThreaded, (flat, prev) => {
+ const oldFlat = prev;
+ if (oldFlat !== flat) {
props.setOrderedMessages(flat);
computeListContext(flat);
- updateDelayedByTyping = false;
- } else if (typing && oldFlat !== flat) {
- updateDelayedByTyping = true;
}
})
);
+ // Thread reply inputs are portaled to the correct message container. This keeps them in the correct location even as new thread replies come in, but if they are re-portaled while a user is typing, the user can momentarily lose input. To address this, we gate updates to the thread that a user is currently typing in.
+ const [localTypingThreadId, setLocalTypingThreadId] = createSignal<
+ string | undefined
+ >();
+
+ let dirtyTypingThreadId: string | undefined;
+
+ // Maintain a local snapshot of threads that freezes changes for threads in which a user is actively typing.
+ createEffect(() => {
+ const baseMessages = props.messages;
+ const activeThreadId = untrack(localTypingThreadId);
+
+ for (const message of baseMessages) {
+ const id = message.id;
+ const threadArr = threads[id] ?? [];
+ const currentView = viewThreads[id];
+ const isTypingThisThread = id === activeThreadId;
+
+ if (isTypingThisThread) {
+ if (currentView !== threadArr) {
+ dirtyTypingThreadId = id;
+ }
+ } else {
+ if (currentView !== threadArr) {
+ setViewThreads(id, reconcile(threadArr));
+ }
+ if (dirtyTypingThreadId === id) {
+ dirtyTypingThreadId = undefined;
+ }
+ }
+ }
+ });
+
+ // When active typing thread changes flush any pending changes for the previous typing thread.
+ createEffect((prevTypingId: string | undefined) => {
+ const currentTypingId = localTypingThreadId();
+
+ if (
+ prevTypingId &&
+ prevTypingId !== currentTypingId &&
+ dirtyTypingThreadId === prevTypingId
+ ) {
+ const threadArr = untrack(() => threads[prevTypingId] ?? []);
+ setViewThreads(prevTypingId, reconcile(threadArr));
+ dirtyTypingThreadId = undefined;
+ }
+
+ return currentTypingId;
+ });
+
// Provide stable row models to VList so item instances are preserved across moves/insertions
type RowModel = {
id: string;
@@ -350,7 +395,8 @@ export function MessageList(props: MessageListProps) {
(threadId &&
((next && next.thread_id !== msg.thread_id) || !next) &&
threadViewStore[threadId]?.hasActiveReply) ||
- (threadViewStore[msg.id]?.hasActiveReply && !threads[msg.id]?.length)
+ (threadViewStore[msg.id]?.hasActiveReply &&
+ !viewThreads[msg.id]?.length)
) {
indices.push(i);
}
@@ -380,7 +426,7 @@ export function MessageList(props: MessageListProps) {
const lastMessageThread = createMemo(() => {
const base = filteredTopLevelMessages() ?? [];
const lastTopLevelId = base[base.length - 1]?.id;
- return threads[lastTopLevelId];
+ return viewThreads[lastTopLevelId];
});
createEffect(
@@ -622,10 +668,10 @@ export function MessageList(props: MessageListProps) {
setFocusedMessageId={props.setFocusedMessageId}
index={i}
orderedMessages={props.orderedMessages}
- threadSiblings={threads[
+ threadSiblings={viewThreads[
row.message.thread_id ?? ''
]?.filter(messageFilterFn)}
- threadChildren={threads[row.message.id ?? '']?.filter(
+ threadChildren={viewThreads[row.message.id ?? '']?.filter(
messageFilterFn
)}
threadViewStore={threadViewStore}
@@ -729,11 +775,11 @@ export function MessageList(props: MessageListProps) {
orderedMessages={props.orderedMessages}
threadViewStore={threadViewStore}
setThreadViewStore={setThreadViewStore}
- threads={threads}
+ threads={viewThreads}
virtualHandle={virtualHandle}
threadInputAttachmentsStore={threadInputAttachmentsStore}
setThreadInputAttachmentsStore={setThreadInputAttachmentsStore}
- setLocalTyping={setLocalTyping}
+ setLocalTypingThreadId={setLocalTypingThreadId}
/>
</div>
);
diff --git a/js/app/packages/block-channel/component/ReplyInputsPortaler.tsx b/js/app/packages/block-channel/component/ReplyInputsPortaler.tsx
index 22b0935b70..3afdbf786b 100644
--- a/js/app/packages/block-channel/component/ReplyInputsPortaler.tsx
+++ b/js/app/packages/block-channel/component/ReplyInputsPortaler.tsx
@@ -11,7 +11,7 @@ import { blockElementSignal } from '@core/signal/blockElement';
import type { InputAttachment } from '@core/store/cacheChannelInput';
import type { Message } from '@service-comms/generated/models';
import { createCallback } from '@solid-primitives/rootless';
-import { type Accessor, createEffect, For } from 'solid-js';
+import { type Accessor, createEffect, For, type Setter } from 'solid-js';
import type { SetStoreFunction } from 'solid-js/store';
import { Portal } from 'solid-js/web';
import type { VirtualizerHandle } from 'virtua/solid';
@@ -28,7 +28,7 @@ export type ReplyInputsPortalerProps = {
setThreadInputAttachmentsStore: SetStoreFunction<
Record<string, InputAttachment[]>
>;
- setLocalTyping?: (isTyping: boolean) => void;
+ setLocalTypingThreadId?: Setter<string | undefined>;
};
export function ReplyInputsPortaler(props: ReplyInputsPortalerProps) {
@@ -80,15 +80,7 @@ export function ReplyInputsPortaler(props: ReplyInputsPortalerProps) {
);
};
- const onEsc = (threadId: string) => () => {
- props.setThreadViewStore(threadId, (prev) =>
- prev
- ? { ...prev, threadExpanded: true, hasActiveReply: false }
- : { threadExpanded: true, hasActiveReply: false }
- );
- };
-
- const onDeleteReply = (threadId: string) => () => {
+ const onEmptyBlur = (threadId: string) => () => {
clearDraftMessage(props.channelId, threadId);
props.setThreadViewStore(threadId, (prev) =>
prev
@@ -168,7 +160,14 @@ export function ReplyInputsPortaler(props: ReplyInputsPortalerProps) {
setStore: props.setThreadInputAttachmentsStore,
key: threadId,
}}
- setLocalTyping={props.setLocalTyping}
+ setLocalTyping={
+ props.setLocalTypingThreadId
+ ? (isTyping) =>
+ props.setLocalTypingThreadId?.(
+ isTyping ? threadId : undefined
+ )
+ : undefined
+ }
onChange={(content) =>
saveDraftMessage(props.channelId, {
content,
@@ -177,15 +176,13 @@ export function ReplyInputsPortaler(props: ReplyInputsPortalerProps) {
threadId,
})
}
- onEmpty={() => clearDraftMessage(props.channelId, threadId)}
- escHandler={onEsc(threadId)}
initialValue={() =>
loadDraftMessage(props.channelId, threadId)?.content ?? ''
}
onFocusLeaveStart={(e) => {
onFocusLeaveStart(e, threadId);
}}
- onDeleteDraft={onDeleteReply(threadId)}
+ onEmptyBlur={onEmptyBlur(threadId)}
isReplyInput
/>
</div>