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): navigate an open document when a comment mention is clicked (#6884)
gbirman4b3375de1e15
diff --git a/apps/web/src/features/block-md/comments/MessageCommentsProvider.tsx b/apps/web/src/features/block-md/comments/MessageCommentsProvider.tsxindex a33c9c8469..45ce46ef7b 100644--- a/apps/web/src/features/block-md/comments/MessageCommentsProvider.tsx+++ b/apps/web/src/features/block-md/comments/MessageCommentsProvider.tsx@@ -1,3 +1,4 @@+import { URL_PARAMS } from '@block-md/constants';import {type CommentId,commentView,@@ -17,6 +18,7 @@ import {DELETE_COMMENT_COMMAND,MARK_SELECTED_COMMENT_COMMAND,} from '@core/component/LexicalMarkdown/plugins/comments/commentPlugin';+import { useParamNavigationCount } from '@core/component/ParamsProvider';import { useUserId } from '@core/context/user';import type { LoroManager } from '@macro-inc/collaboration/collab/manager';import type { CommentNode } from '@macro-inc/lexical-core';@@ -34,8 +36,10 @@ import {} from 'lexical';import {type Accessor,+ createComputed,createEffect,createMemo,+ on,onCleanup,untrack,useContext,@@ -498,18 +502,33 @@ export const MessageCommentsProvider: VoidComponent<{}});- // Navigate to the comment named by the URL `comment_id`, once, after comments- // load. Latched on the raw `comment_id` (not `target.messageId()`, which also- // tracks the resolve query) so a settling GET cannot re-arm and steal focus- // from a later user action such as opening a thread or starting a draft.- let handledComment: string | undefined;+ // Navigate to the comment named by the URL `comment_id`, once per+ // navigation, after comments load. Latched on navigations of `comment_id`+ // (not `target.messageId()`, which also tracks the resolve query) so a+ // settling GET cannot re-arm and steal focus from a later user action such as+ // opening a thread or starting a draft, while a repeat click on a link to the+ // same comment still navigates. Once a link has navigated the block, a value+ // change without a navigation is the URL `comment_id` showing through after a+ // navigation that cleared it, and is not a request to go there.+ const commentNavigationCount = useParamNavigationCount(URL_PARAMS.commentId);+ let navigation = 0;+ let handledNavigation: number | undefined;+ createComputed(+ on(+ [() => props.activeComment?.(), commentNavigationCount],+ ([comment, count], previous) => {+ const [previousComment, previousCount] = previous ?? [];+ if (+ count !== previousCount ||+ (count === 0 && comment !== previousComment)+ )+ navigation += 1;+ }+ )+ );createEffect(() => {const rawComment = props.activeComment?.() ?? undefined;- if (!rawComment) {- handledComment = undefined;- return;- }- if (rawComment === handledComment) return;+ if (!rawComment || navigation === handledNavigation) return;// The following reads resolve asynchronously; the effect re-runs and// completes the navigation once they are ready, then latches.@@ -528,7 +547,7 @@ export const MessageCommentsProvider: VoidComponent<{// Resolved as unanchored (a Discussion root): nothing to open in the margin.activeCommentThreadSignal.set(null);setHighlightedId(null);- handledComment = rawComment;+ handledNavigation = navigation;return;}@@ -542,7 +561,7 @@ export const MessageCommentsProvider: VoidComponent<{firstEl?.scrollIntoView({ behavior: 'smooth', block: 'center' });}activeCommentThreadSignal.set(comment.threadId);- handledComment = rawComment;+ handledNavigation = navigation;});autoRegister(diff --git a/apps/web/src/features/drive-view/views/MarkdownDetail.tsx b/apps/web/src/features/drive-view/views/MarkdownDetail.tsxindex 950c1ccbc8..c29449497b 100644--- a/apps/web/src/features/drive-view/views/MarkdownDetail.tsx+++ b/apps/web/src/features/drive-view/views/MarkdownDetail.tsx@@ -5,6 +5,7 @@ import {} from '@block-md/component/MarkdownDocument';import { ModalsProvider } from '@block-md/component/ModalsProvider';import { MarkdownSidePanelSections } from '@block-md/component/sidepanel/MarkdownSidePanelSections';+import { createMarkdownDocumentState } from '@block-md/context/markdown-document-state';import { OldOverlay } from '@block-md/history/OldOverlay';import {loadMarkdownDocument,@@ -12,14 +13,19 @@ import {} from '@block-md/queries/markdown-document';import { loadMarkdownCachedSnapshot } from '@block-md/queries/markdown-document-operations';import type { MarkdownDocumentKind } from '@block-md/types';-import { useGlobalNotificationSource } from '@components/app/GlobalAppState';+import {+ useGlobalBlockOrchestrator,+ useGlobalNotificationSource,+} from '@components/app/GlobalAppState';import { SidePanel } from '@components/app/side-panel';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';import { ENABLE_MARKDOWN_SIDE_PANEL } from '@core/constant/featureFlags';+import { createMethodRegistration } from '@core/orchestrator';import { DocumentDebouncedNotificationReadMarker } from '@notifications';import SpinnerIcon from '@phosphor/spinner.svg';import { Button } from '@ui';import {+ createComputed,createResource,ErrorBoundary,type JSX,@@ -86,11 +92,23 @@ function MarkdownDetailContent(props: {}) {const panel = useSplitPanelOrThrow();const notificationSource = useGlobalNotificationSource();+ const orchestrator = useGlobalBlockOrchestrator();+ const state = createMarkdownDocumentState();++ // Mention chips and notifications aim an open document at a comment or node+ // through its block handle; without one the click only activates the view.+ createComputed(() => {+ const handle = orchestrator.registerBlockHandle('md', props.documentId);+ createMethodRegistration(() => handle, {+ goToLocationFromParams: state.params.navigate,+ });+ });return (<MarkdownDocumentdocumentId={props.documentId}kind={props.kind}+ state={state}documentSource={{ type: 'sync', source: props.data.source }}permissions={props.data.permissions}persistedName={props.data.metadata.documentName}diff --git a/apps/web/src/lib/core/component/ParamsProvider.test.tsx b/apps/web/src/lib/core/component/ParamsProvider.test.tsxindex 8c56f92ff1..ffb09579c4 100644--- a/apps/web/src/lib/core/component/ParamsProvider.test.tsx+++ b/apps/web/src/lib/core/component/ParamsProvider.test.tsx@@ -9,6 +9,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import {createParamsState,ParamsProvider,+ useParamNavigationCount,useUrlParams,} from './ParamsProvider';@@ -203,4 +204,32 @@ describe('ParamsProvider', () => {commentId: 'comment-1',});});++ it('counts navigations that name a param, not URL fallbacks', async () => {+ mocks.searchParams = createStore<MockSearchParams>({+ comment_id: 'from-url',+ })[0];+ const paramsState = createParamsState();+ let count = () => -1;+ let comment = () => undefined as string | undefined;+ function Reader() {+ count = useParamNavigationCount('comment_id');+ comment = useUrlParams(URL_PARAMS).commentId;+ return null;+ }+ render(() => (+ <ParamsProvider state={paramsState}>+ <Reader />+ </ParamsProvider>+ ));+ expect(count()).toBe(0);++ paramsState.navigate({ comment_id: 'from-link' });+ paramsState.navigate({ comment_id: 'from-link' });+ expect(count()).toBe(2);++ paramsState.navigate({ node_id: 'node-1' });+ expect(comment()).toBe('from-url');+ expect(count()).toBe(2);+ });});diff --git a/apps/web/src/lib/core/component/ParamsProvider.tsx b/apps/web/src/lib/core/component/ParamsProvider.tsxindex 07b7dbd4e5..dd9246f634 100644--- a/apps/web/src/lib/core/component/ParamsProvider.tsx+++ b/apps/web/src/lib/core/component/ParamsProvider.tsx@@ -26,10 +26,12 @@ type ResolvedParams<T extends ParamSchema> = {*/type ParamsContextValue = {getParam: (param: string) => Accessor<string | undefined>;+ getNavigationCount: (param: string) => Accessor<number>;};const ParamsContext = createContext<ParamsContextValue>({getParam: () => () => undefined,+ getNavigationCount: () => () => 0,});function flattenParamValue(@@ -48,6 +50,7 @@ export function createParamsState() {navigationVersions[param];return blockParams[param];},+ getNavigationCount: (param: string) => () => navigationVersions[param] ?? 0,navigate: (params: Record<string, string>) => {batch(() => {const paramNames = new Set([@@ -81,6 +84,7 @@ export function ParamsProvider(const blockValue = state.getParam(param);return () => blockValue() ?? flattenParamValue(searchParams[param]);},+ getNavigationCount: state.getNavigationCount,};return (@@ -104,3 +108,11 @@ export function useUrlParams<T extends ParamSchema>(Object.entries(schema).map(([key, param]) => [key, params.getParam(param)])) as ResolvedParams<T>;}++/**+ * Counts `goToLocationFromParams` calls that named `param`, including repeats+ * with the same value. Stays 0 while the value only comes from the URL.+ */+export function useParamNavigationCount(param: string): Accessor<number> {+ return useContext(ParamsContext).getNavigationCount(param);+}diff --git a/apps/web/src/lib/core/orchestrator.test.tsx b/apps/web/src/lib/core/orchestrator.test.tsxindex b7370d383d..a2310e6e41 100644--- a/apps/web/src/lib/core/orchestrator.test.tsx+++ b/apps/web/src/lib/core/orchestrator.test.tsx@@ -1,5 +1,5 @@import { render } from '@solidjs/testing-library';-import type { ParentProps } from 'solid-js';+import { createRoot, type ParentProps } from 'solid-js';import { expect, it, vi } from 'vitest';import { createBlockOrchestrator } from './orchestrator';@@ -44,3 +44,29 @@ it('keeps one live mount and preserves its handle when a duplicate unmounts', asexpect(reopenedView.container.textContent).toBe('Channel content');reopenedView.unmount();});++it('exposes a handle for content mounted outside a block container until its owner disposes', async () => {+ const orchestrator = createBlockOrchestrator();+ const navigate = vi.fn();+ const dispose = createRoot((dispose) => {+ const handle = orchestrator.registerBlockHandle('channel', 'channel-1');+ handle?.registerMethod('goToLocationFromParams', navigate);+ expect(+ orchestrator.registerBlockHandle('channel', 'channel-1')+ ).toBeUndefined();+ return dispose;+ });++ const handle = await orchestrator.getBlockHandle('channel-1', 'channel');+ await handle?.goToLocationFromParams({ message: 'message-1' });+ expect(navigate).toHaveBeenCalledWith({ message: 'message-1' });++ dispose();+ const mounted = orchestrator.createBlockInstance('channel', 'channel-1');+ const view = render(mounted.element);+ expect(view.container.textContent).toBe('Channel content');+ expect(+ orchestrator.registerBlockHandle('channel', 'channel-1')+ ).toBeUndefined();+ view.unmount();+});diff --git a/apps/web/src/lib/core/orchestrator.tsx b/apps/web/src/lib/core/orchestrator.tsxindex 5ebcb5678c..55ae672c58 100644--- a/apps/web/src/lib/core/orchestrator.tsx+++ b/apps/web/src/lib/core/orchestrator.tsx@@ -9,7 +9,7 @@ import {onMount,Suspense,} from 'solid-js';-import { createStore } from 'solid-js/store';+import { createStore, unwrap } from 'solid-js/store';import { Dynamic } from 'solid-js/web';import {type BlockAlias,@@ -346,6 +346,18 @@ export type BlockOrchestrator = {* already taken.*/rekeyBlockInstance: (type: BlockName, fromId: string, toId: string) => void;+ /**+ * Registers a handle for block content mounted without a block container,+ * such as an entity detail view, so openers that navigate through+ * [getBlockHandle] reach it. The handle is removed when the calling owner+ * is disposed.+ *+ * Returns undefined while another block holds the id.+ */+ registerBlockHandle: <T extends BlockName>(+ type: T,+ id: string+ ) => OwnedBlockHandle<BlockMethodsFor<T>> | undefined;};export function createBlockOrchestrator(): BlockOrchestrator {@@ -488,12 +500,22 @@ export function createBlockOrchestrator(): BlockOrchestrator {setBlocks(toId, { ...existing, id: toId });}+ function registerBlockHandle<T extends BlockName>(type: T, id: string) {+ if (unwrap(blocks)[id]) return;+ const handle = registerBlock(type, id);+ onCleanup(() => {+ if (unwrap(blocks)[id]?.handle === handle) setBlocks(id, undefined!);+ });+ return handle;+ }+return {isBlockMounted: (type, id) =>instances.get(keyOf(type, id))?.isMounted() ?? false,getBlockHandle,createBlockInstance: createManagedBlockInstance,rekeyBlockInstance,+ registerBlockHandle,};}