Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .changeset/37029-list-back-scroll-key.md
Original file line number Diff line number Diff line change
@@ -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.
102 changes: 102 additions & 0 deletions ui/packages/components/src/__tests__/record-list-face-37029.test.tsx
Original file line number Diff line number Diff line change
@@ -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) => (
<ActiveListRow<HTMLDivElement> key={id} recordId={id}>
{(active, ref) => (
<div ref={ref} data-testid={`row-${id}`} data-active={active ? '' : undefined}>
{id}
</div>
)}
</ActiveListRow>
))}
</>
);
}

/** The list root, marked as `ListView` marks a return to a kept position. */
function List({ kept, children }: { kept: boolean; children: React.ReactNode }) {
return <div {...(kept ? { 'data-list-kept-position': '' } : {})}>{children}</div>;
}

function tree(recordId: string | null, kept: boolean, mounted?: string[]) {
return (
<ActiveListRecordProvider recordId={recordId}>
<List kept={kept}>
<Rows mounted={mounted} />
</List>
</ActiveListRecordProvider>
);
}

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']);
});
});
37 changes: 33 additions & 4 deletions ui/packages/components/src/custom/record-list-face.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down Expand Up @@ -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<T extends HTMLElement>(active: boolean) {
export function useScrollActiveListRecordIntoView<T extends HTMLElement>(active: boolean, recordId?: string | null) {
const ref = React.useRef<T | null>(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;
}

Expand All @@ -118,6 +147,6 @@ export function ActiveListRow<T extends HTMLElement = HTMLTableRowElement>({
children: (active: boolean, ref: React.RefObject<T | null>) => React.ReactNode;
}) {
const active = useIsActiveListRecord(recordId);
const ref = useScrollActiveListRecordIntoView<T>(active);
const ref = useScrollActiveListRecordIntoView<T>(active, recordId);
return <>{children(active, ref)}</>;
}
35 changes: 29 additions & 6 deletions ui/packages/plugin-list/src/ListView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2968,12 +2968,26 @@ export const ListView = React.forwardRef<ListViewHandle, ListViewProps>(({
// 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<number | null>(null);
const infiniteAppendSkipRef = React.useRef<number | null>(null);
const pageControlled = page !== undefined;
Expand Down Expand Up @@ -3185,6 +3199,14 @@ export const ListView = React.forwardRef<ListViewHandle, ListViewProps>(({
// (`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
Expand Down Expand Up @@ -7791,6 +7813,7 @@ export const ListView = React.forwardRef<ListViewHandle, ListViewProps>(({
{...(schema.aria?.live ? { 'aria-live': schema.aria.live } : {})}
aria-busy={loading || undefined}
data-state={loading ? 'loading' : 'idle'}
{...(returnsToKeptPosition ? { 'data-list-kept-position': '' } : {})}
>
{pullDistance > 0 && (
<div
Expand Down
Loading
Loading