diff --git a/.changeset/37029-list-back-scroll-key.md b/.changeset/37029-list-back-scroll-key.md new file mode 100644 index 00000000000..732429df1db --- /dev/null +++ b/.changeset/37029-list-back-scroll-key.md @@ -0,0 +1,14 @@ +--- +'@object-ui/plugin-list': patch +'@object-ui/components': patch +--- + +fix(plugin-list, components): browser Back to a scroll-loaded list restores the rows and the position it left, as the record page's close button does + +Clause-②: no +Metadata-protocol: none + +A list that loads as it scrolls keeps its position and the rows it held under a key naming the list's address. Two things stopped browser Back from returning there when the record drawer had been open over the list: + +- The key carried the drawer's `recordId` and `recordObject` parameters. The drawer opens over the list without remounting it, so a record opened while the drawer was open left a history entry carrying the drawer. Back returned to that address, missed the kept position and showed the first window at the top. The close button returns to the list without the drawer and found it. A list that first mounted under an open drawer lost its position on every return. The key now leaves out those two parameters; every other address parameter still keys the list. +- On that return the drawer reopened and scrolled its record's row into view over the restored position. A list that returns to a kept position now says so on its root (`data-list-kept-position`), and there the drawer's first record is not scrolled into view. A row click, a step to another record, or a deep link with no kept position scrolls the open row into view as before. diff --git a/ui/packages/components/src/__tests__/record-list-face-37029.test.tsx b/ui/packages/components/src/__tests__/record-list-face-37029.test.tsx new file mode 100644 index 00000000000..6bc373ab569 --- /dev/null +++ b/ui/packages/components/src/__tests__/record-list-face-37029.test.tsx @@ -0,0 +1,102 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#37029 — browser Back to a list entry whose record drawer was + * open: the list restores the scroll position it kept, and the drawer's open + * row is not scrolled into view over it. Everywhere else the open row still + * scrolls into view: a fresh deep link, a row click, a step + * (`record-list-face.tsx`, objectstack#27545). + * + * A list returning to a kept position carries `data-list-kept-position` on + * its root (`ListView` in @object-ui/plugin-list writes it). + */ + +import * as React from 'react'; +import { describe, it, expect, afterEach, beforeEach, vi } from 'vitest'; +import { render, cleanup } from '@testing-library/react'; +import { ActiveListRecordProvider, ActiveListRow } from '../custom/record-list-face'; + +const IDS = ['a', 'b', 'c']; +let scrolled: string[] = []; + +beforeEach(() => { + scrolled = []; + vi.spyOn(HTMLElement.prototype, 'scrollIntoView').mockImplementation(function (this: HTMLElement) { + scrolled.push(this.dataset.testid ?? ''); + }); +}); +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); +}); + +function Rows({ mounted = IDS }: { mounted?: string[] }) { + return ( + <> + {mounted.map((id) => ( + key={id} recordId={id}> + {(active, ref) => ( +
+ {id} +
+ )} + + ))} + + ); +} + +/** The list root, marked as `ListView` marks a return to a kept position. */ +function List({ kept, children }: { kept: boolean; children: React.ReactNode }) { + return
{children}
; +} + +function tree(recordId: string | null, kept: boolean, mounted?: string[]) { + return ( + + + + + + ); +} + +describe('objectstack#37029 — a kept list position wins over the drawer\'s open-row scroll on a return', () => { + it('Back to a drawer-open entry: the drawer\'s record is not scrolled into view, and a remount of its row is not either', () => { + // The drawer opens once its record has loaded: no open record, then "b". + const { rerender } = render(tree(null, true)); + rerender(tree('b', true)); + expect(scrolled).toEqual([]); + // The rows re-mount as the list's windows land: still the restore's. + rerender(tree('b', true, ['a', 'c'])); + rerender(tree('b', true)); + expect(scrolled).toEqual([]); + }); + + it('after the return, a step to another record scrolls as before, and so does the way back', () => { + const { rerender } = render(tree('b', true)); + expect(scrolled).toEqual([]); + rerender(tree('c', true)); + expect(scrolled).toEqual(['row-c']); + rerender(tree('b', true)); + expect(scrolled).toEqual(['row-c', 'row-b']); + }); + + it('a fresh deep link (no kept position) still scrolls the drawer\'s record into view', () => { + const { rerender } = render(tree(null, false)); + rerender(tree('b', false)); + expect(scrolled).toEqual(['row-b']); + }); + + it('a row click on a list with no kept position scrolls the new open row', () => { + const { rerender } = render(tree('a', false)); + rerender(tree('c', false)); + expect(scrolled).toEqual(['row-a', 'row-c']); + }); +}); diff --git a/ui/packages/components/src/custom/record-list-face.tsx b/ui/packages/components/src/custom/record-list-face.tsx index 3dea607f3ee..462b3536a3a 100644 --- a/ui/packages/components/src/custom/record-list-face.tsx +++ b/ui/packages/components/src/custom/record-list-face.tsx @@ -28,18 +28,30 @@ interface ActiveListRecordStore { get(): string | null; set(recordId: string | null): void; subscribe(listener: () => void): () => void; + /** + * Whether `recordId` is the first record this drawer opened over the list + * and no other record has been opened since (objectstack#37029). + */ + isOnlyRecordOpened(recordId: string): boolean; } function createActiveListRecordStore(initial: string | null): ActiveListRecordStore { let current = initial; + let first = initial; + let movedOn = false; const listeners = new Set<() => void>(); return { get: () => current, set: (recordId) => { if (recordId === current) return; + if (recordId !== null) { + if (first === null) first = recordId; + else if (recordId !== first) movedOn = true; + } current = recordId; listeners.forEach((listener) => listener()); }, + isOnlyRecordOpened: (recordId) => !movedOn && first === recordId, subscribe: (listener) => { listeners.add(listener); return () => { @@ -91,17 +103,34 @@ export function useIsActiveListRecord(recordId: string | null): boolean { ); } +/** + * Marks a list that is returning to a scroll position it kept + * (objectstack#37029). Written by `ListView` in @object-ui/plugin-list on its + * root, spelled the same there; read here, so the two packages share no + * import. + */ +const KEPT_POSITION_SELECTOR = '[data-list-kept-position]'; + /** * The open row's DOM side: once its row becomes the open record — a row click, * a step, a deep link — it is scrolled into view, by the least distance. + * + * objectstack#37029 — except on a return to a list that kept its scroll + * position (browser Back to an entry whose drawer was open): there the list + * restores the position the reader left, and the drawer's record — the only + * one opened since the list came back — is not scrolled over it. The first + * row click or step to another record scrolls as before. */ -export function useScrollActiveListRecordIntoView(active: boolean) { +export function useScrollActiveListRecordIntoView(active: boolean, recordId?: string | null) { const ref = React.useRef(null); + const store = React.useContext(ActiveListRecordContext); React.useLayoutEffect(() => { if (!active) return; const el = ref.current; - if (el && typeof el.scrollIntoView === 'function') el.scrollIntoView({ block: 'nearest' }); - }, [active]); + if (!el || typeof el.scrollIntoView !== 'function') return; + if (store && recordId != null && store.isOnlyRecordOpened(recordId) && el.closest(KEPT_POSITION_SELECTOR)) return; + el.scrollIntoView({ block: 'nearest' }); + }, [active, recordId, store]); return ref; } @@ -118,6 +147,6 @@ export function ActiveListRow({ children: (active: boolean, ref: React.RefObject) => React.ReactNode; }) { const active = useIsActiveListRecord(recordId); - const ref = useScrollActiveListRecordIntoView(active); + const ref = useScrollActiveListRecordIntoView(active, recordId); return <>{children(active, ref)}; } diff --git a/ui/packages/plugin-list/src/ListView.tsx b/ui/packages/plugin-list/src/ListView.tsx index 9557937c654..be0f1962a2e 100644 --- a/ui/packages/plugin-list/src/ListView.tsx +++ b/ui/packages/plugin-list/src/ListView.tsx @@ -2968,12 +2968,26 @@ export const ListView = React.forwardRef(({ // objectstack#35554 — the infinite list's windows (see `infiniteScroll`). // The key the list's scroll position is kept under: this list as the // address bar names it, read once. - const [scrollRestoreKey] = React.useState(() => - typeof window === 'undefined' - ? undefined - : `${schema.objectName ?? ''}|${window.location.pathname}${window.location.search}`, - ); - const [restoreRows] = React.useState(() => readListScrollState(scrollRestoreKey)?.rows ?? null); + // + // objectstack#37029 — without the record drawer's own parameters + // (`recordId`, `recordObject`: app-shell's `RECORD_DRAWER_PARAM` and + // `RECORD_DRAWER_OBJECT_PARAM`). The drawer opens and closes over the list + // without remounting it, so they are not the list's address: the record + // page's ✕ returns to the list without them (app-shell `listOriginOf`), + // while browser Back returns to the entry the record was opened from, + // drawer and all. Keyed with them, the two exits read two keys, and Back — + // or any return after the list mounted under an open drawer — missed the + // kept position. Every other parameter stays: it can change the rows. + const [scrollRestoreKey] = React.useState(() => { + if (typeof window === 'undefined') return undefined; + const params = new URLSearchParams(window.location.search); + params.delete('recordId'); + params.delete('recordObject'); + const search = params.toString(); + return `${schema.objectName ?? ''}|${window.location.pathname}${search ? `?${search}` : ''}`; + }); + const [keptScroll] = React.useState(() => readListScrollState(scrollRestoreKey)); + const restoreRows = keptScroll?.rows ?? null; const [loadedWindows, setLoadedWindows] = React.useState(null); const infiniteAppendSkipRef = React.useRef(null); const pageControlled = page !== undefined; @@ -3185,6 +3199,14 @@ export const ListView = React.forwardRef(({ // (`view.zod.ts`), so its presence is the declaration. The capped posture // (a page block's bounded list) keeps its one window. const infiniteScroll = paginate && !cappedWindow && schema.pagination === undefined; + // objectstack#37029 — this mount returns to a kept position (the grid + // restores it once its rows are back, `useInfiniteRowLoad`). Marked on the + // list's root as `data-list-kept-position`, which the record drawer's + // open-row scroll reads (`record-list-face.tsx` in @object-ui/components): + // on a return to a list whose drawer is open, the kept position wins over + // scrolling the drawer's record into view, as the record page's ✕ return + // does. The attribute's name is spelled the same in both files. + const returnsToKeptPosition = infiniteScroll && (keptScroll?.top ?? 0) > 0; // How many windows the list holds. `null` until the reader scrolls: then // it is the windows needed to cover the rows a kept position was taken over // (`readListScrollState`), so a return to the list loads back to the row it @@ -7791,6 +7813,7 @@ export const ListView = React.forwardRef(({ {...(schema.aria?.live ? { 'aria-live': schema.aria.live } : {})} aria-busy={loading || undefined} data-state={loading ? 'loading' : 'idle'} + {...(returnsToKeptPosition ? { 'data-list-kept-position': '' } : {})} > {pullDistance > 0 && (
; + +const OBJECT = 'back_object'; +const LIST_PATH = '/apps/demo/back_object'; +/** The list's window, the spec's display default for an unauthored page size. */ +const WINDOW = 50; +const ROWS: Row[] = Array.from({ length: 120 }, (_, i) => ({ id: `r${i + 1}`, name: `Row ${i + 1}` })); + +let lastGridProps: any = null; +let previous: unknown; +let startUrl = ''; +beforeAll(() => { + previous = ComponentRegistry.get('object-grid'); + ComponentRegistry.register('object-grid', (props: any) => { + lastGridProps = props; + return
; + }); +}); +afterAll(() => { + if (previous) ComponentRegistry.register('object-grid', previous as any); + else ComponentRegistry.unregister('object-grid'); +}); +beforeEach(() => { + lastGridProps = null; + startUrl = window.location.pathname + window.location.search; + window.sessionStorage.clear(); +}); +afterEach(() => { + cleanup(); + window.sessionStorage.clear(); + window.history.replaceState(null, '', startUrl); +}); + +function dataSource() { + const store = new ValueDataSource({ items: ROWS }); + return { + find: vi.fn(async (object: string, params: any) => store.find(object, params)), + findOne: vi.fn(), + create: vi.fn(), + update: vi.fn(), + delete: vi.fn(), + getObjectSchema: async (name: string) => ({ + name, + fields: { id: { type: 'text' }, name: { type: 'text' } }, + }), + } as any; +} + +/** The rows the grid was last handed. */ +const handedRows = (): Row[] => (lastGridProps?.data ?? lastGridProps?.schema?.data?.items ?? []) as Row[]; +/** The key the grid keeps the list's position under. */ +const handedKey = (): string | undefined => lastGridProps?.schema?.scrollRestoreKey ?? lastGridProps?.scrollRestoreKey; + +/** Mount the list at `address`, as a navigation to that history entry does. */ +async function mountAt(address: string) { + window.history.replaceState(null, '', address); + lastGridProps = null; // read only what THIS mount hands the grid + const ds = dataSource(); + return render( + + + , + ); +} + +/** Mount and wait for the first rows the grid is handed. */ +async function mountAndLoad(address: string) { + const view = await mountAt(address); + await waitFor(() => expect(handedRows().length).toBeGreaterThan(0)); + return view; +} + +describe('objectstack#37029 — the list scroll key leaves out the record drawer', () => { + it('Back to an entry carrying the drawer loads back the rows the list kept with the drawer closed', async () => { + // The position the list kept while scrolled with no drawer in the address + // (the key ✕ returns to): 110 rows, past two windows. + await mountAndLoad(LIST_PATH); + const plainKey = handedKey(); + expect(plainKey).toBe(`${OBJECT}|${LIST_PATH}`); + cleanup(); + window.sessionStorage.setItem(`os:list-scroll:${plainKey}`, JSON.stringify({ top: 4000, rows: 110 })); + + // Back lands on the entry the record was opened from, drawer open. + await mountAndLoad(`${LIST_PATH}?recordId=r2&recordObject=${OBJECT}`); + expect(handedKey()).toBe(plainKey); + await waitFor(() => expect(handedRows()).toHaveLength(120)); + }); + + it('a list that mounted under an open drawer keeps its position under the key a plain return reads', async () => { + await mountAndLoad(`${LIST_PATH}?recordId=r2`); + expect(handedKey()).toBe(`${OBJECT}|${LIST_PATH}`); + }); + + it('every other parameter stays in the key: two filters are two lists', async () => { + await mountAndLoad(`${LIST_PATH}?filter=open&recordId=r2`); + const openKey = handedKey(); + cleanup(); + await mountAndLoad(`${LIST_PATH}?filter=closed`); + const closedKey = handedKey(); + expect(openKey).toBe(`${OBJECT}|${LIST_PATH}?filter=open`); + expect(closedKey).toBe(`${OBJECT}|${LIST_PATH}?filter=closed`); + }); +}); + +describe('objectstack#37029 — a mount that returns to a kept position says so on its root', () => { + const marked = (container: HTMLElement) => container.querySelectorAll('[data-list-kept-position]').length; + + it('marks the root when the address it returns to kept a scrolled position, drawer open or not', async () => { + window.sessionStorage.setItem(`os:list-scroll:${OBJECT}|${LIST_PATH}`, JSON.stringify({ top: 4000, rows: 60 })); + const { container } = await mountAndLoad(`${LIST_PATH}?recordId=r2`); + expect(marked(container)).toBe(1); + }); + + it('leaves it unmarked with no kept position, or one kept at the top', async () => { + const first = await mountAndLoad(`${LIST_PATH}?recordId=r2`); + expect(marked(first.container)).toBe(0); + cleanup(); + window.sessionStorage.setItem(`os:list-scroll:${OBJECT}|${LIST_PATH}`, JSON.stringify({ top: 0, rows: 50 })); + const second = await mountAndLoad(`${LIST_PATH}?recordId=r2`); + expect(marked(second.container)).toBe(0); + }); +});