diff --git a/.changeset/36897-list-objectgrid.md b/.changeset/36897-list-objectgrid.md new file mode 100644 index 00000000000..cde12ec6b63 --- /dev/null +++ b/.changeset/36897-list-objectgrid.md @@ -0,0 +1,13 @@ +--- +'@object-ui/plugin-grid': patch +'@object-ui/app-shell': patch +--- + +feat(app-shell): every metadata type's list is drawn by ObjectGrid, and its New on a read-only base creates in the base's paired `.custom` package + +Clause-②: yes (widening) +Metadata-protocol: none + +- `@object-ui/plugin-grid`: `ObjectGrid` takes two generic host props for its table view — `hostCells` (a host draws a column's cells) and `rowTint` (a palette name per row, over `rowColor`). +- `@object-ui/app-shell`: the metadata list (Setup and Studio's All metadata area) is an `ObjectGrid` fed a declared schema and the page's rows in the list's own order; diagnostics tint, lock, the Active switch, Clone, the served columns and the 「修改时间」 column (its time, its unpublished-changes mark and its `changed` sort, objectstack#36898) are the page's cells; sort, search and page live in the address. The grid's personal columns, export, selection and inline edit are off for it. +- On a read-only base in Studio, the list's New creates in the paired `.custom` package (ADR-0146 D3): an object (with its organization-wide sharing default) and a flow (from a starting point) open the list's create dialog; another type opens the area's create in the pair. Under the customization wall no New is offered. diff --git a/ui/e2e/live/declared-sharing-rules-reach-13091.spec.ts b/ui/e2e/live/declared-sharing-rules-reach-13091.spec.ts index 5d5b27acfed..b2bcfe76aff 100644 --- a/ui/e2e/live/declared-sharing-rules-reach-13091.spec.ts +++ b/ui/e2e/live/declared-sharing-rules-reach-13091.spec.ts @@ -10,8 +10,8 @@ import { test, expect, type Locator } from '@playwright/test'; * - the first Clone button and the first Active switch both lie wholly inside * the viewport AND inside the visible box of the table's scroller, with the * table not scrolled at all; - * - when the table is wider than its box, the box says so - * (`data-overflow-right`, which drives the seam shadow on the pinned cells). + * - when the table is wider than its box, the grid draws its seam shadow at + * the pinned cells (objectstack#36897: the list is drawn by ObjectGrid). * * The unit pins for the same page are in * `ResourceListPage.declaredSharingRules-12982.test.tsx`. @@ -30,9 +30,10 @@ test.use({ viewport: { width: 1440, height: 1000 } }); test('at 1440 px, Clone and the Active switch are inside the viewport and the table box', async ({ page }) => { await page.goto(LIST); - // The table's own scroll box, found by structure rather than by a test id, - // so the measurement reads the same element before and after the fix. - const scroller = page.locator('table').first().locator('xpath=..'); + // The table's own scroll box. objectstack#36897 — the list is drawn by + // ObjectGrid, whose table box marks itself (`data-table-scroll-box`); the + // table's parent is no longer the element that scrolls. + const scroller = page.locator('[data-table-scroll-box]').first(); await expect(scroller).toBeVisible(); const clone = page.locator('[data-testid^="catalog-clone-"]').first(); const active = page.locator('[data-testid^="catalog-active-"]').first(); @@ -50,9 +51,9 @@ test('at 1440 px, Clone and the Active switch are inside the viewport and the ta expect(b.x + b.width, `${what} ends inside the table box`).toBeLessThanOrEqual(frame.x + frame.width + 0.5); } - // The box reports its overflow, which is what draws the seam shadow. + // While columns remain to the right, the grid draws its seam shadow. const widths = await scroller.evaluate((el) => ({ scroll: el.scrollWidth, client: el.clientWidth })); if (widths.scroll > widths.client + 1) { - await expect(scroller).toHaveAttribute('data-overflow-right', 'true'); + await expect(page.getByTestId('data-table-scroll-shadow-right').first()).toBeVisible(); } }); diff --git a/ui/packages/app-shell/src/views/metadata-admin/MetadataListCreateDialog.pairCreate-36897.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/MetadataListCreateDialog.pairCreate-36897.test.tsx new file mode 100644 index 00000000000..dfbd1b91204 --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/MetadataListCreateDialog.pairCreate-36897.test.tsx @@ -0,0 +1,140 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36897 — the metadata list's 「新建」 for an object and a flow. + * + * - On a read-only base the item is written to the pair the ensure door + * answers (ADR-0146 D3), never to the base, and an object does not try to + * join an app menu (the pair has no app). On a writable package — the + * control — the door is never knocked on, the item is written to the list's + * package and the object joins the menu. + * - The object carries the organization-wide default it was given. + * - A flow is created from a starting point; one that watches an object + * writes nothing until it has one. + */ + +// Paid at collection, not inside a case's clock (check:test-source-alias). +import '@objectstack/lint'; +import '@testing-library/jest-dom/vitest'; +import * as React from 'react'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; + +const save = vi.fn(async (..._args: unknown[]) => ({})); +vi.mock('./useMetadata', async (importOriginal) => ({ + ...(await importOriginal>()), + useMetadataClient: () => ({ save }), +})); + +const ensure = vi.fn(async (baseId: string) => ({ + basePackageId: baseId, + packageId: `${baseId}.custom`, + namespace: 'hrx', + created: true, + writable: true, +})); +vi.mock('../studio-design/packages-io.js', async (importOriginal) => ({ + ...(await importOriginal>()), + ensureCustomizationPackage: (baseId: string) => ensure(baseId), + fetchPackages: async () => [ + { id: 'com.vendor.hr', namespace: 'hr' }, + { id: 'com.example.crm', namespace: 'crm' }, + ], +})); +const publish = vi.fn(async () => ({ ok: true })); +vi.mock('../studio-design/studioSaveBar.js', async (importOriginal) => ({ + ...(await importOriginal>()), + publishSavedItem: (...args: unknown[]) => publish(...(args as [])), +})); +vi.mock('../studio-design/StudioPillarKit.js', async (importOriginal) => ({ + ...(await importOriginal>()), + findTakenIdentifier: async () => null, +})); +const joinMenu = vi.fn(async () => ({ kind: 'joined' })); +vi.mock('../studio-design/newObjectJoinsAppMenu.js', async (importOriginal) => ({ + ...(await importOriginal>()), + addNewObjectToAppMenu: (...args: unknown[]) => joinMenu(...(args as [])), +})); + +import { MetadataListCreateDialog } from './MetadataListCreateDialog'; +import { t } from './i18n'; + +afterEach(() => { + cleanup(); + vi.clearAllMocks(); +}); + +const L = 'en-US' as const; + +function open(type: 'object' | 'flow', packageId: string, inPair: boolean) { + const onCreated = vi.fn(); + render( + {}} + packageId={packageId} + inPair={inPair} + locale={L} + onCreated={onCreated} + />, + ); + return onCreated; +} + +function fill(labelKey: string, idKey: string, label: string, id: string) { + fireEvent.change(screen.getByLabelText(t(labelKey, L)), { target: { value: label } }); + fireEvent.change(screen.getByLabelText(t(idKey, L)), { target: { value: id } }); + fireEvent.click(screen.getByRole('button', { name: t('engine.studio.createLive', L) })); +} + +describe('list 「新建」 lands in the paired .custom package on a read-only base (objectstack#36897)', () => { + it('an object on a read-only base: the ensure door is asked, the pair is written, its namespace names it, no menu join', async () => { + const onCreated = open('object', 'com.vendor.hr', true); + fireEvent.keyDown(screen.getByTestId('create-object-owd'), { key: 'ArrowDown' }); + fireEvent.click(await screen.findByRole('option', { name: t('engine.studio.settings.sharingPublicRead', L) })); + fill('engine.studio.data.nameLabel', 'engine.studio.data.idLabel', 'Leave request', 'leave_request'); + await waitFor(() => expect(onCreated).toHaveBeenCalled()); + expect(ensure).toHaveBeenCalledWith('com.vendor.hr'); + expect(save).toHaveBeenCalledTimes(1); + const [type, name, body, opts] = save.mock.calls[0] as unknown as [string, string, any, any]; + expect([type, name]).toEqual(['object', 'hrx_leave_request']); + expect(opts).toMatchObject({ mode: 'draft', packageId: 'com.vendor.hr.custom', ifNoneMatch: '*' }); + expect(body).toHaveProperty('sharingModel', 'public_read'); + expect(publish).toHaveBeenCalledWith(expect.anything(), { type: 'object', name: 'hrx_leave_request', packageId: 'com.vendor.hr.custom' }, false); + expect(onCreated).toHaveBeenCalledWith({ name: 'hrx_leave_request', packageId: 'com.vendor.hr.custom' }); + expect(joinMenu).not.toHaveBeenCalled(); + }); + + it('CONTROL — an object in a writable package: no ensure, the list package is written and the object joins its menu', async () => { + const onCreated = open('object', 'com.example.crm', false); + fill('engine.studio.data.nameLabel', 'engine.studio.data.idLabel', 'Lead', 'lead'); + await waitFor(() => expect(onCreated).toHaveBeenCalledWith({ name: 'crm_lead', packageId: 'com.example.crm' })); + expect(ensure).not.toHaveBeenCalled(); + expect(save.mock.calls[0]?.[3]).toMatchObject({ packageId: 'com.example.crm' }); + await waitFor(() => expect(joinMenu).toHaveBeenCalledTimes(1)); + }); + + it('a flow on a read-only base: from a starting point, written to the pair, born off', async () => { + const onCreated = open('flow', 'com.vendor.hr', true); + fireEvent.click(screen.getByTestId('create-flow-preset-manual')); + fill('engine.studio.auto.nameLabel', 'engine.studio.auto.idLabel', 'Escalate', 'escalate'); + await waitFor(() => expect(onCreated).toHaveBeenCalledWith({ name: 'escalate', packageId: 'com.vendor.hr.custom' })); + expect(ensure).toHaveBeenCalledWith('com.vendor.hr'); + const [type, , body, opts] = save.mock.calls[0] as unknown as [string, string, any, any]; + expect(type).toBe('flow'); + expect(opts).toMatchObject({ packageId: 'com.vendor.hr.custom' }); + expect(body.status).toBe('obsolete'); + expect(JSON.stringify(body)).toContain('"triggerType":"manual"'); + }); + + it('a starting point that watches an object writes nothing until it has one', async () => { + const onCreated = open('flow', 'com.vendor.hr', true); + fireEvent.click(screen.getByTestId('create-flow-preset-record_created')); + fill('engine.studio.auto.nameLabel', 'engine.studio.auto.idLabel', 'On hire', 'on_hire'); + expect(await screen.findByText(t('engine.studio.auto.preset.needsObject', L))).toBeInTheDocument(); + expect(ensure).not.toHaveBeenCalled(); + expect(save).not.toHaveBeenCalled(); + expect(onCreated).not.toHaveBeenCalled(); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/MetadataListCreateDialog.tsx b/ui/packages/app-shell/src/views/metadata-admin/MetadataListCreateDialog.tsx new file mode 100644 index 00000000000..4d8f1fe4389 --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/MetadataListCreateDialog.tsx @@ -0,0 +1,380 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The metadata list's 「新建」 for an object and a flow (objectstack#36897, + * epic objectstack#36890): the create the Data and Automations pillars offer, + * offered from the list, so the designers can give up their own. + * + * - The item is created in the list's package, or — on a read-only base — in + * the base's paired `.custom` package, which the ensure door answers + * (`ensureCustomizationPackage`, ADR-0146 D3): its id, and for an object + * its namespace, come from that answer, never from a spelling here. + * - An object asks for its record sharing (the organization-wide default, + * `OWD_CREATE_MODELS`), and once live joins the menu of its package's one + * app (`addNewObjectToAppMenu`); not in a pair, whose package has no app. + * - A flow opens on the starting points (`flowPresets.ts`), with the Start + * node's whole trigger list under Advanced; it is born switched off. + * + * Both are written as a draft under the first-write pin and published at + * once, as the pillars write them (`publishSavedItem`); a name already taken + * is refused before anything is written (`findTakenIdentifier`). + */ + +import * as React from 'react'; +import { toast } from 'sonner'; +import { customizationNamespace } from '@objectstack/spec/kernel'; + +import { CreateItemDialog } from '../studio-design/CreateItemDialog.js'; +import { CreateTakenNotice, findTakenIdentifier } from '../studio-design/StudioPillarKit.js'; +import { StudioPicker } from '../studio-design/StudioPicker.js'; +import { OWD_CREATE_MODELS, OWD_DEFAULT, type OwdCreateModel } from '../studio-design/owd-sharing.js'; +import { OWD_OPTION_DESC_KEY, OWD_OPTION_LABEL_KEY } from '../studio-design/DataPillarHelpers.js'; +import { buildFlowSkeleton, buildObjectSkeleton } from '../studio-design/skeletons.js'; +import { ensureCustomizationPackage, fetchPackages, prefixObjectName } from '../studio-design/packages-io.js'; +import { publishSavedItem } from '../studio-design/studioSaveBar.js'; +import { plainRefusal, type StudioRefusal } from '../studio-design/metadataError.js'; +import { addNewObjectToAppMenu } from '../studio-design/newObjectJoinsAppMenu.js'; +import { FLOW_PRESETS, flowPresetTrigger, type FlowPreset } from '../studio-design/flowPresets.js'; +import { newFlowTriggerFields, withStartTrigger, type NewFlowTrigger } from '../studio-design/AutomationsFlowRail.js'; +import { ObjectPicker } from './inspectors/ObjectPicker.js'; +import { navItemLabelText } from './previews/navItemLabel.js'; +import { useMetadataClient } from './useMetadata.js'; +import { t, tFormat, type SupportedLocale } from './i18n.js'; + +/** The types whose list 「新建」 opens this dialog. */ +export const LIST_CREATE_DIALOG_TYPES: readonly string[] = ['object', 'flow']; + +export interface MetadataListCreateDialogProps { + type: string; + open: boolean; + onOpenChange: (open: boolean) => void; + /** The list's package. */ + packageId: string; + /** The package is a read-only base: the item lands in its `.custom` pair. */ + inPair: boolean; + locale: SupportedLocale; + /** The item is live: where it was created. */ + onCreated: (created: { name: string; packageId: string }) => void; +} + +type Taken = { name: string; label: string }; + +export function MetadataListCreateDialog(props: MetadataListCreateDialogProps): React.ReactElement | null { + if (props.type === 'object') return ; + if (props.type === 'flow') return ; + return null; +} + +/** + * Where the item is written: the pair the ensure door answers on a read-only + * base, else the list's package — with its namespace read now when the + * dialog's preview read has not answered yet, so a quick submit is not + * written unprefixed. + */ +async function createTarget(packageId: string, inPair: boolean, namespace: string | null | undefined) { + if (!inPair) { + const ns = namespace !== undefined ? namespace : ((await fetchPackages()).find((p) => p.id === packageId)?.namespace ?? null); + return { packageId, namespace: ns }; + } + const pair = await ensureCustomizationPackage(packageId); + return { packageId: pair.packageId, namespace: pair.namespace }; +} + +function ObjectCreate({ open, onOpenChange, packageId, inPair, locale, onCreated }: MetadataListCreateDialogProps) { + const client = useMetadataClient(); + const [owd, setOwd] = React.useState(OWD_DEFAULT); + const [busy, setBusy] = React.useState(false); + const [error, setError] = React.useState(null); + const [taken, setTaken] = React.useState(null); + // The package's object-name namespace (framework#2694): the dialog previews + // the stored name; on a read-only base the pair's, by the spec's pairing + // rule, while the save prefixes with the namespace the ensure door answers. + // `undefined` while the read has not answered. + const [namespace, setNamespace] = React.useState(undefined); + React.useEffect(() => { + if (!open) return; + let cancelled = false; + setOwd(OWD_DEFAULT); + setError(null); + setTaken(null); + setNamespace(undefined); + fetchPackages() + .then((list) => { + if (!cancelled) setNamespace(list.find((p) => p.id === packageId)?.namespace ?? null); + }) + .catch(() => { + // Best-effort preview: the save names the namespace it writes with. + }); + return () => { + cancelled = true; + }; + }, [open, packageId]); + const pairNamespace = customizationNamespace(namespace ?? null); + const previewNamespace = inPair ? (pairNamespace.ok ? pairNamespace.value : null) : (namespace ?? null); + + const create = async (label: string, rawName: string) => { + setBusy(true); + setError(null); + setTaken(null); + try { + const target = await createTarget(packageId, inPair, namespace); + const name = prefixObjectName(rawName, target.namespace); + const held = await findTakenIdentifier(client, 'object', name, locale); + if (held) { + setTaken(held); + return; + } + const body = buildObjectSkeleton(name, label, t('engine.studio.data.nameFieldLabel', locale), owd); + await client.save('object', name, body, { mode: 'draft', packageId: target.packageId, ifNoneMatch: '*', surface: 'studio' }); + const live = await publishSavedItem(client, { type: 'object', name, packageId: target.packageId }, false); + if (!live.ok) { + setError(plainRefusal(live.error)); + return; + } + toast.success(tFormat('engine.studio.save.done', locale, { items: label })); + onCreated({ name, packageId: target.packageId }); + // objectstack#36748 — and it joins the menu of its package's one app; a + // failure keeps the object and says the menu was left as it was. + if (!inPair) { + const join = await addNewObjectToAppMenu( + client as unknown as Parameters[0], + { packageId: target.packageId, objectName: name }, + { + notListed: t('engine.studio.data.appMenu.unreadable', locale), + pendingDraft: t('engine.studio.data.appMenu.pendingDraft', locale), + noVersion: t('engine.studio.data.appMenu.unreadable', locale), + notWritable: t('engine.studio.data.appMenu.unreadable', locale), + }, + ); + if (join.kind === 'failed') { + const reason = plainRefusal(join.error).message; + toast.warning( + join.app + ? tFormat('engine.studio.data.appMenu.failed', locale, { + object: label, + app: navItemLabelText(join.app.label, locale) || join.app.name, + reason, + }) + : tFormat('engine.studio.data.appMenu.failedNoApp', locale, { object: label, reason }), + ); + } + } + } catch (e) { + setError(plainRefusal(e)); + } finally { + setBusy(false); + } + }; + + return ( + prefixObjectName(identifier, previewNamespace)} + extra={ + <> + {taken && ( + + )} + {/* The object's record sharing (OWD): without it the object is + refused at publish by `security-owd-unset`. The gloss is the + Settings tab's own string for each model. */} + + + } + onSubmit={({ label, name }) => void create(label, name)} + /> + ); +} + +function FlowCreate({ open, onOpenChange, packageId, inPair, locale, onCreated }: MetadataListCreateDialogProps) { + const client = useMetadataClient(); + const startTrigger = React.useMemo(() => newFlowTriggerFields(locale), [locale]); + const watchesObject = startTrigger.object?.showWhen?.equals ?? []; + const [choice, setChoice] = React.useState(FLOW_PRESETS[0]); + const [trigger, setTrigger] = React.useState(''); + const [triggerObject, setTriggerObject] = React.useState(''); + const [needs, setNeeds] = React.useState(null); + const [busy, setBusy] = React.useState(false); + const [error, setError] = React.useState(null); + const [taken, setTaken] = React.useState(null); + const group = React.useId(); + React.useEffect(() => { + if (!open) return; + setChoice(FLOW_PRESETS[0]); + setTrigger(''); + setTriggerObject(''); + setNeeds(null); + setError(null); + setTaken(null); + }, [open]); + + const create = async (label: string, name: string, start: NewFlowTrigger | null) => { + setBusy(true); + setError(null); + setTaken(null); + try { + const held = await findTakenIdentifier(client, 'flow', name, locale); + if (held) { + setTaken(held); + return; + } + // Born switched off (`obsolete`, what the switch writes for Off): + // enabling it is the author's own flip. + const skeleton = withStartTrigger( + { + ...buildFlowSkeleton(name, label, t('engine.studio.auto.nodeStart', locale), t('engine.studio.auto.nodeEnd', locale)), + status: 'obsolete', + }, + start, + ); + const target = await createTarget(packageId, inPair, null); + await client.save('flow', name, skeleton, { mode: 'draft', packageId: target.packageId, ifNoneMatch: '*', surface: 'studio' }); + const live = await publishSavedItem(client, { type: 'flow', name, packageId: target.packageId }, false); + if (!live.ok) { + setError(plainRefusal(live.error)); + return; + } + toast.success(tFormat('engine.studio.auto.createdOff', locale, { name: label })); + onCreated({ name, packageId: target.packageId }); + } catch (e) { + setError(plainRefusal(e)); + } finally { + setBusy(false); + } + }; + + const objectPicker = (onCommit: (v: string) => void) => + startTrigger.object && ( + + ); + + return ( + + {taken && ( + + )} +
+ {t('engine.studio.auto.presets', locale)} + {FLOW_PRESETS.map((p) => ( +
+ + {choice === p && watchesObject.includes(p.triggerType) && ( +
+ {objectPicker((v) => { + setTriggerObject(v); + setNeeds(null); + })} +
+ )} +
+ ))} +
+ + {/* The Start node's own trigger field: the same choices and labels. */} + {choice === 'advanced' && startTrigger.trigger && ( +
+ + {trigger && watchesObject.includes(trigger) && objectPicker(setTriggerObject)} +
+ )} +
+
+ + } + onSubmit={({ label, name }) => { + if (choice === 'advanced') { + const object = watchesObject.includes(trigger) ? triggerObject.trim() : ''; + void create(label, name, trigger ? { triggerType: trigger, ...(object ? { objectName: object } : {}) } : null); + return; + } + // A preset: its trigger, or nothing sent while it waits for its object. + const start = flowPresetTrigger(choice, watchesObject, triggerObject); + if (!start) { + setNeeds(t('engine.studio.auto.preset.needsObject', locale)); + return; + } + void create(label, name, start); + }} + /> + ); +} diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.bundleMember-26649.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.bundleMember-26649.test.tsx index c3e94420e58..0d20919e548 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.bundleMember-26649.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.bundleMember-26649.test.tsx @@ -20,6 +20,8 @@ * - a row that declares no member (the canonical one) links by its name alone; * - CONTROL: a type with no members gets no column and no `?member=`. */ +// Paid at collection, not inside a case's clock (check:test-source-alias). +import '@objectstack/lint'; import { describe, it, expect, vi, afterEach } from 'vitest'; import { render, cleanup, screen, within } from '@testing-library/react'; import '@testing-library/jest-dom'; @@ -88,6 +90,9 @@ function queryOf(href: string): URLSearchParams { return new URLSearchParams(q === -1 ? '' : href.slice(q + 1)); } +/** The table row of `el`'s first cell: the row's test id sits there, and `ObjectGrid` draws the row (objectstack#36897). */ +const trOf = (el: HTMLElement) => el.closest('tr') as HTMLElement; + describe('Setup list: each bundle member opens itself (objectstack#26649)', () => { it('two members of one template are two rows whose links differ by ?member=, keeping the scope', async () => { mount('email_template', '?scope=environment'); @@ -117,7 +122,7 @@ describe('Setup list: each bundle member opens itself (objectstack#26649)', () = const headers = screen.getAllByRole('columnheader').map((h) => h.textContent?.trim()); expect(headers[1]).toBe(t('engine.list.col.locale', 'en-US')); expect(t('engine.list.col.locale', 'en-US')).toBe('Locale'); - const [enRow, zhRow] = screen.getAllByTestId('metadata-row-duly.task_overdue'); + const [enRow, zhRow] = screen.getAllByTestId('metadata-row-duly.task_overdue').map(trOf); expect(within(enRow!).getAllByRole('cell')[1]).toHaveTextContent('en'); expect(within(zhRow!).getAllByRole('cell')[1]).toHaveTextContent('zh-CN'); }); diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.changedColumn-36898.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.changedColumn-36898.test.tsx index c00c855dde7..77a25686921 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.changedColumn-36898.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.changedColumn-36898.test.tsx @@ -14,7 +14,7 @@ import '@testing-library/jest-dom/vitest'; import * as React from 'react'; import { describe, it, expect, vi, afterEach } from 'vitest'; -import { render, cleanup, screen, within } from '@testing-library/react'; +import { render, cleanup, screen, within, fireEvent } from '@testing-library/react'; import { MemoryRouter, Route, Routes } from 'react-router-dom'; // Dynamic imports the page's anchors and editors reach, paid at collection // rather than inside a case's clocked window. @@ -80,14 +80,17 @@ function mount(search = '') { ); } -const cellOf = (name: string) => within(screen.getByTestId(`metadata-row-${name}`)).getByTestId('metadata-changed-cell'); +/** The row of an item: its test id sits on the row's identity cell (objectstack#36897, the grid's table). */ +const rowOf = (name: string) => screen.getByTestId(`metadata-row-${name}`).closest('tr') as HTMLElement; +const findRowOf = async (name: string) => (await screen.findByTestId(`metadata-row-${name}`)).closest('tr') as HTMLElement; +const cellOf = (name: string) => within(rowOf(name)).getByTestId('metadata-changed-cell'); describe('the 「修改时间」 column (objectstack#36898)', () => { it('an item with a stored row shows its time; a code-shipped item an empty cell', async () => { mount(); await screen.findByRole('table'); expect(await screen.findByRole('columnheader', { name: 'Modified' })).toBeInTheDocument(); - const time = await within(screen.getByTestId('metadata-row-by_ai')).findByText( + const time = await within(rowOf('by_ai')).findByText( new Intl.DateTimeFormat('en-US', { dateStyle: 'medium', timeStyle: 'short' }).format(Date.parse(CHANGED_AT.by_ai)), ); expect(time.closest('time')).toHaveAttribute('dateTime', CHANGED_AT.by_ai); @@ -96,13 +99,23 @@ describe('the 「修改时间」 column (objectstack#36898)', () => { it('`?sort=-changed` draws newest first, the code-shipped item last', async () => { mount('&sort=-changed'); - await within(await screen.findByTestId('metadata-row-by_ai')).findByText(/2026/); + await within(await findRowOf('by_ai')).findByText(/2026/); const order = screen - .getAllByTestId(/^metadata-row-/) - .filter((el) => el.tagName === 'TR') - .map((tr) => tr.getAttribute('data-testid')); + .getAllByTestId(/^metadata-row-(?!api-name$|source$|lock$)/) + .map((cell) => cell.getAttribute('data-testid')); expect(order).toEqual(['metadata-row-by_ai', 'metadata-row-by_person', 'metadata-row-shipped']); }); + + it('objectstack#36897 — a click on the Modified header sorts by it: oldest first, the code-shipped item still last', async () => { + mount(); + await within(await findRowOf('by_ai')).findByText(/2026/); + fireEvent.click(screen.getByRole('columnheader', { name: 'Modified' })); + await vi.waitFor(() => + expect( + screen.getAllByTestId(/^metadata-row-(?!api-name$|source$|lock$)/).map((cell) => cell.getAttribute('data-testid')), + ).toEqual(['metadata-row-by_person', 'metadata-row-by_ai', 'metadata-row-shipped']), + ); + }); }); describe('the 「有未发布的改动」 mark (objectstack#36898)', () => { @@ -125,7 +138,7 @@ describe('the 「有未发布的改动」 mark (objectstack#36898)', () => { it('an item off the ledger — published — carries no mark (control)', async () => { mount(); await screen.findByRole('table'); - await within(screen.getByTestId('metadata-row-by_ai')).findByText(/2026/); + await within(rowOf('by_ai')).findByText(/2026/); expect(screen.queryByTestId('metadata-draft-mark')).toBeNull(); }); }); diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.declaredSharingRules-12982.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.declaredSharingRules-12982.test.tsx index abdb321dfd6..d2ed603a694 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.declaredSharingRules-12982.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.declaredSharingRules-12982.test.tsx @@ -27,13 +27,17 @@ * projection served) continues in the pre-filled New form; * - the control: the permission-set catalog keeps its create affordance and * shows no Clone column; - * - objectui#13091: the row's controls (the Active switch, Clone) are pinned - * to the right edge of the table's overflow box, which draws the seam + * - objectui#13091: the row's controls (the Active switch, Clone) are pinned, + * in one cell since objectstack#36897 put the list on `ObjectGrid`, to the + * right edge of the table's overflow box, which draws the seam * shadow, so a 1440 or 1024 screen reaches them (the measured reach is * `e2e/live/declared-sharing-rules-reach-13091.spec.ts`); and a principal * the ledger read refuses reads a plain-language state, with the server's * own sentence for why, never a bare "?". */ +// Paid at collection, not inside a case's clock (check:test-source-alias). +import '@objectstack/lint'; +import '@object-ui/plugin-detail'; import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'; import { render, cleanup, screen, waitFor, fireEvent, within } from '@testing-library/react'; import '@testing-library/jest-dom'; @@ -448,37 +452,27 @@ describe("the row's controls stay in reach on a narrow screen (objectui#13091)", /** The cell (`td` / `th`) holding `el`. */ const cellOf = (el: Element) => el.closest('td, th') as HTMLElement; - it('Clone and the Active switch sit in cells pinned to the right edge of the overflow box', async () => { + it('Clone and the Active switch share the one cell pinned to the right edge of the table (objectstack#36897)', async () => { mount(); const clone = cellOf(await screen.findByTestId(`catalog-clone-${KEY}`)); const active = cellOf(await screen.findByTestId(`catalog-active-${KEY}`)); const scroller = screen.getByTestId('metadata-list-scroller'); expect(scroller).toContainElement(clone); - // Clone holds the right edge at its fixed width; Active sits just left of it. - expect(clone).toHaveClass('sticky', 'right-0', 'w-28'); - expect(active).toHaveClass('sticky', 'right-28'); - // The pinned pair is the row's trailing pair, Active then Clone. - const row = clone.parentElement!; - expect(row.lastElementChild).toBe(clone); - expect(clone.previousElementSibling).toBe(active); - // Their header cells are pinned the same way, so the column heads stay with them. + // The grid holds one column at its right edge: the row's controls are that + // column, its trailing cell. + expect(active).toBe(clone); + expect(clone).toHaveClass('sticky', 'right-0'); + expect(clone.parentElement!.lastElementChild).toBe(clone); + // Its header cell is pinned the same way, so the column head stays with it. const headers = Array.from(scroller.querySelectorAll('thead th')); expect(headers[headers.length - 1]).toHaveClass('sticky', 'right-0'); - expect(headers[headers.length - 2]).toHaveClass('sticky', 'right-28'); - // Separated borders: in a collapsed-border table Chrome lets the text - // scrolling beneath a sticky cell show through its edge (measured live). - expect(scroller.querySelector('table')).toHaveClass('border-separate', 'border-spacing-0'); + expect(headers[headers.length - 1]).toHaveTextContent(t('engine.catalog.col.active', ADMIN_LOCALE)); }); - it('the first pinned cell draws the seam shadow, and the box leaves the shadow to it', async () => { + it('the pinned cell draws the seam shadow', async () => { mount(); const active = cellOf(await screen.findByTestId(`catalog-active-${KEY}`)); - const clone = cellOf(screen.getByTestId(`catalog-clone-${KEY}`)); expect(active.className).toContain('group-data-[overflow-right=true]/hscroll:before:opacity-100'); - expect(clone.className).not.toContain('group-data-[overflow-right=true]/hscroll:before:opacity-100'); - // `seam="pinned"`: no edge overlay competes with the seam. - expect(screen.getByTestId('metadata-list-scroller')).toHaveClass('group/hscroll'); - expect(screen.queryByTestId('horizontal-overflow-shadow')).toBeNull(); }); it('without Clone, the Active column alone holds the right edge and draws the seam', async () => { diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.listStateInUrl-36896.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.listStateInUrl-36896.test.tsx index 642431c13c1..c900913cdec 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.listStateInUrl-36896.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.listStateInUrl-36896.test.tsx @@ -34,13 +34,20 @@ const SKILLS: Record[] = [ { name: 'tribute', label: 'Zeal tribute', _packageId: 'crm' }, ]; -const CLIENT = { list: async (type: string) => (type === 'skill' ? SKILLS : []) }; +/** More tools than one page of the table holds (objectstack#36897). */ +const TOOLS: Record[] = Array.from({ length: 53 }, (_, i) => ({ + name: `tool_${String(i + 1).padStart(2, '0')}`, + label: `Tool ${i + 1}`, +})); + +const CLIENT = { list: async (type: string) => (type === 'skill' ? SKILLS : type === 'tool' ? TOOLS : []) }; const SKILL_ENTRY = { type: 'skill', label: 'Skill', allowEnvironmentOverlay: false, allowRuntimeCreate: true }; +const TOOL_ENTRY = { type: 'tool', label: 'Tool', allowEnvironmentOverlay: false, allowRuntimeCreate: true }; vi.mock('./useMetadata', async (importOriginal) => ({ ...(await importOriginal>()), useMetadataClient: () => CLIENT, - useMetadataTypes: () => ({ loading: false, error: null, entries: [SKILL_ENTRY] }), + useMetadataTypes: () => ({ loading: false, error: null, entries: [SKILL_ENTRY, TOOL_ENTRY] }), })); vi.mock('./i18n', async (importOriginal) => ({ ...(await importOriginal>()), @@ -108,9 +115,8 @@ function mount(at: string) { async function rowNames(): Promise { await screen.findByRole('table'); return screen - .getAllByTestId(/^metadata-row-/) - .filter((el) => el.tagName === 'TR') - .map((tr) => tr.getAttribute('data-testid')!.replace('metadata-row-', '')); + .getAllByTestId(/^metadata-row-(?!api-name$|source$|lock$)/) + .map((el) => el.getAttribute('data-testid')!.replace('metadata-row-', '')); } describe('the metadata list keeps its state in its address (objectstack#36896)', () => { @@ -186,3 +192,42 @@ describe('the detail ‹ › order reads the list context (objectstack#36896)', expect(ordered).toHaveTextContent(''); }); }); + +/** + * objectstack#36897 — the list is drawn by `ObjectGrid`, fed the rows in the + * list's own order: what the table shows, in order, is what the detail's ‹ › + * step through, a header click is the list's sort, and the table pages. + */ +describe("the table's order is the ‹ › order (objectstack#36897)", () => { + async function orderedOnDetail(linkName: string): Promise { + fireEvent.click(screen.getByRole('link', { name: linkName })); + const ordered = await screen.findByTestId('ordered'); + await waitFor(() => expect(ordered).toHaveAttribute('data-status', 'ready')); + return ordered.textContent ?? ''; + } + + it('the rows the table draws, in order, are the names the detail steps through', async () => { + mount(`${LIST}?scope=environment&q=tri&sort=-label`); + const shown = await rowNames(); + expect(shown).toEqual(['tribute', 'triage']); + expect(await orderedOnDetail('Triage desk')).toBe(shown.join(',')); + }); + + it('a click on the Label header sorts the list by label, in the address, and the detail follows', async () => { + mount(`${LIST}?scope=environment`); + await rowNames(); + fireEvent.click(screen.getByRole('columnheader', { name: /Label/ })); + await waitFor(() => expect(screen.getByTestId('location')).toHaveTextContent(`${LIST}?scope=environment&sort=label`)); + const shown = await rowNames(); + expect(shown).toEqual(['translate', 'billing', 'triage', 'tribute']); + expect(await orderedOnDetail('Billing')).toBe(shown.join(',')); + }); + + it('pages by the address, and a new search starts again at the first page', async () => { + mount(`/apps/setup/metadata/tool?scope=environment&page=2`); + expect(await rowNames()).toEqual(['tool_51', 'tool_52', 'tool_53']); + fireEvent.change(screen.getByTestId('metadata-list-search'), { target: { value: 'Tool' } }); + await waitFor(() => expect(screen.getByTestId('location')).toHaveTextContent('/apps/setup/metadata/tool?scope=environment&q=Tool')); + expect(await rowNames()).toHaveLength(50); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.objectExtensionName-29569.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.objectExtensionName-29569.test.tsx index c1f7d6f0bdf..8b2ba56366c 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.objectExtensionName-29569.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.objectExtensionName-29569.test.tsx @@ -158,6 +158,8 @@ function mountList(host: MetadataAreaHost, type: string, search = '') { ); } +/** The table row of `el`'s first cell: the row's test id sits there, and `ObjectGrid` draws the row (objectstack#36897). */ +const trOf = (el: HTMLElement) => el.closest('tr') as HTMLElement; const linkOf = (row: HTMLElement) => within(row).getAllByRole('link')[0]!; const marksOf = (row: HTMLElement) => within(row) @@ -167,7 +169,7 @@ const marksOf = (row: HTMLElement) => describe('an object_extension row names, links and marks the object it extends (objectstack#29569)', () => { it('the cross-package leg shows `extend` under an "Object" header and links to that extension', async () => { mountList(area(null), 'object_extension'); - const row = await screen.findByTestId('metadata-row-showcase_task'); + const row = trOf(await screen.findByTestId('metadata-row-showcase_task')); const cells = within(row).getAllByRole('cell'); expect(cells[0]).toHaveTextContent('showcase_task'); @@ -187,7 +189,7 @@ describe('an object_extension row names, links and marks the object it extends ( it("in the base's area the pair's row is found by `extend`, marked Added, and opens that extension", async () => { mountList(area(BASE), 'object_extension', `?package=${BASE}`); - const row = await screen.findByTestId('metadata-row-showcase_task'); + const row = trOf(await screen.findByTestId('metadata-row-showcase_task')); await within(row).findByTestId('customization-mark'); expect(within(row).getAllByRole('cell')[0]).toHaveTextContent('showcase_task'); @@ -204,12 +206,12 @@ describe('an object_extension row names, links and marks the object it extends ( counts: { ...EMPTY_COUNTS, overrides: 1, extensions: 1 }, }; mountList(area(BASE), 'object_extension', `?package=${BASE}`); - const row = await screen.findByTestId('metadata-row-showcase_task'); + const row = trOf(await screen.findByTestId('metadata-row-showcase_task')); await within(row).findByTestId('customization-mark'); expect(marksOf(row)).toEqual(['customized']); // CONTROL: the other extension the read does not list stays "Added". - expect(marksOf(screen.getByTestId('metadata-row-showcase_project'))).toEqual(['added']); + expect(marksOf(trOf(screen.getByTestId('metadata-row-showcase_project')))).toEqual(['added']); }); it('the search box matches `extend`', async () => { @@ -223,15 +225,15 @@ describe('an object_extension row names, links and marks the object it extends ( it("the Label column shows the extension's own label", async () => { mountList(area(null), 'object_extension'); - const row = await screen.findByTestId('metadata-row-showcase_task'); + const row = trOf(await screen.findByTestId('metadata-row-showcase_task')); expect(within(row).getAllByRole('cell')[1]).toHaveTextContent('Work items'); - expect(within(screen.getByTestId('metadata-row-showcase_project')).getAllByRole('cell')[1]).toHaveTextContent('—'); + expect(within(trOf(screen.getByTestId('metadata-row-showcase_project'))).getAllByRole('cell')[1]).toHaveTextContent('—'); }); it('CONTROL: a row of another type still names and links by `name`', async () => { mountList(area(null), 'page'); - const row = await screen.findByTestId('metadata-row-task_board'); + const row = trOf(await screen.findByTestId('metadata-row-task_board')); expect(within(row).getAllByRole('cell')[0]).toHaveTextContent('task_board'); expect(linkOf(row).getAttribute('href')).toBe( diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.pairCreate-36897.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.pairCreate-36897.test.tsx new file mode 100644 index 00000000000..ab4d10aa2fa --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.pairCreate-36897.test.tsx @@ -0,0 +1,146 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36897 — the list's 「新建」 on a read-only base in Studio's area. + * + * - It is offered: the item is created in the base's paired `.custom` + * package (ADR-0146 D3). An object and a flow open the list's own create + * dialog (`MetadataListCreateDialog`, whose landing is its own suite); + * another type goes to the area's create, which moves to the pair. + * - Where the area opens no create in the pair (`host.pairCreate`: the + * customization wall, under which the server refuses the pair's ensure + * for this caller) nothing is offered. + * - Setup (no area) is unchanged — the control: its 「新建」 goes to the + * item page's create and opens no dialog. + */ + +// Paid at collection, not inside a case's clock (check:test-source-alias). +import '@objectstack/lint'; +import '@testing-library/jest-dom/vitest'; +import * as React from 'react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'; +import '@objectstack/spec/identity'; +import { MetadataAreaHostContext, type MetadataAreaHost } from './metadataAreaHost'; + +const BASE = 'hotcrm'; + +const CLIENT = { + list: async (type: string) => + type === 'package' + ? [{ manifest: { id: BASE, name: 'HotCRM', scope: 'installed' } }] + : [{ name: `crm_${type}_one`, label: `One ${type}`, _packageId: BASE }], +}; +const entry = (type: string, domain: string) => ({ type, label: type, domain, allowEnvironmentOverlay: false, allowRuntimeCreate: true }); +const ENTRIES = [entry('object', 'data'), entry('flow', 'automation'), entry('email_template', 'system')]; + +vi.mock('./useMetadata', async (importOriginal) => ({ + ...(await importOriginal>()), + useMetadataClient: () => CLIENT, + useMetadataTypes: () => ({ loading: false, error: null, entries: ENTRIES }), +})); +vi.mock('./i18n', async (importOriginal) => ({ + ...(await importOriginal>()), + useMetadataLocale: () => 'en-US', +})); +vi.mock('../../hooks/useCanAuthorMetadata', async (importOriginal) => ({ + ...(await importOriginal>()), + useCanAuthorMetadata: () => true, +})); + +import { MetadataResourceListPage } from './ResourceListPage'; +import { registerDefaultMetadataSchemas } from './default-schemas'; +import { t } from './i18n'; + +registerDefaultMetadataSchemas(); + +const fetchMock = vi.fn(async (url: string) => { + const json = (status: number, body: unknown) => + new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }); + const u = String(url); + if (u === '/api/v1/packages') { + return json(200, { success: true, data: { packages: [{ manifest: { id: BASE, name: 'HotCRM', scope: 'installed' }, writable: false }] } }); + } + if (u.endsWith('/customizations')) { + return json(200, { + success: true, + data: { packageId: BASE, overrides: [], extensions: [], switchedOff: [], arrangements: [], contributions: [], counts: { overrides: 0, extensions: 0, switchedOff: 0, arrangements: 0, contributions: 0 } }, + }); + } + if (u.startsWith('/api/v1/data/sys_metadata_activation')) { + return json(200, { object: 'sys_metadata_activation', records: [], hasMore: false }); + } + return json(404, { success: false }); +}); + +beforeEach(() => { + fetchMock.mockClear(); + vi.stubGlobal('fetch', fetchMock); +}); +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); +}); + +const READ_ONLY_BASE: MetadataAreaHost = { packageId: BASE, readOnly: true, basePath: `/studio/${BASE}/metadata`, pairCreate: true }; +/** The area opens no create in the pair: its ensure door refuses this caller (the wall), or it has no customization. */ +const NO_PAIR_CREATE: MetadataAreaHost = { ...READ_ONLY_BASE, pairCreate: false }; + +function Location() { + const l = useLocation(); + return
{`${l.pathname}${l.search}`}
; +} + +function mount(host: MetadataAreaHost | null, type: string) { + const base = host?.basePath ?? '/apps/setup/metadata'; + const tree = ( + + + } /> + + + + + ); + return render(host ? {tree} : tree); +} + +const createButton = () => screen.queryByRole('button', { name: t('engine.list.create', 'en-US') }); + +describe('the list offers 「新建」 on a read-only base, into its pair (objectstack#36897)', () => { + it('an object: 新建 is offered and opens the list create dialog', async () => { + mount(READ_ONLY_BASE, 'object'); + await screen.findByTestId(`metadata-row-crm_object_one`); + fireEvent.click(createButton()!); + expect(await screen.findByTestId('create-object-owd')).toBeInTheDocument(); + }); + + it('a flow: 新建 opens the starting points', async () => { + mount(READ_ONLY_BASE, 'flow'); + await screen.findByTestId(`metadata-row-crm_flow_one`); + fireEvent.click(createButton()!); + expect(await screen.findByTestId('create-flow-preset-manual')).toBeInTheDocument(); + }); + + it("another type goes to the area's create, which moves it to the pair", async () => { + mount(READ_ONLY_BASE, 'email_template'); + await screen.findByTestId(`metadata-row-crm_email_template_one`); + fireEvent.click(createButton()!); + await waitFor(() => expect(screen.getByTestId('location')).toHaveTextContent(`/studio/${BASE}/metadata/email_template/new?package=${BASE}`)); + }); + + it('where the area opens no create in the pair (the customization wall) nothing is offered', async () => { + mount(NO_PAIR_CREATE, 'object'); + await screen.findByTestId(`metadata-row-crm_object_one`); + expect(createButton()).toBeNull(); + }); + + it('CONTROL — Setup: 新建 goes to the item create and opens no dialog', async () => { + mount(null, 'object'); + await screen.findByTestId(`metadata-row-crm_object_one`); + fireEvent.click(createButton()!); + await waitFor(() => expect(screen.getByTestId('location').textContent).toMatch(/^\/apps\/setup\/metadata\/object\/new/)); + expect(screen.queryByTestId('create-object-owd')).toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.positionGrants-25333.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.positionGrants-25333.test.tsx index eb2bef41500..cee97cf562a 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.positionGrants-25333.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.positionGrants-25333.test.tsx @@ -24,6 +24,9 @@ * the localized header, and a position without one shows the empty cell * (objectstack#25909). */ +// Paid at collection, not inside a case's clock (check:test-source-alias). +import '@objectstack/lint'; +import '@object-ui/plugin-detail'; import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'; import { render, cleanup, screen, waitFor, fireEvent, within } from '@testing-library/react'; import '@testing-library/jest-dom'; @@ -138,6 +141,9 @@ function mount(type = 'position', search = '?scope=environment') { const LOCALE = 'en-US'; +/** The table row of `name`: its test id sits on the row's first cell, and `ObjectGrid` draws the row (objectstack#36897). */ +const rowOf = (name: string) => screen.getByTestId(`metadata-row-${name}`).closest('tr') as HTMLElement; + describe('the position list reads its two columns from the server (objectstack#25333)', () => { it('asks the position list with include=grants; the permission-set list (control) asks the plain list', async () => { mount(); @@ -154,7 +160,7 @@ describe('the position list reads its two columns from the server (objectstack#2 it('shows the served holder count, and "—" — never 0 — where the server served none', async () => { mount(); expect(await screen.findByRole('columnheader', { name: t('engine.list.col._holderCount', LOCALE) })).toBeInTheDocument(); - const count = (name: string) => within(screen.getByTestId(`metadata-row-${name}`)).getByTestId('position-holder-count'); + const count = (name: string) => within(rowOf(name)).getByTestId('position-holder-count'); await waitFor(() => expect(count('sales_manager')).toHaveTextContent('3')); expect(count('support_agent')).toHaveTextContent('—'); expect(count('support_agent')).toHaveAttribute('title', t('engine.position.holders.unknown', LOCALE)); @@ -165,7 +171,7 @@ describe('the position list reads its two columns from the server (objectstack#2 it('lists the granted sets as served, each badge the set name alone', async () => { mount(); expect(await screen.findByRole('columnheader', { name: t('engine.list.col._grantedPermissionSets', LOCALE) })).toBeInTheDocument(); - const cell = within(screen.getByTestId('metadata-row-sales_manager')).getByTestId('position-granted-sets'); + const cell = within(rowOf('sales_manager')).getByTestId('position-granted-sets'); const badges = Array.from(cell.querySelectorAll('[data-via]')); expect(badges.map((b) => [b.textContent, b.getAttribute('data-via')])).toEqual([ ['crm_sales_user', 'definition'], @@ -173,9 +179,9 @@ describe('the position list reads its two columns from the server (objectstack#2 ]); for (const badge of badges) expect(badge).not.toHaveAttribute('title'); - expect(within(screen.getByTestId('metadata-row-support_agent')).getByTestId('position-granted-sets')) + expect(within(rowOf('support_agent')).getByTestId('position-granted-sets')) .toHaveTextContent(t('engine.position.grants.none', LOCALE)); - expect(within(screen.getByTestId('metadata-row-auditor')).getByTestId('position-granted-sets')).toHaveTextContent('—'); + expect(within(rowOf('auditor')).getByTestId('position-granted-sets')).toHaveTextContent('—'); }); }); @@ -188,7 +194,7 @@ describe('the position list shows the served description (objectstack#25909)', ( expect(headers[col - 1]).toHaveTextContent(t('engine.list.col.label', LOCALE)); expect(headers[col + 1]).toHaveTextContent(t('engine.list.col._holderCount', LOCALE)); - const cell = (name: string) => screen.getByTestId(`metadata-row-${name}`).querySelectorAll('td')[col] as HTMLElement; + const cell = (name: string) => rowOf(name).querySelectorAll('td')[col] as HTMLElement; await waitFor(() => expect(cell('sales_manager')).toHaveTextContent('Leads the regional sales team and approves its forecasts.'), ); @@ -204,14 +210,16 @@ describe('the position list shows the served description (objectstack#25909)', ( describe('the whole row opens the position (objectstack#25333)', () => { it('a click on a plain cell opens the position, keeping the scope', async () => { mount(); - const row = await screen.findByTestId('metadata-row-sales_manager'); + await screen.findByTestId('metadata-row-sales_manager'); + const row = rowOf('sales_manager'); fireEvent.click(within(row).getByTestId('position-holder-count')); expect(await screen.findByTestId('where')).toHaveTextContent('/apps/setup/metadata/position/sales_manager?scope=environment'); }); it('control: a click on the Active switch is the switch\'s, and a modified click is the browser\'s', async () => { mount(); - const row = await screen.findByTestId('metadata-row-sales_manager'); + await screen.findByTestId('metadata-row-sales_manager'); + const row = rowOf('sales_manager'); const sw = await screen.findByTestId('catalog-active-sales_manager'); await waitFor(() => expect(sw).toHaveAttribute('aria-checked', 'true')); fireEvent.click(sw); diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.setupLabelFirst-27356.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.setupLabelFirst-27356.test.tsx index 6d9725dcf8f..197d5310a9c 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.setupLabelFirst-27356.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.setupLabelFirst-27356.test.tsx @@ -8,6 +8,8 @@ * The same page outside Setup is the control: the API name column, the Label * column and the type's label as the title, as before. */ +// Paid at collection, not inside a case's clock (check:test-source-alias). +import '@objectstack/lint'; import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'; import { render, cleanup, screen, within } from '@testing-library/react'; import '@testing-library/jest-dom'; @@ -104,6 +106,9 @@ function mount(appName: string) { const headers = () => Array.from(document.querySelectorAll('thead th')).map((th) => th.textContent); +/** The table row of `el`'s first cell: the row's test id sits there, and `ObjectGrid` draws the row (objectstack#36897). */ +const trOf = (el: HTMLElement) => el.closest('tr') as HTMLElement; + describe('a metadata list under Setup leads with labels (objectstack#27356 row 5)', () => { it('titles the page as the navigation entry that opens it', async () => { mount('setup'); @@ -139,7 +144,7 @@ describe('a metadata list under Setup leads with labels (objectstack#27356 row 5 it('clamps a description to two lines and keeps the whole text on hover', async () => { mount('setup'); await screen.findByRole('link', { name: 'Sales Director' }); - const row = screen.getByTestId('metadata-row-sales_director'); + const row = trOf(screen.getByTestId('metadata-row-sales_director')); const clamp = within(row).getByText(LONG); expect(clamp).toHaveClass('line-clamp-2'); expect(clamp).toHaveAttribute('title', LONG); diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.tsx index 1f06aa9c03a..831aed3a963 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.tsx @@ -5,11 +5,10 @@ * (Phase 3c). * * Reads `/meta/:type`, applies registry-driven columns + search + - * source/overlay filters, and renders an ObjectGrid-like table. - * Each row links to its EditPage at `./:name?type=…`. - * - * No virtualisation in MVP — metadata lists are typically < 200 items - * per type, well under the threshold where it'd matter. + * source/overlay filters, and draws the rows in the record list's + * `ObjectGrid` (objectstack#36897: every type's list is the same table, + * `metadataListGrid.ts`), a page at a time. Each row links to its EditPage + * at `./:name?type=…`. */ import * as React from 'react'; @@ -17,8 +16,6 @@ import { Link, Navigate, useLocation, useNavigate, useNavigationType, useParams, import { Plus, Search, RefreshCw, AlertTriangle, Lock, Copy } from 'lucide-react'; import { Button, - HorizontalOverflowBox, - PINNED_RIGHT_SEAM_SHADOW_CLASSES, Tooltip, TooltipContent, TooltipProvider, @@ -58,7 +55,7 @@ import { resolveResourceConfig, } from './registry.js'; import { t, tFormat, translateMetadataType, useMetadataLocale } from './i18n.js'; -import { servedListColumns, withExtraColumns, type ListColumns } from './servedListColumns.js'; +import { servedListColumns, valueAtPath, withExtraColumns, type ListColumns } from './servedListColumns.js'; import { buildPackageScopeOptions } from './package-scope.js'; import { ENVIRONMENT_SCOPE_QUERY, isEnvironmentScope, useWalledCatalogReadOnly } from './catalog-scope.js'; import { useMetadataAreaHost } from './metadataAreaHost.js'; @@ -106,6 +103,7 @@ import { SharingRuleCloneDialog, type SharingRuleCloneDialogProps } from './Shar import { postureHasOrgWall, useTenancyPosture } from '../../hooks/useTenancyPosture.js'; import { applyListState, + DEFAULT_LIST_SORT, decodeListSort, decodeListState, LIST_SORT_KEYS, @@ -117,6 +115,19 @@ import { type MetadataListState, } from './metadataListState.js'; import { useListScrollRestore } from './useListScrollRestore.js'; +import { LIST_CREATE_DIALOG_TYPES, MetadataListCreateDialog } from './MetadataListCreateDialog.js'; +import { ObjectGrid } from '@object-ui/plugin-grid'; +import { + LIST_PAGE_PARAM, + MetadataListSource, + gridSortOf, + listSortOfGrid, + metadataGridField, + metadataListGridSchema, + metadataListObjectSchema, + pageWindow, + type MetadataGridColumn, +} from './metadataListGrid.js'; import { useListChangedAt } from './listChangedAt.js'; import { useListDraftMarks } from './listDraftMarks.js'; import { ListChangedCell } from './ListChangedCell.js'; @@ -235,7 +246,15 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string const listState: MetadataListState = { ...urlListState, query: queryDraft }; const updateListState = React.useCallback( (patch: Partial) => { - setSearchParams((prev) => writeListState(prev, { ...decodeListState(prev), ...patch }), { replace: true }); + // A changed filter or sort starts the table over at its first page. + setSearchParams( + (prev) => { + const next = writeListState(prev, { ...decodeListState(prev), ...patch }); + next.delete(LIST_PAGE_PARAM); + return next; + }, + { replace: true }, + ); }, [setSearchParams], ); @@ -451,7 +470,19 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string // writable base exists, create into it (defaulting away from the Local/null // scope); when none exists yet, prompt to create a base first. const [showCreateBase, setShowCreateBase] = React.useState(false); + // objectstack#36897 — in the Studio area an object or a flow is created in + // the list's own dialog (`MetadataListCreateDialog`), and on a read-only + // base every create lands in the base's `.custom` pair (ADR-0146 D3) — where + // the area opens one there (`host.pairCreate`; none where the ensure door + // refuses this caller, as on the pillars). + const createInPair = !!host?.readOnly && host.pairCreate === true; + const createInDialog = !!host?.packageId && LIST_CREATE_DIALOG_TYPES.includes(type); + const [createOpen, setCreateOpen] = React.useState(false); const handleCreate = React.useCallback(() => { + if (createInDialog) { + setCreateOpen(true); + return; + } // An environment-authored item belongs to no package (ADR-0131 D3). if (envScope) { navigate(`./new?${ENVIRONMENT_SCOPE_QUERY}`); @@ -480,7 +511,7 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string return; } navigate(`./new${pkgSuffix}`); - }, [projectPackages, activePackage, pickedPackage, pkgSuffix, navigate, envScope, host?.packageId, allLeg]); + }, [projectPackages, activePackage, pickedPackage, pkgSuffix, navigate, envScope, host?.packageId, allLeg, createInDialog]); // objectui#7611 — the activation state the switch column shows. Re-read on // the list's own refresh, never on an unrelated render. The anchors arrive @@ -780,7 +811,8 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string const typeWritable = !!(entry?.allowEnvironmentOverlay || entry?.allowRuntimeCreate); // A declaration-only catalog is never authored here: its items are created // on the authored object's page. - const canCreate = typeWritable && !walled && (!envScope || canAuthor) && !authoredObject && !host?.readOnly; + const canCreate = + typeWritable && !walled && (!envScope || canAuthor) && !authoredObject && (!host?.readOnly || createInPair); // The wall is the gate to NAME only where the type would otherwise admit a // write: a type with no runtime write channel is read-only for the operator // too, and its page says nothing about the wall. @@ -836,19 +868,345 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string ); - // objectui#13091 — the row's controls pinned to the table's right edge: the - // Clone column at `right-0`, at its fixed width, and the Active column just - // left of it. The first pinned column draws the seam shadow. - const pinned = activation || !!CloneDialog; - const cloneCellPin = CloneDialog - ? cn(PINNED_CELL_CLASSES, 'right-0 w-28 min-w-28', !activation && PINNED_SEAM_CLASSES) - : undefined; - const activeCellPin = activation - ? cn(PINNED_CELL_CLASSES, CloneDialog ? 'right-28' : 'right-0', PINNED_SEAM_CLASSES) - : undefined; + // objectstack#36897 — what each row of the table draws, by its row key: + // `ObjectGrid` keeps a row's key and its column values only, so the item, + // its package, lock and diagnostics are looked up here, never carried on + // the grid's row. + const rowInfos = new Map(); + const gridRowsAll = filtered.map((row, i) => { + const info = metadataRowInfo(row, i); + rowInfos.set(info.id, info); + const values: Record = { id: info.id }; + shownColumns.forEach((c, ci) => { + values[metadataGridField(ci)] = gridValue(valueAtPath(row.item, c.key)); + }); + return values; + }); + const rowInfoOf = (rec: unknown): MetadataRowInfo | undefined => + rowInfos.get(String((rec as { id?: unknown } | null)?.id ?? '')); + function metadataRowInfo(row: ItemRow, i: number): MetadataRowInfo { + const pk = config.primaryKey ?? 'name'; + const name = String(row.item[pk] ?? `(unnamed-${i})`); + const holding = holdingOfRow(row); + // ADR-0048 — link to this row's OWNING package so the editor resolves the + // right item even in the unscoped "all" list where two packages may ship + // the same name. Falls back to the workspace suffix for runtime/overlay-only + // rows (no real package, or the `sys_metadata` rehydration sentinel). The + // environment scope keeps its own scope instead: the editor reads the name + // as a caller with no package does (ADR-0150 D5, `holdingOfRead`). + const rowPkg = (row.item as { _packageId?: string })._packageId; + const editSuffix = envScope + ? pkgSuffix + : rowPkg && rowPkg !== 'sys_metadata' + ? `?package=${encodeURIComponent(rowPkg)}` + : pkgSuffix; + // objectstack#26649 — two members of one name are two rows; each opens its + // OWN member. objectstack#36896 (decision 10) — and the list's filters and + // sort ride along, for the detail's ‹ ›. + const member = bundleMemberOf(row.item, config.bundleMemberField); + const href = `./${encodeURIComponent(name)}${withQueryParam( + withQueryParam(editSuffix, member ? `${BUNDLE_MEMBER_PARAM}=${encodeURIComponent(member)}` : ''), + listContext, + )}`; + const invalid = row.diagnostics?.valid === false; + const warnList = row.diagnostics?.warnings ?? []; + return { + id: `${i}:${name}`, + row, + name, + holding, + rowPkg, + member: member || undefined, + href, + invalid, + warnOnly: !invalid && warnList.length > 0, + }; + } + + // The table's columns: the list's own, then the source (with the lock), + // then the row's controls — the Active switch, Clone, or both in one cell — + // pinned at its right edge (objectui#13091). One column, because the grid + // holds one column at that edge. + const gridColumns: MetadataGridColumn[] = [ + ...shownColumns.map((c, ci) => ({ + key: c.key, + label: localizeColumnLabel(ci === 0 && labelColumn ? labelColumn : c), + width: c.width, + })), + // objectstack#36898 — the item's change time and its pending-draft mark. + { key: CHANGED_COLUMN, label: t('engine.list.col.changedAt', locale) }, + { key: SOURCE_COLUMN, label: t('engine.list.col.source', locale) }, + ...(activation || CloneDialog + ? [ + { + key: CONTROLS_COLUMN, + label: t(activation ? 'engine.catalog.col.active' : 'engine.list.col.actions', locale), + pinnedRight: true, + }, + ] + : []), + ]; + // A header sorts by what it reads: the first column drawn label-first is + // headed (and sorted by) the label, otherwise by the API name. + const sortKeyOfColumn = (c: MetadataGridColumn): ListSortKey | undefined => + c.key === primaryKey + ? labelColumn + ? 'label' + : 'name' + : c.key === 'label' + ? 'label' + : c.key === CHANGED_COLUMN + ? 'changed' + : undefined; + const typeEntryLabel = entry?.label ?? type; + const gridSchema = React.useMemo( + () => metadataListGridSchema(type, gridColumns, sortKeyOfColumn, LIST_PAGE_SIZE), + // Re-keyed on the columns' content, never on the array's identity. + // eslint-disable-next-line react-hooks/exhaustive-deps + [type, JSON.stringify(gridColumns), primaryKey, !!labelColumn], + ); + const gridSource = React.useMemo( + () => new MetadataListSource(gridRowsAll, metadataListObjectSchema(type, typeEntryLabel, gridColumns)), + // The source answers the schema; the rows reach the grid as `data`. + // eslint-disable-next-line react-hooks/exhaustive-deps + [type, JSON.stringify(gridColumns), typeEntryLabel], + ); + const listPage = Number(searchParams.get(LIST_PAGE_PARAM) ?? '1'); + const gridPage = pageWindow(gridRowsAll, listPage, LIST_PAGE_SIZE); + const setListPage = React.useCallback( + (next: number) => { + setSearchParams( + (prev) => { + const out = new URLSearchParams(prev); + if (next <= 1) out.delete(LIST_PAGE_PARAM); + else out.set(LIST_PAGE_PARAM, String(next)); + return out; + }, + { replace: true }, + ); + }, + [setSearchParams], + ); + + const cellClass = inSetup ? 'align-middle' : 'align-top'; + const firstCell = (info: MetadataRowInfo, c: ListColumns[number]) => { + const { row } = info; + const value = valueAtPath(row.item, c.key); + const cell = c.render ? c.render(row.item[c.key], row.item) : defaultCell(value); + const errorList = row.diagnostics?.errors ?? []; + const warnList = row.diagnostics?.warnings ?? []; + const lines = (list: Array<{ path?: string; message: string }>) => + list + .slice(0, 3) + .map((e) => `${e.path || '(root)'}: ${e.message}`) + .join('\n') + (list.length > 3 ? `\n+${list.length - 3} more` : ''); + const labelValue = labelColumn ? row.item[labelColumn.key] : undefined; + const hasLabel = labelValue != null && labelValue !== ''; + // ADR-0146 D3 — the row's customization mark: under a base, from its + // served read; in the cross-package leg, an item of a pair names its base. + const mark = markOf(row); + const pairBase = host && host.packageId === null ? customizationBaseOfRow(info.rowPkg) : null; + return ( + + {info.invalid && ( + + + + )} + {info.warnOnly && ( + + + + )} + {labelColumn && hasLabel ? ( + + + {labelColumn.render ? labelColumn.render(labelValue, row.item) : defaultCell(labelValue)} + + + {cell} + + + ) : ( + + {cell} + + )} + {mark && customizations.status === 'read' ? ( + + ) : pairBase ? ( + + ) : null} + + ); + }; + const cellDraws: Record React.ReactNode> = {}; + shownColumns.forEach((c, ci) => { + cellDraws[metadataGridField(ci)] = (_value, rec) => { + const info = rowInfoOf(rec); + if (!info) return null; + if (ci === 0) return firstCell(info, c); + const value = info.row.item[c.key]; + const cell = c.render ? c.render(value, info.row.item) : defaultCell(valueAtPath(info.row.item, c.key)); + // objectstack#27356 — two lines at most, so a row stays a row on a + // phone; the whole text on hover. + return inSetup && c.key === 'description' && typeof value === 'string' && value !== '' ? ( + + {cell} + + ) : ( + cell + ); + }; + }); + // The page's own columns are drawn under their place in `gridColumns`. + const pageField = (key: string) => metadataGridField(gridColumns.findIndex((c) => c.key === key)); + cellDraws[pageField(CHANGED_COLUMN)] = (_value, rec) => { + const info = rowInfoOf(rec); + if (!info) return null; + return ( + + ); + }; + cellDraws[pageField(SOURCE_COLUMN)] = (_value, rec) => { + const info = rowInfoOf(rec); + if (!info) return null; + const { row } = info; + const sourceDesc = + row.source === 'artifact' + ? `${t('engine.list.source.artifactDesc', locale)}${row.item._packageId ? ` (${String(row.item._packageId)})` : ''}` + : t('engine.list.source.runtimeDesc', locale); + const lock = row.item._lock as string | undefined; + return ( + + {lock && lock !== 'none' && ( + + + + )} + {inSetup ? ( + // Under Setup the source is plain text with its explanation in a + // tooltip, not a chip on every row (objectui#12606). + + + + + {t(`engine.list.source.${row.source}`, locale)} + + + + {sourceDesc} + + + + ) : ( + + {t(`engine.list.source.${row.source}`, locale)} + + )} + + ); + }; + if (activation || CloneDialog) { + cellDraws[pageField(CONTROLS_COLUMN)] = (_value, rec) => { + const info = rowInfoOf(rec); + if (!info) return null; + return ( + + {activation && ( + toggleActive(itemName, enabled, info.holding)} + /> + )} + {CloneDialog && ( + + )} + + ); + }; + } + + // The grid keeps the cells it was handed as table state, re-seeded a commit + // after they change; so the cells it holds are stable and draw through the + // latest render's drawers, and a ledger or mark that changes redraws at once. + const cellDrawsRef = React.useRef(cellDraws); + cellDrawsRef.current = cellDraws; + const cellKeys = Object.keys(cellDraws).join(','); + const hostCells = React.useMemo( + () => + Object.fromEntries( + cellKeys.split(',').map((key) => [key, (value: unknown, rec: unknown) => cellDrawsRef.current[key]?.(value, rec) ?? null]), + ), + [cellKeys], + ); const body = (
+ {createInDialog && host?.packageId && ( + { + setCreateOpen(false); + refresh(); + navigate(`./${encodeURIComponent(name)}?package=${encodeURIComponent(packageId)}`); + }} + /> + )} )} {!loading && filtered.length > 0 && ( - // objectui#13091 — a table wider than its box says so (the shared - // overflow affordance, objectui#12708), and the row's controls (the - // Active switch, Clone) stay pinned at its right edge, the seam - // shadow on the first of them (objectui#12463). - - {/* Separated borders: Chrome paints a sticky cell of a collapsed-border - table without covering the text scrolling beneath its edge - (objectui#13091), so the row dividers are drawn on the cells. */} - - {/* Under Setup the table reads as the console's record list - (objectui#12606): sentence-case headers, the grid's 36px - rows, middle-aligned cells. */} - - - {shownColumns.map((c, ci) => ( - - ))} - - - {activation && ( - - )} - {CloneDialog && ( - - )} - - - - {filtered.map((row, i) => { - const pk = config.primaryKey ?? 'name'; - const name = String(row.item[pk] ?? `(unnamed-${i})`); - const rowHolding = holdingOfRow(row); - // ADR-0048 — link to this row's OWNING package so the editor - // resolves the right item even in the unscoped "all" list - // where two packages may ship the same name. Falls back to the - // workspace suffix for runtime/overlay-only rows (no real - // package, or the `sys_metadata` rehydration sentinel). - const rowPkg = (row.item as any)._packageId as string | undefined; - // The environment scope keeps its own scope instead: the - // editor reads the name as a caller with no package does - // (ADR-0150 D5, `holdingOfRead`) — the name's one holder, or - // the environment's own set where it holds the name; a name - // two packages hold is refused by name alone, and the editor - // then draws no holder's sections (objectstack#32774). - const rowEditSuffix = envScope - ? pkgSuffix - : rowPkg && rowPkg !== 'sys_metadata' - ? `?package=${encodeURIComponent(rowPkg)}` - : pkgSuffix; - const invalid = row.diagnostics?.valid === false; - const errorList = row.diagnostics?.errors ?? []; - const warnList = (row.diagnostics as any)?.warnings ?? []; - const warnOnly = !invalid && warnList.length > 0; - const errorTitle = invalid - ? errorList - .slice(0, 3) - .map((e) => `${e.path || '(root)'}: ${e.message}`) - .join('\n') + - (errorList.length > 3 ? `\n+${errorList.length - 3} more` : '') - : warnOnly - ? warnList - .slice(0, 3) - .map((w: any) => `${w.path || '(root)'}: ${w.message}`) - .join('\n') + - (warnList.length > 3 ? `\n+${warnList.length - 3} more` : '') - : ''; - const cellClass = inSetup ? 'h-9 px-3 py-1.5 align-middle' : 'px-3 py-2 align-top'; - const sourceDesc = - row.source === 'artifact' - ? `${t('engine.list.source.artifactDesc', locale)}${row.item._packageId ? ` (${row.item._packageId})` : ''}` - : t('engine.list.source.runtimeDesc', locale); - // objectstack#26649 — two members of one name are two rows; - // each opens its OWN member. A row that declares none is the - // canonical member, which the bare name already opens. - const rowMember = bundleMemberOf(row.item, config.bundleMemberField); - // objectstack#36896 (decision 10) — and the list's filters and - // sort, for the detail's ‹ ›. - const rowHref = `./${encodeURIComponent(name)}${withQueryParam( - withQueryParam( - rowEditSuffix, - rowMember ? `${BUNDLE_MEMBER_PARAM}=${encodeURIComponent(rowMember)}` : '', - ), - listContext, - )}`; - // ADR-0146 D3 — the row's customization mark: under a base, - // from its served read; in the cross-package leg, an item of a - // pair names its base. - const mark = markOf(row); - const pairBase = host && host.packageId === null ? customizationBaseOfRow(rowPkg) : null; - const markNode = - mark && customizations.status === 'read' ? ( - - ) : pairBase ? ( - - ) : null; - return ( - openRowFromClick(e, () => navigate(rowHref))} - className={cn( - 'cursor-pointer hover:bg-accent/50', - invalid ? 'bg-destructive/[0.04]' : warnOnly ? 'bg-amber-500/[0.05]' : '', - // The same fills, for the pinned cells to layer over - // their opaque background. - invalid ? INVALID_ROW_TINT : warnOnly ? WARN_ROW_TINT : '', - HOVER_ROW_TINT, - )} - > - {shownColumns.map((c, ci) => { - const value = row.item[c.key]; - const cell = c.render ? c.render(value, row.item) : defaultCell(value); - const labelValue = labelColumn ? row.item[labelColumn.key] : undefined; - const hasLabel = labelValue != null && labelValue !== ''; - return ( - - ); - })} - - - {activation && ( - - )} - {CloneDialog && ( - - )} - - ); - })} - -
- {localizeColumnLabel(ci === 0 && labelColumn ? labelColumn : c)} - {t('engine.list.col.changedAt', locale)}{t('engine.list.col.source', locale)} - {t('engine.catalog.col.active', locale)} - - {t('engine.list.col.actions', locale)} -
- {ci === 0 ? ( - - {invalid && ( - - - - )} - {warnOnly && ( - - - - )} - {labelColumn && hasLabel ? ( - - - {labelColumn.render ? labelColumn.render(labelValue, row.item) : defaultCell(labelValue)} - - - {cell} - - - ) : ( - - {cell} - - )} - {markNode} - - ) : inSetup && c.key === 'description' && typeof value === 'string' && value !== '' ? ( - // objectstack#27356 — two lines at most, so a row - // stays a row on a phone; the whole text on hover. - - {cell} - - ) : ( - cell - )} - - - - {(row.item._lock as string | undefined) && row.item._lock !== 'none' && ( - - - - )} - {inSetup ? ( - // Under Setup the source is plain text with its - // explanation in a tooltip, not a chip on every row - // (objectui#12606). - - - - - {t(`engine.list.source.${row.source}`, locale)} - - - - {sourceDesc} - - - - ) : ( - - {t(`engine.list.source.${row.source}`, locale)} - - )} - - toggleActive(itemName, enabled, rowHolding)} - /> - - -
-
+ // objectstack#36897 — every type's list is the same table: the + // record list's `ObjectGrid`, fed the rows above in their order + // (`metadataListGrid.ts`), its cells drawn here by row key. +
+ updateListState({ sort: listSortOfGrid(next, gridColumns, sortKeyOfColumn) ?? DEFAULT_LIST_SORT })} + search={query} + hostCells={hostCells} + rowTint={(rec) => { + const info = rowInfoOf(rec); + return info?.invalid ? 'red' : info?.warnOnly ? 'amber' : null; + }} + rowOpensRecord={false} + cellSelection={false} + onRowClick={(rec, event) => { + const info = rowInfoOf(rec); + if (!info || (event && (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey))) return; + navigate(info.href); + }} + /> +
)}
); @@ -1434,52 +1539,38 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string ); } -/** - * objectui#13091 — a cell pinned to the right edge of the list's overflow box. - * It paints an opaque background, because the other columns scroll beneath - * it, and layers its row's fill (`--os-row-tint`, the convention `data-table` - * keeps for its sticky cells) over it, so a pinned cell reads as part of its - * row. The Clone column is the fixed `w-28` the Active column's `right-28` - * offset counts on; its button truncates its label to stay inside it. - * - * Complete literals: Tailwind v4 builds only from scanned source text. - */ -const PINNED_CELL_CLASSES = - 'sticky z-10 bg-background bg-[image:linear-gradient(var(--os-row-tint,transparent),var(--os-row-tint,transparent))]'; -const PINNED_SEAM_CLASSES = `border-l border-border ${PINNED_RIGHT_SEAM_SHADOW_CLASSES}`; -const HEAD_ROW_TINT = '[--os-row-tint:color-mix(in_oklab,var(--color-muted)_30%,transparent)]'; -const INVALID_ROW_TINT = '[--os-row-tint:color-mix(in_oklab,var(--color-destructive)_4%,transparent)]'; -const WARN_ROW_TINT = '[--os-row-tint:color-mix(in_oklab,var(--color-amber-500)_5%,transparent)]'; -const HOVER_ROW_TINT = 'hover:[--os-row-tint:color-mix(in_oklab,var(--color-accent)_50%,transparent)]'; +/** The page columns after the list's own (`metadataListGrid.ts` keys none of them as a field). */ +const CHANGED_COLUMN = '__changed'; +const SOURCE_COLUMN = '__source'; +const CONTROLS_COLUMN = '__controls'; -/** - * The whole row opens its item (objectstack#25333), the way a record list's - * row does. The first cell keeps its link, which is what a keyboard, a screen - * reader and a modified click (new tab) use; this handler is the pointer's - * larger target and stands aside for everything the row already does: - * - * - a click on a control in the row (the link itself, the Active switch, - * Clone, a tooltip trigger) is that control's; - * - a click that reached the row through a React portal (a dialog a row - * control opened) did not happen on the row; - * - a modified or non-primary click, and a click that ends a text selection, - * are the browser's. - */ -export function openRowFromClick(e: React.MouseEvent, open: () => void): void { - if (e.defaultPrevented || e.button !== 0) return; - if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return; - const target = e.target as Node | null; - if (!target || !e.currentTarget.contains(target)) return; - const el = target instanceof Element ? target : target.parentElement; - if (el?.closest(ROW_OWN_CONTROLS)) return; - const selection = typeof window !== 'undefined' ? window.getSelection?.() : null; - if (selection && !selection.isCollapsed && selection.toString().trim() !== '') return; - open(); -} +/** Rows per page of the list. */ +const LIST_PAGE_SIZE = 50; -const ROW_OWN_CONTROLS = - 'a,button,input,select,textarea,label,summary,[role="button"],[role="switch"],[role="checkbox"],[role="menuitem"],[role="link"],[contenteditable="true"]'; +/** What one row of the table draws, looked up by its row key (objectstack#36897). */ +interface MetadataRowInfo { + id: string; + row: ItemRow; + name: string; + holding: PermissionSetHolding | undefined; + rowPkg: string | undefined; + /** The bundle member the row is (objectstack#26649), for its draft mark. */ + member: string | undefined; + href: string; + invalid: boolean; + warnOnly: boolean; +} +/** A column value as the grid's row keeps it: a scalar as is, anything else as its JSON. */ +function gridValue(value: unknown): string | number | boolean | null { + if (value == null) return null; + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') return value; + try { + return JSON.stringify(value); + } catch { + return String(value); + } +} /** * objectstack#26649 — the member column of a type whose identity is a pair, diff --git a/ui/packages/app-shell/src/views/metadata-admin/metadataAreaHost.customizations-28568.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/metadataAreaHost.customizations-28568.test.tsx index 41357274e93..648ed576314 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/metadataAreaHost.customizations-28568.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/metadataAreaHost.customizations-28568.test.tsx @@ -200,6 +200,8 @@ describe('the All metadata lists mark a base\'s customizations (objectstack#2856 it('the translation list marks the served override "Customized (HotCRM)", and the filter shows it alone', async () => { mountList(area(BASE), 'translation', `?package=${BASE}`); const only = await screen.findByTestId('metadata-only-customizations'); + // The grid draws its rows once its table is ready (objectstack#36897). + await screen.findByTestId('metadata-row-crm_en'); expect(marksOf('crm_en')).toEqual([`customized:${tFormat('engine.customizationMark.customized', 'en-US', { baseName: 'HotCRM' })}`]); expect(marksOf('crm_en')).toEqual(['customized:Customized (HotCRM)']); // CONTROL: the base's item the read does not list carries no mark. @@ -218,6 +220,7 @@ describe('the All metadata lists mark a base\'s customizations (objectstack#2856 it('the email-template list holds the pair\'s item beside the base\'s, marked "Added"', async () => { mountList(area(BASE), 'email_template', `?package=${BASE}`); await screen.findByTestId('metadata-only-customizations'); + await screen.findByTestId('metadata-row-renewal_notice'); expect(marksOf('renewal_notice')).toEqual([`added:${t('engine.customizationMark.added', 'en-US')}`]); // The read overrides `welcome` in zh-CN only: the en member is the base's own. expect(marksOf('welcome')).toEqual([]); @@ -229,6 +232,7 @@ describe('the All metadata lists mark a base\'s customizations (objectstack#2856 const failed = await screen.findByTestId('metadata-customizations-failed'); expect(failed).toHaveTextContent('The customization ledger is unavailable.'); // The pair's item is still listed (the list read is its own), unmarked. + await screen.findByTestId('metadata-row-renewal_notice'); expect(marksOf('renewal_notice')).toEqual([]); expect(screen.queryByTestId('metadata-only-customizations')).toBeNull(); }); diff --git a/ui/packages/app-shell/src/views/metadata-admin/metadataAreaHost.ts b/ui/packages/app-shell/src/views/metadata-admin/metadataAreaHost.ts index 9d0d93eb46a..c72026f83ad 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/metadataAreaHost.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/metadataAreaHost.ts @@ -49,6 +49,13 @@ export interface MetadataAreaHost { readOnly: boolean; /** The area's root route, `/studio//metadata`, without a trailing slash. */ basePath: string; + /** + * objectstack#36897 — on a read-only base, a create lands in the base's + * `.custom` pair (ADR-0146 D3): the area opens it there (`AreaCreate`), so + * the list offers its 「新建」. `false` or absent where the area has no + * customization to create with, or the ensure door refuses this caller. + */ + pairCreate?: boolean; } export const MetadataAreaHostContext = React.createContext(null); diff --git a/ui/packages/app-shell/src/views/metadata-admin/metadataListGrid.test.ts b/ui/packages/app-shell/src/views/metadata-admin/metadataListGrid.test.ts new file mode 100644 index 00000000000..971e473bdfd --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/metadataListGrid.test.ts @@ -0,0 +1,84 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36897 — the adapter between a type's `/meta/:type` rows and + * `ObjectGrid`: the grid is told a schema declared from the columns (never + * one guessed from the first row), sorts only where the list sorts, and the + * header's sort and the list's sort round-trip. + */ + +import { describe, expect, it } from 'vitest'; + +import { + MetadataListSource, + gridSortOf, + listSortOfGrid, + metadataListGridSchema, + metadataListObjectSchema, + pageWindow, + type MetadataGridColumn, +} from './metadataListGrid'; +import type { ListSortKey } from './metadataListState'; + +const COLUMNS: MetadataGridColumn[] = [ + { key: 'name', label: 'API name', width: '220px' }, + { key: 'label', label: 'Label', width: '30%' }, + { key: 'config.type', label: 'Type' }, + { key: '__controls', label: 'Active', pinnedRight: true }, +]; +const sortKeyOf = (c: MetadataGridColumn): ListSortKey | undefined => + c.key === 'name' ? 'name' : c.key === 'label' ? 'label' : undefined; + +describe('metadataListGrid (objectstack#36897)', () => { + it('answers the schema declared from the columns, not one guessed from the first row', async () => { + const declared = metadataListObjectSchema('flow', 'Flow', COLUMNS); + // The first row carries a key no column declares, and lacks a declared one. + const source = new MetadataListSource([{ id: '0:a', c0: 'a', stray: 1 }], declared); + const schema = await source.getObjectSchema('anything'); + expect(Object.keys(schema.fields)).toEqual(['c0', 'c1', 'c2', 'c3']); + expect(schema.fields.c1).toEqual({ name: 'c1', type: 'text', label: 'Label' }); + expect(schema.fields).not.toHaveProperty('stray'); + expect(schema.name).toBe('metadata_list_flow'); + }); + + it("turns off the grid's search, selection, inline edit, resize and reorder; sortable only where the list sorts", () => { + const g = metadataListGridSchema('flow', COLUMNS, sortKeyOf, 50) as any; + expect(g).toMatchObject({ + showSearch: false, + searchableFields: [], + selection: { type: 'none' }, + editable: false, + resizable: false, + reorderableColumns: false, + pagination: { pageSize: 50 }, + }); + expect(g.columns.map((c: any) => c.sortable)).toEqual([true, true, false, false]); + expect(g.columns[0].width).toBe(220); + expect(g.columns[1]).not.toHaveProperty('width'); + expect(g.columns[3].pinned).toBe('right'); + expect(g.columns.filter((c: any) => c.pinned)).toHaveLength(1); + }); + + it("round-trips the list's sort through the header's", () => { + for (const sort of [ + { key: 'name', dir: 'asc' }, + { key: 'name', dir: 'desc' }, + { key: 'label', dir: 'desc' }, + ] as const) { + expect(listSortOfGrid(gridSortOf(sort, COLUMNS, sortKeyOf), COLUMNS, sortKeyOf)).toEqual(sort); + } + // A sort the table has no header for shows no arrow; a cleared or unknown header sort is none. + expect(gridSortOf({ key: 'updated' as ListSortKey, dir: 'asc' }, COLUMNS, sortKeyOf)).toEqual([]); + expect(listSortOfGrid([], COLUMNS, sortKeyOf)).toBeNull(); + expect(listSortOfGrid([{ field: 'c2', order: 'asc' }], COLUMNS, sortKeyOf)).toBeNull(); + }); + + it('clamps the page into range', () => { + const rows = Array.from({ length: 53 }, (_, i) => i); + expect(pageWindow(rows, 2, 50)).toEqual({ page: 2, rows: [50, 51, 52] }); + expect(pageWindow(rows, 9, 50).page).toBe(2); + expect(pageWindow(rows, 0, 50).page).toBe(1); + expect(pageWindow(rows, Number.NaN, 50).rows).toHaveLength(50); + expect(pageWindow([], 3, 50)).toEqual({ page: 1, rows: [] }); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/metadataListGrid.ts b/ui/packages/app-shell/src/views/metadata-admin/metadataListGrid.ts new file mode 100644 index 00000000000..b8968fa6ede --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/metadataListGrid.ts @@ -0,0 +1,165 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The metadata list on `ObjectGrid` (objectstack#36897, epic objectstack#36890: + * every type's list is the same table): the adapter between a type's + * `/meta/:type` rows and the grid. + * + * A metadata item is not a record of an object, so the grid is handed what it + * needs to draw one anyway: + * + * - a REAL schema — {@link metadataListObjectSchema}, one field per column, + * declared from the columns, never guessed from the first row (the + * `ValueDataSource` default) — answered by {@link MetadataListSource}; + * - the rows of the current page, already filtered and sorted by + * `applyListState` (`metadataListState.ts`), the ONE implementation the + * detail's ‹ › order reads too, so the grid's visible order and that order + * cannot disagree: the grid is driven in its host mode and never re-sorts; + * - for each row only its key (`id`) and its column values. Everything else a + * cell needs — the item, its package, lock and diagnostics — the page looks + * up by that key (`ObjectGrid` selects by column, so nothing else would + * survive on the row). + * + * The grid's own personal columns, export, selection and inline edit are off + * ({@link metadataListGridSchema}); the cells are the page's (`hostCells`). + */ + +import { ValueDataSource } from '@object-ui/core'; +import type { ObjectGridSchema, TableSortItem } from '@object-ui/types'; + +import type { ListSort, ListSortKey } from './metadataListState.js'; + +/** The fictitious object the grid is told it lists; never read or written. */ +export function metadataListObjectName(type: string): string { + return `metadata_list_${type.replace(/[^a-z0-9_]/gi, '_')}`; +} + +/** One column the page shows: the list column's key, its header, and its width. */ +export interface MetadataGridColumn { + /** The column's key in the item (`name`, `config.type`, `_holderCount`) or a page column (`__source`). */ + key: string; + label: string; + /** A CSS width hint; only a pixel width reaches the grid. */ + width?: string; + /** Pinned at the table's right edge (the row's controls). */ + pinnedRight?: boolean; +} + +/** + * The grid field each column is drawn under: positional, so a dotted path, a + * leading underscore or a key spelled like the row id never reaches the grid + * as a field name. + */ +export function metadataGridField(index: number): string { + return `c${index}`; +} + +/** The pixel width of a `'180px'` hint; a percentage or nothing gives none. */ +function pixelWidth(width: string | undefined): number | undefined { + const m = typeof width === 'string' ? /^(\d+(?:\.\d+)?)px$/.exec(width.trim()) : null; + return m ? Number(m[1]) : undefined; +} + +/** + * The schema the grid reads for the list: one text field per column, under + * its column's header. Every cell is drawn by the page, so the type only keeps + * the grid from treating a column as unknown. + */ +export function metadataListObjectSchema( + type: string, + label: string, + columns: readonly MetadataGridColumn[], +): { name: string; label: string; fields: Record } { + const fields: Record = {}; + columns.forEach((c, i) => { + const name = metadataGridField(i); + fields[name] = { name, type: 'text', label: c.label }; + }); + return { name: metadataListObjectName(type), label, fields }; +} + +/** The `ValueDataSource` of the list, answering the declared schema instead of one guessed from a row. */ +export class MetadataListSource> extends ValueDataSource { + private readonly declared: ReturnType; + constructor(items: T[], declared: ReturnType) { + super({ items, idField: 'id' }); + this.declared = declared; + } + override async getObjectSchema(_objectName: string): Promise { + return this.declared; + } +} + +/** + * The grid schema of the list: its columns, sortable only where the list + * sorts (the API name and the label), and none of the grid's record-list + * extras — no search box (the page's filter row owns the term), no + * selection, no inline edit, no export, no column resize or reorder (so no + * personal column layout is kept), no row actions. + */ +export function metadataListGridSchema( + type: string, + columns: readonly MetadataGridColumn[], + sortKeyOf: (column: MetadataGridColumn) => ListSortKey | undefined, + pageSize: number, +): ObjectGridSchema { + return { + type: 'object-grid', + objectName: metadataListObjectName(type), + columns: columns.map((c, i) => { + const width = pixelWidth(c.width); + return { + field: metadataGridField(i), + label: c.label, + sortable: sortKeyOf(c) !== undefined, + resizable: false, + ...(width ? { width } : {}), + ...(c.pinnedRight ? { pinned: 'right' as const } : {}), + }; + }), + showSearch: false, + searchableFields: [], + selection: { type: 'none' }, + editable: false, + resizable: false, + reorderableColumns: false, + pagination: { pageSize }, + }; +} + +/** The list's sort as the grid's header arrows read it. */ +export function gridSortOf( + sort: ListSort, + columns: readonly MetadataGridColumn[], + sortKeyOf: (column: MetadataGridColumn) => ListSortKey | undefined, +): TableSortItem[] { + const index = columns.findIndex((c) => sortKeyOf(c) === sort.key); + return index < 0 ? [] : [{ field: metadataGridField(index), order: sort.dir }]; +} + +/** + * A header click back to the list's sort: the column's key, the way the grid + * asked. A cleared sort is the list's default; a column the list does not + * sort by is not one the grid offers. + */ +export function listSortOfGrid( + next: readonly TableSortItem[], + columns: readonly MetadataGridColumn[], + sortKeyOf: (column: MetadataGridColumn) => ListSortKey | undefined, +): ListSort | null { + const first = next[0]; + if (!first) return null; + const index = columns.findIndex((_, i) => metadataGridField(i) === first.field); + const key = index < 0 ? undefined : sortKeyOf(columns[index]); + return key ? { key, dir: first.order === 'desc' ? 'desc' : 'asc' } : null; +} + +/** The page of `rows` the grid shows (1-based `page`, clamped into range). */ +export function pageWindow(rows: readonly T[], page: number, pageSize: number): { page: number; rows: T[] } { + const last = Math.max(1, Math.ceil(rows.length / pageSize)); + const at = Math.min(Math.max(1, Math.floor(page) || 1), last); + return { page: at, rows: rows.slice((at - 1) * pageSize, at * pageSize) }; +} + +/** The page param of the list's address (the list state's own params stay `metadataListState.ts`'s). */ +export const LIST_PAGE_PARAM = 'page'; diff --git a/ui/packages/app-shell/src/views/studio-design/CreateItemDialog.oneLabel-11787.test.ts b/ui/packages/app-shell/src/views/studio-design/CreateItemDialog.oneLabel-11787.test.ts index a2977a9c878..3d8908f7266 100644 --- a/ui/packages/app-shell/src/views/studio-design/CreateItemDialog.oneLabel-11787.test.ts +++ b/ui/packages/app-shell/src/views/studio-design/CreateItemDialog.oneLabel-11787.test.ts @@ -81,9 +81,12 @@ describe('Studio create dialogs say what the create does (objectui#11787, object } }); - it('CONTROL — the enumeration reaches each live dialog once, the New permission set one included', () => { + it('CONTROL — the enumeration reaches each live dialog, the New permission set one included', () => { const live = createDialogSites().filter((site) => LIVE_TITLES.includes(titleKeyOf(site) ?? '')); - expect(live.map(titleKeyOf).sort()).toEqual([...LIVE_TITLES].sort()); + // An object and a flow are created from their pillar AND from the metadata + // list (objectstack#36897, `MetadataListCreateDialog.tsx`): each title is + // reached, by one site or more. + expect([...new Set(live.map(titleKeyOf))].sort()).toEqual([...LIVE_TITLES].sort()); for (const site of live) expect(site.submitLabel).toBe(LIVE_LABEL); }); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioMetadataArea.routes-28561.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioMetadataArea.routes-28561.test.tsx index 6ce4ab68fce..cfde5f18fb6 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioMetadataArea.routes-28561.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioMetadataArea.routes-28561.test.tsx @@ -207,6 +207,82 @@ describe('the area mounts the metadata pages (objectstack#28561)', () => { }); }); +/** + * objectstack#36897 — on a read-only base with its customization handed in, + * the create is the pair's: the ensure door is asked once and its answer's + * package opens the create; a walled door, or a refusal, never writes. + */ +describe("a read-only base's create opens in its .custom pair (objectstack#36897)", () => { + const PAIR = `${READ_ONLY}.custom`; + const customizationOf = (walled: boolean, ensurePackage: () => Promise) => + ({ base: READ_ONLY, baseLabel: 'HR', basedOn: null, walled, pairId: null, ensure: async () => PAIR, ensurePackage }) as any; + function mountCustomized(customization: unknown, at = `/studio/${READ_ONLY}/metadata/translation/new?package=${READ_ONLY}`) { + return render( + + + + } /> + } /> + + , + ); + } + + it("the ensure door's pair opens the create", async () => { + listed.set(PAIR, { id: PAIR, name: 'HR (customizations)', writable: true, manifest: {} }); + const ensurePackage = vi.fn(async () => ({ basePackageId: READ_ONLY, packageId: PAIR, namespace: 'hrx', created: true, writable: true })); + mountCustomized(customizationOf(false, ensurePackage)); + await waitFor(() => expect(where()).toBe(`/studio/${PAIR}/metadata/translation/new?package=${encodeURIComponent(PAIR)}`)); + expect((await page()).page).toBe('create'); + expect(ensurePackage).toHaveBeenCalledTimes(1); + }); + + it('a refusal is shown where the create was asked, and nothing opens', async () => { + const ensurePackage = vi.fn(async () => { + throw new Error('The customization package could not be created.'); + }); + mountCustomized(customizationOf(false, ensurePackage)); + expect(await screen.findByTestId('studio-area-pair-create-refused')).toHaveTextContent('could not be created'); + expect(where()).toBe(`/studio/${READ_ONLY}/metadata/translation/new?package=${READ_ONLY}`); + }); + + it("the list is told it may offer the create exactly where the area opens one in the pair", async () => { + const list = `/studio/${READ_ONLY}/metadata/translation?package=${READ_ONLY}`; + mountCustomized(customizationOf(false, vi.fn()), list); + expect((await page()).host).toMatchObject({ readOnly: true, pairCreate: true }); + cleanup(); + mountCustomized(customizationOf(true, vi.fn()), list); + expect((await page()).host).not.toHaveProperty('pairCreate'); + cleanup(); + mount(list); + expect((await page()).host).not.toHaveProperty('pairCreate'); + }); + + it('a kernel package has no pair: no create is offered, and its create URL lands on the list', async () => { + const ensurePackage = vi.fn(); + const kernelCustomization = { ...customizationOf(false, ensurePackage), base: KERNEL }; + render( + + + + } /> + + , + ); + const at = await page(); + expect(at.page).toBe('list'); + expect(at.host).not.toHaveProperty('pairCreate'); + expect(ensurePackage).not.toHaveBeenCalled(); + }); + + it('a walled door never asks, and lands on the list as before', async () => { + const ensurePackage = vi.fn(); + mountCustomized(customizationOf(true, ensurePackage)); + expect((await page()).page).toBe('list'); + expect(ensurePackage).not.toHaveBeenCalled(); + }); +}); + describe('a pillar type opened from the area opens its pillar', () => { for (const [type, pillar] of [ ['object', 'data'], diff --git a/ui/packages/app-shell/src/views/studio-design/StudioMetadataArea.tsx b/ui/packages/app-shell/src/views/studio-design/StudioMetadataArea.tsx index 73d2a085959..59360eedffe 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioMetadataArea.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioMetadataArea.tsx @@ -89,26 +89,31 @@ const MetadataResourceHistoryPage = React.lazy(() => * verdict rule is the one `parsePackages` applies. One request either way: the * readers of that endpoint share it (`packages-io.ts`). */ -function useListedPackageWritable(packageId: string | null): boolean | null | undefined { - const [answer, setAnswer] = React.useState<{ id: string; writable: boolean | null } | null>(null); +function useListedPackageWritable(packageId: string | null): { writable: boolean | null | undefined; kernel: boolean } { + const [answer, setAnswer] = React.useState<{ id: string; writable: boolean | null; kernel: boolean } | null>(null); React.useEffect(() => { if (packageId === null) return; let cancelled = false; fetchListedPackageManifests().then( (manifests) => { - if (!cancelled) setAnswer({ id: packageId, writable: manifests.get(packageId)?.writable ?? null }); + if (cancelled) return; + const listed = manifests.get(packageId); + // objectstack#36897 — a kernel package (manifest scope `system` or + // `cloud`) has no pair: the ensure door refuses it (ADR-0146 D3). + const scope = listed?.manifest?.scope; + setAnswer({ id: packageId, writable: listed?.writable ?? null, kernel: scope === 'system' || scope === 'cloud' }); }, () => { // The surface reports the failure once (its package-list toast). - if (!cancelled) setAnswer({ id: packageId, writable: null }); + if (!cancelled) setAnswer({ id: packageId, writable: null, kernel: false }); }, ); return () => { cancelled = true; }; }, [packageId]); - if (packageId === null) return null; - return answer?.id === packageId ? answer.writable : undefined; + if (packageId === null) return { writable: null, kernel: false }; + return answer?.id === packageId ? { writable: answer.writable, kernel: answer.kernel } : { writable: undefined, kernel: false }; } function AreaLoading({ locale }: { locale: string }): React.ReactElement { @@ -207,17 +212,70 @@ function AreaHistoryRedirect(): React.ReactElement { return ; } -/** `/:type/new`: a read-only package takes no new item, so its create URL lands on the list. */ -function AreaCreate(): React.ReactElement { +/** + * `/:type/new`. A read-only package takes no new item of its own: + * objectstack#36897 — on a read-only base the create is its `.custom` pair's + * (ADR-0146 D3), asked of the ensure door and opened there; where the door + * refuses this caller (`customization.walled`), the package is a kernel + * package (which has no pair), or there is no base to pair, + * the create URL lands on the list, as before. + */ +function AreaCreate({ customization }: { customization: StudioBaseCustomization | null }): React.ReactElement { const { type = '' } = useParams<{ type: string }>(); const { search } = useLocation(); const host = useMetadataAreaHost(); if (host?.readOnly) { + if (customization && host.pairCreate) { + return ; + } return ; } return ; } +/** The create of a read-only base's pair: the ensure door names the pair (creating it on first use), then its create opens. */ +function AreaPairedCreate({ + type, + search, + customization, +}: { + type: string; + search: string; + customization: StudioBaseCustomization; +}): React.ReactElement { + const locale = useMetadataLocale(); + const [answer, setAnswer] = React.useState<{ to: string } | { error: string } | null>(null); + // Asked once per create: the surface may hand a new `customization` on any render. + const ensureRef = React.useRef(customization.ensurePackage); + ensureRef.current = customization.ensurePackage; + React.useEffect(() => { + let cancelled = false; + ensureRef.current().then( + (pair) => { + if (cancelled) return; + const query = new URLSearchParams(search); + query.set('package', pair.packageId); + setAnswer({ to: `${studioMetadataAreaPath(pair.packageId)}/${encodeURIComponent(type)}/new?${query.toString()}` }); + }, + (e: unknown) => { + if (!cancelled) setAnswer({ error: e instanceof Error ? e.message : String(e) }); + }, + ); + return () => { + cancelled = true; + }; + }, [type, search]); + if (answer && 'to' in answer) return ; + if (answer) { + return ( +
+ {answer.error} +
+ ); + } + return ; +} + export interface StudioMetadataAreaProps { /** The package the area is open on, or `null` for the cross-package leg. */ packageId: string | null; @@ -254,10 +312,14 @@ export function StudioMetadataArea({ // manifests (see the hook). Unknown stays ungated, as on the pillars: the // server's write gate is the authority, and a failed probe must not lock an // author out of a writable package. - const writable = useListedPackageWritable(packageId); + const { writable, kernel } = useListedPackageWritable(packageId); + const readOnly = packageId !== null && writable === false; + // objectstack#36897 — the list offers a create exactly where `AreaCreate` + // opens one in the pair; never on a kernel package, which has none. + const pairCreate = readOnly && !kernel && !!customization && !customization.walled; const host = React.useMemo( - () => ({ packageId, readOnly: packageId !== null && writable === false, basePath }), - [packageId, writable, basePath], + () => ({ packageId, readOnly, basePath, ...(pairCreate ? { pairCreate } : {}) }), + [packageId, readOnly, basePath, pairCreate], ); const editor: AreaEditorProps = { customization, publishNonce, onDraftSaved, publishRefusalFor }; @@ -278,7 +340,7 @@ export function StudioMetadataArea({ } /> } /> } /> - } /> + } /> } /> } /> diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index a14d70792ec..c33d5e0246c 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -86,7 +86,7 @@ import { type ConcurrentUpdateConflict, } from '@object-ui/plugin-detail'; import { ChevronRight, ChevronLeft, ChevronsLeft, ChevronsRight, Download, Rows2, Rows3, Rows4, AlignJustify, Loader2, Check } from 'lucide-react'; -import { useRowColor } from './useRowColor'; +import { useRowColor, rowTintClass } from './useRowColor'; import { GroupRow } from './GroupRow'; import { resolveRowCrudAffordances, resolveRowRecordCrudAffordance } from './rowCrudAffordances'; import { useRecordCrudVerdicts } from './hooks/useRecordCrudVerdicts'; @@ -379,6 +379,39 @@ export interface ObjectGridComponentProps extends ObjectGridExternalPaginationPr * composes, nothing an author writes, and no node key reaches it. */ recordLinkAdornment?: (record: any) => React.ReactNode; + /** + * [objectstack#36897] Host-drawn cells, by column field: a shown column + * whose field is a key here draws what the host returns for the row, in + * place of the grid's own cell renderer. Called with the row's value at + * that field and the row record. A column whose field is not a key keeps + * the grid's own cell, and an absent prop changes nothing. + * + * For a host whose rows are not records of an object (the console's + * metadata list: a switch with a confirm, a lock, a clone button): the grid + * still owns the table, its header, sort arrows, paging and row clicks; the + * host owns what a cell says. Table view only: the phone's card rows keep + * the grid's own title and summary. + * + * The table keeps its columns as state, re-seeded after a change of their + * identity: a host whose cells draw from state of its own passes the same + * functions on every render and reads that state when called (a ref), so + * a change redraws at once. + * + * A RUNTIME prop, never authored metadata: it is a React node a host + * composes, nothing an author writes, and no node key reaches it. + */ + hostCells?: Readonly React.ReactNode>>; + /** + * [objectstack#36897] A host-chosen tint for ONE row, as a colour name of + * the palette `rowColor` resolves (`red`, `amber`, …). `null`, `undefined` + * or a name outside the palette tints nothing; where it names one it wins + * over the row's authored `rowColor`. The tint reaches the row's sticky + * cells as `rowColor`'s does. + * + * A RUNTIME prop, never authored metadata: the host decides it, and no node + * key reaches it. + */ + rowTint?: (record: any) => string | null | undefined; /** * [objectstack#33317] Whether a click on a row opens anything, as the HOST * that owns the row click knows it. `false` ⇒ the row's record-link cells @@ -913,6 +946,8 @@ export const ObjectGrid: React.FC = ({ rowOperations, rowAdornment, recordLinkAdornment, + hostCells, + rowTint, rowOpensRecord, cellSelection: cellSelectionProp, headerMenu: hostHeaderMenu, @@ -3563,15 +3598,24 @@ export const ObjectGrid: React.FC = ({ // objectui#13330 — the host's node beside each row's title (`rowAdornment`): // in the declared name field's column when one is shown, else the first // shown column. After the cell's own content, never in place of it. + // objectstack#36897 — the host's own cells (`hostCells`), by column field. + const hostCelledColumns = hostCells + ? (orderedColumns as any[]).map((c) => { + const draw = typeof c?.accessorKey === 'string' && Object.prototype.hasOwnProperty.call(hostCells, c.accessorKey) + ? hostCells[c.accessorKey] + : undefined; + return draw ? { ...c, cell: (value: any, row: any) => draw(value, row) } : c; + }) + : orderedColumns; const tableColumns = (() => { - if (!rowAdornment) return orderedColumns; + if (!rowAdornment) return hostCelledColumns; const declaredTitle = declaredNameField(objectSchema); - const shown = (orderedColumns as any[]).filter((c) => c?.accessorKey !== '_actions'); + const shown = (hostCelledColumns as any[]).filter((c) => c?.accessorKey !== '_actions'); const titleColumn = (typeof declaredTitle === 'string' && declaredTitle !== '' ? shown.find((c) => c.accessorKey === declaredTitle) : undefined) ?? shown[0]; - if (!titleColumn) return orderedColumns; + if (!titleColumn) return hostCelledColumns; const cell = titleColumn.cell; const adorned = { ...titleColumn, @@ -3587,7 +3631,7 @@ export const ObjectGrid: React.FC = ({ ); }, }; - return (orderedColumns as any[]).map((c) => (c === titleColumn ? adorned : c)); + return (hostCelledColumns as any[]).map((c) => (c === titleColumn ? adorned : c)); })(); // objectstack#36290 — the card a cell's 「Change history」 item opened @@ -4005,7 +4049,9 @@ export const ObjectGrid: React.FC = ({ // that verdict, which is what this adds. showAddRow: !!operations?.create && addRowGranted, onAddRecord: onAddRecord, - rowClassName: schema.rowColor ? (row: any, _idx: number) => getRowClassName(row) : undefined, + rowClassName: schema.rowColor || rowTint + ? (row: any, _idx: number) => rowTintClass(rowTint?.(row)) ?? getRowClassName(row) + : undefined, rowStyle: schema.conditionalFormatting?.length ? (row: any, _idx: number) => getRowStyle(row) : undefined, frozenColumns: effectiveFrozenColumns, onSelectionChange: (rows: any[]) => { diff --git a/ui/packages/plugin-grid/src/__tests__/rowAdornment-13330.test.tsx b/ui/packages/plugin-grid/src/__tests__/rowAdornment-13330.test.tsx index 16dfc998cab..c27b863f187 100644 --- a/ui/packages/plugin-grid/src/__tests__/rowAdornment-13330.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/rowAdornment-13330.test.tsx @@ -64,6 +64,8 @@ function renderGrid(opts: { columns: unknown[]; objectExtra?: Record; rowAdornment?: (row: any) => React.ReactNode; + hostCells?: Record React.ReactNode>; + rowTint?: (row: any) => string | null | undefined; width?: number; }) { const dataSource = { @@ -84,6 +86,8 @@ function renderGrid(opts: { schema={schema} dataSource={dataSource} {...(opts.rowAdornment ? { rowAdornment: opts.rowAdornment } : {})} + {...(opts.hostCells ? { hostCells: opts.hostCells } : {})} + {...(opts.rowTint ? { rowTint: opts.rowTint } : {})} /> , @@ -133,3 +137,43 @@ describe('ObjectGrid rowAdornment (objectui#13330)', () => { expect(document.querySelector('[data-testid="grid-row-adornment"]')).toBeNull(); }); }); + +/** + * objectstack#36897 — `hostCells` (a host draws a column's cells, by field) + * and `rowTint` (a host tints a row by a palette name), for a host whose rows + * are not records of an object (the console's metadata list). + */ +describe('ObjectGrid hostCells and rowTint (objectstack#36897)', () => { + const rowOf = async (text: string) => (await cellOf(text)).closest('tr') as HTMLElement; + + it('a column whose field the host draws shows the host node; the other columns keep their own cells', async () => { + renderGrid({ + columns: [{ field: 'name' }, { field: 'notes' }], + hostCells: { notes: (value, row) => {`[${String(value)}]`} }, + }); + const host = await screen.findByTestId('host-r1'); + expect(host).toHaveTextContent('[Boiler room]'); + expect(host.closest('td')).toHaveTextContent(/^\[Boiler room\]$/); + expect(screen.getByTestId('host-r2')).toHaveTextContent('[Loading dock]'); + // The name column is the grid's own cell, unchanged. + expect(await cellOf('Plant A check')).toHaveTextContent(/^Plant A check$/); + }); + + it('a row the host tints carries the palette tint; a null answer and a name outside the palette tint nothing', async () => { + renderGrid({ + columns: [{ field: 'name' }, { field: 'notes' }], + rowTint: (row) => (row.id === 'r1' ? 'red' : 'bg-red-500'), + }); + const tinted = await rowOf('Plant A check'); + expect(tinted.className).toContain('[--os-row-tint:var(--color-red-100)]'); + const plain = await rowOf('Plant B check'); + expect(plain.className).not.toContain('--color-red-100'); + expect(plain.className).not.toContain('bg-red-500'); + }); + + it('CONTROL: without either prop every cell is the grid\'s own and no row is tinted', async () => { + renderGrid({ columns: [{ field: 'name' }, { field: 'notes' }] }); + expect(await cellOf('Boiler room')).toHaveTextContent(/^Boiler room$/); + expect((await rowOf('Plant A check')).className).not.toContain('--os-row-tint:var('); + }); +}); diff --git a/ui/packages/plugin-grid/src/useRowColor.ts b/ui/packages/plugin-grid/src/useRowColor.ts index 025f6a3451b..25ff3ed1801 100644 --- a/ui/packages/plugin-grid/src/useRowColor.ts +++ b/ui/packages/plugin-grid/src/useRowColor.ts @@ -117,6 +117,19 @@ function colorToClass(color: string): string | undefined { : undefined; } +/** + * The row class of a palette colour NAME (objectstack#36897, `ObjectGrid`'s + * host `rowTint`): `undefined` for none and for a name outside the palette. + * Unlike an authored `rowColor` value, a raw `bg-*` class is not admitted. + */ +export function rowTintClass(name: string | null | undefined): string | undefined { + if (typeof name !== 'string') return undefined; + const lower = name.toLowerCase().trim(); + return Object.prototype.hasOwnProperty.call(COLOR_TO_CLASS, lower) + ? `${ROW_TINT_SURFACE} ${COLOR_TO_CLASS[lower]}` + : undefined; +} + /** * Hook that returns a row-className resolver based on RowColorConfig. *