⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.
TypeScript agenticagileai-agentsbug-reportingbug-trackerganttissue-trackerjirajira-alternativekanbanlinearlinear-alternativeopen-sourceproduct-managementproject-managementroadmapself-hostedsprint-planningteam-collaborationtrello-alternative
fix(web): preserve activated row during history scroll restoration (#252)
Denis Zabozhanov64bb58d74db2
diff --git a/apps/web/src/features/issue/components/detail/IssueLinksPanel.tsx b/apps/web/src/features/issue/components/detail/IssueLinksPanel.tsxindex 1cb7fe0e..46ca905d 100644--- a/apps/web/src/features/issue/components/detail/IssueLinksPanel.tsx+++ b/apps/web/src/features/issue/components/detail/IssueLinksPanel.tsx@@ -87,6 +87,7 @@ export default function IssueLinksPanel({key={link.id}project={project}issue={link.issue}+ scrollAnchorKey={`link:${link.id}`}removeLabel={t('remove', { issue: link.issue.identifier })}readOnly={readOnly}onOpen={onOpenIssue && (() => onOpenIssue(link.issue.id))}diff --git a/apps/web/src/features/issue/components/detail/IssueRefRow.tsx b/apps/web/src/features/issue/components/detail/IssueRefRow.tsxindex dee276a8..d6360154 100644--- a/apps/web/src/features/issue/components/detail/IssueRefRow.tsx+++ b/apps/web/src/features/issue/components/detail/IssueRefRow.tsx@@ -4,7 +4,10 @@ import { type IssueRef, type ProjectDetail } from '@/lib/api';import { issuePath } from '@/utils/paths';import { Button } from '@/components/ui/button';import ArchivedBadge from '@/components/common/ArchivedBadge';-import { historyScrollRestorationLinkProps } from '@/hooks/useHistoryScrollRestoration';+import {+ historyScrollRestorationAnchorProps,+ historyScrollRestorationLinkProps,+} from '@/hooks/useHistoryScrollRestoration';import { StateIcon } from '../shared/IssueIcons';// One other issue in the Links or Subtasks panel — the far end of a relation, a@@ -17,6 +20,7 @@ import { StateIcon } from '../shared/IssueIcons';export default function IssueRefRow({project,issue,+ scrollAnchorKey,removeLabel,onRemove,onOpen,@@ -24,6 +28,7 @@ export default function IssueRefRow({}: {project: ProjectDetail;issue: IssueRef;+ scrollAnchorKey: string;removeLabel: string;onRemove?: () => void;onOpen?: () => void;@@ -49,6 +54,7 @@ export default function IssueRefRow({return (<Link{...historyScrollRestorationLinkProps}+ {...historyScrollRestorationAnchorProps(scrollAnchorKey)}href={issuePath(project.project.key, issue.sequenceNumber)}className={labelClass}>diff --git a/apps/web/src/features/issue/components/detail/IssueSubtasksPanel.tsx b/apps/web/src/features/issue/components/detail/IssueSubtasksPanel.tsxindex d5e30e4c..0ab63643 100644--- a/apps/web/src/features/issue/components/detail/IssueSubtasksPanel.tsx+++ b/apps/web/src/features/issue/components/detail/IssueSubtasksPanel.tsx@@ -67,6 +67,7 @@ export default function IssueSubtasksPanel({<IssueRefRowproject={project}issue={parent}+ scrollAnchorKey={`parent:${parent.id}`}removeLabel={t('detachFromParent', { parent: parent.identifier })}readOnly={readOnly}onOpen={onOpenIssue && (() => onOpenIssue(parent.id))}@@ -84,6 +85,7 @@ export default function IssueSubtasksPanel({key={subtask.id}project={project}issue={subtask}+ scrollAnchorKey={`subtask:${subtask.id}`}removeLabel={t('detach', { subtask: subtask.identifier })}readOnly={readOnly}onOpen={onOpenIssue && (() => onOpenIssue(subtask.id))}diff --git a/apps/web/src/hooks/useHistoryScrollRestoration.test.tsx b/apps/web/src/hooks/useHistoryScrollRestoration.test.tsxindex 48d5ce6e..62dc5b43 100644--- a/apps/web/src/hooks/useHistoryScrollRestoration.test.tsx+++ b/apps/web/src/hooks/useHistoryScrollRestoration.test.tsx@@ -9,6 +9,10 @@ interface SavedScrollPosition {entryId: string;pathname: string;scrollTop: number;+ anchor?: {+ key: string;+ offsetTop: number;+ };}interface TestHistoryState {@@ -26,8 +30,10 @@ const replacedGlobals = ['window','document','navigator',+ 'Element','HTMLElement','Event',+ 'MouseEvent','ResizeObserver','requestAnimationFrame','cancelAnimationFrame',@@ -37,15 +43,29 @@ const replacedGlobals = [let dom: JSDOM;let root: Root;let maxScrollTop: number;+let anchorContentTop: number;let resizeObservers: ResizeObserverHarness[];let originalGlobalDescriptors: Map<string, PropertyDescriptor | undefined>;-function ScrollContainer({ pathname }: { pathname: string }) {+function ScrollContainer({+ pathname,+ anchorKey = 'subtask:4',+}: {+ pathname: string;+ anchorKey?: string | null;+}) {const restorationProps = useHistoryScrollRestoration({ pathname });return (<div data-testid="scroll-container" {...restorationProps}>- <div>Content</div>+ <div>+ Content+ {anchorKey && (+ <button type="button" data-history-scroll-restoration-anchor={anchorKey}>+ Subtask+ </button>+ )}+ </div></div>);}@@ -56,15 +76,19 @@ function currentPosition(): SavedScrollPosition {return state.__itsaplanScrollRestoration;}-function render(pathname: string): HTMLDivElement {- act(() => root.render(<ScrollContainer pathname={pathname} />));+function render(pathname: string, anchorKey?: string | null): HTMLDivElement {+ act(() => root.render(<ScrollContainer pathname={pathname} anchorKey={anchorKey} />));const container = document.querySelector<HTMLDivElement>('[data-testid="scroll-container"]');assert.ok(container);return container;}-function dispatch(container: HTMLDivElement, type: string) {- act(() => container.dispatchEvent(new window.Event(type, { bubbles: true })));+function dispatch(target: HTMLElement, type: string) {+ act(() => target.dispatchEvent(new window.Event(type, { bubbles: true })));+}++function click(target: HTMLElement) {+ act(() => target.dispatchEvent(new window.MouseEvent('click', { bubbles: true, detail: 1 })));}beforeEach(async () => {@@ -75,6 +99,7 @@ beforeEach(async () => {url: `https://example.test${parentPath}`,});maxScrollTop = Number.POSITIVE_INFINITY;+ anchorContentTop = 2100;resizeObservers = [];const scrollPositions = new WeakMap<HTMLElement, number>();@@ -87,6 +112,24 @@ beforeEach(async () => {scrollPositions.set(this, Math.min(value, maxScrollTop));},});+ Object.defineProperty(dom.window.HTMLElement.prototype, 'getBoundingClientRect', {+ configurable: true,+ value(this: HTMLElement) {+ if (this.dataset.testid === 'scroll-container') {+ return new dom.window.DOMRect(0, 100, 800, 600);+ }+ if (this.dataset.historyScrollRestorationAnchor) {+ const container = this.closest<HTMLElement>('[data-testid="scroll-container"]');+ return new dom.window.DOMRect(+ 0,+ 100 + anchorContentTop - (container?.scrollTop ?? 0),+ 400,+ 24,+ );+ }+ return new dom.window.DOMRect();+ },+ });class TestResizeObserver {private readonly harness: ResizeObserverHarness;@@ -112,8 +155,10 @@ beforeEach(async () => {window: { configurable: true, value: dom.window },document: { configurable: true, value: dom.window.document },navigator: { configurable: true, value: dom.window.navigator },+ Element: { configurable: true, value: dom.window.Element },HTMLElement: { configurable: true, value: dom.window.HTMLElement },Event: { configurable: true, value: dom.window.Event },+ MouseEvent: { configurable: true, value: dom.window.MouseEvent },ResizeObserver: { configurable: true, value: TestResizeObserver },requestAnimationFrame: {configurable: true,@@ -189,6 +234,127 @@ describe('useHistoryScrollRestoration', () => {assert.equal(observer.disconnected, true);});+ it('keeps the activated anchor in place while content above it changes height', () => {+ const container = render(parentPath);+ const anchor = container.querySelector<HTMLElement>(+ '[data-history-scroll-restoration-anchor="subtask:4"]',+ );+ assert.ok(anchor);++ container.scrollTop = 1800;+ dispatch(container, 'scroll');+ dispatch(anchor, 'pointerdown');+ const parentState = window.history.state;+ assert.deepEqual(currentPosition().anchor, { key: 'subtask:4', offsetTop: 300 });++ act(() => {+ window.history.pushState({}, '', childPath);+ root.render(<ScrollContainer pathname={childPath} />);+ });+ act(() => {+ window.history.replaceState(parentState, '', parentPath);+ root.render(<ScrollContainer pathname={parentPath} />);+ });+ assert.equal(container.scrollTop, 1800);++ anchorContentTop += 80;+ const observer = resizeObservers.at(-1);+ assert.ok(observer);+ act(() => observer.trigger());++ assert.equal(container.scrollTop, 1880);+ assert.equal(anchor.getBoundingClientRect().top - container.getBoundingClientRect().top, 300);+ assert.equal(currentPosition().scrollTop, 1880);+ assert.equal(observer.disconnected, false);++ container.scrollTop = 1900;+ dispatch(container, 'scroll');+ assert.equal(observer.disconnected, true);+ anchorContentTop += 80;+ act(() => observer.trigger());+ assert.equal(container.scrollTop, 1900);+ });++ it('captures the final anchor position after momentum scroll between pointerdown and click', async () => {+ const container = render(parentPath);+ const anchor = container.querySelector<HTMLElement>(+ '[data-history-scroll-restoration-anchor="subtask:4"]',+ );+ assert.ok(anchor);++ container.scrollTop = 1800;+ dispatch(container, 'scroll');+ dispatch(anchor, 'pointerdown');++ container.scrollTop = 1860;+ dispatch(container, 'scroll');+ click(anchor);++ assert.deepEqual(currentPosition().anchor, { key: 'subtask:4', offsetTop: 240 });+ await new Promise((resolve) => setTimeout(resolve, 120));+ assert.deepEqual(currentPosition().anchor, { key: 'subtask:4', offsetTop: 240 });+ });++ it('does not reapply the absolute fallback after it has been reached without the anchor', () => {+ const container = render(parentPath);+ const anchor = container.querySelector<HTMLElement>(+ '[data-history-scroll-restoration-anchor="subtask:4"]',+ );+ assert.ok(anchor);++ container.scrollTop = 1800;+ dispatch(container, 'scroll');+ dispatch(anchor, 'pointerdown');+ const parentState = window.history.state;++ act(() => {+ window.history.pushState({}, '', childPath);+ root.render(<ScrollContainer pathname={childPath} />);+ });+ act(() => {+ window.history.replaceState(parentState, '', parentPath);+ root.render(<ScrollContainer pathname={parentPath} anchorKey={null} />);+ });+ assert.equal(container.scrollTop, 1800);++ container.scrollTop = 1700;+ const observer = resizeObservers.at(-1);+ assert.ok(observer);+ act(() => observer.trigger());++ assert.equal(container.scrollTop, 1700);+ assert.equal(observer.disconnected, false);+ });++ it('stops restoration when an anchor that was restored disappears', () => {+ const container = render(parentPath);+ const anchor = container.querySelector<HTMLElement>(+ '[data-history-scroll-restoration-anchor="subtask:4"]',+ );+ assert.ok(anchor);++ container.scrollTop = 1800;+ dispatch(container, 'scroll');+ dispatch(anchor, 'pointerdown');+ const parentState = window.history.state;++ act(() => {+ window.history.pushState({}, '', childPath);+ root.render(<ScrollContainer pathname={childPath} />);+ });+ act(() => {+ window.history.replaceState(parentState, '', parentPath);+ root.render(<ScrollContainer pathname={parentPath} />);+ });++ const observer = resizeObservers.at(-1);+ assert.ok(observer);+ act(() => root.render(<ScrollContainer pathname={parentPath} anchorKey={null} />));+ act(() => observer.trigger());++ assert.equal(observer.disconnected, true);+ });+it('cancels a pending restoration when the user scrolls', () => {window.history.replaceState({diff --git a/apps/web/src/hooks/useHistoryScrollRestoration.ts b/apps/web/src/hooks/useHistoryScrollRestoration.tsindex e26b3556..7b811acc 100644--- a/apps/web/src/hooks/useHistoryScrollRestoration.ts+++ b/apps/web/src/hooks/useHistoryScrollRestoration.ts@@ -10,18 +10,31 @@ import {} from 'react';const SCROLL_SAVE_DELAY_MS = 100;+const SCROLL_ANCHOR_ATTRIBUTE = 'data-history-scroll-restoration-anchor';const scrollContainerStyle = { overflowAnchor: 'none' } satisfies CSSProperties;const scrollPositions = new Map<string, number>();let nextHistoryEntryId = 0;export const historyScrollRestorationLinkProps = { scroll: false } as const;+export function historyScrollRestorationAnchorProps(key: string) {+ return { [SCROLL_ANCHOR_ATTRIBUTE]: key };+}++interface ScrollRestorationAnchor {+ key: string;+ offsetTop: number;+}++interface ScrollRestorationPosition {+ entryId: string;+ pathname: string;+ scrollTop: number;+ anchor?: ScrollRestorationAnchor;+}+interface ScrollRestorationHistoryState {- __itsaplanScrollRestoration?: {- entryId: string;- pathname: string;- scrollTop: number;- };+ __itsaplanScrollRestoration?: ScrollRestorationPosition;}interface HistoryScrollRestorationOptions {@@ -36,6 +49,42 @@ interface ScrollRestorationProps<T extends HTMLElement> {onPointerDownCapture: PointerEventHandler<T>;}+function findAnchorElement(container: HTMLElement, key: string) {+ return Array.from(container.querySelectorAll<HTMLElement>(`[${SCROLL_ANCHOR_ATTRIBUTE}]`)).find(+ (element) => element.getAttribute(SCROLL_ANCHOR_ATTRIBUTE) === key,+ );+}++function captureAnchor(container: HTMLElement, target: EventTarget | null) {+ if (!(target instanceof Element)) return undefined;+ const element = target.closest(`[${SCROLL_ANCHOR_ATTRIBUTE}]`);+ if (!(element instanceof HTMLElement) || !container.contains(element)) return undefined;+ const key = element.getAttribute(SCROLL_ANCHOR_ATTRIBUTE);+ if (!key) return undefined;+ return {+ key,+ offsetTop: element.getBoundingClientRect().top - container.getBoundingClientRect().top,+ };+}++function validAnchor(value: unknown): value is ScrollRestorationAnchor {+ if (!value || typeof value !== 'object') return false;+ const anchor = value as Partial<ScrollRestorationAnchor>;+ return (+ typeof anchor.key === 'string' &&+ anchor.key.length > 0 &&+ typeof anchor.offsetTop === 'number' &&+ Number.isFinite(anchor.offsetTop)+ );+}++function replaceHistoryPosition(position: ScrollRestorationPosition) {+ window.history.replaceState(+ { ...window.history.state, __itsaplanScrollRestoration: position },+ '',+ );+}+export function useHistoryScrollRestoration<T extends HTMLElement = HTMLDivElement>({pathname,}: HistoryScrollRestorationOptions): ScrollRestorationProps<T> {@@ -46,12 +95,14 @@ export function useHistoryScrollRestoration<T extends HTMLElement = HTMLDivElemeconst restoredScrollTopRef = useRef<number | null>(null);const restoreObserverRef = useRef<ResizeObserver | null>(null);const pendingScrollTopRef = useRef<number | null>(null);+ const pendingAnchorRef = useRef<ScrollRestorationAnchor | undefined>(undefined);const saveTimerRef = useRef<number | null>(null);const clearPendingSave = useCallback(() => {if (saveTimerRef.current != null) window.clearTimeout(saveTimerRef.current);saveTimerRef.current = null;pendingScrollTopRef.current = null;+ pendingAnchorRef.current = undefined;}, []);const stopRestoration = useCallback(() => {@@ -65,6 +116,7 @@ export function useHistoryScrollRestoration<T extends HTMLElement = HTMLDivElemeconst activeEntryId = activeEntryIdRef.current;const activePathname = activePathnameRef.current;const scrollTop = pendingScrollTopRef.current;+ const anchor = pendingAnchorRef.current;if (activeEntryId == null || activePathname == null || scrollTop == null) return;scrollPositions.set(activeEntryId, scrollTop);@@ -76,25 +128,24 @@ export function useHistoryScrollRestoration<T extends HTMLElement = HTMLDivEleme}clearPendingSave();- window.history.replaceState(- {- ...window.history.state,- __itsaplanScrollRestoration: {- entryId: activeEntryId,- pathname: activePathname,- scrollTop,- },- },- '',- );+ replaceHistoryPosition({+ entryId: activeEntryId,+ pathname: activePathname,+ scrollTop,+ ...(anchor ? { anchor } : {}),+ });}, [clearPendingSave]);- const saveCurrentScrollPosition = useCallback(() => {- if (!scrollRef.current) return;- stopRestoration();- pendingScrollTopRef.current = scrollRef.current.scrollTop;- saveScrollPosition();- }, [saveScrollPosition, stopRestoration]);+ const saveCurrentScrollPosition = useCallback(+ (target?: EventTarget | null) => {+ if (!scrollRef.current) return;+ stopRestoration();+ pendingScrollTopRef.current = scrollRef.current.scrollTop;+ pendingAnchorRef.current = captureAnchor(scrollRef.current, target ?? null);+ saveScrollPosition();+ },+ [saveScrollPosition, stopRestoration],+ );useLayoutEffect(() => {stopRestoration();@@ -116,19 +167,22 @@ export function useHistoryScrollRestoration<T extends HTMLElement = HTMLDivEleme: `${performance.timeOrigin}:${++nextHistoryEntryId}`;const persistedScrollTop = ownsHistoryEntry ? savedPosition.scrollTop : 0;const scrollTop = scrollPositions.get(entryId) ?? persistedScrollTop;+ const anchor =+ ownsHistoryEntry && validAnchor(savedPosition.anchor) ? savedPosition.anchor : undefined;activeEntryIdRef.current = entryId;activePathnameRef.current = pathname;isRestoringRef.current = true;scrollPositions.set(entryId, scrollTop);- window.history.replaceState(- {- ...window.history.state,- __itsaplanScrollRestoration: { entryId, pathname, scrollTop },- },- '',- );+ replaceHistoryPosition({+ entryId,+ pathname,+ scrollTop,+ ...(anchor ? { anchor } : {}),+ });+ let absoluteScrollRestored = false;+ let anchorWasFound = false;const restore = () => {if (isRestoringRef.current &&@@ -136,9 +190,37 @@ export function useHistoryScrollRestoration<T extends HTMLElement = HTMLDivElemeactivePathnameRef.current === pathname &&scrollRef.current) {- scrollRef.current.scrollTop = scrollTop;- restoredScrollTopRef.current = scrollRef.current.scrollTop;- if (Math.abs(scrollRef.current.scrollTop - scrollTop) < 1) stopRestoration();+ const container = scrollRef.current;+ const anchorElement = anchor ? findAnchorElement(container, anchor.key) : undefined;+ if (anchor && anchorElement) {+ anchorWasFound = true;+ const currentOffset =+ anchorElement.getBoundingClientRect().top - container.getBoundingClientRect().top;+ container.scrollTop += currentOffset - anchor.offsetTop;+ restoredScrollTopRef.current = container.scrollTop;+ scrollPositions.set(entryId, container.scrollTop);+ const currentState = window.history.state as ScrollRestorationHistoryState | null;+ if (+ window.location.pathname === pathname &&+ currentState?.__itsaplanScrollRestoration?.entryId === entryId+ ) {+ replaceHistoryPosition({+ entryId,+ pathname,+ scrollTop: container.scrollTop,+ anchor,+ });+ }+ } else if (anchorWasFound) {+ stopRestoration();+ } else if (!absoluteScrollRestored) {+ container.scrollTop = scrollTop;+ restoredScrollTopRef.current = container.scrollTop;+ if (Math.abs(container.scrollTop - scrollTop) < 1) {+ absoluteScrollRestored = true;+ if (!anchor) stopRestoration();+ }+ }}};@@ -170,16 +252,16 @@ export function useHistoryScrollRestoration<T extends HTMLElement = HTMLDivEleme}pendingScrollTopRef.current = scrollTop;+ pendingAnchorRef.current = undefined;const activeEntryId = activeEntryIdRef.current;if (activeEntryId != null) scrollPositions.set(activeEntryId, scrollTop);if (saveTimerRef.current != null) window.clearTimeout(saveTimerRef.current);saveTimerRef.current = window.setTimeout(saveScrollPosition, SCROLL_SAVE_DELAY_MS);};- const onPointerDownCapture: PointerEventHandler<T> = saveCurrentScrollPosition;- const onClickCapture: MouseEventHandler<T> = (event) => {- if (event.detail === 0) saveCurrentScrollPosition();- };+ const onPointerDownCapture: PointerEventHandler<T> = (event) =>+ saveCurrentScrollPosition(event.target);+ const onClickCapture: MouseEventHandler<T> = (event) => saveCurrentScrollPosition(event.target);return {ref: scrollRef,