diff --git a/.changeset/36256-drill-dialog-standard-list.md b/.changeset/36256-drill-dialog-standard-list.md new file mode 100644 index 00000000000..d61596e5d75 --- /dev/null +++ b/.changeset/36256-drill-dialog-standard-list.md @@ -0,0 +1,20 @@ +--- +'@object-ui/plugin-dashboard': patch +'@object-ui/plugin-report': patch +'@object-ui/react': patch +'@object-ui/app-shell': patch +'@object-ui/components': patch +--- + +feat(plugin-dashboard): a dashboard or report drill opens a centred dialog over the standard list, and a report's chart marks drill + +Clause-②: yes (widening) — additive members only, among them the new `PageRegionPostureReset` export of `@object-ui/components`; nothing is removed or renamed +Metadata-protocol: none + +Clicking a number on a dashboard (a chart mark, a metric tile, a table cell) or on a dataset report used to open a full-height side drawer whose table listed every field of the object, with no sort, no filter and no word on which conditions selected the records; a row stacked a second record panel on top. The drill now opens a dialog about 70% wide and 65% tall that dims and blurs nothing behind it, and its body is the standard list the object list page draws (`list-view`): the same row height, column-header sort, filter chips, added columns, record count and column calculations. The drill's conditions (the clicked bucket, the widget's filter, the measure's scope) are the list's own chips and can be changed or removed; a condition no chip can say (a relationship path, an `$or`) still filters the list. The default columns are the record's name, the grouped fields and the measured fields. Nothing done in the dialog is saved, and it writes nothing. A record's name opens the record's full page, whose 「N of M」 stepper walks the drill's rows and whose way back is the dashboard or report; no second panel is stacked. 「Open in list」 is unchanged. On a phone the drill keeps the side drawer, with the same list. + +A dataset report's chart marks now drill too: a bar opens the same records as the summary line it stands for. + +Additive members: `DrillNavigationValue.openRecord` and the `DrillRecordOrigin` type (`@object-ui/react`), `DrillDownDrawerProps.defaultColumns` (`@object-ui/plugin-dashboard`), `DatasetDrillArgs.fields` (`@object-ui/plugin-report`), `PageRegionPostureReset` (`@object-ui/components`). A renderer without `@object-ui/plugin-list` registered lists the drilled records in the dashboard's data table. A host that gives no `openRecord` (a page block's metric or pivot) opens the drilled record in a dialog, from either body. + +Inside a page the drill draws the same standard list: the page region's posture (the compact or capped list a page block draws) is cleared for the drill's dialog by the new `PageRegionPostureReset` (`@object-ui/components`), so a page block's metric or pivot drill shows its chips, its record count and its pager, and no 「View all」 link to a list without the drill's condition. A drill whose filter names no condition any read can carry (a string, a number) lists nothing and says so, instead of listing every record. diff --git a/ui/packages/app-shell/src/views/DashboardView.tsx b/ui/packages/app-shell/src/views/DashboardView.tsx index 692315c07d1..e4507c81e0b 100644 --- a/ui/packages/app-shell/src/views/DashboardView.tsx +++ b/ui/packages/app-shell/src/views/DashboardView.tsx @@ -110,8 +110,6 @@ type DashboardRefreshState = Parameters< // --------------------------------------------------------------------------- export function DashboardView({ dataSource }: { dataSource?: any }) { - // Drill "escape hatch": lets the drill drawers open an object's full list page. - const drillNavigation = useRecordListDrillNavigation(); const { dashboardName } = useParams<{ dashboardName: string }>(); // Setup's own System Overview (`platform-objects`' `system_overview`). const isSystemOverview = useInSetupApp() && dashboardName === 'system_overview'; @@ -235,6 +233,12 @@ export function DashboardView({ dataSource }: { dataSource?: any }) { const missedName = !dashboard && dashboardsSettled && !previewDrafts && dashboardName ? dashboardName : null; const access = useMetaItemRefusal('dashboard', missedName); + // Drill navigation: the drill list's 「Open in list」 and its record pages, + // which name this dashboard as their way back (objectstack-ai/objectstack#36256). + const drillNavigation = useRecordListDrillNavigation( + dashboard ? resolveKeyedI18nLabel(dashboard.label, t) || dashboard.name : undefined, + ); + // ---- Runtime capability gate -------------------------------------------- // Hide widgets whose `requiresObject` is not registered (mirrors // NavigationItem.requiresObject for nav entries). Defaults to widget.object diff --git a/ui/packages/app-shell/src/views/ReportView.tsx b/ui/packages/app-shell/src/views/ReportView.tsx index b82635d55b6..5633ab40f19 100644 --- a/ui/packages/app-shell/src/views/ReportView.tsx +++ b/ui/packages/app-shell/src/views/ReportView.tsx @@ -105,8 +105,10 @@ export function ReportView({ dataSource }: { dataSource?: DataSource }) { // Drill-through (ADR-0021 D2): clicking an aggregated row/cell opens the // underlying records in an in-place drawer (peek without leaving the report), // with an "Open in list →" escape hatch to the full object list page. - const drillNavigation = useRecordListDrillNavigation(); - const [drill, setDrill] = useState<{ object: string; filter: Record; title: string } | null>(null); + const drillNavigation = useRecordListDrillNavigation( + metadataText(reportData?.title, language) ?? metadataText(reportData?.label, language), + ); + const [drill, setDrill] = useState<{ object: string; filter: Record; title: string; fields?: string[] } | null>(null); const getFieldsForObject = useCallback( (objName: string | undefined) => { @@ -152,7 +154,7 @@ export function ReportView({ dataSource }: { dataSource?: DataSource }) { // dim (the drill lands on a superset rather than filtering wrongly) // - granularity-bucketed dates → need a range, not equality; skip too const handleDatasetDrill = useCallback( - async ({ dataset, groupKey, object, objectFilter }: DatasetDrillArgs) => { + async ({ dataset, groupKey, object, objectFilter, fields }: DatasetDrillArgs) => { try { // Drawer header: the clicked group's display values (e.g. "West / Q3"), // else the report's label in the viewer's language (objectui#13470). @@ -165,7 +167,7 @@ export function ReportView({ dataSource }: { dataSource?: DataSource }) { // server's drillRawRows — correct for select/lookup dims (a stored // value, not a display label) with NO dataset-definition round-trip. if (object && objectFilter) { - setDrill({ object, filter: objectFilter, title }); + setDrill({ object, filter: objectFilter, title, fields }); return; } @@ -602,15 +604,17 @@ export function ReportView({ dataSource }: { dataSource?: DataSource }) { /> - {/* Drill-through drawer: peek the records behind a clicked group, then - click a row to open a record, or use "Open in list →" to escalate to - the full object list page. */} + {/* Drill-through dialog: the records behind a clicked group or bar in the + standard list; a record's name opens its page, 「Open in list」 the + object's list page (objectstack-ai/objectstack#36256). */} setDrill(null)} title={drill?.title ?? ''} objectName={drill?.object ?? ''} filter={drill?.filter} + defaultColumns={drill?.fields} + target="dialog" dataSource={dataSource as any} /> diff --git a/ui/packages/app-shell/src/views/drillDialogStandardList-36256.test.tsx b/ui/packages/app-shell/src/views/drillDialogStandardList-36256.test.tsx new file mode 100644 index 00000000000..cb5453bb3f5 --- /dev/null +++ b/ui/packages/app-shell/src/views/drillDialogStandardList-36256.test.tsx @@ -0,0 +1,104 @@ +/** + * objectstack-ai/objectstack#36256 items 3, 5 and 8 — the drill dialog draws + * the REAL standard list (`@object-ui/plugin-list`'s `list-view`): the + * drill's conditions are the list's own chips, removable; the default + * columns are the record's name and the drilled fields; and nothing the + * reader does in it writes anything — no record write through the data + * source, no request that is not a read, no stored preference. + */ +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import React from 'react'; +import { DrillNavigationProvider, SchemaRendererProvider } from '@object-ui/react'; +import { DrillDownDrawer } from '@object-ui/plugin-dashboard'; +import '@object-ui/plugin-list'; + +const DEFINITION = { + name: 'deal_36256', + label: 'Deal', + nameField: 'name', + fields: { + name: { type: 'text', label: 'Name' }, + stage: { + type: 'select', + label: 'Stage', + options: [ + { value: 'proposal', label: 'Proposal' }, + { value: 'negotiation', label: 'Negotiation' }, + ], + }, + amount: { type: 'number', label: 'Amount' }, + owner: { type: 'text', label: 'Owner' }, + }, +}; + +function mount() { + const ds = { + find: vi.fn().mockResolvedValue({ data: [{ id: 'd1', name: 'Acme', stage: 'negotiation', amount: 3 }], total: 1 }), + findOne: vi.fn(), + create: vi.fn(), + update: vi.fn(), + delete: vi.fn(), + bulk: vi.fn(), + getObjectSchema: vi.fn(async () => structuredClone(DEFINITION)), + }; + const fetchSpy = vi.fn(async () => ({ ok: true, json: async () => ({}) })); + vi.stubGlobal('fetch', fetchSpy); + const setItem = vi.spyOn(Storage.prototype, 'setItem'); + const openRecord = vi.fn(); + render( + + + + + , + ); + return { ds, fetchSpy, setItem, openRecord }; +} + +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +describe('the drill dialog draws the standard list (#36256)', () => { + it('shows the drill conditions as removable chips, and removing one re-reads without writing', async () => { + const { ds, fetchSpy, setItem } = mount(); + const dialog = await screen.findByTestId('drill-down-dialog'); + const chip = await within(dialog).findByTestId('filter-chip-stage'); + expect(chip).toHaveTextContent('Stage: Negotiation'); + await waitFor(() => expect(ds.find).toHaveBeenCalled()); + const firstQuery = JSON.stringify(ds.find.mock.calls.at(-1)); + expect(firstQuery).toContain('negotiation'); + + const reads = ds.find.mock.calls.length; + await act(async () => fireEvent.click(within(dialog).getByTestId('filter-chip-remove-stage'))); + await waitFor(() => expect(ds.find.mock.calls.length).toBeGreaterThan(reads)); + expect(JSON.stringify(ds.find.mock.calls.at(-1))).not.toContain('negotiation'); + + for (const write of [ds.create, ds.update, ds.delete, ds.bulk]) expect(write).not.toHaveBeenCalled(); + for (const [, init] of fetchSpy.mock.calls as unknown as Array<[unknown, { method?: string } | undefined]>) { + expect((init?.method ?? 'GET').toUpperCase()).toBe('GET'); + } + expect(setItem).not.toHaveBeenCalled(); + }); + + it("leads with the record's name, then the drilled fields", async () => { + mount(); + const dialog = await screen.findByTestId('drill-down-dialog'); + await within(dialog).findByText('Acme'); + const headers = within(dialog).getAllByRole('columnheader').map((h) => h.textContent?.trim()).filter(Boolean); + expect(headers.slice(0, 3)).toEqual(['Name', 'Stage', 'Amount']); + }); +}); diff --git a/ui/packages/app-shell/src/views/pageBlockDrillFilter-36256.test.tsx b/ui/packages/app-shell/src/views/pageBlockDrillFilter-36256.test.tsx new file mode 100644 index 00000000000..7db63bc5317 --- /dev/null +++ b/ui/packages/app-shell/src/views/pageBlockDrillFilter-36256.test.tsx @@ -0,0 +1,113 @@ +/** + * objectstack-ai/objectstack#36256 — a page block's drill lists the records + * its number counts. + * + * HotCRM's 销售主页 KPI tile is an `object-metric` block whose `filter` is the + * spec's rule-array form, `[{ field: 'stage', operator: 'equals', value: + * 'closed_won' }]`, handed to the drill as written. The drill draws the REAL + * standard list (`@object-ui/plugin-list`) over an in-memory matcher + * (`ValueDataSource`), so the read it sends is judged as a server would judge + * it. The tile counts the won deals. The drill must read with that condition + * and list exactly those deals, never every record of the object. + */ +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import React from 'react'; +import { SchemaRenderer, SchemaRendererProvider } from '@object-ui/react'; +import { ValueDataSource } from '@object-ui/core'; +import '@object-ui/plugin-dashboard'; +import '@object-ui/plugin-list'; + +const DEFINITION = { + name: 'opp_36256', + label: 'Opportunity', + nameField: 'name', + fields: { + name: { type: 'text', label: 'Name' }, + stage: { type: 'text', label: 'Stage' }, + amount: { type: 'number', label: 'Amount' }, + }, +}; + +const ROWS = [ + { id: 'o1', name: 'Initech Phase 1', stage: 'closed_won', amount: 90000 }, + { id: 'o2', name: 'Wayne Q1 Expansion', stage: 'closed_won', amount: 380000 }, + { id: 'o3', name: 'Apex Logistics Data Hub', stage: 'needs_analysis', amount: 93000 }, +]; +const WON = ROWS.filter((r) => r.stage === 'closed_won'); + +function mount(filter: unknown = [{ field: 'stage', operator: 'equals', value: 'closed_won' }]) { + const matcher = new ValueDataSource({ items: ROWS }); + const ds = { + find: vi.fn((object: string, params?: Record) => matcher.find(object, params as never)), + // The tile's own number: the won deals' sum. + aggregate: vi.fn(async (_object: string, _params: Record) => [{ amount_sum: WON.reduce((a, r) => a + r.amount, 0) }]), + getObjectSchema: vi.fn(async () => structuredClone(DEFINITION)), + }; + vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, json: async () => ({}) }))); + render( + + + , + ); + return ds; +} + +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +describe("a page block's rule-array filter reaches its drill's read (#36256)", () => { + it('lists exactly the records the tile counts, and the read carries the condition', async () => { + const ds = mount(); + fireEvent.click(await screen.findByRole('button', { name: /revenue won|470,000/i })); + const dialog = await screen.findByTestId('drill-down-dialog'); + for (const won of WON) expect(await within(dialog).findByText(won.name)).toBeInTheDocument(); + await waitFor(() => expect(within(dialog).queryByText('Apex Logistics Data Hub')).toBeNull()); + // The read the list sent, and the condition it carries. + const reads = ds.find.mock.calls.filter(([object]) => object === 'opp_36256'); + expect(reads.length).toBeGreaterThan(0); + expect(JSON.stringify(reads.at(-1)?.[1]?.$filter)).toContain('closed_won'); + }); + + it.each([ + ['an array that is neither rules nor AST', [{ stage: 'closed_won' }]], + ['a rule with a blank field', [{ field: '', operator: 'equals', value: 'closed_won' }]], + ['a valid rule beside a malformed one', [{ field: 'stage', operator: 'equals', value: 'closed_won' }, { stage: 'x' }]], + ])('hands a filter the conversion answers nothing for to the list as its base filter, never an unfiltered read: %s', async (_, filter) => { + const ds = mount(filter); + fireEvent.click(await screen.findByRole('button', { name: /revenue won|470,000/i })); + const dialog = await screen.findByTestId('drill-down-dialog'); + await waitFor(() => expect(ds.find.mock.calls.some(([object]) => object === 'opp_36256')).toBe(true)); + // Every read carries the filter (a server refuses it as malformed; it is + // never read as no filter). + for (const [object, params] of ds.find.mock.calls) { + if (object === 'opp_36256') expect(params?.$filter).toBeDefined(); + } + await waitFor(() => expect(within(dialog).queryByText('Apex Logistics Data Hub')).toBeNull()); + }); + + it.each([ + ['a string', 'stage = closed_won'], + ['a number', 7], + ])('lists nothing for a filter no read can carry, and sends no read: %s', async (_, filter) => { + const ds = mount(filter); + fireEvent.click(await screen.findByRole('button', { name: /revenue won|470,000/i })); + const dialog = await screen.findByTestId('drill-down-dialog'); + expect(within(dialog).getByTestId('drill-down-notice')).toHaveAttribute('data-notice', 'unavailable'); + await new Promise((r) => setTimeout(r, 50)); + expect(ds.find.mock.calls.filter(([object]) => object === 'opp_36256')).toEqual([]); + }); +}); diff --git a/ui/packages/app-shell/src/views/pageBlockDrillPosture-36550.test.tsx b/ui/packages/app-shell/src/views/pageBlockDrillPosture-36550.test.tsx new file mode 100644 index 00000000000..3ecbfedcbdc --- /dev/null +++ b/ui/packages/app-shell/src/views/pageBlockDrillPosture-36550.test.tsx @@ -0,0 +1,147 @@ +/** + * objectstack-ai/objectstack#36550 (#36256) — a page block's drill draws the + * standard list, not the page region's posture. + * + * A page region tells its blocks their posture (compact or capped), and React + * context crosses the drill dialog's portal. So a metric block's drill, opened + * from a region half the page or wider, drew its list capped: no toolbar, no + * chips, no pager, and a 「View all N」 link to the object's list without the + * drill's condition. The drill clears the posture for its own subtree. + * + * Everything renders through the REAL page renderer, the REAL `list-view` and + * the REAL `object-metric`, with the stand-in `ResizeObserver` the + * objectui#12703 / objectstack#26613 pins use for the region widths. CONTROL: + * the page's own list block in the same region stays capped. + */ +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import React from 'react'; +import { + ActionProvider, + I18nProvider, + RelatedRecordActionsProvider, + SchemaRenderer, + SchemaRendererProvider, + type RelatedRecordActionsValue, +} from '@object-ui/react'; +import { ValueDataSource } from '@object-ui/core'; +import '@object-ui/components'; +import '@object-ui/plugin-dashboard'; +import '@object-ui/plugin-list'; + +const OBJECT = 'opp_36550'; +const DEFINITION = { + name: OBJECT, + label: 'Opportunity', + nameField: 'name', + fields: { + name: { type: 'text', label: 'Name' }, + stage: { type: 'text', label: 'Stage' }, + amount: { type: 'number', label: 'Amount' }, + }, +}; +const ROWS = [ + { id: 'o1', name: 'Initech Phase 1', stage: 'closed_won', amount: 90000 }, + { id: 'o2', name: 'Wayne Q1 Expansion', stage: 'closed_won', amount: 380000 }, + { id: 'o3', name: 'Apex Logistics Data Hub', stage: 'needs_analysis', amount: 93000 }, +]; + +/** Installs a `ResizeObserver` that reports these widths for the page body and each region. */ +function stubWidths(widths: { page: number; regions: Record }) { + class WidthReportingObserver { + constructor(private readonly callback: ResizeObserverCallback) {} + observe(target: Element) { + const region = target.getAttribute('data-region'); + const width = region != null + ? widths.regions[region] + : target.matches('[data-page-type] > div') ? widths.page : undefined; + if (width === undefined) return; + this.callback([{ target, contentRect: { width } } as unknown as ResizeObserverEntry], this as never); + } + unobserve() {} + disconnect() {} + } + vi.stubGlobal('ResizeObserver', WidthReportingObserver); +} + +const host = (): RelatedRecordActionsValue => ({ + resolve: () => ({}), + listHref: (objectName: string) => `/apps/crm/${objectName}`, + openList: vi.fn(), +}); + +function mount() { + const matcher = new ValueDataSource({ items: ROWS }); + const ds = { + find: vi.fn((object: string, params?: Record) => matcher.find(object, params as never)), + aggregate: vi.fn(async () => [{ amount_sum: 470000 }]), + getObjectSchema: vi.fn(async () => structuredClone(DEFINITION)), + }; + vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, json: async () => ({}) }))); + stubWidths({ page: 1200, regions: { main: 856, aside: 320 } }); + const view = render( + + + + + + + + + , + ); + return { ds, ...view }; +} + +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +describe("a page block's drill draws the standard list, not the region's posture (#36550)", () => { + it('shows its chips and its record count and no 「View all」, while the block list beside it stays capped', async () => { + const { container } = mount(); + const main = container.querySelector('[data-region="main"]') as HTMLElement; + + // CONTROL: the page's own list block in the same region is capped. + await waitFor(() => expect(within(main).getAllByTestId('list-capped-row')).toHaveLength(3)); + expect(within(main).getByRole('link', { name: /^View all 3/ })).toBeInTheDocument(); + + fireEvent.click(await screen.findByRole('button', { name: /revenue won|470,000/i })); + const dialog = await screen.findByTestId('drill-down-dialog'); + for (const name of ['Initech Phase 1', 'Wayne Q1 Expansion']) { + expect(await within(dialog).findByText(name)).toBeInTheDocument(); + } + // The standard list: the drill's condition as a chip, and its record count. + expect(await within(dialog).findByTestId('filter-chip-stage')).toBeInTheDocument(); + expect(await within(dialog).findByText('2 records')).toBeInTheDocument(); + // Not the capped list, and no link to a list without the condition. + expect(within(dialog).queryByTestId('list-capped-table')).toBeNull(); + expect(within(dialog).queryByRole('link', { name: /View all/ })).toBeNull(); + expect(within(dialog).queryByText('Apex Logistics Data Hub')).toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/views/useOpenRecordList.drillRecordPage-36256.test.tsx b/ui/packages/app-shell/src/views/useOpenRecordList.drillRecordPage-36256.test.tsx new file mode 100644 index 00000000000..b6a1574f12e --- /dev/null +++ b/ui/packages/app-shell/src/views/useOpenRecordList.drillRecordPage-36256.test.tsx @@ -0,0 +1,57 @@ +/** + * objectstack-ai/objectstack#36256 item 6 — a drilled record's name opens its + * page with the history-state `from` a list hands the page it opens: the + * record page's 「N of M」 stepper walks the drill list's rows, and its way + * back is the dashboard the drill was opened on. Read here through the record + * page's own reader (`useRecordPageReturn`), so the page needs no change. + */ +import { describe, it, expect } from 'vitest'; +import { renderHook, act } from '@testing-library/react'; +import { MemoryRouter, Routes, Route, useLocation } from 'react-router-dom'; +import type { ReactNode } from 'react'; +import { FilterScopeProvider } from '@object-ui/react'; +import { useRecordListDrillNavigation } from './useOpenRecordList'; +import { useRecordPageReturn } from './recordDrawerStack'; + +function Wrapper({ children }: { children: ReactNode }) { + return ( + + + + {children}} /> + + + + ); +} + +function useHarness() { + const nav = useRecordListDrillNavigation('Executive Overview'); + const location = useLocation(); + const recordId = location.pathname.match(/\/record\/([^/]+)$/)?.[1]; + const pageReturn = useRecordPageReturn(recordId); + return { nav, location, pageReturn }; +} + +describe('a drilled record opens its page with the drill list as its set (#36256)', () => { + it('pages through the drill rows and returns to the dashboard', () => { + const { result } = renderHook(useHarness, { wrapper: Wrapper }); + act(() => result.current.nav.openRecord('crm_opportunity', 'o2', { siblings: ['o1', 'o2', 'o3'], total: 3 })); + + expect(result.current.location.pathname).toBe('/apps/crm/crm_opportunity/record/o2'); + expect((result.current.location.state as any).from).toEqual({ + pathname: '/apps/crm/dashboard/executive?tab=1', + label: 'Executive Overview', + siblings: ['o1', 'o2', 'o3'], + total: 3, + }); + expect(result.current.pageReturn.stepper?.position).toEqual({ index: 1, total: 3 }); + + act(() => result.current.pageReturn.stepper!.onNext!()); + expect(result.current.location.pathname).toBe('/apps/crm/crm_opportunity/record/o3'); + expect(result.current.pageReturn.stepper?.position).toEqual({ index: 2, total: 3 }); + + act(() => result.current.pageReturn.toList!()); + expect(result.current.location.pathname + result.current.location.search).toBe('/apps/crm/dashboard/executive?tab=1'); + }); +}); diff --git a/ui/packages/app-shell/src/views/useOpenRecordList.ts b/ui/packages/app-shell/src/views/useOpenRecordList.ts index 3302a7ee1f2..ad907cfef3c 100644 --- a/ui/packages/app-shell/src/views/useOpenRecordList.ts +++ b/ui/packages/app-shell/src/views/useOpenRecordList.ts @@ -7,14 +7,14 @@ */ import { useCallback, useMemo } from 'react'; -import { useNavigate, useParams } from 'react-router-dom'; +import { useLocation, useNavigate, useParams } from 'react-router-dom'; import { convertFiltersToAST, resolveFilterPlaceholders, toFilterNodeSafely, type FilterTokenScope, } from '@object-ui/core'; -import { useFilterScope } from '@object-ui/react'; +import { useFilterScope, type DrillRecordOrigin } from '@object-ui/react'; import { usePermissions } from '@object-ui/permissions'; import { parseFilterAST } from '@objectstack/spec/data'; import { @@ -248,6 +248,8 @@ export interface RecordListDrillNavigation { openRecordList: (objectName: string, filter?: Record) => void; /** Whether the list route can say this drill's filter exactly. */ canOpenRecordList: (objectName: string, filter?: Record) => boolean; + /** Open a drilled record's page, this page as its way back (objectstack-ai/objectstack#36256). */ + openRecord: (objectName: string, recordId: string, origin?: DrillRecordOrigin) => void; } /** @@ -308,8 +310,9 @@ export interface RecordListDrillNavigation { * everything else through untouched, so a placeholder-free drill produces a * byte-identical URL. */ -export function useRecordListDrillNavigation(): RecordListDrillNavigation { +export function useRecordListDrillNavigation(originLabel?: string): RecordListDrillNavigation { const navigate = useNavigate(); + const location = useLocation(); const { appName } = useParams<{ appName?: string }>(); // Session scope for `{current_user_id}` / `{current_org_id}`. Read at hook // level — the returned handlers are callbacks, and hooks cannot be called @@ -337,7 +340,31 @@ export function useRecordListDrillNavigation(): RecordListDrillNavigation { }, [navigate, appName, filterScope, canRead], ); - return useMemo(() => ({ openRecordList, canOpenRecordList }), [openRecordList, canOpenRecordList]); + // objectstack-ai/objectstack#36256 — a drilled record opens as its page, + // with the history-state `from` a list hands the page it opens + // (`listOriginOf`): this page as the way back, the drill list's rows as the + // ↑ ↓ set and the count it matched for 「N of M」. + const openRecord = useCallback( + (objectName: string, recordId: string, origin?: DrillRecordOrigin) => { + const base = appName ? `/apps/${appName}` : ''; + const siblings = origin?.siblings?.length ? [...origin.siblings] : undefined; + navigate(`${base}/${objectName}/record/${encodeURIComponent(recordId)}`, { + state: { + from: { + pathname: location.pathname + location.search, + label: originLabel ?? '', + ...(siblings ? { siblings } : {}), + ...(siblings && origin?.total != null && origin.total >= siblings.length ? { total: origin.total } : {}), + }, + }, + }); + }, + [navigate, appName, location.pathname, location.search, originLabel], + ); + return useMemo( + () => ({ openRecordList, canOpenRecordList, openRecord }), + [openRecordList, canOpenRecordList, openRecord], + ); } /** The navigate half of {@link useRecordListDrillNavigation}. */ diff --git a/ui/packages/components/src/index.ts b/ui/packages/components/src/index.ts index d5ce96187f0..0a56c97d0e6 100644 --- a/ui/packages/components/src/index.ts +++ b/ui/packages/components/src/index.ts @@ -103,7 +103,9 @@ export type { PageBlockSpan } from './renderers/layout/page-block-span'; // renderer (objectui#12703): `compact` when the region is narrower than half // the page. Exported for the blocks that read it in other packages — the // `list-view` block in `@object-ui/plugin-list` draws a short list there. -export { usePageRegionPosture } from './renderers/layout/page-region-posture'; +// `PageRegionPostureReset` clears it for a surface a block opens over the page +// (a drill dialog), so the list there draws in full (objectstack#36256). +export { usePageRegionPosture, PageRegionPostureReset } from './renderers/layout/page-region-posture'; export type { PageRegionPosture } from './renderers/layout/page-region-posture'; // The count channel a `page:tabs` panel opens to the blocks inside it diff --git a/ui/packages/components/src/renderers/layout/page-region-posture.tsx b/ui/packages/components/src/renderers/layout/page-region-posture.tsx index 761c974f5b5..d0ec4ee9882 100644 --- a/ui/packages/components/src/renderers/layout/page-region-posture.tsx +++ b/ui/packages/components/src/renderers/layout/page-region-posture.tsx @@ -174,6 +174,21 @@ export const PageRegionPostureProvider: React.FC<{ return {children}; }; +/** + * Clears the page-region posture for its subtree, so a block under it reads + * `null` and draws its full rendering, as it would outside any page. + * + * For a surface a page block opens over the page that is not a part of the + * block's region: a drill dialog (objectstack-ai/objectstack#36256). React + * context crosses a dialog's portal, so without this the dialog's list would + * take the posture of the region that holds the block that opened it, and + * draw the compact or capped list there: no toolbar, no chips, no pager, and + * a 「View all」 link to a list that does not carry the dialog's condition. + */ +export const PageRegionPostureReset: React.FC<{ children: React.ReactNode }> = ({ children }) => ( + {children} +); + /** * The posture of the page region this block renders in: `'compact'` when the * region is narrower than half the page, `'full'` when it is not, `null` diff --git a/ui/packages/plugin-dashboard/src/DatasetWidget.tsx b/ui/packages/plugin-dashboard/src/DatasetWidget.tsx index c40bc3e3213..cf7366307c5 100644 --- a/ui/packages/plugin-dashboard/src/DatasetWidget.tsx +++ b/ui/packages/plugin-dashboard/src/DatasetWidget.tsx @@ -112,6 +112,7 @@ import { DrillDownDrawer, type DrillDownNotice } from './DrillDownDrawer'; import { DatasetQueryCoalescerContext } from './datasetQueryBatch'; import { metricDrillFilter, readMeasureDrillScope } from './metricDrill'; import { sharedMeasureDrillScope, scopeDrillFilter } from './measureDrill'; +import { measuredFieldsOf } from './drillConditions'; import { specDefaultWidgetType } from './widgetDispatch'; import { DASHBOARD_WIDGET_MULTI_MEASURE_TYPES } from '@objectstack/spec/ui'; import { SnakeCaseIdentifierSchema } from '@objectstack/spec/shared'; @@ -1054,7 +1055,7 @@ export function DatasetWidget({ widget, dataSource, heading, onForbidden, packag // while each hop's schema is read, and keeps one when the path cannot be // drilled (`resolveDatasetDrillFilter`); `filter` is set once there is a list // to read. - const [drill, setDrill] = useState<{ filter?: Record; title: string; notice?: DrillDownNotice } | null>(null); + const [drill, setDrill] = useState<{ filter?: Record; title: string; notice?: DrillDownNotice; columns?: string[] } | null>(null); // The click a pending relationship resolution answers: a later click, or the // drawer closing, makes an earlier answer stale. const drillRequest = useRef(0); @@ -1495,6 +1496,16 @@ export function DatasetWidget({ widget, dataSource, heading, onForbidden, packag const scope = sharedMeasureDrillScope(state, measures); if (!scope) return; const drillTitle = title || String(widget?.title ?? ''); + // objectstack-ai/objectstack#36256 item 4 — the list shows the record's + // name, the fields this bucket is grouped by and the fields the measure + // aggregates; the reader adds the rest. A relationship path + // (`crm_account.industry`) shows its lookup field (`crm_account`): the + // list draws no dotted column. + const columns = Array.from(new Set([ + ...drillDims.map((d) => dimensionFields?.[d]).filter((f): f is string => !!f).map((f) => f.split('.')[0]), + ...Object.values(drillRanges?.[index] ?? {}).map((range) => range.field.split('.')[0]), + ...measuredFieldsOf(scope), + ])); const request = ++drillRequest.current; const scopedFilter = scopeDrillFilter(runtimeFilter, scope); // A dimension whose field is a `relationship.field` path drills as one @@ -1517,7 +1528,7 @@ export function DatasetWidget({ widget, dataSource, heading, onForbidden, packag }).then( (resolution) => { if (drillRequest.current !== request) return; - if (resolution.status === 'resolved') setDrill({ filter: resolution.filter, title: drillTitle }); + if (resolution.status === 'resolved') setDrill({ filter: resolution.filter, title: drillTitle, columns }); else setDrill({ title: drillTitle, notice: resolution.status === 'too-many' ? 'too-many' : 'unavailable' }); }, (error: unknown) => { @@ -1545,7 +1556,7 @@ export function DatasetWidget({ widget, dataSource, heading, onForbidden, packag console.warn(`[DatasetWidget] drill-down refused — the drilled list cannot be scoped: ${error.message}`); return; } - setDrill({ filter: merged, title: drillTitle }); + setDrill({ filter: merged, title: drillTitle, columns }); }; const closeDrill = () => { drillRequest.current += 1; @@ -1559,6 +1570,8 @@ export function DatasetWidget({ widget, dataSource, heading, onForbidden, packag objectName={drillObject} filter={drill.filter} notice={drill.notice} + defaultColumns={drill.columns} + target="dialog" dataSource={dataSource} /> ) : null; @@ -1626,7 +1639,11 @@ export function DatasetWidget({ widget, dataSource, heading, onForbidden, packag ranges: drillRanges?.[0], }); const openTileDrill = tileDrillFilter - ? () => setDrill({ filter: tileDrillFilter, title: heading?.title || measureLabel }) + ? () => setDrill({ + filter: tileDrillFilter, + title: heading?.title || measureLabel, + columns: measuredFieldsOf(readMeasureDrillScope(state, tileMeasure)), + }) : undefined; const tileDrillProps = openTileDrill ? { diff --git a/ui/packages/plugin-dashboard/src/DrillDownDrawer.tsx b/ui/packages/plugin-dashboard/src/DrillDownDrawer.tsx index baa9251a489..2d82d9adbca 100644 --- a/ui/packages/plugin-dashboard/src/DrillDownDrawer.tsx +++ b/ui/packages/plugin-dashboard/src/DrillDownDrawer.tsx @@ -2,12 +2,18 @@ * ObjectUI * Copyright (c) 2024-present ObjectStack Inc. * - * DrillDownDrawer — opens a side drawer (or dialog) that lists the - * underlying records behind a clicked pivot cell / chart segment. + * DrillDownDrawer — lists the underlying records behind a clicked pivot + * cell / chart segment / metric tile, in a centred dialog (or a side drawer). * - * Composition: + . The data table receives - * the merged filter (widget filter ∧ drill filter) and the data source - * inherited from the schema renderer context. + * The dialog (objectstack-ai/objectstack#36256) floats over the page about + * 70% wide and 65% tall with the shared dialog card, and dims and blurs + * nothing behind it: it is non-modal, so the page stays readable, and a + * click outside it closes it. A phone keeps the side drawer. Either way the + * body is the standard list (`DrillRecordList`) when the renderer has one + * registered; a renderer without `@object-ui/plugin-list` lists the records + * in `ObjectDataTable`. A record's name opens its page through the host + * (`DrillNavigationContext.openRecord`); a host that offers no page (a + * page block's metric or pivot) opens the record in a dialog, as before. */ import React from 'react'; @@ -21,12 +27,14 @@ import { DialogHeader, DialogTitle, cn, + useIsMobile, } from '@object-ui/components'; import { SchemaRenderer, useDrillNavigation } from '@object-ui/react'; import { useSafeTranslate } from '@object-ui/i18n'; import { AlertTriangle, Loader2 } from 'lucide-react'; import { ObjectDataTable } from './ObjectDataTable'; import { OpenInListButton } from './OpenInListButton'; +import { DrillRecordList, drillListAvailable } from './DrillRecordList'; export interface DrillDownDrawerProps { open: boolean; @@ -48,6 +56,12 @@ export interface DrillDownDrawerProps { dataSource?: any; /** Optional column whitelist. */ columns?: string[]; + /** + * The fields the drilled number stands for — its grouped and measured + * fields — shown after the record's name when no `columns` whitelist is + * given (objectstack-ai/objectstack#36256 item 4). The reader adds the rest. + */ + defaultColumns?: string[]; /** Optional max rows. */ maxRows?: number; /** Optional className on the inner container. */ @@ -144,12 +158,20 @@ export const DrillDownDrawer: React.FC = ({ filter, dataSource, columns, + defaultColumns, maxRows, className, report, - notice, + notice: givenNotice, }) => { - const { openRecordList, canOpenRecordList } = useDrillNavigation(); + // A filter that is neither an object nor an array (a string, a number) + // names no condition any read can carry: every list below would read it as + // no filter and list every record (objectstack-ai/objectstack#36256). So no + // list is drawn, and no read is sent. + const notice: DrillDownNotice | undefined = + givenNotice ?? (filter != null && typeof filter !== 'object' ? 'unavailable' : undefined); + const phone = useIsMobile(); + const { openRecordList, canOpenRecordList, openRecord } = useDrillNavigation(); const tt = useSafeTranslate(); const isReportDrill = isDatasetBoundReport(report); @@ -223,6 +245,20 @@ export const DrillDownDrawer: React.FC = ({ }; return ; })() + : drillListAvailable() + ? ( + + ) : ( = ({ pagination: true, searchable: false, pageSize: maxRows, - // Complete the drill chain: a row in this filtered record list - // opens that record. Dialog target so it stacks over this drawer. - // Mirrors the chart / KPI drill tables — every drill-through list - // (pivot, dataset, chart, metric) lands on a clickable record. - drillDown: { enabled: true, mode: 'record', target: 'dialog' }, + // A host with no record page: the row opens its record in a dialog. + ...(openRecord ? {} : { drillDown: { enabled: true, mode: 'record', target: 'dialog' } }), }} dataSource={dataSource} failureMessage={tt(DRILL_NOTICE_COPY.failed.key, DRILL_NOTICE_COPY.failed.fallback)} @@ -246,15 +279,20 @@ export const DrillDownDrawer: React.FC = ({ ); - if (target === 'dialog') { + if (target === 'dialog' && !phone) { + // Non-modal: Radix draws no overlay for it, so nothing behind is dimmed + // or blurred, and an outside click dismisses it like a popover. return ( - !v && onClose()}> - - - {title} + !v && onClose()}> + + + {title} {escapeHatch} - {body} +
{body}
); diff --git a/ui/packages/plugin-dashboard/src/DrillRecordList.tsx b/ui/packages/plugin-dashboard/src/DrillRecordList.tsx new file mode 100644 index 00000000000..9c50c980953 --- /dev/null +++ b/ui/packages/plugin-dashboard/src/DrillRecordList.tsx @@ -0,0 +1,202 @@ +/** + * 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. + */ + +/** + * The records behind a drilled number, drawn by the standard list + * (objectstack-ai/objectstack#36256 item 5): the `list-view` block the object + * list page draws its table with, mounted through the registry, so the drill + * has the list's row height, sorting, filter chips, added columns, record + * count and column calculations, and no table of its own. + * + * What the reader does here is this mount's state alone (item 8): the sort, + * the edited chips, the added columns and the column calculations live in the + * list and in this component, are written nowhere (no view, no preference), + * and are gone when the drill closes. The list is read-only: no inline edit, + * no create, no bulk action, no view switch, no saved view. + * + * The record's name opens its full page through the host + * (`DrillNavigationContext.openRecord`, item 6), with the rows the list shows + * as the page's ↑ ↓ set and the count it matched; no record panel is stacked + * over the drill. A host with no record page (a page block's metric or pivot + * mounts no navigation) opens the record in a dialog showing the fields the + * list lists: the list reads only those (`$select`), so a field it did not + * read is not drawn as empty. + * + * Inside a page the list draws in full as well: the page region's posture + * (compact or capped) is cleared for the drill (`PageRegionPostureReset`). + */ + +import React from 'react'; +import { PageRegionPostureReset } from '@object-ui/components'; +import { ComponentRegistry, resolveFilterPlaceholders, resolveNameField } from '@object-ui/core'; +import { SchemaRenderer, SchemaRendererContext, useDrillNavigation, useFilterScope } from '@object-ui/react'; +import { FILTER_DATE_LIKE_TYPES } from '@object-ui/types'; +import { Loader2 } from 'lucide-react'; +import { RecordDetailDrawer } from './RecordDetailDrawer'; +import { drillListConditions } from './drillConditions'; + +/** The registry key of the standard list (`@object-ui/plugin-list`). */ +export const DRILL_LIST_COMPONENT = 'list-view'; + +/** Whether the standard list is registered in this renderer, loaded or lazily (the Console registers it lazily). */ +export function drillListAvailable(): boolean { + return ComponentRegistry.has(DRILL_LIST_COMPONENT) || ComponentRegistry.hasLazy(DRILL_LIST_COMPONENT); +} + +export interface DrillRecordListProps { + objectName: string; + /** The drill's filter, as composed (placeholders still authored). */ + filter?: Record; + /** An authored column whitelist (`drillDown.columns`): shown as written. */ + columns?: string[]; + /** The columns the drill stands for (the grouped and measured fields), after the record's name. */ + defaultColumns?: string[]; + /** Rows per page (`drillDown.maxRows`). */ + maxRows?: number; + dataSource?: any; + /** Called after the host opened a record's page. */ + onNavigate?: () => void; +} + +type Summary = string | Record; + +/** The types the list's filter draws as dates (its own set). */ +const DATE_TYPES: ReadonlySet = new Set(FILTER_DATE_LIKE_TYPES); + +const rowId = (row: Record): string | undefined => { + const id = row?.id ?? row?._id; + return id == null || id === '' ? undefined : String(id); +}; + +export const DrillRecordList: React.FC = ({ + objectName, + filter, + columns, + defaultColumns, + maxRows, + dataSource: ownDataSource, + onNavigate, +}) => { + const context = React.useContext(SchemaRendererContext); + const dataSource = ownDataSource ?? context?.dataSource; + const { openRecord } = useDrillNavigation(); + const scope = useFilterScope(); + // One resolution per mount: a chip shows the value the query compares. + const resolved = React.useMemo( + () => resolveFilterPlaceholders(filter, scope) as unknown, + // The drill's filter is fixed for the life of this mount (the dialog keys it). + // eslint-disable-next-line react-hooks/exhaustive-deps + [], + ); + + // The object's definition: its name field leads the default columns, as on + // the list page, and its date fields word their bounds as the list does. + const [definition, setDefinition] = React.useState( + typeof dataSource?.getObjectSchema !== 'function' ? null : undefined, + ); + React.useEffect(() => { + if (definition !== undefined) return; + let live = true; + Promise.resolve(dataSource.getObjectSchema(objectName)) + .then((def: unknown) => { if (live) setDefinition(def ?? null); }) + .catch(() => { if (live) setDefinition(null); }); + return () => { live = false; }; + }, [dataSource, objectName, definition]); + const nameField = definition === undefined ? undefined : columns?.length ? null : resolveNameField(definition) ?? null; + const conditions = React.useMemo(() => { + const fields = (definition as { fields?: Record } | null)?.fields ?? {}; + const dateFields = new Set(Object.keys(fields).filter((f) => DATE_TYPES.has(fields[f]?.type ?? ''))); + return drillListConditions(resolved, { dateFields }); + }, [definition, resolved]); + + const [added, setAdded] = React.useState([]); + const [summaries, setSummaries] = React.useState>({}); + const shown = React.useRef<{ ids: string[]; total?: number }>({ ids: [] }); + const [opened, setOpened] = React.useState | null>(null); + + const baseColumns = React.useMemo(() => { + if (columns?.length) return columns; + const lead = nameField ? [nameField] : []; + return Array.from(new Set([...lead, ...(defaultColumns ?? [])])); + }, [columns, defaultColumns, nameField]); + + if (nameField === undefined) { + return ( +
+
+ ); + } + + const listedFields = [...baseColumns, ...added.filter((f) => !baseColumns.includes(f))]; + const listColumns = listedFields.map((field) => + summaries[field] ? { field, summary: summaries[field] } : field, + ); + const schema = { + type: DRILL_LIST_COMPONENT, + // The page node's binding (`PageComponentSchema.dataSource`): the block + // lands its `object` on the list's `objectName`. The default kind is the grid. + dataSource: { object: objectName }, + ...(conditions.rest ? { filter: conditions.rest } : {}), + // An empty list lets the list pick its own columns (no name field known). + ...(listColumns.length > 0 ? { columns: listColumns } : {}), + ...(maxRows ? { pagination: { pageSize: maxRows } } : {}), + userActions: { editInline: false, addRecordForm: false, rowColor: false, group: false }, + }; + + return ( + // The drill is not a part of the page region that holds the block it was + // opened from: its list draws in full there too (chips, pager, no + // 「View all」 link to an unfiltered list), not in the region's posture. + + { + setSummaries((prev) => { + const next = { ...prev }; + if (summary) next[field] = summary; + else delete next[field]; + return next; + }); + }} + onRowsChange={(rows: ReadonlyArray>) => { + shown.current = { ...shown.current, ids: rows.map(rowId).filter((id): id is string => !!id) }; + }} + onTotalChange={(total: number) => { shown.current = { ...shown.current, total }; }} + rowOpensRecord + onRowClick={(record: Record) => { + if (!openRecord) return setOpened(record); + const id = rowId(record); + if (!id) return; + const { ids, total } = shown.current; + openRecord(objectName, id, { siblings: ids.includes(id) ? ids : [id], ...(total != null ? { total } : {}) }); + onNavigate?.(); + }} + /> + {!openRecord && ( + 0 ? listedFields : undefined} + // Values stay masked while the field types are unknown (objectui#10657). + objectTypesPending={typeof dataSource?.getObjectSchema === 'function' && !(definition as { fields?: unknown } | null | undefined)?.fields} + target="dialog" + onClose={() => setOpened(null)} + /> + )} + + ); +}; diff --git a/ui/packages/plugin-dashboard/src/__tests__/DatasetWidget.drillDialog-36256.test.tsx b/ui/packages/plugin-dashboard/src/__tests__/DatasetWidget.drillDialog-36256.test.tsx new file mode 100644 index 00000000000..d228c0f035e --- /dev/null +++ b/ui/packages/plugin-dashboard/src/__tests__/DatasetWidget.drillDialog-36256.test.tsx @@ -0,0 +1,122 @@ +/** + * objectstack-ai/objectstack#36256 — DatasetWidget itself opens its drill in + * the dialog, with the default columns it derives: the fields the bucket is + * grouped by, then the range fields, then the fields the measure aggregates + * (`measuredFieldsOf(scope)`). A metric tile opens the dialog on its measure's + * fields alone. + * + * The relationship-path case: a slice grouped by `crm_account.industry` + * (HotCRM's 行业收入分布) drills on the nested condition beneath the lookup + * field, and the default columns carry that lookup field (`crm_account`, the + * account's name), since the list draws no dotted column. + * + * The drawer is a stub that records the props each open render hands it. + */ +import { describe, it, expect, vi, beforeAll, afterEach } from 'vitest'; +import { render, screen, cleanup, waitFor, fireEvent } from '@testing-library/react'; +import { ComponentRegistry, chartRowBucketId } from '@object-ui/core'; +import { DatasetWidget } from '../DatasetWidget'; + +const drawerProps: Array> = []; +vi.mock('../DrillDownDrawer', () => ({ + DrillDownDrawer: (props: Record) => { + if (props.open) drawerProps.push(props); + return null; + }, +})); + +let chartProps: any = null; +beforeAll(() => { + ComponentRegistry.register('chart', (props: any) => { + chartProps = props; + return null; + }); +}); + +const SCHEMAS: Record = { + crm_opportunity: { + name: 'crm_opportunity', + fields: { + crm_account: { type: 'lookup', reference: 'crm_account', label: 'Account' }, + stage: { type: 'text', label: 'Stage' }, + close_date: { type: 'date', label: 'Close date' }, + amount: { type: 'currency' }, + }, + }, + crm_account: { name: 'crm_account', fields: { industry: { type: 'select', label: 'Industry' } } }, +}; + +// The widget's dimension-metadata read goes through `fetch`: answered by a +// double for the whole file, so no read after a test body can reach a socket. +vi.stubGlobal('fetch', vi.fn(async (url: string) => { + const name = String(url).split('/').pop()?.split('?')[0] ?? ''; + return { ok: true, json: async () => ({ item: SCHEMAS[name] ?? { name, fields: {} } }) }; +})); + +afterEach(() => { + cleanup(); + chartProps = null; + drawerProps.length = 0; +}); + +const lastOpened = () => drawerProps.filter((p) => p.filter).at(-1)!; + +const source = (answer: Record) => ({ + queryDataset: vi.fn(async () => ({ object: 'crm_opportunity', ...answer })), + find: vi.fn(async () => ({ data: [] })), + getObjectSchema: vi.fn(async (object: string) => SCHEMAS[object]), +}); + +describe('DatasetWidget opens its drill in the dialog (#36256)', () => { + it('a chart mark: grouped field, then range field, then measured field', async () => { + const src = source({ + rows: [{ stage: 'Won', revenue: 300 }], + fields: [{ name: 'stage', type: 'string', label: 'Stage' }, { name: 'revenue', type: 'number', label: 'Revenue' }], + dimensionFields: { stage: 'stage' }, + drillScopes: { revenue: { amount: { $null: false } } }, + drillRawRows: [{ stage: 'won' }], + drillRanges: [{ close_month: { field: 'close_date', gte: '2026-07-01', lt: '2026-10-01' } }], + }); + render(); + await waitFor(() => expect(chartProps?.schema?.data?.length).toBe(1)); + const row = chartProps.schema.data[0]; + chartProps.onSegmentClick({ category: String(row.stage), categoryId: chartRowBucketId(row) }); + await waitFor(() => expect(drawerProps.some((p) => p.filter)).toBe(true)); + const opened = lastOpened(); + expect(opened.target).toBe('dialog'); + expect(opened.open).toBe(true); + expect(opened.defaultColumns).toEqual(['stage', 'close_date', 'amount']); + }); + + it("a metric tile: the measure's fields", async () => { + const src = source({ + rows: [{ total_amount: 814400 }], + fields: [{ name: 'total_amount', type: 'number', label: 'Total Amount', aggregate: 'sum' }], + drillScopes: { total_amount: { amount: { $null: false } } }, + }); + render(); + fireEvent.click(await screen.findByTestId('dataset-metric-drill')); + await waitFor(() => expect(drawerProps.some((p) => p.filter)).toBe(true)); + const opened = lastOpened(); + expect(opened.target).toBe('dialog'); + expect(opened.open).toBe(true); + expect(opened.defaultColumns).toEqual(['amount']); + }); + + it('a relationship-path slice: the nested condition, with crm_account and the measured field as columns', async () => { + const src = source({ + rows: [{ account_industry: 'Technology', revenue: 300 }], + fields: [{ name: 'account_industry', type: 'string', label: 'Account Industry' }, { name: 'revenue', type: 'number', label: 'Revenue' }], + dimensionFields: { account_industry: 'crm_account.industry' }, + drillScopes: { revenue: { amount: { $null: false } } }, + drillRawRows: [{ account_industry: 'technology' }], + }); + render(); + fireEvent.click(await screen.findByTestId('dataset-drill-row')); + await waitFor(() => expect(drawerProps.some((p) => p.filter)).toBe(true)); + const opened = lastOpened(); + expect(JSON.stringify(opened.filter)).toContain('{"crm_account":{"industry":"technology"}}'); + expect(opened.target).toBe('dialog'); + expect(opened.defaultColumns).toEqual(['crm_account', 'amount']); + }); +}); diff --git a/ui/packages/plugin-dashboard/src/__tests__/DrillDownDialog-36256.test.tsx b/ui/packages/plugin-dashboard/src/__tests__/DrillDownDialog-36256.test.tsx new file mode 100644 index 00000000000..da251e06ef0 --- /dev/null +++ b/ui/packages/plugin-dashboard/src/__tests__/DrillDownDialog-36256.test.tsx @@ -0,0 +1,152 @@ +/** + * objectstack-ai/objectstack#36256 — the drill opens a centred, non-modal + * dialog whose body is the standard list (`list-view`), with the drill's + * conditions as the list's own chips, the record's name and the drilled + * fields as its default columns, a read-only toolbar, and the record's name + * opening its page through the host with the shown rows as its ↑ ↓ set. No + * record panel is stacked over the drill. + * + * The registered `list-view` here is a stub that records the props it is + * handed: what the real list does with them is pinned in app-shell + * (`drillDialogStandardList-36256.test.tsx`). + */ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { render, screen, fireEvent, waitFor } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import React from 'react'; +import { ComponentRegistry } from '@object-ui/core'; +import { DrillNavigationProvider } from '@object-ui/react'; +import '@object-ui/components'; +import { DrillDownDrawer } from '../DrillDownDrawer'; + +// The phone flag the drawer reads, flipped per test; the rest of the +// components package is the real one. +const viewport = vi.hoisted(() => ({ phone: false })); +vi.mock('@object-ui/components', async (importOriginal) => ({ + ...(await importOriginal()), + useIsMobile: () => viewport.phone, +})); + +// The props each render handed the stub, read back through the spy: a +// component writes nothing outside itself during render. +const seenProps = vi.fn(); +const lastProps = (): Record | null => seenProps.mock.calls.at(-1)?.[0] ?? null; +const StubList = (props: Record) => { + seenProps(props); + return ( + + ); +}; + +const dataSource = { + find: vi.fn(async () => ({ data: [] })), + getObjectSchema: vi.fn(async () => ({ name: 'opportunity', nameField: 'name', fields: { name: { type: 'text' } } })), +}; + +function renderDialog(props: Record = {}, openRecord = vi.fn()) { + const onClose = props.onClose ?? vi.fn(); + render( + + + , + ); + return { onClose, openRecord }; +} + +describe('drill dialog over the standard list (#36256)', () => { + beforeEach(() => { + seenProps.mockClear(); + ComponentRegistry.register('list-view', StubList as any); + }); + afterEach(() => { + ComponentRegistry.unregister('list-view'); + }); + + it('is a centred dialog with no overlay behind it', async () => { + renderDialog(); + const dialog = await screen.findByTestId('drill-down-dialog'); + expect(dialog).toHaveAttribute('role', 'dialog'); + expect(dialog.className).toContain('w-[70vw]'); + expect(dialog.className).toContain('h-[65vh]'); + // Radix draws its overlay only for a modal dialog. + expect(document.querySelector('[data-state="open"].fixed.inset-0')).toBeNull(); + }); + + it('mounts the standard list read-only, with the drill conditions as chips and the drilled fields as columns', async () => { + renderDialog(); + await waitFor(() => expect(lastProps()).not.toBeNull()); + const { schema, initialFilters, showViewSwitcher } = lastProps()!; + expect(schema).toMatchObject({ + type: 'list-view', + dataSource: { object: 'opportunity' }, + columns: ['name', 'industry', 'amount'], + userActions: { editInline: false, addRecordForm: false }, + }); + expect(schema.filter).toBeUndefined(); + expect(initialFilters.conditions.map((c: any) => [c.field, c.operator, c.value])).toEqual([ + ['stage', 'equals', 'closed_won'], + ['industry', 'equals', 'tech'], + ['amount', 'is_not_null', undefined], + ]); + expect(showViewSwitcher).toBe(false); + for (const door of ['onSaveView', 'onAddRecord', 'onBulkAction', 'onEdit', 'onDelete', 'onSortChange', 'onFilterChange']) { + expect(lastProps()![door]).toBeUndefined(); + } + }); + + it("an added column and a picked calculation stay in the dialog's own state", async () => { + renderDialog(); + await waitFor(() => expect(lastProps()).not.toBeNull()); + React.act(() => lastProps()!.onAddedFieldsChange(['owner_id'])); + React.act(() => { lastProps()!.onColumnSummaryPick('amount', 'sum'); }); + expect(lastProps()!.schema.columns).toEqual(['name', 'industry', { field: 'amount', summary: 'sum' }, 'owner_id']); + }); + + it("the record's name opens its page with the shown rows, and closes the drill", async () => { + const { onClose, openRecord } = renderDialog(); + fireEvent.click(await screen.findByTestId('stub-row')); + expect(openRecord).toHaveBeenCalledWith('opportunity', 'o2', { siblings: ['o1', 'o2', 'o3'], total: 3 }); + expect(onClose).toHaveBeenCalled(); + }); + + it('keeps the side drawer on a phone, with the same list', async () => { + viewport.phone = true; + try { + renderDialog(); + await waitFor(() => expect(lastProps()).not.toBeNull()); + expect(screen.queryByTestId('drill-down-dialog')).toBeNull(); + expect(document.querySelector('[role="dialog"]')?.className).toContain('right-0'); + } finally { + viewport.phone = false; + } + }); + + it('keeps the side drawer and the same list when target is drawer', async () => { + renderDialog({ target: 'drawer' }); + await waitFor(() => expect(lastProps()).not.toBeNull()); + expect(screen.queryByTestId('drill-down-dialog')).toBeNull(); + }); +}); + +describe('drill dialog without the standard list registered (#36256)', () => { + it('lists the records in the data table and stacks no record panel on a row', async () => { + renderDialog(); + expect(await screen.findByTestId('drill-down-dialog')).toBeInTheDocument(); + expect(screen.queryByTestId('stub-row')).toBeNull(); + expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(1); + }); +}); diff --git a/ui/packages/plugin-dashboard/src/__tests__/DrillDownDrawer.chain.test.tsx b/ui/packages/plugin-dashboard/src/__tests__/DrillDownDrawer.chain.test.tsx index cd276e12744..b5134f35ae4 100644 --- a/ui/packages/plugin-dashboard/src/__tests__/DrillDownDrawer.chain.test.tsx +++ b/ui/packages/plugin-dashboard/src/__tests__/DrillDownDrawer.chain.test.tsx @@ -2,15 +2,19 @@ * ObjectUI * Copyright (c) 2024-present ObjectStack Inc. * - * Verifies the drill chain completes through DrillDownDrawer: the filtered - * record list it renders (for pivot / dataset / chart drill-through) is itself - * drill-to-record, so clicking a row opens that record. + * The drill list stacks no record panel over the drill + * (objectstack-ai/objectstack#36256 item 6): a record opens as its page from + * the standard list's record name. Without the standard list registered, the + * data-table fallback lists the records and, when the host offers a record + * page, its rows open nothing. A host with no record page (a page block) + * keeps the rows drill-to-record, as before. */ import { describe, it, expect, vi } from 'vitest'; import { render, screen, waitFor } from '@testing-library/react'; import '@testing-library/jest-dom'; import React from 'react'; +import { DrillNavigationProvider } from '@object-ui/react'; import { DrillDownDrawer } from '../DrillDownDrawer'; // Registers the renderers at module scope, NOT inside a `beforeAll` — there the // cold transform is billed to `hookTimeout`, which is why this carried a raised @@ -31,27 +35,31 @@ function makeDataSource() { }; } -describe('DrillDownDrawer — completes the drill chain to a record', () => { - it('wires record drill on the filtered drill list (chain completion)', async () => { - render( - , - ); +const drill = () => ( + +); - // The drill-through list renders the underlying records. - await waitFor(() => expect(screen.getByText('Acme Renewal')).toBeInTheDocument()); +/** The data-table marks a row `cursor-pointer` only when an onRowClick is wired. */ +const rowOf = async (name: string) => { + await waitFor(() => expect(screen.getByText(name)).toBeInTheDocument()); + return screen.getByText(name).closest('tr') as HTMLElement; +}; - // Its rows are drill-to-record: the data-table marks clickable rows with - // `cursor-pointer` only when an onRowClick is wired, which ObjectDataTable - // does only when record drill is enabled. (The record drawer opening on - // click is covered by ObjectDataTable.drill.test.) - const row = screen.getByText('Acme Renewal').closest('tr') as HTMLElement; - expect(row.className).toContain('cursor-pointer'); +describe('DrillDownDrawer — no record panel stacked over the drill', () => { + it('the data-table fallback rows open no record drawer when the host offers a record page', async () => { + render({drill()}); + expect((await rowOf('Acme Renewal')).className).not.toContain('cursor-pointer'); + }); + + it('a host with no record page keeps the rows drill-to-record', async () => { + render(drill()); + expect((await rowOf('Acme Renewal')).className).toContain('cursor-pointer'); }); }); diff --git a/ui/packages/plugin-dashboard/src/__tests__/ObjectMetricWidget.drillOpensRecord-36256.test.tsx b/ui/packages/plugin-dashboard/src/__tests__/ObjectMetricWidget.drillOpensRecord-36256.test.tsx new file mode 100644 index 00000000000..ab230f4b857 --- /dev/null +++ b/ui/packages/plugin-dashboard/src/__tests__/ObjectMetricWidget.drillOpensRecord-36256.test.tsx @@ -0,0 +1,111 @@ +/** + * objectstack-ai/objectstack#36256 — a page block (`object-metric`) mounts the + * drill with no DrillNavigationProvider, so the host offers no record page. + * A drilled row then opens its record in a dialog, as these hosts did before + * the drill moved to the standard list; a host that offers a page is pinned in + * `DrillDownDialog-36256.test.tsx`. + * + * Both drill bodies are covered: the standard list (`list-view`, a stub here + * that clicks a row) and the data table used when no list is registered. + * + * The standard list reads only the fields it lists (`$select`), so the row it + * hands back holds only those. The dialog draws exactly those fields, each + * with its value: a field the list did not read is not drawn as empty. + */ +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { render, screen, cleanup, fireEvent, within, waitFor } from '@testing-library/react'; +import { ComponentRegistry } from '@object-ui/core'; +import { SchemaRenderer, SchemaRendererProvider } from '@object-ui/react'; +import '../index'; + +const StubList = (props: Record) => ( + +); + +/** The record as stored: more fields than the drill lists. */ +const DEAL = { id: '1', name: 'Acme Renewal', stage: 'won', amount: 120, owner: 'Dana', description: 'Three-year renewal' }; + +/** Answers with the record projected to the listed columns, as the list's `$select` read does. */ +interface ListProps { + schema?: { columns?: Array }; + onRowClick?: (row: Record) => void; +} +const ProjectingList = (props: ListProps) => { + const listed = (props.schema?.columns ?? []).map((c) => (typeof c === 'string' ? c : c.field)); + const row = Object.fromEntries(Object.entries(DEAL).filter(([k]) => k === 'id' || listed.includes(k))); + return ; +}; + +afterEach(() => { + cleanup(); + ComponentRegistry.unregister('list-view'); +}); + +const adapter = () => ({ + aggregate: vi.fn(async () => [{ amount_sum: 120 }]), + find: vi.fn(async () => ({ data: [{ id: '1', name: 'Acme Renewal' }] })), + getObjectSchema: vi.fn(async () => ({ + name: 'deal', + nameField: 'name', + fields: { + name: { type: 'text', label: 'Name' }, + stage: { type: 'text', label: 'Stage' }, + amount: { type: 'number', label: 'Amount' }, + owner: { type: 'text', label: 'Owner' }, + description: { type: 'text', label: 'Description' }, + }, + })), +}); + +const mount = (drillDown: Record = { enabled: true, target: 'dialog' }) => + render( + + + , + ); + +describe('a page block with no record page opens the drilled record in a dialog (#36256)', () => { + it('from the standard list', async () => { + ComponentRegistry.register('list-view', StubList as any); + mount(); + fireEvent.click(await screen.findByRole('button', { name: /revenue|120/i })); + fireEvent.click(await screen.findByTestId('stub-row')); + const body = await screen.findByTestId('record-detail-body'); + expect(within(body).getByText('Acme Renewal')).toBeTruthy(); + expect(body.closest('[role="dialog"]')).not.toBeNull(); + }); + + it('draws the fields the list read, each with its value, and no field it did not read', async () => { + ComponentRegistry.register('list-view', ProjectingList as never); + mount({ enabled: true, target: 'dialog', columns: ['name', 'stage', 'amount'] }); + fireEvent.click(await screen.findByRole('button', { name: /revenue|120/i })); + fireEvent.click(await screen.findByTestId('stub-row')); + const body = await screen.findByTestId('record-detail-body'); + // The values are masked until the field types are in; wait for them. + await waitFor(() => expect(within(body).getByText('Acme Renewal')).toBeTruthy()); + const labels = Array.from(body.querySelectorAll('dt')).map((dt) => dt.textContent); + expect(labels).toEqual(['Name', 'Stage', 'Amount']); + for (const dd of Array.from(body.querySelectorAll('dd'))) { + expect(dd.textContent?.trim()).not.toMatch(/^(—|No value)?$/); + } + }); + + it('from the data table when no list is registered', async () => { + mount(); + fireEvent.click(await screen.findByRole('button', { name: /revenue|120/i })); + fireEvent.click(await screen.findByText('Acme Renewal')); + const body = await screen.findByTestId('record-detail-body'); + expect(within(body).getByText('Acme Renewal')).toBeTruthy(); + expect(body.closest('[role="dialog"]')).not.toBeNull(); + }); +}); diff --git a/ui/packages/plugin-dashboard/src/__tests__/drillConditions-36256.test.ts b/ui/packages/plugin-dashboard/src/__tests__/drillConditions-36256.test.ts new file mode 100644 index 00000000000..97801cb4790 --- /dev/null +++ b/ui/packages/plugin-dashboard/src/__tests__/drillConditions-36256.test.ts @@ -0,0 +1,126 @@ +/** + * objectstack-ai/objectstack#36256 item 3 — a drill's conditions become the + * standard list's own chips where a chip can say them, and stay its base + * filter where none can. + */ +import { describe, it, expect } from 'vitest'; +import { drillListConditions, measuredFieldsOf } from '../drillConditions'; + +const rows = (filter: Record) => + drillListConditions(filter).chips.conditions.map(({ field, operator, value }) => ({ field, operator, value })); + +describe('drillListConditions', () => { + it('reads each field compared with a value as one chip row, through $and', () => { + expect(rows({ + $and: [ + { stage: 'closed_won', close_date: { $gte: '2026-01-01', $lt: '2026-04-01' } }, + { lead_source: { $in: ['web', 'referral'] }, amount: { $null: false } }, + ], + })).toEqual([ + { field: 'stage', operator: 'equals', value: 'closed_won' }, + { field: 'close_date', operator: 'greater_than_or_equal', value: '2026-01-01' }, + { field: 'close_date', operator: 'less_than', value: '2026-04-01' }, + { field: 'lead_source', operator: 'in', value: ['web', 'referral'] }, + { field: 'amount', operator: 'is_not_null', value: undefined }, + ]); + }); + + it('keeps what no chip can say as the base filter, ANDed', () => { + const { chips, rest } = drillListConditions({ + stage: { $ne: 'closed_lost' }, + account: { industry: 'tech' }, + $or: [{ a: 1 }, { b: 2 }], + owner: { $regex: 'x' }, + }); + expect(chips.conditions.map((c) => c.operator)).toEqual(['not_equals']); + expect(rest).toEqual({ $and: [{ account: { industry: 'tech' } }, { $or: [{ a: 1 }, { b: 2 }] }, { owner: { $regex: 'x' } }] }); + }); + + it('draws a condition stated twice as one chip', () => { + expect(rows({ + $and: [{ close_date: { $gte: '2026-10-01' } }, { close_date: { $gte: '2026-10-01', $lt: '2027-01-01' } }], + })).toEqual([ + { field: 'close_date', operator: 'greater_than_or_equal', value: '2026-10-01' }, + { field: 'close_date', operator: 'less_than', value: '2027-01-01' }, + ]); + }); + + it("words a date field's open bounds as the list's date filter does", () => { + const { chips } = drillListConditions( + { close_date: { $gt: '2026-09-30', $lt: '2027-01-01' }, amount: { $lt: 5 } }, + { dateFields: new Set(['close_date']) }, + ); + expect(chips.conditions.map((c) => [c.field, c.operator])).toEqual([ + ['close_date', 'after'], + ['close_date', 'before'], + ['amount', 'less_than'], + ]); + }); + + it("lowers a page block's rule array, and an AST node, to chips", () => { + // HotCRM's 销售主页 KPI tile: the spec's rule-array form, handed as written. + expect(drillListConditions([{ field: 'stage', operator: 'equals', value: 'closed_won' }]).chips.conditions + .map(({ field, operator, value }) => ({ field, operator, value }))) + .toEqual([{ field: 'stage', operator: 'equals', value: 'closed_won' }]); + expect(drillListConditions([['stage', '=', 'closed_won'], ['amount', '>', 5]]).chips.conditions + .map(({ field, operator, value }) => ({ field, operator, value }))) + .toEqual([ + { field: 'stage', operator: 'equals', value: 'closed_won' }, + { field: 'amount', operator: 'greater_than', value: 5 }, + ]); + }); + + it('lowers an `and` node to chips, and keeps an `or` node and an any-of group as the base filter', () => { + expect(drillListConditions(['and', ['stage', '=', 'closed_won'], ['amount', '>', 5]]).chips.conditions + .map(({ field, operator, value }) => ({ field, operator, value }))) + .toEqual([ + { field: 'stage', operator: 'equals', value: 'closed_won' }, + { field: 'amount', operator: 'greater_than', value: 5 }, + ]); + expect(drillListConditions(['or', ['stage', '=', 'closed_won'], ['stage', '=', 'negotiation']])).toEqual({ + chips: { logic: 'and', conditions: [] }, + rest: { $or: [{ stage: 'closed_won' }, { stage: 'negotiation' }] }, + }); + // A rule array with an any-of group (`{ or: [rule, ...] }`): the rule is a + // chip, the group the base filter's `$or`. + const { chips, rest } = drillListConditions([ + { field: 'stage', operator: 'equals', value: 'closed_won' }, + { or: [ + { field: 'lead_source', operator: 'equals', value: 'web' }, + { field: 'lead_source', operator: 'equals', value: 'referral' }, + ] }, + ]); + expect(chips.conditions.map(({ field, operator, value }) => ({ field, operator, value }))) + .toEqual([{ field: 'stage', operator: 'equals', value: 'closed_won' }]); + expect(rest).toEqual({ $or: [{ lead_source: 'web' }, { lead_source: 'referral' }] }); + }); + + it('keeps a filter it cannot lower as the base filter, exactly as it arrived', () => { + // A scalar on a list operator: the spec's lowering refuses it. + const refused = [['stage', 'in', 'won']]; + expect(drillListConditions(refused)).toEqual({ chips: { logic: 'and', conditions: [] }, rest: refused }); + }); + + it.each([ + ['an array that is neither rules nor AST', [{ stage: 'closed_won' }]], + ['a rule with a blank field', [{ field: '', operator: 'equals', value: 'closed_won' }]], + ['a rule with no field', [{ operator: 'equals', value: 'closed_won' }]], + ['a valid rule beside a malformed one', [{ field: 'stage', operator: 'equals', value: 'closed_won' }, { stage: 'x' }]], + ['a string', 'stage = closed_won'], + ['a number', 7], + ])('keeps a filter the conversion answers nothing for as the base filter, exactly as it arrived: %s', (_, filter) => { + // Not empty, so never read as no filter: that would list every record. + expect(drillListConditions(filter)).toEqual({ chips: { logic: 'and', conditions: [] }, rest: filter }); + }); + + it.each([undefined, null, [], {}])('answers no rows and no rest for no filter: %j', (filter) => { + expect(drillListConditions(filter)).toEqual({ chips: { logic: 'and', conditions: [] }, rest: undefined }); + }); +}); + +describe('measuredFieldsOf', () => { + it('names the fields a measure scope says hold a value', () => { + expect(measuredFieldsOf({ $and: [{ stage: 'won' }, { amount: { $null: false } }] })).toEqual(['amount']); + expect(measuredFieldsOf({})).toEqual([]); + }); +}); diff --git a/ui/packages/plugin-dashboard/src/__tests__/pageBlockDrillFilter-36256.test.tsx b/ui/packages/plugin-dashboard/src/__tests__/pageBlockDrillFilter-36256.test.tsx new file mode 100644 index 00000000000..cc60dd614f7 --- /dev/null +++ b/ui/packages/plugin-dashboard/src/__tests__/pageBlockDrillFilter-36256.test.tsx @@ -0,0 +1,106 @@ +/** + * objectstack-ai/objectstack#36256 — a page block's drill keeps its filter. + * + * A page block's `filter` is authored in the spec's rule-array form + * (`[{ field, operator, value }]`; HotCRM's 销售主页 KPI tiles). The + * `object-metric` block hands it to the drill as written. The `object-pivot` + * block composes it with the clicked cell through `composeDrillFilter` first. + * Either way, every condition must reach the drill list: as one of its chips, + * or as its base filter. + * + * The registered `list-view` is a stub that records the props it is handed. + * What the real list reads with them is pinned in app-shell + * (`pageBlockDrillFilter-36256.test.tsx` there). + */ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { render, screen, cleanup, fireEvent, waitFor } from '@testing-library/react'; +import { ComponentRegistry } from '@object-ui/core'; +import { SchemaRenderer, SchemaRendererProvider } from '@object-ui/react'; +import '../index'; + +const seen = vi.fn(); +const StubList = (props: Record) => { + seen(props); + return null; +}; +const last = () => seen.mock.calls.at(-1)?.[0] as + | { schema: { filter?: unknown }; initialFilters?: { conditions: Array<{ field: string; operator: string; value?: unknown }> } } + | undefined; + +/** The drill list's conditions: its chips and its base filter. */ +const conditionsSeen = () => ({ + chips: (last()?.initialFilters?.conditions ?? []).map(({ field, operator, value }) => ({ field, operator, value })), + base: last()?.schema.filter, +}); + +beforeEach(() => { + seen.mockClear(); + ComponentRegistry.register('list-view', StubList as never); + vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, json: async () => ({}) }))); +}); +afterEach(() => { + cleanup(); + ComponentRegistry.unregister('list-view'); + vi.unstubAllGlobals(); +}); + +const adapter = () => ({ + aggregate: vi.fn(async () => [{ amount_sum: 1290000 }]), + find: vi.fn(async () => ({ data: [] })), + getObjectSchema: vi.fn(async () => ({ + name: 'crm_opportunity', + nameField: 'name', + fields: { name: { type: 'text' }, stage: { type: 'text' }, lead_source: { type: 'text' }, amount: { type: 'number' } }, + })), +}); + +const mount = (schema: Record) => + render( + + + , + ); + +describe("a page block's drill keeps its rule-array filter (#36256)", () => { + it('object-metric: the tile\'s `stage = closed_won` reaches the drill list', async () => { + mount({ + type: 'object-metric', + objectName: 'crm_opportunity', + label: 'Revenue won', + aggregate: { field: 'amount', function: 'sum' }, + filter: [{ field: 'stage', operator: 'equals', value: 'closed_won' }], + drillDown: { enabled: true, target: 'dialog' }, + }); + fireEvent.click(await screen.findByRole('button', { name: /revenue won|1,290,000/i })); + await waitFor(() => expect(last()).toBeDefined()); + expect(conditionsSeen()).toEqual({ + chips: [{ field: 'stage', operator: 'equals', value: 'closed_won' }], + base: undefined, + }); + }); + + it('object-pivot: the block\'s filter and the clicked cell both reach the drill list', async () => { + mount({ + type: 'object-pivot', + objectName: 'crm_opportunity', + rowField: 'stage', + columnField: 'lead_source', + valueField: 'amount', + aggregation: 'sum', + data: [ + { id: 'a', stage: 'closed_won', lead_source: 'web', amount: 10 }, + { id: 'b', stage: 'prospecting', lead_source: 'web', amount: 20 }, + ], + filter: [{ field: 'stage', operator: 'equals', value: 'closed_won' }], + drillDown: { enabled: true, target: 'dialog' }, + }); + fireEvent.click(await screen.findByLabelText('Drill into stage=closed_won, lead_source=web')); + await waitFor(() => expect(last()).toBeDefined()); + const { chips, base } = conditionsSeen(); + expect(base).toBeUndefined(); + expect(chips).toEqual(expect.arrayContaining([ + { field: 'stage', operator: 'equals', value: 'closed_won' }, + { field: 'lead_source', operator: 'equals', value: 'web' }, + ])); + }); +}); diff --git a/ui/packages/plugin-dashboard/src/drillConditions.ts b/ui/packages/plugin-dashboard/src/drillConditions.ts new file mode 100644 index 00000000000..c1191d87767 --- /dev/null +++ b/ui/packages/plugin-dashboard/src/drillConditions.ts @@ -0,0 +1,202 @@ +/** + * 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. + */ + +/** + * The drill list's conditions, as the list's own filter chips + * (objectstack-ai/objectstack#36256 item 3). + * + * A drill hands the list one filter object (the widget filter, the clicked + * bucket and the measure's scope, composed by `composeDrillFilter`). The list + * draws the reader's conditions as chips that can be changed and removed, and + * the view's own filter as locked chips it can only read when it is a rule + * array. So each condition of the drill that is one field compared with one + * value becomes a row of the list's filter group (`initialFilters`), drawn as an + * ordinary chip; everything else (a nested relationship condition, an `$or`, an + * operator the rows have no id for) stays the list's base `filter`, applied + * as it was. Both are ANDed, so the list matches the drill exactly until the + * reader edits a chip. + * + * A filter that is not the object form (a page block's authored rule array + * `[{ field, operator, value }]`, an AST node) is lowered to it first, through + * the drill's own composition (`composeDrillFilter`: `mergeFilterNodes`, then + * the spec's `parseFilterAST`). A shape that cannot be lowered stays the base + * `filter` exactly as it arrived: one the conversion refuses (a + * `FilterOperatorError`), and one it answers with nothing although it is not + * empty (an array that is neither rules nor AST, a rule with no field beside a + * valid one, a string or a number; the drill drawer lists nothing for the + * last two, since no list reads them). The spec's `parseFilterAST` answers + * `undefined` for such an array, the hazard `ObjectMetricWidget`'s + * `specShapeWhere` guards its own read against, and reading that as "no + * filter" would list every record. No condition is ever dropped. + * + * Values must already be resolved (`resolveFilterPlaceholders`): a chip shows + * what the query compares, never a `{token}`. + */ + +import type { FilterBuilderRow, FilterBuilderRowGroup } from '@object-ui/components'; +import { composeDrillFilter, FilterOperatorError } from '@object-ui/core'; + +/** The row operator each comparison operator of the filter dialect reads as. */ +const ROW_OPERATOR: Readonly> = { + $eq: 'equals', + $ne: 'not_equals', + $in: 'in', + $nin: 'not_in', + $gt: 'greater_than', + $gte: 'greater_than_or_equal', + $lt: 'less_than', + $lte: 'less_than_or_equal', + $contains: 'contains', +}; + +/** A value one chip row compares with: the filter dialect's own scalars. */ +const isScalar = (v: unknown): v is string | number | boolean => + typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean'; + +const isPlainObject = (v: unknown): v is Record => + !!v && typeof v === 'object' && !Array.isArray(v); + +/** + * Split a filter into its ANDed parts: `$and` members and the keys of one + * object, each `{ field: condition }`. A member that is not an object is one + * part as it is, never dropped. + */ +function andParts(filter: unknown): unknown[] { + if (!isPlainObject(filter)) return [filter]; + const parts: unknown[] = []; + for (const [key, value] of Object.entries(filter)) { + if (key === '$and' && Array.isArray(value)) { + for (const member of value) parts.push(...andParts(member)); + } else { + parts.push({ [key]: value }); + } + } + return parts; +} + +/** Does every ANDed part read as `{ field: condition }`? */ +const splits = (filter: unknown): filter is Record => + isPlainObject(filter) && andParts(filter).every(isPlainObject); + +/** No filter: absent, an empty array or an empty object. */ +const isEmptyFilter = (v: unknown): boolean => + v === undefined || v === null || (Array.isArray(v) && v.length === 0) || (isPlainObject(v) && Object.keys(v).length === 0); + +/** + * The filter in the object form, or `null` when it cannot be lowered (see the + * file header). `undefined` is no filter. + */ +function objectFormOf(filter: unknown): Record | undefined | null { + if (isEmptyFilter(filter)) return undefined; + if (splits(filter)) return filter; + try { + const lowered: unknown = composeDrillFilter(filter, undefined); + // A filter that is not empty never lowers to no filter: kept as it arrived. + if (isEmptyFilter(lowered)) return null; + return splits(lowered) ? lowered : null; + } catch (error) { + if (error instanceof FilterOperatorError) return null; + throw error; + } +} + +/** The rows one `{ field: condition }` part reads as, or `null` when it is no row. */ +function rowsOf(field: string, condition: unknown): Omit[] | null { + if (field.startsWith('$')) return null; + if (isScalar(condition)) return [{ field, operator: 'equals', value: condition }]; + if (!isPlainObject(condition)) return null; + const entries = Object.entries(condition); + if (entries.length === 0) return null; + const rows: Omit[] = []; + for (const [op, value] of entries) { + if (op === '$null' && typeof value === 'boolean') { + rows.push({ field, operator: value ? 'is_null' : 'is_not_null' }); + continue; + } + const operator = ROW_OPERATOR[op]; + if (!operator) return null; + const list = operator === 'in' || operator === 'not_in'; + if (list ? !Array.isArray(value) || !value.every(isScalar) : !isScalar(value)) return null; + rows.push({ field, operator, value: value as FilterBuilderRow['value'] }); + } + return rows; +} + +export interface DrillListConditions { + /** The conditions drawn as the list's chips, its `initialFilters`. */ + chips: FilterBuilderRowGroup; + /** What no chip can say, kept as the list's base `filter`; `undefined` when nothing is left. */ + rest: Record | unknown[] | undefined; +} + +/** + * The words the list's chips give a date bound: `before` / `after` lower to + * the same `<` / `>` as `less_than` / `greater_than`, and are the operators + * the list's date filter draws, so a half-open date bucket reads 「before + * 2027-01-01」, not an operator id. + */ +const DATE_ROW_OPERATOR: Readonly> = { + less_than: 'before', + greater_than: 'after', +}; + +export interface DrillListConditionOptions { + /** The fields that hold a date or a date-time (read from the object's definition). */ + dateFields?: ReadonlySet; +} + +/** Split a resolved drill filter into chip rows and the rest (see the file header). */ +export function drillListConditions( + filter: unknown, + { dateFields }: DrillListConditionOptions = {}, +): DrillListConditions { + const conditions: FilterBuilderRow[] = []; + const lowered = objectFormOf(filter); + // Not lowered: the list's base filter, exactly as it arrived. + if (lowered === null) { + return { chips: { logic: 'and', conditions }, rest: filter as Record | unknown[] }; + } + const rest: Record[] = []; + const seen = new Set(); + for (const part of andParts(lowered ?? {}) as Record[]) { + const [field, condition] = Object.entries(part)[0]; + const rows = rowsOf(field, condition); + if (!rows) { + rest.push(part); + continue; + } + // A condition stated twice (the widget filter's range and the clicked + // bucket's) ANDs to itself: one chip says it. + for (const stated of rows) { + const dated = dateFields?.has(stated.field) ? DATE_ROW_OPERATOR[stated.operator] : undefined; + const row = dated ? { ...stated, operator: dated } : stated; + const key = JSON.stringify([row.field, row.operator, row.value]); + if (seen.has(key)) continue; + seen.add(key); + conditions.push({ ...row, id: `drill-${conditions.length}` }); + } + } + return { + chips: { logic: 'and', conditions }, + rest: rest.length === 0 ? undefined : rest.length === 1 ? rest[0] : { $and: rest }, + }; +} + +/** + * The fields a drill's measure scope says hold a value — `{ field: { $null: + * false } }`, which the dataset answer's `drillScopes` writes for a measure + * over a field (the spec's `drillScopes` description). Those are the fields + * the clicked number aggregates, so the list shows them by default. + */ +export function measuredFieldsOf(scope: unknown): string[] { + return andParts(scope) + .filter(isPlainObject) + .map((part) => Object.entries(part)[0]) + .filter(([field, c]) => !field.startsWith('$') && isPlainObject(c) && c.$null === false && Object.keys(c).length === 1) + .map(([field]) => field); +} diff --git a/ui/packages/plugin-report/src/DatasetReportRenderer.tsx b/ui/packages/plugin-report/src/DatasetReportRenderer.tsx index 9d6ad9b5bc4..19b5f63ddfa 100644 --- a/ui/packages/plugin-report/src/DatasetReportRenderer.tsx +++ b/ui/packages/plugin-report/src/DatasetReportRenderer.tsx @@ -110,6 +110,8 @@ import { // family lives (#4466 / #4497 / #4673 / #4500 / #4508), so routing through it // INHERITS those fixes instead of re-deriving them on a third surface. buildChartSeries, + findChartSeriesRow, + type ChartSegmentClickEvent, // The authored half of objectui#4229's data/presentation split (objectui#4877): // the chrome and the per-series presentation. No axis is lowered, and none // needs to be: a report's `chart.xAxis`/`chart.yAxis` are bare @@ -215,6 +217,12 @@ export interface DatasetDrillArgs { * would mis-filter — without re-fetching the dataset definition. */ objectFilter?: Record; + /** + * The object fields the clicked number stands for — the bucket's grouped + * fields and the measure's aggregated ones — which the drill list shows + * after the record's name (objectstack-ai/objectstack#36256). + */ + fields?: string[]; } /** A report (or joined block) bound to a dataset. Field access is permissive — */ @@ -921,6 +929,75 @@ function resolveRelationshipDrill( ); } +/** + * Drill one clicked bucket — a table line or a chart mark — to its records: + * the exact field-to-stored-value filter when the answer names its `object` + * (a relationship path resolved first), else the host's `groupKey` fallback. + * One function for both, so a bar and the table line it stands for open the + * same list (objectstack-ai/objectstack#36256). `fields` names the grouped + * and measured fields the drill list shows by default. + */ +function emitBucketDrill({ + state, + dataset, + groupKey, + drillDims, + rawRow, + rowRanges, + scope, + runtimeFilter, + dataSource, + onDrill, +}: { + state: { object?: string; dimensionFields?: Record }; + dataset: string; + groupKey: Record; + drillDims: string[]; + rawRow: Record | undefined; + rowRanges: Record | undefined; + scope: MeasureDrillScope; + runtimeFilter: Record | undefined; + dataSource: unknown; + onDrill: (args: DatasetDrillArgs) => void; +}): void { + const hasRange = !!rowRanges && Object.keys(rowRanges).length > 0; + const fields = Array.from(new Set([ + // A relationship path shows its lookup field: the list draws no dotted column. + ...drillDims.map((d) => state.dimensionFields?.[d]).filter((f): f is string => !!f).map((f) => f.split('.')[0]), + ...Object.values(rowRanges ?? {}).map((range) => range.field.split('.')[0]), + ...measuredFieldsOf(scope), + ])); + if (state.object && datasetDrillHasRelationshipPath(drillDims, state.dimensionFields)) { + const object = state.object; + resolveRelationshipDrill(object, scope, rawRow, drillDims, state.dimensionFields ?? {}, runtimeFilter, rowRanges, dataSource, (resolved) => + onDrill({ dataset, groupKey, runtimeFilter, object, objectFilter: resolved, ...(fields.length ? { fields } : {}) })); + return; + } + let objectFilter: Record | undefined; + if (state.object && (drillDims.length > 0 || hasRange)) { + const built = drillFilterOrRefusal(scope, rawRow, drillDims, state.dimensionFields ?? {}, runtimeFilter, rowRanges); + // Refused: no drill at all — see `drillFilterOrRefusal`. + if (built === null) return; + objectFilter = built; + } else if (Object.keys(scope).length > 0) { + // No exact bucket filter to carry the scope, and the host's groupKey + // fallback rebuilds the list from the bucket ALONE: no drill. + return; + } + onDrill({ dataset, groupKey, runtimeFilter, object: state.object, objectFilter, ...(fields.length ? { fields } : {}) }); +} + +/** + * The fields a measure scope says hold a value (`{ field: { $null: false } }`, + * which `drillScopes` writes for a measure over a field): the fields the + * clicked number aggregates. + */ +function measuredFieldsOf(scope: MeasureDrillScope): string[] { + return Object.entries(scope ?? {}) + .filter(([field, c]) => !field.startsWith('$') && !!c && typeof c === 'object' && (c as { $null?: unknown }).$null === false) + .map(([field]) => field); +} + function EmptyMeasures({ dataset }: { dataset: string }) { return (
@@ -1111,25 +1188,7 @@ function DatasetReportTable({ const rowRanges = members ? spanDrillRanges(members.map((i) => state.drillRanges?.[i])) : state.drillRanges?.[index]; - const hasRange = !!rowRanges && Object.keys(rowRanges).length > 0; - let objectFilter: Record | undefined; - if (state.object && datasetDrillHasRelationshipPath(drillDims, state.dimensionFields)) { - const object = state.object; - resolveRelationshipDrill(object, scope, state.drillRawRows?.[index], drillDims, state.dimensionFields ?? {}, runtimeFilter, rowRanges, dataSource, (resolved) => - onDrill!({ dataset, groupKey, runtimeFilter, object, objectFilter: resolved })); - return; - } - if (state.object && (drillDims.length > 0 || hasRange)) { - const built = drillFilterOrRefusal(scope, state.drillRawRows?.[index], drillDims, state.dimensionFields ?? {}, runtimeFilter, rowRanges); - // Refused: no drill at all — see `drillFilterOrRefusal`. - if (built === null) return; - objectFilter = built; - } else if (Object.keys(scope).length > 0) { - // No exact bucket filter to carry the scope, and the host's groupKey - // fallback rebuilds the list from the bucket ALONE: no drill. - return; - } - onDrill!({ dataset, groupKey, runtimeFilter, object: state.object, objectFilter }); + emitBucketDrill({ state, dataset, groupKey, drillDims, rawRow: state.drillRawRows?.[index], rowRanges, scope, runtimeFilter, dataSource, onDrill: onDrill! }); }; // objectui#7534 — resolve a BUILT-IN default measure's caption through the @@ -1435,7 +1494,7 @@ export function planReportChart(t: unknown): ReportChartPlan { */ function useRegistryComponent( type: string, -): React.ComponentType<{ schema: Record }> | undefined { +): React.ComponentType<{ schema: Record; onChartClick?: (event: ChartSegmentClickEvent) => void }> | undefined { const [, bump] = React.useReducer((x: number) => x + 1, 0); React.useEffect(() => { if (ComponentRegistry.get(type)) return; @@ -1452,7 +1511,7 @@ function useRegistryComponent( return unsub; }, [type]); return ComponentRegistry.get(type) as - | React.ComponentType<{ schema: Record }> + | React.ComponentType<{ schema: Record; onChartClick?: (event: ChartSegmentClickEvent) => void }> | undefined; } @@ -1548,6 +1607,7 @@ function DatasetReportChart({ dataSource, order, timeWindow, + onDrill, }: { dataset: string; chart: Record; @@ -1555,6 +1615,8 @@ function DatasetReportChart({ dataSource?: unknown; order?: SelectionOrder; timeWindow?: ReportTimeWindow; + /** The report's drill sink: a clicked mark drills like its table line (objectstack-ai/objectstack#36256). */ + onDrill?: (args: DatasetDrillArgs) => void; }) { const xAxis = typeof chart.xAxis === 'string' ? chart.xAxis : ''; const yAxis = typeof chart.yAxis === 'string' ? chart.yAxis : ''; @@ -1851,6 +1913,36 @@ function DatasetReportChart({ // itself — not spec `ChartAxis` objects, so there is no axis presentation to // merge. (`@object-ui/core`'s object-axis lowering, `mergeAuthoredPresentation`, // was deliberately not used here and was removed by objectui#11372.) + // objectstack-ai/objectstack#36256 — a mark drills to the records its + // bucket counted, through the table's own `emitBucketDrill`, so a bar and + // its summary line open the same list. A measure the answer gives no record + // list (`drillScopes`) offers no click. + const markScope: MeasureDrillScope | undefined = state.object ? measureDrillScope(state.drillScopes, yAxis) : {}; + const handleMarkClick = onDrill && markScope !== undefined + ? (ev: ChartSegmentClickEvent) => { + const at = findChartSeriesRow(plotRows, queryDimensions, [yAxis], ev?.category, ev?.series, { + nullCategoryLabel, + bucketId: ev?.categoryId, + }); + if (at < 0) return; + const index = plotLayout ? plotLayout[at] : at; + const groupKey: Record = {}; + for (const dim of queryDimensions) groupKey[dim] = displayRows[index]?.[dim]; + emitBucketDrill({ + state, + dataset, + groupKey, + drillDims: state.dimensionFields ? queryDimensions.filter((d) => d in state.dimensionFields!) : [], + rawRow: state.drillRawRows?.[index], + rowRanges: state.drillRanges?.[index], + scope: markScope, + runtimeFilter, + dataSource, + onDrill, + }); + } + : undefined; + const authoredSeries = mergeAuthoredSeries(derivedSeries, chart.series); // #4020's three-level display name OUTRANKS both of the labels above: the // derivation's `fields[].label` (level ② without the i18n field-label @@ -1922,6 +2014,7 @@ function DatasetReportChart({ // chart's own default (value-descending) still applies. ...(categoryOrder ? { categoryOrder } : {}), }} + onChartClick={handleMarkClick} />
); @@ -2555,6 +2648,7 @@ const DatasetReportRendererBody: React.FC = ({ dataSource={dataSource} order={reportOrder} timeWindow={timeWindow} + onDrill={drillSink} /> ) : null; diff --git a/ui/packages/plugin-report/src/__tests__/DatasetReportRenderer.chartMarkDrill-36256.test.tsx b/ui/packages/plugin-report/src/__tests__/DatasetReportRenderer.chartMarkDrill-36256.test.tsx new file mode 100644 index 00000000000..6ea75537227 --- /dev/null +++ b/ui/packages/plugin-report/src/__tests__/DatasetReportRenderer.chartMarkDrill-36256.test.tsx @@ -0,0 +1,96 @@ +/** + * objectstack-ai/objectstack#36256 item 2 — a report's chart mark drills, and + * a bar opens the same records as the summary line it stands for: both go + * through one drill builder, with the same object filter and the same default + * fields (the grouped field and the measured one). + */ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { render, screen, fireEvent, waitFor, cleanup, act } from '@testing-library/react'; +import { ComponentRegistry } from '@object-ui/core'; +import { DatasetReportRenderer } from '../DatasetReportRenderer'; + +let chartProps: Record | null = null; + +function makeSource() { + return { + queryDataset: vi.fn(async () => ({ + rows: [{ stage: 'Negotiation', total_amount: 30 }, { stage: 'Prospecting', total_amount: 10 }], + object: 'opportunity', + dimensionFields: { stage: 'stage' }, + drillRawRows: [{ stage: 'negotiation' }, { stage: 'prospecting' }], + drillScopes: { total_amount: { amount: { $null: false } } }, + })), + }; +} + +beforeEach(() => { + chartProps = null; + vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, json: async () => ({}) }))); + ComponentRegistry.register('chart', (props: any) => { + chartProps = props; + return null; + }); +}); +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +const report = { + name: 'opps_by_stage', + type: 'summary', + dataset: 'opportunity_metrics', + rows: ['stage'], + values: ['total_amount'], + chart: { type: 'bar', xAxis: 'stage', yAxis: 'total_amount' }, +}; + +describe('a report chart mark drills like its table line (#36256)', () => { + it('emits the same drill for the bar and the summary line', async () => { + const onDrill = vi.fn(); + render(); + await waitFor(() => expect(chartProps?.onChartClick).toBeTypeOf('function')); + act(() => chartProps!.onChartClick({ category: 'Negotiation', series: 'total_amount' })); + + const rows = await screen.findAllByTestId('dataset-drill-row'); + fireEvent.click(rows.find((r) => r.textContent?.includes('Negotiation'))!); + + expect(onDrill).toHaveBeenCalledTimes(2); + const [bar, line] = onDrill.mock.calls.map((c) => c[0]); + expect(bar.object).toBe('opportunity'); + expect(bar.objectFilter).toEqual(line.objectFilter); + expect(JSON.stringify(bar.objectFilter)).toContain('negotiation'); + expect(bar.fields).toEqual(['stage', 'amount']); + expect(line.fields).toEqual(bar.fields); + }); + + it("a relationship-path bucket drills on the nested condition with its lookup field as the column", async () => { + const onDrill = vi.fn(); + const pathSource = { + queryDataset: vi.fn(async () => ({ + rows: [{ industry: 'Technology', total_amount: 30 }], + object: 'opportunity', + dimensionFields: { industry: 'crm_account.industry' }, + drillRawRows: [{ industry: 'technology' }], + drillScopes: { total_amount: { amount: { $null: false } } }, + })), + find: vi.fn(async () => ({ data: [] })), + getObjectSchema: vi.fn(async (object: string) => (object === 'opportunity' + ? { fields: { crm_account: { type: 'lookup', reference: 'crm_account' }, amount: { type: 'currency' } } } + : { fields: { industry: { type: 'select' } } })), + }; + render(); + fireEvent.click(await screen.findByTestId('dataset-drill-row')); + await waitFor(() => expect(onDrill).toHaveBeenCalled()); + const [args] = onDrill.mock.calls[0]; + expect(JSON.stringify(args.objectFilter)).toContain('{"crm_account":{"industry":"technology"}}'); + expect(args.fields).toEqual(['crm_account', 'amount']); + }); + + it('offers no click when the report turns drill off', async () => { + render(); + await waitFor(() => expect(chartProps).not.toBeNull()); + expect(chartProps!.onChartClick).toBeUndefined(); + }); +}); diff --git a/ui/packages/plugin-report/src/__tests__/DatasetReportRenderer.summarySubtotals-27975.test.tsx b/ui/packages/plugin-report/src/__tests__/DatasetReportRenderer.summarySubtotals-27975.test.tsx index fa3244b08ba..122ad286737 100644 --- a/ui/packages/plugin-report/src/__tests__/DatasetReportRenderer.summarySubtotals-27975.test.tsx +++ b/ui/packages/plugin-report/src/__tests__/DatasetReportRenderer.summarySubtotals-27975.test.tsx @@ -296,6 +296,8 @@ describe('summary report subtotals (objectstack-ai/objectstack#27975)', () => { runtimeFilter: undefined, object: 'opportunity', objectFilter: { owner_id: 'usr_amy' }, + // objectstack-ai/objectstack#36256 — the grouped field the drill list shows. + fields: ['owner_id'], }); }); diff --git a/ui/packages/react/src/context/DrillNavigationContext.tsx b/ui/packages/react/src/context/DrillNavigationContext.tsx index 3cbc890f4f4..dec928276b1 100644 --- a/ui/packages/react/src/context/DrillNavigationContext.tsx +++ b/ui/packages/react/src/context/DrillNavigationContext.tsx @@ -63,6 +63,21 @@ export interface DrillNavigationValue { * destination, which is how a host behaved before this member existed. */ canOpenRecordList?: (objectName: string, filter?: Record) => boolean; + /** + * Open one drilled record's full page (objectstack-ai/objectstack#36256): + * the drill list's record name calls it. `origin` is the drill list the + * page came from: the ids of the rows it shows, in order, which the page + * steps through with ↑ ↓ under its 「N of M」 counter, and the count it + * matched. The host makes the page it opened from (the dashboard, the + * report) the page's way back. Absent ⇒ the drill opens the record in a dialog. + */ + openRecord?: (objectName: string, recordId: string, origin?: DrillRecordOrigin) => void; +} + +/** The drill list a record page was opened from — see {@link DrillNavigationValue.openRecord}. */ +export interface DrillRecordOrigin { + siblings: readonly string[]; + total?: number; } export const DrillNavigationContext = createContext({});