Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(md): improve scroll-to-comment lifecyle logic (#5331)
Seamus575dfbbbe083
diff --git a/apps/web/src/features/block-md/comments/CommentsProvider.tsx b/apps/web/src/features/block-md/comments/CommentsProvider.tsxindex 062ec82c73..3cb733cdd4 100644--- a/apps/web/src/features/block-md/comments/CommentsProvider.tsx+++ b/apps/web/src/features/block-md/comments/CommentsProvider.tsx@@ -17,6 +17,7 @@ import {type Accessor,createEffect,createMemo,+ createSignal,untrack,useContext,type VoidComponent,@@ -36,6 +37,8 @@ import {import { commentThreadsResource, sortComments } from './commentsResource';import type { Mark, ThreadMetadata, ThreadStore } from './commentType';+const DISCUSSION_MARK_PREFIX = 'DISCUSSION:';+function getHighlightThread(highlight: Mark): { root: Root; replies: Reply[] } | null {@@ -311,22 +314,50 @@ export const CommentsProvider: VoidComponent<{);});- // Navigate to comment from URL param once comments are loaded+ const [targetRequest, setTargetRequest] = createSignal(0);+ let pendingTargetCommentId: string | undefined;+createEffect(() => {- if (!commentMarksInitializedSignal()) return;- const rawId = props.activeComment?.();+ pendingTargetCommentId = props.activeComment?.();+ setTargetRequest((request) => request + 1);+ });++ // Navigate to comment from URL param once comments are loaded.+ // Keep this one-shot so a persistent `comment_id` does not steal focus from+ // later user actions, like creating a new comment.+ createEffect(() => {+ targetRequest();+ const rawId = pendingTargetCommentId;if (!rawId) return;++ if (!commentMarksInitializedSignal()) return;const commentId = Number(rawId);if (isNaN(commentId)) return;++ const commentThreads = commentThreadsData() ?? [];+ const targetThread = commentThreads.find((thread) =>+ thread.comments.some((comment) => comment.commentId === commentId)+ );+ const targetMetadata = targetThread?.thread.metadata as+ | ThreadMetadata+ | undefined;+ if (targetMetadata?.markId?.startsWith(DISCUSSION_MARK_PREFIX)) {+ activeCommentThreadSignal.set(null);+ highlightedCommentIdSignal.set(null);+ pendingTargetCommentId = undefined;+ return;+ }+const comment = commentsStore.get[commentId];if (!comment) return;- activeCommentThreadSignal.set(comment.threadId);highlightedCommentIdSignal.set(commentId);const mark = marks[comment.anchorId];if (mark) {const firstEl = Object.values(mark.markNodes)[0];firstEl?.scrollIntoView({ behavior: 'smooth', block: 'center' });}+ activeCommentThreadSignal.set(comment.threadId);+ pendingTargetCommentId = undefined;});autoRegister(diff --git a/apps/web/src/features/block-md/comments/documentDiscussionSource.ts b/apps/web/src/features/block-md/comments/documentDiscussionSource.tsindex 33fe0a1657..0d804f54a1 100644--- a/apps/web/src/features/block-md/comments/documentDiscussionSource.ts+++ b/apps/web/src/features/block-md/comments/documentDiscussionSource.ts@@ -13,6 +13,7 @@ import type { CommentThread } from '@service-storage/generated/schemas/commentThimport type { CreateCommentRequestMentions } from '@service-storage/generated/schemas/createCommentRequestMentions';import { createMemo } from 'solid-js';import { URL_PARAMS } from '../constants';+import { mdStore } from '../signal/markdownBlockData';import {discussionThreads,sortComments,@@ -71,17 +72,40 @@ export function createDocumentDiscussionSource(): DiscussionSource {const createReplyFn = useCreateDiscussionReply();const editFn = useEditDiscussionComment();const deleteFn = useDeleteDiscussionComment();+ const md = mdStore.get;const threads = createMemo(() =>(discussionThreads() ?? []).map(toViewThread));- const targetCommentId = createMemo(() => urlParams.commentId() ?? null);+ const targetRequest = createMemo(+ () => {+ const commentId = urlParams.commentId();+ return commentId ? { commentId } : null;+ },+ undefined,+ { equals: false }+ );++ const targetCommentId = createMemo(() => {+ const request = targetRequest();+ if (!request) return null;+ const { commentId } = request;+ if (!md.locationReady) return null;++ const currentThreads = threads();+ const hasDiscussionComment = currentThreads.some((thread) =>+ thread.comments.some((comment) => comment.id === commentId)+ );+ return hasDiscussionComment ? commentId : null;+ });+ const targetRevision = () => targetRequest();return {threads,canEdit: canComment,currentUserId: userId,targetCommentId,+ targetRevision,async createThread(text, mentions) {await createThreadFn(text, buildCommentMentions(mentions));},diff --git a/apps/web/src/features/block-md/component/MarkdownEditor.tsx b/apps/web/src/features/block-md/component/MarkdownEditor.tsxindex b29f1443b3..726338eb3c 100644--- a/apps/web/src/features/block-md/component/MarkdownEditor.tsx+++ b/apps/web/src/features/block-md/component/MarkdownEditor.tsx@@ -455,6 +455,13 @@ export function MarkdownEditor(props: {createSignal<PersistentLocation>();const [locationReady, setLocationReady] = createSignal(false);+ createEffect(() => {+ setMdStore({ locationReady: locationReady() });+ });+ onCleanup(() => {+ setMdStore({ locationReady: undefined });+ });+const { nodeId, location, commentId } = useUrlParams(URL_PARAMS);createEffect(on(nodeId, (id) => setHighlightNodeId(id ?? undefined)));createEffect(diff --git a/apps/web/src/features/block-md/signal/markdownBlockData.ts b/apps/web/src/features/block-md/signal/markdownBlockData.tsindex 9d7acd1d74..41824a9ecc 100644--- a/apps/web/src/features/block-md/signal/markdownBlockData.ts+++ b/apps/web/src/features/block-md/signal/markdownBlockData.ts@@ -22,6 +22,8 @@ export const blockDataSignal = blockDataSignalAs<MarkdownData>('md');* clamped to a max width.* @property scrollContainer The scroll container is the direct sibling of the top bar* and takes the full width of the block. This is where the scroll bar is attached.+ * @property locationReady True after the editor is initialized and the first+ * location-scroll window has opened.*/export type MdData = {editor?: LexicalEditor;@@ -35,6 +37,7 @@ export type MdData = {scrollContainer?: HTMLElement;commentMargin?: HTMLElement;contentRef?: HTMLElement;+ locationReady?: boolean;};export const mdStore = createBlockStore<MdData>({});diff --git a/apps/web/src/lib/core/comments/discussion/Discussion.tsx b/apps/web/src/lib/core/comments/discussion/Discussion.tsxindex 33a03d368b..d48368e0d9 100644--- a/apps/web/src/lib/core/comments/discussion/Discussion.tsx+++ b/apps/web/src/lib/core/comments/discussion/Discussion.tsx@@ -11,7 +11,7 @@ import { tryMacroId, useDisplayName } from '@core/user';import CaretDown from '@phosphor/caret-down.svg';import CaretRight from '@phosphor/caret-right.svg';import { Key } from '@solid-primitives/keyed';-import { createEffect, createSignal, onMount, Show } from 'solid-js';+import { createEffect, createSignal, onCleanup, onMount, Show } from 'solid-js';import { useDiscussion } from './context';import { DiscussionInput } from './DiscussionInput';import {@@ -31,12 +31,66 @@ import type {export function Discussion() {const source = useDiscussion();const [isExpanded, setIsExpanded] = createSignal(true);+ const [mountedCommentsVersion, setMountedCommentsVersion] = createSignal(0);+ const mountedComments = new Map<string, HTMLElement>();+ let scrolledTarget: { commentId: string; revision: unknown } | undefined;// Deep-linking to a comment expands the discussion.createEffect(() => {if (source.targetCommentId() !== null) setIsExpanded(true);});+ const registerMountedComment = (commentId: string, element: HTMLElement) => {+ mountedComments.set(commentId, element);+ setMountedCommentsVersion((version) => version + 1);+ };++ const unregisterMountedComment = (+ commentId: string,+ element: HTMLElement+ ) => {+ if (mountedComments.get(commentId) === element) {+ mountedComments.delete(commentId);+ setMountedCommentsVersion((version) => version + 1);+ }+ };++ createEffect(() => {+ const targetCommentId = source.targetCommentId();+ const targetRevision = source.targetRevision?.() ?? targetCommentId;+ if (!targetCommentId) return;++ const currentThreads = source.threads();+ const targetThread = currentThreads.find((thread) =>+ thread.comments.some((comment) => comment.id === targetCommentId)+ );+ if (!targetThread) return;++ setIsExpanded(true);+ mountedCommentsVersion();++ const target = mountedComments.get(targetCommentId);+ if (!target) return;+ if (+ scrolledTarget?.commentId === targetCommentId &&+ Object.is(scrolledTarget.revision, targetRevision)+ ) {+ return;+ }++ const frame = requestAnimationFrame(() => {+ scrolledTarget = {+ commentId: targetCommentId,+ revision: targetRevision,+ };+ target.scrollIntoView({ behavior: 'smooth', block: 'center' });+ });++ onCleanup(() => {+ cancelAnimationFrame(frame);+ });+ });+let newThreadInputHandle: { clear: () => void } | undefined;const handleCreateThread = async (snapshot: InputSnapshot) => {@@ -70,7 +124,13 @@ export function Discussion() {<div class="py-2 text-xs"><div><Key each={source.threads()} by="id">- {(thread) => <DiscussionThreadView thread={thread()} />}+ {(thread) => (+ <DiscussionThreadView+ thread={thread()}+ onCommentMount={registerMountedComment}+ onCommentCleanup={unregisterMountedComment}+ />+ )}</Key></div>@@ -93,7 +153,11 @@ export function Discussion() {);}-export function DiscussionThreadView(props: { thread: ViewThread }) {+export function DiscussionThreadView(props: {+ thread: ViewThread;+ onCommentMount?: (commentId: string, element: HTMLElement) => void;+ onCommentCleanup?: (commentId: string, element: HTMLElement) => void;+}) {const source = useDiscussion();const canEdit = source.canEdit;@@ -190,6 +254,8 @@ export function DiscussionThreadView(props: { thread: ViewThread }) {onEditSave={(snapshot) => handleEdit(rootComment(), snapshot)}onEditCancel={() => setEditingId(null)}isHighlighted={source.targetCommentId() === rootComment().id}+ onMount={props.onCommentMount}+ onCleanup={props.onCommentCleanup}/><Show when={hasReplies() || isReplying()}>@@ -214,6 +280,8 @@ export function DiscussionThreadView(props: { thread: ViewThread }) {isHighlighted={source.targetCommentId() === reply().id}+ onMount={props.onCommentMount}+ onCleanup={props.onCommentCleanup}/></div>)}@@ -278,15 +346,21 @@ function DiscussionMessageView(props: {onEditSave: (snapshot: InputSnapshot) => void;onEditCancel: () => void;isHighlighted?: boolean;+ onMount?: (commentId: string, element: HTMLElement) => void;+ onCleanup?: (commentId: string, element: HTMLElement) => void;}) {const isEditing = () => props.editingId === props.comment.id;const messageData = () => discussionCommentToMessageData(props.comment);let containerRef: HTMLDivElement | undefined;+onMount(() => {- if (props.isHighlighted) {- containerRef?.scrollIntoView({ behavior: 'smooth', block: 'center' });- }+ if (!containerRef) return;+ props.onMount?.(props.comment.id, containerRef);+ onCleanup(() => {+ if (!containerRef) return;+ props.onCleanup?.(props.comment.id, containerRef);+ });});return (diff --git a/apps/web/src/lib/core/comments/discussion/types.ts b/apps/web/src/lib/core/comments/discussion/types.tsindex b00f51355c..7b93878b22 100644--- a/apps/web/src/lib/core/comments/discussion/types.ts+++ b/apps/web/src/lib/core/comments/discussion/types.ts@@ -48,6 +48,11 @@ export interface DiscussionSource {currentUserId: Accessor<string | undefined>;/** Comment id to highlight/scroll to (deep link), or null. */targetCommentId: Accessor<string | null>;+ /**+ * Optional revision for target requests. Increment when the same target id is+ * requested again so the UI can scroll again without replaying on remounts.+ */+ targetRevision?: Accessor<unknown>;/** Start a new thread. */createThread(text: string, mentions: ItemMention[]): Promise<void>;/** Reply to an existing thread. */diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/comments/commentPlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/comments/commentPlugin.tsindex a4d8bd45a5..8adff8b591 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/comments/commentPlugin.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/comments/commentPlugin.ts@@ -369,6 +369,11 @@ function registerPlugin(editor: LexicalEditor, props: CommentPluginProps) {continue;}+ if (node.getIsDraft()) {+ $unwrapMarkNode(node);+ continue;+ }+if (node.getIDs().length > 1) {node.deleteID(markId);continue;