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): keep the reading position when the comment margin opens (#6867)
gbirman40c12a4d87e7
diff --git a/apps/web/src/features/block-md/comments/commentLayout.ts b/apps/web/src/features/block-md/comments/commentLayout.tsindex 06f77e8d79..d5de59b3eb 100644--- a/apps/web/src/features/block-md/comments/commentLayout.ts+++ b/apps/web/src/features/block-md/comments/commentLayout.ts@@ -11,7 +11,6 @@ import {registerEditorWidthObserver,registerInternalLayoutShiftListener,} from '@core/component/LexicalMarkdown/plugins';-import { getScrollParentElement } from '@core/util/scrollParent';import { createElementSize } from '@solid-primitives/resize-observer';import { leadingAndTrailing, throttle } from '@solid-primitives/scheduled';import {@@ -49,43 +48,6 @@ export function createCommentLayout() {Partial<Record<MarkId, number>>>({});- const [marginTop, setMarginTop] = createSignal(0);- const [scrollY, setScrollY] = createSignal(0);-- createEffect(() => {- const commentMargin = md.commentMargin;-- if (!commentMargin) {- return;- }-- // Track the top of the bounding NON-scrolling element.- const blockContent = commentMargin.closest('[data-block-content]');- if (blockContent) {- const resizeObserver = new ResizeObserver(() => {- const top = blockContent?.getBoundingClientRect().top ?? 0;- setMarginTop(top);- });- resizeObserver.observe(blockContent);- onCleanup(() => {- resizeObserver.disconnect();- });- }-- // Track the scroll top of the bounding scrolling element.- const scrollParent = getScrollParentElement(commentMargin);- if (scrollParent) {- const updateScrollY = () => {- const scrollTop = scrollParent.scrollTop;- setScrollY(scrollTop);- };- scrollParent.addEventListener('scroll', updateScrollY, { passive: true });- onCleanup(() => {- scrollParent.removeEventListener('scroll', updateScrollY);- });- }- });-// Sort comments by their marks' positions.function markElementSort(a: HTMLElement, b: HTMLElement) {const { left: aLeft, top: aTop } = a.getBoundingClientRect();@@ -97,7 +59,13 @@ export function createCommentLayout() {}createEffect(() => {+ const commentMargin = md.commentMargin;+ if (!commentMargin) return;++ // Measure marks against the margin itself: it scrolls with the document,+ // so the offsets hold at any scroll position without tracking scrollTop.const updateMarkPositions = () => {+ const marginTop = commentMargin.getBoundingClientRect().top;for (const markId in commentState.marks) {const mark = commentState.marks[markId];if (!mark) continue;@@ -107,7 +75,7 @@ export function createCommentLayout() {// attach the comment layout to the top element of the markconst topEl = markEls.sort(markElementSort)[0];- const top = topEl.getBoundingClientRect().top + scrollY();+ const top = topEl.getBoundingClientRect().top - marginTop;setMarkLocationTops(markId, top);}};@@ -120,6 +88,12 @@ export function createCommentLayout() {LAYOUT_THROTTLE);+ // The margin is display:none until the document has a comment; re-measure+ // once it is laid out.+ const marginResizeObserver = new ResizeObserver(() => throttledUpdate());+ marginResizeObserver.observe(commentMargin);+ onCleanup(() => marginResizeObserver.disconnect());+// Throttle updates on comment positions. Update on (1) editor updates, (2)// internal layout shifts causes by non-updating element height changed to// embeds and media and (3) editor width changes.@@ -152,7 +126,7 @@ export function createCommentLayout() {return {id: m.id,layout: {- top: top - marginTop(),+ top,},};}diff --git a/apps/web/src/features/block-md/component/Notebook.tsx b/apps/web/src/features/block-md/component/Notebook.tsxindex 19ad135111..51ea2ffb48 100644--- a/apps/web/src/features/block-md/component/Notebook.tsx+++ b/apps/web/src/features/block-md/component/Notebook.tsx@@ -22,9 +22,11 @@ import type { LoroManager } from '@macro-inc/collaboration/collab/manager';import { makeResizeObserver } from '@solid-primitives/resize-observer';import { makePersisted } from '@solid-primitives/storage';import {+ createComputed,createEffect,createMemo,createSignal,+ on,onCleanup,onMount,Show,@@ -45,6 +47,11 @@ import {MarkdownOutline,useMarkdownOutline,} from './MarkdownOutline';+import {+ captureScrollAnchor,+ restoreScrollAnchor,+ type ScrollAnchor,+} from './scrollAnchor';import { TaskDuplicateMatchPill } from './TaskDuplicateMatches';import { TitleEditor } from './TitleEditor';import {@@ -135,14 +142,48 @@ export function Notebook(props: {// comment drawer is the only comment surface. CommentMargin stays mounted// inside the hidden wrapper — it hosts the drawer.const showComments = () => hasComment() && !history.isOpen() && !isMobile();- const layoutMode = (): CommentLayoutMode => {+ const layoutMode = createMemo((): CommentLayoutMode => {if (!showComments() || width() === undefined) {return CommentLayoutMode.none;}if (commentBreakpoints.lg()) return CommentLayoutMode.lg;if (commentBreakpoints.md()) return CommentLayoutMode.md;return CommentLayoutMode.xs;- };+ });++ // Switching layout mode resizes the text column and reflows the document+ // under an unchanged scrollTop; the first comment on a document would+ // otherwise scroll its own anchor text out of view. Browser scroll anchoring+ // is suppressed because the switch changes the column's padding and margins.+ // The computed captures the anchor before the new classes are applied, the+ // effect restores it after.+ let scrollAnchor: ScrollAnchor | undefined;+ createComputed(+ on(+ layoutMode,+ () => {+ const scroller = md.scrollContainer;+ const editorRoot = md.editor?.getRootElement();+ scrollAnchor =+ scroller && editorRoot+ ? captureScrollAnchor(scroller, editorRoot)+ : undefined;+ },+ { defer: true }+ )+ );+ createEffect(+ on(+ layoutMode,+ () => {+ const anchor = scrollAnchor;+ const scroller = md.scrollContainer;+ scrollAnchor = undefined;+ if (anchor && scroller) restoreScrollAnchor(scroller, anchor);+ },+ { defer: true }+ )+ );const currentEditorState = () => {const editor = md.editor;diff --git a/apps/web/src/features/block-md/component/scrollAnchor.test.ts b/apps/web/src/features/block-md/component/scrollAnchor.test.tsnew file mode 100644index 0000000000..3a508c92f0--- /dev/null+++ b/apps/web/src/features/block-md/component/scrollAnchor.test.ts@@ -0,0 +1,116 @@+/**+ * @vitest-environment jsdom+ */++import { afterEach, describe, expect, it, vi } from 'vitest';+import { captureScrollAnchor, restoreScrollAnchor } from './scrollAnchor';++const rect = (top: number, bottom: number) =>+ ({+ top,+ bottom,+ left: 0,+ right: 0,+ width: 0,+ height: bottom - top,+ }) as DOMRect;++function setup(blockTops: number[]) {+ const scroller = document.createElement('div');+ const root = document.createElement('div');+ scroller.append(root);+ document.body.append(scroller);+ vi.spyOn(scroller, 'getBoundingClientRect').mockReturnValue(rect(0, 500));+ const tops = [...blockTops];+ const blocks = tops.map((_, i) => {+ const block = document.createElement('p');+ block.textContent = `block ${i}`;+ vi.spyOn(block, 'getBoundingClientRect').mockImplementation(() =>+ rect(tops[i]!, tops[i]! + 100)+ );+ root.append(block);+ return block;+ });+ return { scroller, root, blocks, tops };+}++afterEach(() => {+ Reflect.deleteProperty(document, 'caretRangeFromPoint');+ Reflect.deleteProperty(Range.prototype, 'getClientRects');+ document.body.replaceChildren();+ getSelection()?.removeAllRanges();+ vi.restoreAllMocks();+});++describe('scroll anchor', () => {+ it('keeps the first visible block in place when the document reflows', () => {+ const { scroller, root, tops } = setup([-250, -150, -50, 50]);+ scroller.scrollTop = 1000;++ const anchor = captureScrollAnchor(scroller, root);+ expect(anchor?.top).toBe(-50);++ tops[2] = 250;+ restoreScrollAnchor(scroller, anchor!);+ expect(scroller.scrollTop).toBe(1300);+ });++ it('prefers the on-screen selection over the first visible block', () => {+ const { scroller, root, blocks } = setup([0, 100, 200, 300]);+ let selectionTop = 320;+ const range = document.createRange();+ range.selectNodeContents(blocks[3]!);+ // jsdom has no layout, so Range lacks getClientRects.+ range.getClientRects = () =>+ [rect(selectionTop, selectionTop + 20)] as unknown as DOMRectList;+ getSelection()?.addRange(range);+ scroller.scrollTop = 1000;++ const anchor = captureScrollAnchor(scroller, root);+ expect(anchor?.top).toBe(320);++ selectionTop = 1120;+ restoreScrollAnchor(scroller, anchor!);+ expect(scroller.scrollTop).toBe(1800);+ });++ it('anchors text at the viewport top inside a block that starts above it', () => {+ const { scroller, root, blocks } = setup([-300, 400]);+ vi.spyOn(blocks[0]!, 'getBoundingClientRect').mockReturnValue(+ rect(-300, 300)+ );+ const text = blocks[0]!.firstChild!;+ let caretTop = 5;+ // jsdom has no layout, so caret hit-testing and Range rects are stubbed.+ document.caretRangeFromPoint = () => {+ const range = document.createRange();+ range.setStart(text, 3);+ return range;+ };+ Range.prototype.getClientRects = function (this: Range) {+ return (this.startContainer === text+ ? [rect(caretTop, caretTop + 20)]+ : []) as unknown as DOMRectList;+ };+ scroller.scrollTop = 1000;++ const anchor = captureScrollAnchor(scroller, root);+ expect(anchor?.top).toBe(5);++ // The block rewraps taller while its own top stays put.+ caretTop = 85;+ restoreScrollAnchor(scroller, anchor!);+ expect(scroller.scrollTop).toBe(1080);+ });++ it('ignores a selection outside the editor', () => {+ const { scroller, root } = setup([0, 100]);+ const outside = document.createElement('input');+ document.body.append(outside);+ const range = document.createRange();+ range.selectNode(outside);+ getSelection()?.addRange(range);++ expect(captureScrollAnchor(scroller, root)?.top).toBe(0);+ });+});diff --git a/apps/web/src/features/block-md/component/scrollAnchor.ts b/apps/web/src/features/block-md/component/scrollAnchor.tsnew file mode 100644index 0000000000..9b93c44527--- /dev/null+++ b/apps/web/src/features/block-md/component/scrollAnchor.ts@@ -0,0 +1,81 @@+/**+ * A point in the document whose on-screen position should survive a reflow.+ * `top` is its viewport offset when captured; `measure` reads it again.+ */+export type ScrollAnchor = {+ top: number;+ measure: () => number | undefined;+};++function rangeTop(range: Range): number | undefined {+ const rect = range.getClientRects()[0];+ return rect?.top;+}++function caretRangeAt(doc: Document, x: number, y: number): Range | undefined {+ const position = doc.caretPositionFromPoint?.(x, y);+ if (position) {+ const range = doc.createRange();+ range.setStart(position.offsetNode, position.offset);+ return range;+ }+ return doc.caretRangeFromPoint?.(x, y) ?? undefined;+}++/**+ * Captures the point the reader is looking at: the editor selection when it is+ * on screen, otherwise the first editor text that reaches into the viewport.+ */+export function captureScrollAnchor(+ scroller: HTMLElement,+ editorRoot: HTMLElement+): ScrollAnchor | undefined {+ const view = scroller.getBoundingClientRect();+ const isOnScreen = (top: number) => top >= view.top && top <= view.bottom;++ const selection = editorRoot.ownerDocument.getSelection();+ if (selection && selection.rangeCount > 0) {+ const range = selection.getRangeAt(0);+ const top = editorRoot.contains(range.startContainer)+ ? rangeTop(range)+ : undefined;+ if (top !== undefined && isOnScreen(top)) {+ return { top, measure: () => rangeTop(range) };+ }+ }++ for (const block of editorRoot.children) {+ const rect = block.getBoundingClientRect();+ if (rect.bottom <= view.top) continue;+ if (rect.top >= view.bottom) return undefined;+ // A block that starts above the viewport rewraps above it too, so anchor+ // the text at the viewport's top edge rather than the block's top.+ if (rect.top < view.top) {+ const range = caretRangeAt(+ editorRoot.ownerDocument,+ rect.left + 1,+ view.top + 1+ );+ if (range && block.contains(range.startContainer)) {+ const top = rangeTop(range);+ if (top !== undefined) return { top, measure: () => rangeTop(range) };+ }+ }+ return {+ top: rect.top,+ measure: () =>+ block.isConnected ? block.getBoundingClientRect().top : undefined,+ };+ }+ return undefined;+}++/** Scrolls so the anchor is back at the viewport offset it was captured at. */+export function restoreScrollAnchor(+ scroller: HTMLElement,+ anchor: ScrollAnchor+) {+ const top = anchor.measure();+ if (top === undefined) return;+ scroller.scrollTop += top - anchor.top;+}