diff --git a/.changeset/36015-lookup-chip-opens-in-drawer.md b/.changeset/36015-lookup-chip-opens-in-drawer.md new file mode 100644 index 00000000000..f52ffed4fb8 --- /dev/null +++ b/.changeset/36015-lookup-chip-opens-in-drawer.md @@ -0,0 +1,20 @@ +--- +'@object-ui/components': patch +'@object-ui/fields': patch +'@object-ui/plugin-grid': patch +'@object-ui/plugin-list': patch +'@object-ui/app-shell': patch +--- + +feat(grid): on the list page a lookup chip opens its record in the side drawer, and a lookup cell has an edit button + +Clause-②: yes (widening) +Metadata-protocol: none + +On the console's list page, a single click on a lookup chip (a record of another object, such as a contact's account) now opens that record in the side drawer over the list. This replaces, for lookup chips on that page, the earlier change in this release where a plain click on a lookup chip only selected its cell. The list stays where it was: closing the drawer leaves its scroll position and the selected cell as they were. The drawer's address carries the record and its object (`?recordId=…&recordObject=…`), so a reload keeps it open and Back closes it, as with the name cell's "Open in side panel" icon. A click beside the chips only selects the cell. A cell of several chips opens the chip that was clicked; Ctrl/Cmd+Enter on the selected cell opens the first one in the drawer; Ctrl/Cmd-click still opens the record's page in a new tab. + +A lookup cell now draws an edit (pencil) button while the pointer is over it and while it is selected. It opens the cell's editor, as a double-click or Enter does, and it is not drawn when the cell cannot be edited (no permission, a read-only field, a locked record). It takes the place of the open button a selected cell shows. + +A chip naming a person (an owner, a creator: a lookup to `sys_user`) keeps the behaviour it had: a single click only selects the cell, and it opens from the open button or Ctrl/Cmd+Enter. Email, phone and URL cells and the name column are unchanged. On a phone every record still opens as its page. + +For hosts: `ListView` and `ObjectGrid` take a new runtime prop, `openReferencedRecord(objectName, recordId)`, that opens such a record in the host's place; `GridCellSelection` gains an optional `referenceCells` member (`isReferenceColumn`, `openRecord`), exported with its type `GridReferenceCells` from `@object-ui/components`. A host that passes neither keeps the previous behaviour, where a chip only selects its cell. `ReferencedRecordLink`'s anchor now carries `data-record-object` and `data-record-id`. diff --git a/content/docs/frontend/plugins/plugin-grid.mdx b/content/docs/frontend/plugins/plugin-grid.mdx index 9d060c2986f..8db647681dd 100644 --- a/content/docs/frontend/plugins/plugin-grid.mdx +++ b/content/docs/frontend/plugins/plugin-grid.mdx @@ -398,13 +398,21 @@ object and the view does not declare `userActions.editInline: false`, and - **A click selects** a cell (a ring around it); it neither edits nor opens the record. Only the name link keeps its own click (it opens the record). Every - other link a cell draws (an email, a phone number, a URL, a file, a lookup or - user chip, an image thumbnail) is selected by a click too (objectstack#36015); - to open it, Ctrl/Cmd-click it, press the **Open** button the selected cell - shows on hover, or press Ctrl/Cmd+Enter. A cell of several chips opens the - first one that way. The email and phone cells draw no copy button here: - Ctrl/Cmd+C copies the selected cell. On a touch screen a tap opens the - record. + other link a cell draws (an email, a phone number, a URL, a file, a user + chip, an image thumbnail, and a lookup chip unless the host opens it in + place, below) is selected by a click too (objectstack#36015); to open it, + Ctrl/Cmd-click it, press the **Open** button the selected cell shows on + hover, or press Ctrl/Cmd+Enter. A cell of several chips opens the first one + that way. The email and phone cells draw no copy button here: Ctrl/Cmd+C + copies the selected cell. On a touch screen a tap opens the record. +- **A lookup chip opens its record in place** when the host passes + `openReferencedRecord` (the console's list page opens it in the side drawer, + over the list): a single click on the chip opens that record, a click beside + it selects the cell, and Ctrl/Cmd+Enter opens the first chip the same way. A + lookup cell draws an **Edit** (pencil) button on hover and while selected, + which opens its editor; it is not drawn when the cell cannot be edited, and + it takes the place of the **Open** button. A chip naming a person (a lookup + to `sys_user`) keeps the click-selects behaviour above. - **A cut-off value shows in full** when its cell is selected: a long text, a multi-line text or a list of tags that the column truncates opens on a layer over the cell, wrapped, scrolling inside past a few lines. Escape, an diff --git a/ui/packages/app-shell/src/urlParams.ts b/ui/packages/app-shell/src/urlParams.ts index cad0969a1f8..6b3c2ca6bdb 100644 --- a/ui/packages/app-shell/src/urlParams.ts +++ b/ui/packages/app-shell/src/urlParams.ts @@ -85,6 +85,14 @@ import { NAV_RUN_ACTION_PARAM } from '@object-ui/layout'; */ export const RECORD_DRAWER_PARAM = 'recordId'; +/** + * The object of the record the drawer's root shows, when it is not the + * listed object's (objectstack#36015): a lookup chip in the list opens the + * record it names in the list's drawer. Absent ⇒ the listed object. Read + * only beside {@link RECORD_DRAWER_PARAM}. + */ +export const RECORD_DRAWER_OBJECT_PARAM = 'recordObject'; + /** Global record-form overlay: `new` | `` (framework#2604). */ export const RECORD_FORM_PARAM = 'form'; @@ -156,6 +164,7 @@ export { NAV_RUN_ACTION_PARAM }; */ export const RESERVED_URL_PARAMS: readonly string[] = [ RECORD_DRAWER_PARAM, + RECORD_DRAWER_OBJECT_PARAM, RECORD_FORM_PARAM, RECORD_FORM_OBJECT_PARAM, RECORD_FORM_LINK_PARAM, diff --git a/ui/packages/app-shell/src/views/ObjectView.tsx b/ui/packages/app-shell/src/views/ObjectView.tsx index b4ce519a337..37856366c6e 100644 --- a/ui/packages/app-shell/src/views/ObjectView.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.tsx @@ -1047,7 +1047,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co // objectstack#27058 — on a phone the record is always a page: a row tap // navigates to it, and no pane is mounted beside or over the list. const phone = usePhoneViewport(); - const { listRecordActions, navOverlay, handleDrawerClose, handleRowClick, handleOpenAsPage, handleOpenRowInPanel, drawerRoot, drawerRestore, handleListRowsChange, handleListTotalChange, handleRootStep, listLabel } = useObjectViewRecordNavigation({ + const { listRecordActions, navOverlay, handleDrawerClose, handleRowClick, handleOpenAsPage, handleOpenRowInPanel, handleOpenReferencedRecord, drawerRoot, drawerRestore, handleListRowsChange, handleListTotalChange, handleRootStep, listLabel } = useObjectViewRecordNavigation({ activeView, objectDef, objects, @@ -1073,6 +1073,9 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co : null), [navOverlay.mode, phone, openInPanelLabel, handleOpenRowInPanel], ); + // objectstack#36015 — a lookup chip in the grid opens its record in the + // same side drawer, where this list has one. + const openReferencedRecord = navOverlay.mode === 'drawer' && !phone ? handleOpenReferencedRecord : undefined; // objectstack#25992 slice 8: the `filter[...]` URL equality filters and the `uf_*` // user-filter selections moved to `./objectViewListUrlState.ts`. @@ -1188,6 +1191,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co handleListRowsChange, handleListTotalChange, openInPanel, + openReferencedRecord, // objectstack#33317 — the resolved mode: `none` for an authored // `none` and for a list-only object (`servesRecordRead`). rowOpensRecord: navOverlay.mode !== 'none', diff --git a/ui/packages/app-shell/src/views/objectViewListRenderer.tsx b/ui/packages/app-shell/src/views/objectViewListRenderer.tsx index d7eff6f3479..94c5ee66155 100644 --- a/ui/packages/app-shell/src/views/objectViewListRenderer.tsx +++ b/ui/packages/app-shell/src/views/objectViewListRenderer.tsx @@ -101,6 +101,7 @@ export function useObjectViewListRenderer({ handleListRowsChange, handleListTotalChange, openInPanel, + openReferencedRecord, rowOpensRecord, phoneTitle, viewBarTrailing, @@ -145,6 +146,8 @@ export function useObjectViewListRenderer({ handleListTotalChange: ReturnType['handleListTotalChange']; /** objectstack#35854 — the name cell's 「在侧边打开」 (`./objectViewOpenAsPage.tsx`), or `null` for none. */ openInPanel: { label: string; open: (recordId: string | number) => void } | null; + /** objectstack#36015 — a lookup chip's record in the side drawer, or `undefined` where the list has none. */ + openReferencedRecord: ((objectName: string, recordId: string) => void) | undefined; /** objectstack#33317 — whether a row click opens the record: `false` for the `none` mode. */ rowOpensRecord: boolean; /** @@ -1183,6 +1186,9 @@ export function useObjectViewListRenderer({ : null; } : undefined} + // objectstack#36015 — a lookup chip in the grid opens the record it + // names in the same side drawer. + openReferencedRecord={openReferencedRecord} // objectstack#33317 — a row that opens nothing (the view // authored `navigation.mode: 'none'`, or a list-only object) // draws no record link and no Open in its context menu. @@ -1203,7 +1209,7 @@ export function useObjectViewListRenderer({ dataSource={ds} /> ); - }, [hasViewBarTrailing, trailStore, rowEndStore, activeView, activeViewDeclaresColumns, activeViewIsSaved, objectDef, objectName, refreshKey, createRecord, urlFilters, initialUfSelections, handleUserFilterSelectionsChange, writeListUrlState, listPage, user?.id, pageOffersCreate, listAddRecordOpensCreate, listIdentityKey, listPrefs.ready, listPrefs.preference, listPrefs.patchView, listDraft.draft, listDraft.patch, managedUsers, managedUserMarker, openInPanel, rowOpensRecord, handleListRowsChange, handleListTotalChange, hasPhoneTitle, leadStore, wideViewport, handleListPersonalizationChange, workspaceTimeZone, viewPanelFilters, offersRename, offersSave, offersReset, offersSummaryPick, summaryPickKey, previewDrafts, previewDataSource, unpublishedObjects]); + }, [hasViewBarTrailing, trailStore, rowEndStore, activeView, activeViewDeclaresColumns, activeViewIsSaved, objectDef, objectName, refreshKey, createRecord, urlFilters, initialUfSelections, handleUserFilterSelectionsChange, writeListUrlState, listPage, user?.id, pageOffersCreate, listAddRecordOpensCreate, listIdentityKey, listPrefs.ready, listPrefs.preference, listPrefs.patchView, listDraft.draft, listDraft.patch, managedUsers, managedUserMarker, openInPanel, openReferencedRecord, rowOpensRecord, handleListRowsChange, handleListTotalChange, hasPhoneTitle, leadStore, wideViewport, handleListPersonalizationChange, workspaceTimeZone, viewPanelFilters, offersRename, offersSave, offersReset, offersSummaryPick, summaryPickKey, previewDrafts, previewDataSource, unpublishedObjects]); return { renderListView }; } diff --git a/ui/packages/app-shell/src/views/objectViewRecordNavigation.listRows-27524.test.tsx b/ui/packages/app-shell/src/views/objectViewRecordNavigation.listRows-27524.test.tsx index 335b797185d..09a8d2e2433 100644 --- a/ui/packages/app-shell/src/views/objectViewRecordNavigation.listRows-27524.test.tsx +++ b/ui/packages/app-shell/src/views/objectViewRecordNavigation.listRows-27524.test.tsx @@ -12,7 +12,7 @@ import * as React from 'react'; import { describe, it, expect, vi } from 'vitest'; import { act, renderHook } from '@testing-library/react'; -import { MemoryRouter, type Location } from 'react-router-dom'; +import { MemoryRouter, useLocation, useNavigate, useSearchParams, type Location } from 'react-router-dom'; import { useObjectViewRecordNavigation } from './objectViewRecordNavigation'; @@ -82,3 +82,110 @@ describe('a page the list opens carries the list\'s rows (objectstack#27524, Tar expect(lastState(navigate)).toEqual({ from: { pathname: '/apps/crm/crm_lead?view=all', label: 'All leads' } }); }); }); + +describe('a lookup chip opens the record it names in the list\'s drawer (objectstack#36015)', () => { + const OBJECTS = [{ name: 'crm_lead', label: 'Lead' }, { name: 'crm_account', label: 'Account' }]; + + function mountDrawer(search: string) { + const navigate = vi.fn(); + const setSearchParams = vi.fn(); + const { result } = renderHook(() => + useObjectViewRecordNavigation({ + activeView: { id: 'all', name: 'all', label: 'All leads' } as never, + objectDef: { name: 'crm_lead', label: 'Lead', fields: {} } as never, + objects: OBJECTS as never, + appName: 'crm', + viewId: undefined, + searchParams: new URLSearchParams(search), + setSearchParams, + location: { ...LIST, search: `?${search}` }, + navigate, + routerRootHref: '/', + servedViews: { views: [], objects: [] } as never, + viewLabel: (_object: string, _view: string, fallback: string) => fallback, + unlabelledViewText: 'Untitled view', + language: 'en', + phone: false, + }), + { wrapper: ({ children }: { children: React.ReactNode }) => {children} }, + ); + act(() => result.current.handleListRowsChange(ROWS)); + const lastParams = () => String(setSearchParams.mock.calls.at(-1)![0]); + return { result, navigate, lastParams, setSearchParams }; + } + + it('another object\'s record: its id and its object in the URL, beside the list\'s own params', () => { + const { result, lastParams } = mountDrawer('view=all'); + act(() => result.current.handleOpenReferencedRecord('crm_account', 'a7')); + expect(lastParams()).toBe('view=all&recordId=a7&recordObject=crm_account'); + }); + + it('the record the drawer already shows is not pushed again, so one Back still closes it', () => { + const foreign = mountDrawer('view=all&recordId=a7&recordObject=crm_account'); + act(() => foreign.result.current.handleOpenReferencedRecord('crm_account', 'a7')); + const own = mountDrawer('view=all&recordId=r-2'); + act(() => own.result.current.handleOpenReferencedRecord('crm_lead', 'r-2')); + expect(foreign.setSearchParams).not.toHaveBeenCalled(); + expect(own.setSearchParams).not.toHaveBeenCalled(); + // The same id under another object is another record. + act(() => foreign.result.current.handleOpenReferencedRecord('crm_lead', 'a7')); + expect(foreign.lastParams()).toBe('view=all&recordId=a7'); + }); + + it('in a router: a chip opened twice (a double-click) leaves one history entry, and one Back closes the drawer', () => { + // The console's declarative router pushes on every navigate, the same URL included. + function useRouted() { + const [searchParams, setSearchParams] = useSearchParams(); + const location = useLocation(); + const navigate = useNavigate(); + const nav = useObjectViewRecordNavigation({ + activeView: { id: 'all', name: 'all', label: 'All leads' } as never, + objectDef: { name: 'crm_lead', label: 'Lead', fields: {} } as never, + objects: OBJECTS as never, + appName: 'crm', + viewId: undefined, + searchParams, + setSearchParams, + location, + navigate, + routerRootHref: '/', + servedViews: { views: [], objects: [] } as never, + viewLabel: (_object: string, _view: string, fallback: string) => fallback, + unlabelledViewText: 'Untitled view', + language: 'en', + phone: false, + }); + return { nav, search: location.search, back: () => navigate(-1) }; + } + const { result } = renderHook(useRouted, { + wrapper: ({ children }: { children: React.ReactNode }) => {children}, + }); + act(() => result.current.nav.handleListRowsChange(ROWS)); + act(() => result.current.nav.handleOpenReferencedRecord('crm_account', 'a7')); + act(() => result.current.nav.handleOpenReferencedRecord('crm_account', 'a7')); + expect(result.current.search).toBe('?view=all&recordId=a7&recordObject=crm_account'); + act(() => result.current.back()); + expect(result.current.search).toBe('?view=all'); + }); + + it('a record of the listed object opens as the name cell\'s icon opens it, with no object param', () => { + const { result, lastParams } = mountDrawer('view=all&recordId=a7&recordObject=crm_account'); + act(() => result.current.handleOpenReferencedRecord('crm_lead', 'r-2')); + expect(lastParams()).toBe('view=all&recordId=r-2'); + }); + + it('the drawer\'s root is that record, with no sibling set; an object the console does not know opens nothing', () => { + expect(mountDrawer('recordId=a7&recordObject=crm_account').result.current.drawerRoot).toEqual({ objectName: 'crm_account', recordId: 'a7' }); + expect(mountDrawer('recordId=a7&recordObject=crm_unknown').result.current.drawerRoot).toBeNull(); + // The listed object's row keeps its sibling set. + expect(mountDrawer('recordId=r-2').result.current.drawerRoot).toEqual({ objectName: 'crm_lead', recordId: 'r-2', siblings: ['r-1', 'r-2', 'r-3'] }); + }); + + it('closing the drawer drops both params; its full-page button opens that object\'s page', () => { + const { result, navigate, lastParams } = mountDrawer('view=all&recordId=a7&recordObject=crm_account'); + act(() => result.current.handleDrawerClose()); + expect(lastParams()).toBe('view=all'); + act(() => result.current.handleOpenAsPage([{ objectName: 'crm_account', recordId: 'a7' }])); + expect(navigate).toHaveBeenLastCalledWith('/apps/crm/crm_account/record/a7'); + }); +}); diff --git a/ui/packages/app-shell/src/views/objectViewRecordNavigation.ts b/ui/packages/app-shell/src/views/objectViewRecordNavigation.ts index 3cc39b3e735..0474a084cc9 100644 --- a/ui/packages/app-shell/src/views/objectViewRecordNavigation.ts +++ b/ui/packages/app-shell/src/views/objectViewRecordNavigation.ts @@ -50,7 +50,7 @@ import { deriveRecordSurface, overlayWidthFor } from '@object-ui/plugin-view/cor import { useNavigationOverlay } from '@object-ui/react'; import { usePermissions } from '@object-ui/permissions'; import type { ViewNavigationConfig } from '@object-ui/types'; -import { RECORD_DRAWER_PARAM, RECORD_FORM_PARAM, RECORD_FORM_OBJECT_PARAM, RECORD_FORM_LINK_PARAM } from '../urlParams.js'; +import { RECORD_DRAWER_PARAM, RECORD_DRAWER_OBJECT_PARAM, RECORD_FORM_PARAM, RECORD_FORM_OBJECT_PARAM, RECORD_FORM_LINK_PARAM } from '../urlParams.js'; import { RECORD_FORM_CREATE_VALUES_STATE } from '../utils/recordFormNavigation.js'; import { viewTabLabel } from './viewTabLabel.js'; import { listRecordDetailUrl, listRecordActionsValue } from './objectViewRecordLinks.js'; @@ -223,6 +223,16 @@ export function useObjectViewRecordNavigation({ [activeView?.navigation, objectDef, phone, recordServed] ); const drawerRecordId = searchParams.get(RECORD_DRAWER_PARAM); + // objectstack#36015 — the root's object when a lookup chip opened a record + // of another object; `null` for the listed object's own rows. + const drawerObjectParam = searchParams.get(RECORD_DRAWER_OBJECT_PARAM); + const drawerForeignObject = drawerObjectParam && drawerObjectParam !== objectDef.name ? drawerObjectParam : null; + // A root of another object opens only when the console knows that object + // and the server reads one record of it. + const drawerRootServed = drawerForeignObject + ? objects.some((o) => (o as { name?: unknown } | null)?.name === drawerForeignObject) + && servesRecordRead(drawerForeignObject, perms) + : recordServed; // The location as of the latest render, read when a handler runs: the // handlers below reach the list (its row click, its ↗, the record links it // publishes), which must not re-render when `?recordId=` changes @@ -292,6 +302,7 @@ export function useObjectViewRecordNavigation({ // `?recordId=` a phone redirect leaves behind (objectstack#27058). const originParams = split?.form ? split.origin : new URLSearchParams(search); originParams.delete(RECORD_DRAWER_PARAM); + originParams.delete(RECORD_DRAWER_OBJECT_PARAM); const originSearch = originParams.toString(); const originState = { ...extraState, @@ -350,6 +361,7 @@ export function useObjectViewRecordNavigation({ navOverlay.close(); const newParams = new URLSearchParams(searchParams); newParams.delete(RECORD_DRAWER_PARAM); + newParams.delete(RECORD_DRAWER_OBJECT_PARAM); setSearchParams(newParams); }; /** @@ -401,8 +413,32 @@ export function useObjectViewRecordNavigation({ if (!served || mode !== 'drawer') return; const next = new URLSearchParams(params); next.set(RECORD_DRAWER_PARAM, String(recordId)); + next.delete(RECORD_DRAWER_OBJECT_PARAM); setParams(next); }, []); + /** + * A lookup chip in the list's grid (objectstack#36015): the record it names + * in the side drawer over the list, which stays — the same drawer and the + * same URL state as the name cell's icon, its object beside `?recordId=` + * when it is not the listed object. A chip clicked while the drawer is + * open swaps its root record. The record the drawer already shows is not + * pushed again, so one Back still closes it after a double-click. + */ + const handleOpenReferencedRecord = useCallback((targetObjectName: string, recordId: string) => { + const { searchParams: params, setSearchParams: setParams, mode } = panelInputs.current; + const own = targetObjectName === objectDef.name; + const shownObject = params.get(RECORD_DRAWER_OBJECT_PARAM); + if (params.get(RECORD_DRAWER_PARAM) === recordId && (own ? !shownObject || shownObject === objectDef.name : shownObject === targetObjectName)) return; + if (own) { + handleOpenRowInPanel(recordId); + return; + } + if (mode !== 'drawer') return; + const next = new URLSearchParams(params); + next.set(RECORD_DRAWER_PARAM, recordId); + next.set(RECORD_DRAWER_OBJECT_PARAM, targetObjectName); + setParams(next); + }, [objectDef.name, handleOpenRowInPanel]); /** * The drawer's one `⤢` 「Open as full page」 at any level of the pane's * stack (objectstack#35854): closes the pane (which clears `?recordId=…`) @@ -414,7 +450,7 @@ export function useObjectViewRecordNavigation({ const handleOpenAsPage = useCallback((path: RecordDrawerLevel[]) => { const target = path[path.length - 1]; if (!target) return; - if (path.length === 1) { + if (path.length === 1 && target.objectName === objectDef.name) { handleDrawerClose(); handleNavOverlayNavigate(target.recordId); return; @@ -423,7 +459,7 @@ export function useObjectViewRecordNavigation({ if (to === null) return; handleDrawerClose(); navigate(to); - }, [handleNavOverlayNavigate, appName, objects, navigate, handleDrawerClose]); + }, [handleNavOverlayNavigate, appName, objects, navigate, handleDrawerClose, objectDef.name]); /** * The rows the list shows, in its order (`ListView`'s `onRowsChange`, * objectstack#26679), and on a grouped grid or a board its groups @@ -463,7 +499,10 @@ export function useObjectViewRecordNavigation({ */ const drawerRoot = useMemo( () => { - if (!drawerRecordId || !recordServed) return null; + if (!drawerRecordId || !drawerRootServed) return null; + // A record of another object is no row of this list: it has no + // sibling set to step through. + if (drawerForeignObject) return { objectName: drawerForeignObject, recordId: drawerRecordId }; const set = listSiblingSetOf(listRows, drawerRecordId); // The matched count belongs to the whole list, not to one group. const total = set && !set.scope && listTotal != null && listTotal >= set.siblings.length ? listTotal : undefined; @@ -474,16 +513,23 @@ export function useObjectViewRecordNavigation({ ...(total !== undefined ? { total } : {}), }; }, - [drawerRecordId, objectDef.name, listRows, listTotal, recordServed], + [drawerRecordId, drawerForeignObject, drawerRootServed, objectDef.name, listRows, listTotal], ); // Sync URL-based recordId to overlay state. On a phone there is no pane to // open: the drawer link is answered by the record's page, in its place in // the history (objectstack#27058). // A `?recordId=` link to an object with no record surface opens nothing. useEffect(() => { - const openedId = recordServed ? drawerRecordId : null; + const openedId = drawerRootServed ? drawerRecordId : null; if (phone) { - if (openedId) handleNavOverlayNavigate(openedId, undefined, undefined, true); + if (!openedId) return; + if (!drawerForeignObject) { + handleNavOverlayNavigate(openedId, undefined, undefined, true); + return; + } + // objectstack#36015 — a record of another object: its own page. + const to = expandedRecordPath(appName, objects, [{ objectName: drawerForeignObject, recordId: openedId }]); + if (to !== null) navigate(to, { replace: true }); return; } if (openedId && !navOverlay.isOpen) { @@ -491,6 +537,6 @@ export function useObjectViewRecordNavigation({ } else if (!openedId && navOverlay.isOpen) { navOverlay.close(); } - }, [drawerRecordId, phone, recordServed]); - return { listRecordActions, navOverlay, handleDrawerClose, handleRowClick, handleOpenAsPage, handleOpenRowInPanel, drawerRoot, drawerRestore, handleListRowsChange, handleListTotalChange, handleRootStep, listLabel }; + }, [drawerRecordId, drawerForeignObject, phone, drawerRootServed]); + return { listRecordActions, navOverlay, handleDrawerClose, handleRowClick, handleOpenAsPage, handleOpenRowInPanel, handleOpenReferencedRecord, drawerRoot, drawerRestore, handleListRowsChange, handleListTotalChange, handleRootStep, listLabel }; } diff --git a/ui/packages/app-shell/src/views/objectViewRecordOverlay.tsx b/ui/packages/app-shell/src/views/objectViewRecordOverlay.tsx index fab355357e3..2f852de3ad9 100644 --- a/ui/packages/app-shell/src/views/objectViewRecordOverlay.tsx +++ b/ui/packages/app-shell/src/views/objectViewRecordOverlay.tsx @@ -71,6 +71,7 @@ export function ObjectViewRecordOverlay({ mode={mode} width={navOverlay.width} mainContent={list} + listObjectName={objectDef.name} onClose={handleDrawerClose} onOpenAsPage={handleOpenAsPage} stepScope={stepScope} diff --git a/ui/packages/app-shell/src/views/recordDrawerStack.tsx b/ui/packages/app-shell/src/views/recordDrawerStack.tsx index 0db4c2cda8e..947c6a141f1 100644 --- a/ui/packages/app-shell/src/views/recordDrawerStack.tsx +++ b/ui/packages/app-shell/src/views/recordDrawerStack.tsx @@ -476,6 +476,7 @@ export function RecordStackDrawer({ storageKey, objects, mainContent, + listObjectName, stepScope, onClose, onOpenAsPage, @@ -489,6 +490,12 @@ export function RecordStackDrawer({ objects: ReadonlyArray; /** The list the pane opens from (`NavigationOverlay.mainContent`). */ mainContent?: ReactNode; + /** + * The object of the list's rows (objectstack#36015): the root marks its row + * in the list only when it is a record of that object, not a record a lookup + * chip opened. Absent ⇒ the root is always the list's row. + */ + listObjectName?: string; /** * The root level's set by name — the list view it came from — for the * counter's tooltip, unless the level names its own set (its group). @@ -616,7 +623,7 @@ export function RecordStackDrawer({ if (!next) onClose(); }} mainContent={mainContent} - activeListRecordId={path[0]?.recordId ?? null} + activeListRecordId={path[0] && (listObjectName === undefined || path[0].objectName === listObjectName) ? path[0].recordId : null} storageKey={storageKey} onBack={depth > 0 ? () => popTo(depth - 1) : undefined} trail={trail} diff --git a/ui/packages/components/src/__tests__/data-table-select-first-35684.test.tsx b/ui/packages/components/src/__tests__/data-table-select-first-35684.test.tsx index a8874638074..22dbbc20889 100644 --- a/ui/packages/components/src/__tests__/data-table-select-first-35684.test.tsx +++ b/ui/packages/components/src/__tests__/data-table-select-first-35684.test.tsx @@ -28,6 +28,12 @@ * 6. A touch tap opens the record and edits nothing. * 7. The edit-only row column is never drawn: each cell saves itself * (objectstack#35685, `data-table-autosave-35685.test.tsx`). + * 8. In a reference cell the host names (`referenceCells`), a plain click on + * a record chip opens its record through the host and selects the cell; + * a click beside the chips only selects; Ctrl/Cmd+Enter opens the first + * chip; the cell draws an edit button, not the open button, and the edit + * button opens the editor through the same gate as double-click + * (objectstack#36015). */ import React from 'react'; import { describe, it, expect, afterEach, vi } from 'vitest'; @@ -357,3 +363,144 @@ describe('data-table select-first — a touch tap opens the record', () => { expect(t.editor()).toBeNull(); }); }); + +describe('data-table select-first — a reference chip opens its record in place (objectstack#36015)', () => { + const ACCOUNTS = [ + { id: '1', name: 'Alpha', account: 'acc_1', owner: 'usr_1' }, + { id: '2', name: 'Beta', account: 'acc_2', owner: 'usr_2' }, + ]; + // A chip as `ReferencedRecordLink` draws it. + const chip = (objectName: string, recordId: string, label: string, onFollow: (id: string) => void) => ( + + { e.preventDefault(); onFollow(recordId); }} + > + {label} + + + ); + function renderReferences({ readOnly = false, withHost = true }: { readOnly?: boolean; withHost?: boolean } = {}) { + const DataTable = ComponentRegistry.get('data-table')!; + const openRecord = vi.fn(); + const onFollow = vi.fn(); + const selection: GridCellSelection = { + describeCell: (_row, columnKey) => (readOnly && columnKey === 'account' ? { readOnlyReason: 'Not here.' } : null), + ...(withHost + ? { referenceCells: { isReferenceColumn: (key: string) => key === 'account', openRecord } } + : {}), + }; + const schema = { + type: 'data-table', + columns: [ + { header: 'Name', accessorKey: 'name' }, + { header: 'Account', accessorKey: 'account', cell: (v: string) => chip('crm_account', v, `Account ${v}`, onFollow) }, + { header: 'Owner', accessorKey: 'owner', cell: (v: string) => chip('sys_user', v, `Person ${v}`, onFollow) }, + ], + data: ACCOUNTS, + editable: true, + singleClickEdit: true, + searchable: false, + pagination: false, + }; + const utils = render( + + + , + ); + const cell = (row: number, col: number) => + utils.container.querySelectorAll('tbody tr')[row].querySelectorAll('td[data-grid-cell]')[col] as HTMLElement; + const editor = () => utils.container.querySelector('td[data-editing-cell] input'); + const catcher = () => utils.container.querySelector('[data-slot="cell-type-catcher"]'); + const editButton = (row: number, col: number) => cell(row, col).querySelector('[data-testid="cell-edit-button"]'); + return { ...utils, cell, editor, catcher, editButton, openRecord, onFollow }; + } + + it('a plain click on the chip opens its record through the host and selects the cell; the link is not followed', () => { + const t = renderReferences(); + const plain = fireEvent.click(screen.getByText('Account acc_1')); + expect(t.openRecord).toHaveBeenCalledWith('crm_account', 'acc_1'); + expect(t.onFollow).not.toHaveBeenCalled(); + expect(plain).toBe(false); + expect(t.cell(0, 1)).toHaveAttribute('data-selected-cell'); + // A double-click on the chip does not also edit the cell. + fireEvent.doubleClick(screen.getByText('Account acc_1')); + expect(t.editor()).toBeNull(); + }); + + it('a double-click on the chip opens its record once', () => { + const t = renderReferences(); + const chipText = screen.getByText('Account acc_1'); + fireEvent.click(chipText, { detail: 1 }); + fireEvent.click(chipText, { detail: 2 }); + fireEvent.doubleClick(chipText, { detail: 2 }); + expect(t.openRecord).toHaveBeenCalledTimes(1); + expect(t.openRecord).toHaveBeenCalledWith('crm_account', 'acc_1'); + expect(t.editor()).toBeNull(); + }); + + it('a click beside the chip only selects; a Ctrl or Cmd click follows the link', () => { + const t = renderReferences(); + fireEvent.click(t.cell(1, 1)); + expect(t.cell(1, 1)).toHaveAttribute('data-selected-cell'); + expect(t.openRecord).not.toHaveBeenCalled(); + fireEvent.click(screen.getByText('Account acc_2'), { ctrlKey: true }); + fireEvent.click(screen.getByText('Account acc_2'), { metaKey: true }); + expect(t.onFollow).toHaveBeenCalledTimes(2); + expect(t.openRecord).not.toHaveBeenCalled(); + }); + + it('Ctrl or Cmd+Enter on a selected reference cell opens its first chip through the host', () => { + const t = renderReferences(); + fireEvent.click(t.cell(1, 1)); + fireEvent.keyDown(t.catcher()!, { key: 'Enter', ctrlKey: true }); + expect(t.openRecord).toHaveBeenCalledWith('crm_account', 'acc_2'); + expect(t.onFollow).not.toHaveBeenCalled(); + expect(t.editor()).toBeNull(); + }); + + it('a reference cell draws the edit button, shown on hover and while selected; it edits and draws no open button', () => { + const t = renderReferences(); + const button = t.editButton(0, 1)!; + expect(button).toHaveAccessibleName('Edit'); + // Asked when the pointer enters the cell. + expect(button.className).toContain('hidden'); + fireEvent.pointerEnter(t.cell(0, 1)); + expect(button.className).toMatch(/(^|\s)flex(\s|$)/); + expect(button.className).toContain('group-hover/cell:opacity-100'); + fireEvent.click(t.cell(0, 1)); + expect(t.editButton(0, 1)!.className).toContain('opacity-100'); + expect(t.cell(0, 1).querySelector('[data-testid="cell-open-button"]')).toBeNull(); + fireEvent.click(t.editButton(0, 1)!); + expect(t.editor()).not.toBeNull(); + expect(t.openRecord).not.toHaveBeenCalled(); + }); + + it('a reference cell that opens no editor draws no edit button', () => { + const t = renderReferences({ readOnly: true }); + fireEvent.pointerEnter(t.cell(0, 1)); + fireEvent.click(t.cell(0, 1)); + expect(t.editButton(0, 1)!.className).toContain('hidden'); + }); + + it('a column the host does not name (a person) keeps the link behaviour: the chip only selects, the open button opens it', () => { + const t = renderReferences(); + expect(t.editButton(0, 2)).toBeNull(); + fireEvent.click(screen.getByText('Person usr_1')); + expect(t.openRecord).not.toHaveBeenCalled(); + expect(t.onFollow).not.toHaveBeenCalled(); + expect(t.cell(0, 2)).toHaveAttribute('data-selected-cell'); + expect(t.cell(0, 2).querySelector('[data-testid="cell-open-button"]')).not.toBeNull(); + }); + + it('control: with no host reference cells, the chip only selects and no edit button is drawn', () => { + const t = renderReferences({ withHost: false }); + fireEvent.click(screen.getByText('Account acc_1')); + expect(t.onFollow).not.toHaveBeenCalled(); + expect(t.cell(0, 1)).toHaveAttribute('data-selected-cell'); + expect(t.editButton(0, 1)).toBeNull(); + }); +}); diff --git a/ui/packages/components/src/context/gridCellSelection.tsx b/ui/packages/components/src/context/gridCellSelection.tsx index 7851626eb97..39450027775 100644 --- a/ui/packages/components/src/context/gridCellSelection.tsx +++ b/ui/packages/components/src/context/gridCellSelection.tsx @@ -76,6 +76,27 @@ export interface GridCellFacts { validate?: (value: unknown) => string | null | undefined; } +/** + * The reference cells of a select-first grid (objectstack#36015): the columns + * whose cells name records of another object as chips, and how the host opens + * one in place. In such a cell a single click on a chip opens its record with + * {@link GridReferenceCells.openRecord} (and selects the cell), a click beside + * the chips only selects, Ctrl/Cmd+Enter opens the first chip the same way, + * and an edit button is drawn while the pointer is over the cell or the cell + * is selected and it opens an editor. A Ctrl/Cmd-click on a chip still + * follows its link (a new tab). + */ +export interface GridReferenceCells { + /** + * Whether this column's cells are reference cells. Asked per column on every + * render, so it answers from the column alone. A column of people is not one: + * its chips only select. + */ + isReferenceColumn: (columnKey: string) => boolean; + /** Open the record a chip names, in place (the list's side drawer). */ + openRecord: (objectName: string, recordId: string) => void; +} + export interface GridCellSelection { /** The host's facts for one cell; asked when the reader acts on it, never per render. */ describeCell?: (row: any, columnKey: string) => GridCellFacts | null | undefined; @@ -93,6 +114,12 @@ export interface GridCellSelection { * state-machine field (objectstack#35685). */ confirmCommit?: (row: any, columnKey: string, value: unknown) => Promise | null | undefined; + /** + * The grid's reference cells and how a chip in one opens its record + * (objectstack#36015). Absent ⇒ a chip is like any link a cell draws: a + * single click only selects the cell. + */ + referenceCells?: GridReferenceCells | null; } const GridCellSelectionContext = React.createContext(null); diff --git a/ui/packages/components/src/index.ts b/ui/packages/components/src/index.ts index f3028e5cb4c..d5ce96187f0 100644 --- a/ui/packages/components/src/index.ts +++ b/ui/packages/components/src/index.ts @@ -186,6 +186,7 @@ export { useGridCellSelection, type GridCellSelection, type GridCellFacts, + type GridReferenceCells, } from './context/gridCellSelection'; // The header that opens the column menu instead of sorting (objectstack#35876): diff --git a/ui/packages/components/src/renderers/complex/data-table.tsx b/ui/packages/components/src/renderers/complex/data-table.tsx index 17a35cabba3..306c3e50105 100644 --- a/ui/packages/components/src/renderers/complex/data-table.tsx +++ b/ui/packages/components/src/renderers/complex/data-table.tsx @@ -15,7 +15,7 @@ import { DisabledReasonMenuLabel, menuItemReasonAria, useDisabledReason } from ' import { useGridFieldAuthoring } from '../../context/gridFieldAuthoring'; import { useGridCellSelection } from '../../context/gridCellSelection'; import { useGridHeaderMenu } from '../../context/gridHeaderMenu'; -import { caretToEnd, cellOpenerAt, defaultTyping, defaultValueFromText, firstCellOpener, firstEditorControl, isCellWidgetTarget, isCommandLetter, isImeKey, isPrintableKey } from './dataTableCellSelection'; +import { caretToEnd, cellOpenerAt, defaultTyping, defaultValueFromText, firstCellOpener, firstEditorControl, firstRecordChip, isCellWidgetTarget, isCommandLetter, isImeKey, isPrintableKey, recordChipAt } from './dataTableCellSelection'; import { useHorizontalOverflow, HOVER_SCROLLBAR_CLASSES } from '../../custom/use-horizontal-overflow'; import { ActiveListRow, listRecordIdOf } from '../../custom/record-list-face'; import { describeIgnoredBind, describeNonArrayData } from './dataTableBindDiagnostic'; @@ -1466,6 +1466,63 @@ function CellOpenButton({ label, onOpen }: { label: string; onOpen: (cell: HTMLE ); } +/** + * objectstack#36015 — a reference cell's edit button: drawn while the pointer + * is over the cell, and while the cell is selected, when the cell opens an + * editor. `editable` is asked when the pointer enters the cell or the cell is + * selected, never per render. It takes no focus, so typing carries on in the + * cell; the keyboard's ways in are Enter, F2 and typing. + */ +function CellEditButton({ + label, + selected, + editable, + onEdit, +}: { + label: string; + selected: boolean; + editable: () => boolean; + onEdit: () => void; +}) { + const ref = useRef(null); + const editableRef = useRef(editable); + editableRef.current = editable; + const [allowed, setAllowed] = useState(false); + useLayoutEffect(() => { + if (selected) setAllowed(editableRef.current()); + }, [selected]); + useEffect(() => { + const host = ref.current?.closest('td'); + if (!host) return undefined; + const measure = () => setAllowed(editableRef.current()); + host.addEventListener('pointerenter', measure); + return () => host.removeEventListener('pointerenter', measure); + }, []); + return ( + + ); +} + /** * objectstack#35685 — why a list cell's save was refused, said on that cell: * the server's reasons, one line each, and, when the refusal names a field the @@ -3686,6 +3743,11 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { const factsOf = (row: any, col: TableColumn) => cellSelection?.describeCell?.(row, col.accessorKey) ?? null; + // objectstack#36015 — the host's reference cells: a chip in one opens its + // record in place on a single click, and the cell draws an edit button. + const referenceCells = cellSelection?.referenceCells ?? null; + const isReferenceColumn = (col: TableColumn) => !!referenceCells?.isReferenceColumn(col.accessorKey); + // objectstack#36015 — while set, a click on a cell's opener follows it: the // open button or Ctrl/Cmd+Enter is clicking it on the reader's behalf. const followingOpenerRef = useRef(false); @@ -3882,8 +3944,15 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { } setCellNotice(null); if (onCatcher && e.key === 'Enter' && (e.ctrlKey || e.metaKey) && !e.altKey && !e.shiftKey) { - // objectstack#36015 — Ctrl/Cmd+Enter opens what the selected cell draws. - if (openCellOpener(e.currentTarget)) e.preventDefault(); + // objectstack#36015 — Ctrl/Cmd+Enter opens what the selected cell draws; + // in a reference cell, its first chip's record, in place. + const chip = isReferenceColumn(col) ? firstRecordChip(e.currentTarget) : null; + if (chip && referenceCells) { + e.preventDefault(); + referenceCells.openRecord(chip.objectName, chip.recordId); + } else if (openCellOpener(e.currentTarget)) { + e.preventDefault(); + } return; } const next = navigationTarget(e, rowIndex, colIndex); @@ -5148,6 +5217,11 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { e.preventDefault(); e.stopPropagation(); selectCell(rowIndex, colIndex); + // A reference cell's chip opens its record in place: the + // list's side drawer, with the list and its selection kept. + // A double-click's second click opens it no second time. + const chip = isReferenceColumn(col) && e.detail <= 1 ? recordChipAt(e.target, e.currentTarget) : null; + if (chip && referenceCells) referenceCells.openRecord(chip.objectName, chip.recordId); } : undefined} onMouseDown={selectFirst ? (e) => { // The double-click is the edit gesture here, so its second @@ -5161,6 +5235,9 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { // the second click. A touch never edits in place. A word the // browser selected on the way is not a text selection. if (isEditing || isTouchPress(e) || isCellWidgetTarget(e.target, e.currentTarget)) return; + // objectstack#36015 — the first click on a reference chip opened + // its record; the second does not also edit the cell. + if (isReferenceColumn(col) && recordChipAt(e.target, e.currentTarget) !== null) return; window.getSelection?.()?.removeAllRanges(); e.stopPropagation(); if (!togglesCell(row, col)) attemptEdit(rowIndex, colIndex); @@ -5278,9 +5355,19 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { }} /> )} - {isSelectedCell && !isEditing && ( + {isSelectedCell && !isEditing && !isReferenceColumn(col) && ( )} + {selectFirst && !isEditing && isReferenceColumn(col) && ( + // objectstack#36015 — a reference cell's chip opens its record, + // so the open button's place holds the edit button. + readOnlyReasonOf(row, col) === null} + onEdit={() => attemptEdit(rowIndex, colIndex)} + /> + )} {cellNotice?.rowIndex === rowIndex && cellNotice.colIndex === colIndex && ( setCellNotice(null)} /> )} diff --git a/ui/packages/components/src/renderers/complex/dataTableCellSelection.ts b/ui/packages/components/src/renderers/complex/dataTableCellSelection.ts index 6a65216279a..451b51e6581 100644 --- a/ui/packages/components/src/renderers/complex/dataTableCellSelection.ts +++ b/ui/packages/components/src/renderers/complex/dataTableCellSelection.ts @@ -50,6 +50,37 @@ export function cellOpenerAt(target: EventTarget | null, cell: Element): HTMLEle return opener !== null && opener !== cell && cell.contains(opener) ? opener : null; } +const RECORD_CHIP_SELECTOR = 'a[data-record-link][data-record-object][data-record-id]'; + +/** The record a referenced record's chip names (`ReferencedRecordLink`'s data attributes). */ +export interface RecordChipTarget { + objectName: string; + recordId: string; +} + +function chipTarget(chip: Element | null): RecordChipTarget | null { + const objectName = chip?.getAttribute('data-record-object') ?? ''; + const recordId = chip?.getAttribute('data-record-id') ?? ''; + return objectName !== '' && recordId !== '' ? { objectName, recordId } : null; +} + +/** + * The record named by the referenced record's chip at or around `target` + * inside `cell`, or `null` when the press is not on one. In a reference cell + * of a select-first grid a plain click on a chip opens that record in place + * (objectstack#36015). + */ +export function recordChipAt(target: EventTarget | null, cell: Element): RecordChipTarget | null { + if (!(target instanceof Element) || !cell.contains(target)) return null; + const chip = target.closest(RECORD_CHIP_SELECTOR); + return chip !== null && cell.contains(chip) ? chipTarget(chip) : null; +} + +/** The record the first chip a cell draws names, or `null` (Ctrl/Cmd+Enter in a reference cell). */ +export function firstRecordChip(cell: Element): RecordChipTarget | null { + return chipTarget(cell.querySelector(RECORD_CHIP_SELECTOR)); +} + /** The first opener a cell draws (a cell of several chips opens the first), or `null`. */ export function firstCellOpener(cell: Element): HTMLElement | null { return cell.querySelector(CELL_OPENER_SELECTOR); diff --git a/ui/packages/fields/src/index.tsx b/ui/packages/fields/src/index.tsx index 7657a2af6ec..7a7061a336f 100644 --- a/ui/packages/fields/src/index.tsx +++ b/ui/packages/fields/src/index.tsx @@ -2510,9 +2510,13 @@ function ReferencedRecordLink({ className={cn('text-primary underline-offset-4 hover:underline', className)} // A host's list grid draws a referenced record as a small chip led by // the name's first letter (objectstack#35548); these say which link - // is one and what its letter is. Nothing else reads them. + // is one and what its letter is. data-record-link="" data-initial={recordLinkInitial(label)} + // The record the chip names: a select-first grid opens it in place on + // a single click when its host asks to (objectstack#36015). + data-record-object={objectName} + data-record-id={String(recordId)} onClick={(e) => { // The rows this cell sits in carry their own click handlers — the // detail row copies the field value, a related-list row opens ITS own diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index c77ab8cbaf4..b60a2d4f558 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -406,6 +406,19 @@ export interface ObjectGridComponentProps extends ObjectGridExternalPaginationPr * key reaches it. */ headerMenu?: boolean; + /** + * [objectstack#36015] Opens a record that a lookup cell's chip names, in + * place, as the HOST that owns the page does it (the list page opens it in + * its side drawer). With {@link cellSelection}, a single click on such a + * chip opens its record here and selects the cell, and the cell draws an + * edit button on hover and while selected. A chip naming a person + * (`sys_user`) is not one: it only selects. Absent ⇒ a chip only selects + * its cell, as before this prop existed. + * + * A RUNTIME prop, never authored metadata: the host decides it, and no node + * key reaches it. + */ + openReferencedRecord?: (objectName: string, recordId: string) => void; /** * TWO parameters since objectui#9357, and the second is not decoration: this * prop reaches `useNavigationOverlay` as its `onRowClick`, and `handleClick` @@ -773,6 +786,18 @@ function ratingScaleOf(fieldDef: unknown): number { return typeof max === 'number' && max > 0 ? Math.floor(max) : 5; } +/** + * objectstack#36015 — whether a column's cells are reference cells whose chips + * open their record in place: a lookup, master-detail or tree field naming a + * record of any object but the person object. A chip naming a person only + * selects its cell. + */ +function opensReferenceInPlace(fieldDef: { type?: unknown; reference?: unknown } | undefined): boolean { + const type = fieldDef?.type; + if (type !== 'lookup' && type !== 'master_detail' && type !== 'tree') return false; + return fieldDef?.reference !== 'sys_user'; +} + /** * objectstack#35688 — how wide a field type's editor layer starts. The layer * is never narrower than its cell and grows to fit this; the editor fills it. @@ -826,6 +851,7 @@ export const ObjectGrid: React.FC = ({ rowOpensRecord, cellSelection: hostCellSelection, headerMenu: hostHeaderMenu, + openReferencedRecord, onBulkDelete, onRowSelect, onRowClick, @@ -1385,6 +1411,15 @@ export const ObjectGrid: React.FC = ({ // confirmation, so a state-machine move does not ask twice. confirmCommit: (row, columnKey, value) => requiredPrompt.ask(row, columnKey, value, () => askStateMove(row, columnKey, value)), + // objectstack#36015 — a lookup cell's chip opens its record in place. + ...(openReferencedRecord + ? { + referenceCells: { + isReferenceColumn: (columnKey: string) => opensReferenceInPlace(objectFields?.[columnKey]), + openRecord: openReferencedRecord, + }, + } + : {}), } : null; // objectstack#35685 — the state-machine confirm, the grid's next question diff --git a/ui/packages/plugin-grid/src/__tests__/ObjectGrid.cellSelection-35684.test.tsx b/ui/packages/plugin-grid/src/__tests__/ObjectGrid.cellSelection-35684.test.tsx index 30cc79a7880..953568ee83c 100644 --- a/ui/packages/plugin-grid/src/__tests__/ObjectGrid.cellSelection-35684.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/ObjectGrid.cellSelection-35684.test.tsx @@ -25,6 +25,9 @@ * 5. objectstack#36023: a select cell's editor opens under the cell, which * keeps its value drawn; a required cell refuses Backspace in the form's * words; a value over the field's declared length stays in the editor. + * 6. With the host's `openReferencedRecord`, a lookup chip opens the record + * it names through it on a single click and its cell draws an edit + * button; a person's chip (`sys_user`) only selects (objectstack#36015). */ import React from 'react'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; @@ -344,3 +347,84 @@ describe('ObjectGrid cellSelection — the panel, Backspace and the rules (objec expect(g.cell(0).querySelector('[data-slot="cell-editor-overlay"] input')).toHaveValue('Alphabet'); }); }); + +describe('ObjectGrid cellSelection — a lookup chip opens its record in the host\'s place (objectstack#36015)', () => { + const followed: Array<[string, string | number]> = []; + const host: RelatedRecordActionsValue = { + resolve: () => ({}), + recordHref: (objectName, recordId) => `/apps/demo/${objectName}/record/${encodeURIComponent(String(recordId))}`, + openRecord: (objectName, recordId) => { followed.push([objectName, recordId]); }, + }; + + async function renderReferences(openReferencedRecord?: (objectName: string, recordId: string) => void) { + followed.length = 0; + const utils = render( + + + , + ); + await waitFor(() => expect(utils.container.querySelector('a[href="/apps/demo/crm_account/record/a7"]')).not.toBeNull()); + const cell = (col: number) => + utils.container.querySelectorAll('tbody tr')[0].querySelectorAll('td[data-grid-cell]')[col]; + return { ...utils, cell }; + } + + it('a single click on the account chip opens it through the host; the chip names its record', async () => { + const open = vi.fn(); + const g = await renderReferences(open); + const chip = g.container.querySelector('a[href="/apps/demo/crm_account/record/a7"]')!; + expect(chip).toHaveAttribute('data-record-object', 'crm_account'); + expect(chip).toHaveAttribute('data-record-id', 'a7'); + expect(fireEvent.click(chip)).toBe(false); + expect(open).toHaveBeenCalledWith('crm_account', 'a7'); + expect(followed).toEqual([]); + expect(g.cell(1)).toHaveAttribute('data-selected-cell'); + }); + + it('the lookup cell draws the edit button, which opens its editor; the owner cell draws none', async () => { + const g = await renderReferences(vi.fn()); + const edit = g.cell(1).querySelector('[data-testid="cell-edit-button"]')!; + fireEvent.pointerEnter(g.cell(1)); + await waitFor(() => expect(edit.className).toMatch(/(^|\s)flex(\s|$)/)); + expect(g.cell(2).querySelector('[data-testid="cell-edit-button"]')).toBeNull(); + fireEvent.click(edit); + await waitFor(() => expect(g.container.querySelector('td[data-editing-cell]')).not.toBeNull()); + }); + + it('a person chip only selects its cell, whatever the host passes', async () => { + const open = vi.fn(); + const g = await renderReferences(open); + const person = g.container.querySelector('a[href="/apps/demo/sys_user/record/u3"]')!; + expect(fireEvent.click(person)).toBe(false); + expect(open).not.toHaveBeenCalled(); + expect(followed).toEqual([]); + expect(g.cell(2)).toHaveAttribute('data-selected-cell'); + }); + + it('control: without the host prop the account chip only selects and no edit button is drawn', async () => { + const g = await renderReferences(undefined); + const chip = g.container.querySelector('a[href="/apps/demo/crm_account/record/a7"]')!; + expect(fireEvent.click(chip)).toBe(false); + expect(followed).toEqual([]); + expect(g.cell(1)).toHaveAttribute('data-selected-cell'); + expect(g.cell(1).querySelector('[data-testid="cell-edit-button"]')).toBeNull(); + }); +}); diff --git a/ui/packages/plugin-list/src/ListView.tsx b/ui/packages/plugin-list/src/ListView.tsx index 65f8beee39e..f75c9555af0 100644 --- a/ui/packages/plugin-list/src/ListView.tsx +++ b/ui/packages/plugin-list/src/ListView.tsx @@ -527,6 +527,16 @@ export interface ListViewProps { * Only the grid is handed it. Absent ⇒ every row is exactly what it was. */ recordLinkAdornment?: (record: Record) => React.ReactNode; + /** + * Opens a record a lookup cell's chip names, in place (objectstack#36015), + * handed to `ObjectGrid`'s `openReferencedRecord`: in the grid a single + * click on such a chip opens its record here, and lookup cells draw an edit + * button. The console's object list opens it in its side drawer. + * + * A HOST prop, never a schema key, for the reason `rowAdornment` is one. + * Only the grid is handed it. Absent ⇒ a chip only selects its cell. + */ + openReferencedRecord?: (objectName: string, recordId: string) => void; /** * Whether a click on a row opens anything, as the host that owns the row * click (`onRowClick`) knows it (objectstack#33317), handed to the view's own @@ -2346,6 +2356,7 @@ export const ListView = React.forwardRef(({ conditionRowEnd, rowAdornment, recordLinkAdornment, + openReferencedRecord, rowOpensRecord, compact = false, capped = false, @@ -8367,6 +8378,11 @@ export const ListView = React.forwardRef(({ // link, on the grid's host channel (a React prop, never a node key). ? { recordLinkAdornment } : {})} + {...(viewComponentSchema.type === 'object-grid' && openReferencedRecord + // objectstack#36015 — a lookup chip opens its record in the host's + // place, on the grid's host channel (a React prop, never a node key). + ? { openReferencedRecord } + : {})} {...(viewComponentSchema.type === 'object-grid' // objectstack#35684 — the list page's grid selects a cell on a // click and edits on double-click, Enter or typing, on the