diff --git a/.changeset/36892-studio-detail-header.md b/.changeset/36892-studio-detail-header.md new file mode 100644 index 00000000000..81bb655d0a2 --- /dev/null +++ b/.changeset/36892-studio-detail-header.md @@ -0,0 +1,10 @@ +--- +'@object-ui/i18n': patch +--- + +feat(console): the strings of the one Studio detail header (close, previous, next, position, package, more) + +Clause-②: no +Metadata-protocol: none + +The `studio` namespace gains the `engine.studio.detailHeader.*` keys in English and Chinese, for the header every full-screen Studio detail will share: × back to the list, ‹ › with the item's position in the list, the source package chip and the ⋯ menu. The header itself lives in the private console shell and no page shows it yet. diff --git a/ui/e2e/studio-detail-header-width.spec.ts b/ui/e2e/studio-detail-header-width.spec.ts new file mode 100644 index 00000000000..3ebe26737b5 --- /dev/null +++ b/ui/e2e/studio-detail-header-width.spec.ts @@ -0,0 +1,313 @@ +import { test, expect, type Page } from '@playwright/test'; +import { compile } from 'tailwindcss'; +import { build, type Plugin, type Rollup } from 'vite'; +import { readFileSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import os from 'node:os'; +import path from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { uiRoot } from '../scripts/ui-root.mjs'; + +/** + * TEST PAGE for objectstack#36892: the full-screen Studio detail header + * (`StudioDetailHeader`), mounted at a wide and a narrow content column and + * measured in Chromium. + * + * ## Why a Playwright page and not a vitest test + * + * jsdom has no layout engine. The unit test (`StudioDetailHeader.test.tsx`) + * pins the fold's ORDER against stubbed widths; this page proves the real row + * computes it: on a wide column everything is whole in the row, on a narrow + * one the identity chips (type, package, api name) leave for ⋯ first, then the + * position text, the title keeps its readable width, and no box leaves the + * row. The bundling follows `e2e/studio-item-header-title-width.spec.ts`. + * + * ## What is real here and what is a fixture + * + * REAL: `StudioDetailHeader`, `StudioItemHeader` and everything they import, + * bundled by Vite from source and mounted with React's client renderer, and + * the real Tailwind theme compiled for the classes on the page. + * + * FIXTURES: the props (an object "Lead" from package "CRM", a draft status, a + * five-name list with the current item third, a "Publish" primary button and + * one ⋯ item); the row width is set by the box around the header (its 24 px + * side padding included), not by the console's rail and aside; fonts are + * whatever Chromium falls back to, so the assertions are relations (folded or + * whole, inside the row), never one font's pixels. + */ + +const REPO_ROOT = uiRoot(); +const source = (rel: string) => path.join(REPO_ROOT, rel); + +const DETAIL_HEADER = source('packages/app-shell/src/views/studio-detail/StudioDetailHeader.tsx'); +const COMPONENTS = source('packages/components/src/index.ts'); +const THEME_CSS = source('packages/components/src/index.css'); + +/** `px-6` on the header: the row is this much narrower than the header. */ +const HEADER_SIDE_PADDING = 48; + +const ENTRY = '\0studio-detail-header-width:entry'; + +function workspaceSources(): Plugin { + return { + name: 'studio-detail-header-width-workspace-src', + enforce: 'pre', + async resolveId(id, importer) { + const m = /^@object-ui\/([a-z0-9-]+)(?:\/(.+))?$/.exec(id); + if (!m) return null; + const [, pkg, sub] = m; + const target = + pkg === 'types' && sub === 'zod' + ? source('packages/types/src/zod/index.zod.ts') + : source(`packages/${pkg}/src${sub ? `/${sub}` : ''}`); + const resolved = await this.resolve(target, importer, { skipSelf: true }); + if (!resolved) throw new Error(`${id} did not resolve to a source file under ${target}`); + return resolved; + }, + }; +} + +function entry(): Plugin { + const code = ` +import * as React from 'react'; +import { createRoot } from 'react-dom/client'; +import { DropdownMenuItem } from ${JSON.stringify(COMPONENTS)}; +import { StudioDetailHeader } from ${JSON.stringify(DETAIL_HEADER)}; + +const h = React.createElement; +const Icon = (props) => h('svg', { ...props, viewBox: '0 0 16 16', 'aria-hidden': 'true' }, h('rect', { x: 2, y: 2, width: 12, height: 12 })); + +createRoot(document.getElementById('root')).render( + h('div', { id: 'frame', className: 'bg-background' }, + h(StudioDetailHeader, { + testId: 'hdr', + locale: 'en', + icon: Icon, + label: 'Lead qualification board', + apiName: 'lead_qualification', + typeLabel: 'Object', + packageLabel: 'CRM', + status: { label: 'Unpublished draft' }, + sequence: { names: ['account', 'contact', 'lead_qualification', 'opportunity', 'task'], current: 'lead_qualification' }, + onOpenItem: (name) => { window.__opened = name; }, + onClose: () => { window.__closed = (window.__closed ?? 0) + 1; }, + primaryAction: h('button', { type: 'button', 'data-testid': 'probe-primary', className: 'inline-flex h-7 shrink-0 items-center rounded-md bg-primary px-2.5 text-xs font-medium text-primary-foreground' }, 'Publish'), + menu: h(DropdownMenuItem, { 'data-testid': 'probe-delete' }, 'Delete'), + })), +); +`; + return { + name: 'studio-detail-header-width-entry', + resolveId: (id) => (id === 'studio-detail-header-width:entry' ? ENTRY : null), + load: (id) => (id === ENTRY ? code : null), + }; +} + +async function bundlePage(): Promise { + const result = await build({ + configFile: false, + root: REPO_ROOT, + cacheDir: path.join(os.tmpdir(), 'objectui-studio-detail-header-width'), + logLevel: 'error', + mode: 'production', + define: { 'process.env.NODE_ENV': JSON.stringify('production') }, + plugins: [workspaceSources(), entry()], + build: { + write: false, + minify: false, + target: 'es2022', + modulePreload: false, + reportCompressedSize: false, + rollupOptions: { + input: 'studio-detail-header-width:entry', + output: { format: 'es', codeSplitting: false }, + }, + }, + }); + const outputs = (Array.isArray(result) ? result : [result]) as Rollup.RollupOutput[]; + const chunks = outputs.flatMap((o) => o.output).filter((o): o is Rollup.OutputChunk => o.type === 'chunk'); + if (chunks.length !== 1) throw new Error(`expected one bundled chunk, got ${chunks.length}`); + return chunks[0].code; +} + +async function tailwindFor(candidates: string[]): Promise { + const requireFromComponents = createRequire(source('packages/components/package.json')); + const twEntry = requireFromComponents.resolve('tailwindcss/index.css'); + const compiler = await compile(readFileSync(THEME_CSS, 'utf8'), { + base: path.dirname(THEME_CSS), + loadStylesheet: async (id: string, base: string) => { + const file = id === 'tailwindcss' ? twEntry : path.resolve(base, id); + return { path: file, base: path.dirname(file), content: readFileSync(file, 'utf8') }; + }, + loadModule: async (id: string) => { + const file = requireFromComponents.resolve(id); + const mod = await import(pathToFileURL(file).href); + return { path: file, base: path.dirname(file), module: mod.default ?? mod }; + }, + }); + const css = compiler.build(candidates); + // An unstyled row would measure nothing the console draws. + for (const needle of ['@container', 'text-overflow: ellipsis', '--color-muted']) { + if (!css.includes(needle)) throw new Error(`Tailwind emitted nothing for ${needle}; the row would be unstyled.`); + } + return css; +} + +interface Reading { + row: { width: number; scrollWidth: number }; + title: { width: number; clipped: boolean }; + /** Which identity chips the row holds. */ + inRow: { type: boolean; package: boolean; apiName: boolean }; + /** The position text ("3 / 5") takes room in the row. */ + positionShown: boolean; + /** The actions' fold stage, as the header marks it. */ + fold: string | null; + /** Every box of the row lies inside it. */ + childrenInsideRow: boolean; + /** ×, ‹, › and ⋯ are drawn inside the row. */ + controlsInsideRow: boolean; + documentOverflowX: number; +} + +let bundle = ''; + +/** Mount on a page whose stylesheet is there before the header, as in the console. */ +async function mount(page: Page, row: number): Promise { + await page.setViewportSize({ width: row + HEADER_SIDE_PADDING, height: 400 }); + // First pass: collect the classes both forms of the header use. + const compiled = new Set(); + let css = ''; + for (let round = 0; ; round++) { + await page.setContent( + `
`, + ); + await page.evaluate((text) => { + document.getElementById('tailwind')!.textContent = text; + }, css); + await page.addScriptTag({ content: bundle, type: 'module' }); + await page.waitForSelector('[data-testid="studio-detail-title"]', { state: 'attached', timeout: 30_000 }); + await page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)))); + const candidates = await page.evaluate(() => [ + ...new Set( + [...document.querySelectorAll('[class]')].flatMap((el) => (el.getAttribute('class') ?? '').split(/\s+/)).filter(Boolean), + ), + ]); + if (round > 0 && candidates.every((cls) => compiled.has(cls))) break; + if (round === 5) throw new Error('the page kept adding classes; the stylesheet never caught up'); + candidates.forEach((cls) => compiled.add(cls)); + css = await tailwindFor([...compiled]); + } + await page.evaluate(() => document.fonts?.ready); + // Settle: two consecutive frames with the same title and actions widths. + await page.waitForFunction( + () => { + const title = document.querySelector('[data-testid="studio-detail-title"]'); + const actions = title?.parentElement?.lastElementChild; + if (!title || !actions) return false; + const sig = `${title.getBoundingClientRect().width},${actions.getBoundingClientRect().width},${actions.getAttribute('data-fold')}`; + const w = window as unknown as { __sig?: string }; + const prev = w.__sig; + w.__sig = sig; + return prev === sig; + }, + null, + { polling: 'raf', timeout: 10_000 }, + ); +} + +async function measure(page: Page): Promise { + return page.evaluate(() => { + const round = (n: number) => Math.round(n * 100) / 100; + const title = document.querySelector('[data-testid="studio-detail-title"]')!; + const row = title.parentElement!; + const rowRect = row.getBoundingClientRect(); + const actions = row.lastElementChild as HTMLElement; + const inside = (el: Element | null) => { + if (!el) return false; + const r = el.getBoundingClientRect(); + return r.width > 0 && r.left >= rowRect.left - 0.5 && r.right <= rowRect.right + 0.5; + }; + const inRow = (id: string) => { + const el = row.querySelector(`[data-testid="${id}"]`); + return !!el && el.getBoundingClientRect().width > 0; + }; + const boxes = Array.from(row.children) + .flatMap((el) => (getComputedStyle(el).display === 'contents' ? Array.from(el.children) : [el])) + .filter((el) => getComputedStyle(el).display !== 'none'); + const position = row.querySelector('[data-testid="studio-detail-position"]'); + return { + row: { width: round(rowRect.width), scrollWidth: row.scrollWidth }, + title: { width: round(title.getBoundingClientRect().width), clipped: title.scrollWidth > title.clientWidth }, + inRow: { type: inRow('studio-detail-type'), package: inRow('studio-detail-package'), apiName: inRow('studio-item-api-name') }, + positionShown: !!position && position.getBoundingClientRect().width > 1, + fold: actions.getAttribute('data-fold'), + childrenInsideRow: boxes.every((el) => { + const r = el.getBoundingClientRect(); + return r.left >= rowRect.left - 0.5 && r.right <= rowRect.right + 0.5; + }), + controlsInsideRow: ['studio-detail-close', 'studio-detail-previous', 'studio-detail-next', 'studio-detail-more'].every((id) => + inside(row.querySelector(`[data-testid="${id}"]`)), + ), + documentOverflowX: round(document.documentElement.scrollWidth - document.documentElement.clientWidth), + }; + }); +} + +async function read(page: Page, row: number, testInfo: import('@playwright/test').TestInfo): Promise { + await mount(page, row); + const r = await measure(page); + testInfo.annotations.push({ type: `studio-detail-header@${row}`, description: JSON.stringify(r) }); + process.stdout.write(`[studio-detail-header ${row}] ${JSON.stringify(r)}\n`); + return r; +} + +test.beforeAll(async () => { + test.setTimeout(240_000); + bundle = await bundlePage(); +}); + +test.describe('the Studio detail header at a wide and a narrow column (objectstack#36892)', () => { + test('wide (1024 px row): every part is whole in the row, nothing folded', async ({ page }, testInfo) => { + const r = await read(page, 1024, testInfo); + expect(r.row.width).toBe(1024); + expect(r.inRow).toEqual({ type: true, package: true, apiName: true }); + expect(r.positionShown).toBe(true); + expect(r.fold).toBeNull(); + expect(r.title.clipped).toBe(false); + expect(r.childrenInsideRow).toBe(true); + expect(r.controlsInsideRow).toBe(true); + expect(r.documentOverflowX).toBe(0); + await expect(page.getByTestId('studio-detail-position')).toHaveText('3 / 5'); + }); + + test('narrow (360 px row): the identity chips leave for ⋯, and ×, ‹ ›, ⋯ stay inside the row', async ({ page }, testInfo) => { + const r = await read(page, 360, testInfo); + expect(r.row.width).toBe(360); + expect(r.inRow).toEqual({ type: false, package: false, apiName: false }); + // Both of StudioItemHeader's stages are taken before the title is cut: + // the chips are in ⋯ and the position text is out of the row. + expect(r.fold).toBe('labels'); + expect(r.positionShown).toBe(false); + expect(r.title.width).toBeGreaterThan(0); + expect(r.childrenInsideRow).toBe(true); + expect(r.controlsInsideRow).toBe(true); + expect(r.row.scrollWidth).toBeLessThanOrEqual(Math.ceil(r.row.width)); + expect(r.documentOverflowX).toBe(0); + // The folded chips are in ⋯, above the page's own item. + await page.getByTestId('studio-detail-more').click(); + const menu = page.getByRole('menu'); + await expect(menu.getByTestId('studio-item-header-folded-chips')).toContainText('CRM'); + await expect(menu.getByTestId('probe-delete')).toBeVisible(); + }); + + test('narrow: the keyboard reaches ‹ ›, they step, and Esc triggers ×', async ({ page }, testInfo) => { + await read(page, 360, testInfo); + await page.getByTestId('studio-detail-previous').focus(); + await page.keyboard.press('Tab'); + await expect(page.getByTestId('studio-detail-next')).toBeFocused(); + await page.keyboard.press('Enter'); + expect(await page.evaluate(() => (window as unknown as { __opened?: string }).__opened)).toBe('opportunity'); + await page.keyboard.press('Escape'); + expect(await page.evaluate(() => (window as unknown as { __closed?: number }).__closed)).toBe(1); + }); +}); diff --git a/ui/packages/app-shell/src/views/studio-detail/StudioDetailHeader.test.tsx b/ui/packages/app-shell/src/views/studio-detail/StudioDetailHeader.test.tsx new file mode 100644 index 00000000000..023475cfbb0 --- /dev/null +++ b/ui/packages/app-shell/src/views/studio-detail/StudioDetailHeader.test.tsx @@ -0,0 +1,424 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36892 — the full-screen detail header: × back to the list, the + * type and source package chips, ‹ › with "index / total", the primary button + * and ⋯, composed from `StudioItemHeader`'s slots. + * + * jsdom has no layout, so the narrow-width describe block stubs the title + * row's geometry the way `StudioItemHeader.titleRowFold-12897.test.tsx` does: + * the row's width is the case's, every other box is fixed, and the title's box + * is the room the row leaves it, capped at its text. The real widths are + * measured in Chromium by `e2e/studio-detail-header-width.spec.ts`. + */ + +import '@testing-library/jest-dom/vitest'; +import * as React from 'react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react'; +import { Database } from 'lucide-react'; +import { DropdownMenuItem } from '@object-ui/components'; +import { StudioDetailHeader, detailSequence, type StudioDetailHeaderProps } from './StudioDetailHeader'; +import { registerUnsavedEdits } from '../../chrome/unsavedEdits'; +import { t } from '../metadata-admin/i18n'; + +const NAMES = ['account', 'contact', 'lead', 'opportunity', 'task']; + +function Header(props: Partial) { + return ( + + Publish + + } + menu={Delete} + {...props} + /> + ); +} + +function openMore(): HTMLElement { + fireEvent.pointerDown(screen.getByTestId('studio-detail-more'), { button: 0, ctrlKey: false, pointerType: 'mouse' }); + return screen.getByRole('menu'); +} + +/** The elements Tab reaches, in document order (no positive tabIndex is used here). */ +function tabbable(): HTMLElement[] { + return Array.from( + document.querySelectorAll('button, a[href], input, select, textarea, [tabindex]'), + ).filter((el) => !(el as HTMLButtonElement).disabled && el.tabIndex >= 0 && !el.closest('[hidden]')); +} + +/** `window.confirm`, which the leave guard asks; jsdom here has none of its own. */ +function stubConfirm(answer: boolean) { + const spy = vi.fn((_message?: string) => answer); + Object.defineProperty(window, 'confirm', { configurable: true, writable: true, value: spy }); + return spy; +} + +const releases: Array<() => void> = []; +afterEach(() => { + cleanup(); + for (const release of releases.splice(0)) release(); + vi.restoreAllMocks(); +}); + +describe('detailSequence: the position ‹ › step from', () => { + it('a middle item has both neighbours and a 1-based index', () => { + expect(detailSequence(NAMES, 'lead')).toEqual({ index: 3, total: 5, previous: 'contact', next: 'opportunity' }); + }); + + it('the first item has no previous, the last no next: the ends do not wrap', () => { + expect(detailSequence(NAMES, 'account')).toEqual({ index: 1, total: 5, previous: null, next: 'contact' }); + expect(detailSequence(NAMES, 'task')).toEqual({ index: 5, total: 5, previous: 'opportunity', next: null }); + }); + + it('a lone item has neither neighbour', () => { + expect(detailSequence(['lead'], 'lead')).toEqual({ index: 1, total: 1, previous: null, next: null }); + }); + + it('a name the list does not hold has no position and no neighbours', () => { + expect(detailSequence(NAMES, 'campaign')).toEqual({ index: null, total: 5, previous: null, next: null }); + expect(detailSequence([], 'lead')).toEqual({ index: null, total: 0, previous: null, next: null }); + }); +}); + +describe('the header’s parts', () => { + it('× leads the row, then the label, the api name, the type and package chips and the status', () => { + render(
); + const title = screen.getByTestId('studio-detail-title'); + const row = title.parentElement!; + expect(row.firstElementChild).toBe(screen.getByTestId('studio-detail-close')); + expect(title).toHaveTextContent('Lead'); + expect(screen.getByTestId('studio-item-api-name')).toHaveTextContent('lead'); + expect(screen.getByTestId('studio-detail-type')).toHaveTextContent('Object'); + expect(screen.getByTestId('studio-detail-package')).toHaveTextContent('CRM'); + expect(screen.getByTestId('studio-detail-package')).toHaveAccessibleName('From package CRM'); + expect(screen.getByTestId('studio-item-status')).toHaveTextContent('Unpublished draft'); + expect(screen.getByTestId('studio-detail-close')).toHaveAccessibleName(t('engine.studio.detailHeader.close', 'en')); + }); + + it('the actions are ‹ index / total ›, the primary button and ⋯, in that order', () => { + render(
); + const actions = screen.getByTestId('studio-detail-title').parentElement!.lastElementChild as HTMLElement; + expect(Array.from(actions.children).map((el) => el.getAttribute('data-testid'))).toEqual([ + 'studio-detail-pager', + 'probe-primary', + 'studio-detail-more', + ]); + expect(screen.getByTestId('studio-detail-position')).toHaveTextContent('3 / 5'); + expect(screen.getByTestId('studio-detail-pager')).toHaveAccessibleName('Item 3 of 5'); + }); + + it('no switcher dropdown and no "open in app": the only menu is ⋯, and it holds the page’s own items', () => { + render(
); + expect(screen.queryByRole('combobox')).toBeNull(); + expect(document.querySelectorAll('[aria-haspopup]')).toHaveLength(1); + const menu = openMore(); + expect(within(menu).getByTestId('probe-delete')).toBeInTheDocument(); + expect(within(menu).getAllByRole('menuitem')).toHaveLength(1); + }); + + it('without a sequence there is no ‹ ›; without menu items the row has no ⋯ while nothing is folded', () => { + render(
); + expect(screen.queryByTestId('studio-detail-pager')).toBeNull(); + expect(screen.queryByTestId('studio-detail-more')).toBeNull(); + }); +}); + +describe('‹ › step through the list, and the ends are off', () => { + it('‹ opens the previous name and › the next', () => { + const onOpenItem = vi.fn(); + render(
); + fireEvent.click(screen.getByTestId('studio-detail-previous')); + fireEvent.click(screen.getByTestId('studio-detail-next')); + expect(onOpenItem.mock.calls).toEqual([['contact'], ['opportunity']]); + }); + + it('on the first item ‹ is disabled; on the last › is', () => { + const { unmount } = render(
); + expect(screen.getByTestId('studio-detail-previous')).toBeDisabled(); + expect(screen.getByTestId('studio-detail-next')).toBeEnabled(); + expect(screen.getByTestId('studio-detail-position')).toHaveTextContent('1 / 5'); + unmount(); + render(
); + expect(screen.getByTestId('studio-detail-previous')).toBeEnabled(); + expect(screen.getByTestId('studio-detail-next')).toBeDisabled(); + expect(screen.getByTestId('studio-detail-position')).toHaveTextContent('5 / 5'); + }); + + it('an item outside the list shows no position, both steps off, and says so', () => { + render(
); + expect(screen.queryByTestId('studio-detail-position')).toBeNull(); + expect(screen.getByTestId('studio-detail-previous')).toBeDisabled(); + expect(screen.getByTestId('studio-detail-next')).toBeDisabled(); + expect(screen.getByTestId('studio-detail-pager')).toHaveAccessibleName(t('engine.studio.detailHeader.notInList', 'en')); + }); +}); + +describe('× and ‹ › go through the leave guard', () => { + it('with unsaved edits, Cancel keeps the page: neither × nor › leaves', () => { + releases.push(registerUnsavedEdits('Discard your changes?')); + const confirm = stubConfirm(false); + const onClose = vi.fn(); + const onOpenItem = vi.fn(); + render(
); + fireEvent.click(screen.getByTestId('studio-detail-close')); + fireEvent.click(screen.getByTestId('studio-detail-next')); + expect(confirm).toHaveBeenCalledTimes(2); + expect(confirm).toHaveBeenCalledWith('Discard your changes?'); + expect(onClose).not.toHaveBeenCalled(); + expect(onOpenItem).not.toHaveBeenCalled(); + }); + + it('with unsaved edits, OK leaves', () => { + releases.push(registerUnsavedEdits('Discard your changes?')); + stubConfirm(true); + const onClose = vi.fn(); + const onOpenItem = vi.fn(); + render(
); + fireEvent.click(screen.getByTestId('studio-detail-close')); + fireEvent.click(screen.getByTestId('studio-detail-previous')); + expect(onClose).toHaveBeenCalledTimes(1); + expect(onOpenItem).toHaveBeenCalledWith('contact'); + }); + + it('CONTROL: with nothing unsaved, × leaves without asking', () => { + const confirm = stubConfirm(true); + const onClose = vi.fn(); + render(
); + fireEvent.click(screen.getByTestId('studio-detail-close')); + expect(onClose).toHaveBeenCalledTimes(1); + expect(confirm).not.toHaveBeenCalled(); + }); +}); + +describe('the keyboard: Esc triggers ×, and ‹ › are reachable', () => { + it('Esc on the page triggers ×, through the leave guard', () => { + releases.push(registerUnsavedEdits('Discard your changes?')); + const confirm = stubConfirm(true); + const onClose = vi.fn(); + render(
); + fireEvent.keyDown(document.body, { key: 'Escape' }); + expect(confirm).toHaveBeenCalledTimes(1); + expect(onClose).toHaveBeenCalledTimes(1); + }); + + it('Esc in a text field is the field’s: × is not triggered', () => { + const onClose = vi.fn(); + render( + <> +
+ + , + ); + fireEvent.keyDown(screen.getByTestId('probe-input'), { key: 'Escape' }); + expect(onClose).not.toHaveBeenCalled(); + }); + + it('Esc with the ⋯ menu open closes the menu only; the next Esc triggers ×', () => { + const onClose = vi.fn(); + render(
); + const menu = openMore(); + fireEvent.keyDown(menu, { key: 'Escape' }); + expect(screen.queryByRole('menu')).toBeNull(); + expect(onClose).not.toHaveBeenCalled(); + fireEvent.keyDown(document.body, { key: 'Escape' }); + expect(onClose).toHaveBeenCalledTimes(1); + }); + + it('CONTROL: with closeOnEscape off, Esc does nothing; a modified Esc never closes', () => { + const onClose = vi.fn(); + const { unmount } = render(
); + fireEvent.keyDown(document.body, { key: 'Escape' }); + unmount(); + render(
); + fireEvent.keyDown(document.body, { key: 'Escape', shiftKey: true }); + expect(onClose).not.toHaveBeenCalled(); + }); + + it('×, ‹ and › are native buttons in the tab order, ‹ before ›, and take the focus', () => { + render(
); + const order = tabbable(); + const close = screen.getByTestId('studio-detail-close'); + const previous = screen.getByTestId('studio-detail-previous'); + const next = screen.getByTestId('studio-detail-next'); + for (const el of [close, previous, next]) { + expect(el.tagName).toBe('BUTTON'); + expect(order).toContain(el); + } + expect(order.indexOf(close)).toBeLessThan(order.indexOf(previous)); + expect(order.indexOf(previous)).toBeLessThan(order.indexOf(next)); + act(() => next.focus()); + expect(next).toHaveFocus(); + expect(previous).toHaveAccessibleName(t('engine.studio.detailHeader.previous', 'en')); + expect(next).toHaveAccessibleName(t('engine.studio.detailHeader.next', 'en')); + }); +}); + +// --------------------------------------------------------------------------- +// Narrow width: the fold is StudioItemHeader's, unchanged. +// --------------------------------------------------------------------------- + +/** Stubbed widths, in px. */ +const LEAD = 32; +const ICON = 32; +const STATUS = 30; +const API = 90; +const TYPE = 50; +const PACKAGE = 80; +const PAGER = 64; +const POSITION = 40; +const PRIMARY = 70; +const MORE = 32; +const TITLE_TEXT = 200; +/** The title's first twelve characters. */ +const READABLE = 100; +const layout = { row: 900 }; + +const resizeCallbacks = new Set<() => void>(); +const realRect = HTMLElement.prototype.getBoundingClientRect; +const rect = (width: number) => + ({ left: 0, right: width, width, top: 0, bottom: 32, height: 32, x: 0, y: 0, toJSON: () => ({}) }) as DOMRect; +const isRow = (el: Element) => el.classList.contains('@container'); +const inRow = (testId: string) => { + const el = screen.queryByTestId(testId); + return !!el && !el.closest('[role="menu"]'); +}; +const labelsShown = () => !document.querySelector('[data-fold="labels"]'); +const chipsWidth = () => + (inRow('studio-item-api-name') ? API : 0) + (inRow('studio-detail-type') ? TYPE : 0) + (inRow('studio-detail-package') ? PACKAGE : 0); +const actionsWidth = () => + (screen.queryByTestId('studio-detail-pager') ? PAGER : 0) + + (screen.queryByTestId('studio-detail-position') && labelsShown() ? POSITION : 0) + + (screen.queryByTestId('probe-primary') ? PRIMARY : 0) + + (screen.queryByTestId('studio-detail-more') ? MORE : 0); +const titleBox = () => Math.max(0, Math.min(TITLE_TEXT, layout.row - LEAD - ICON - chipsWidth() - STATUS - actionsWidth())); + +function resizeRow(width: number) { + layout.row = width; + act(() => { + for (const cb of resizeCallbacks) cb(); + }); +} + +describe('on a narrow row the fold follows StudioItemHeader’s rules', () => { + beforeEach(() => { + layout.row = 900; + vi.stubGlobal( + 'ResizeObserver', + class { + private readonly cb: () => void; + constructor(cb: () => void) { + this.cb = cb; + resizeCallbacks.add(cb); + } + observe() {} + unobserve() {} + disconnect() { + resizeCallbacks.delete(this.cb); + } + }, + ); + vi.spyOn(Range.prototype, 'getBoundingClientRect').mockImplementation(() => rect(READABLE)); + vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (this: HTMLElement) { + const id = this.dataset.testid; + if (isRow(this)) return rect(layout.row); + if (id === 'studio-item-api-name') return rect(API); + if (id === 'studio-detail-type') return rect(TYPE); + if (id === 'studio-detail-package') return rect(PACKAGE); + if (id === 'studio-detail-close') return rect(LEAD); + if (id === 'studio-item-status') return rect(STATUS); + if (id === 'studio-detail-title') return rect(titleBox()); + if (this.hasAttribute('data-studio-fold-label')) return rect(labelsShown() ? POSITION : 1); + if (this.parentElement && isRow(this.parentElement)) { + if (this.dataset.slot === 'identity-chips') return rect(chipsWidth()); + if (this.tagName === 'SPAN') return rect(ICON); + if (this.tagName === 'DIV') return rect(actionsWidth()); + } + return realRect.call(this); + }); + vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockImplementation(function (this: HTMLElement) { + if (isRow(this)) return layout.row; + if (this.dataset.testid === 'studio-detail-title') return titleBox(); + return 0; + }); + vi.spyOn(HTMLElement.prototype, 'scrollWidth', 'get').mockImplementation(function (this: HTMLElement) { + return this.dataset.testid === 'studio-detail-title' ? TITLE_TEXT : 0; + }); + }); + + afterEach(() => { + resizeCallbacks.clear(); + vi.unstubAllGlobals(); + }); + + const actions = () => screen.getByTestId('studio-detail-title').parentElement!.lastElementChild as HTMLElement; + + it('wide (900 px): nothing folds — the chips, the position and the title are whole in the row', () => { + render(
); + expect(inRow('studio-detail-type')).toBe(true); + expect(inRow('studio-detail-package')).toBe(true); + expect(inRow('studio-item-api-name')).toBe(true); + expect(actions()).not.toHaveAttribute('data-fold'); + expect(titleBox()).toBe(TITLE_TEXT); + }); + + it('narrow (560 px): the identity chips leave for ⋯ first, the position keeps its text', () => { + layout.row = 560; + render(
); + // Whole: 560 − 32 − 32 − 220 − 30 − 206 = 40 px of title. Chips folded: 260 px. + expect(screen.queryByTestId('studio-detail-type')).toBeNull(); + expect(screen.queryByTestId('studio-detail-package')).toBeNull(); + expect(actions()).not.toHaveAttribute('data-fold'); + expect(titleBox()).toBe(TITLE_TEXT); + const menu = openMore(); + const entry = within(menu).getByTestId('studio-item-header-folded-chips'); + expect(within(entry).getByTestId('studio-detail-type')).toHaveTextContent('Object'); + expect(within(entry).getByTestId('studio-detail-package')).toHaveTextContent('CRM'); + expect(within(menu).getByTestId('probe-delete')).toBeInTheDocument(); + }); + + it('narrower (380 px): then the position text leaves too, ‹ › stay, and the title keeps its readable width', () => { + layout.row = 380; + render(
); + expect(actions()).toHaveAttribute('data-fold', 'labels'); + expect(screen.getByTestId('studio-detail-previous')).toBeInTheDocument(); + expect(screen.getByTestId('studio-detail-next')).toBeInTheDocument(); + // The group keeps the position as its name while the text is out of the row. + expect(screen.getByTestId('studio-detail-pager')).toHaveAccessibleName('Item 3 of 5'); + expect(titleBox()).toBeGreaterThanOrEqual(READABLE); + }); + + it('it follows the row: folds as it narrows, and gives everything back as it widens', () => { + render(
); + resizeRow(380); + expect(actions()).toHaveAttribute('data-fold', 'labels'); + expect(screen.queryByTestId('studio-detail-type')).toBeNull(); + resizeRow(900); + expect(actions()).not.toHaveAttribute('data-fold'); + expect(inRow('studio-detail-type')).toBe(true); + }); + + it('without menu items of its own, the header draws its ⋯ only while the chips are folded', () => { + layout.row = 560; + render(
); + const menu = openMore(); + expect(within(menu).getByTestId('studio-item-header-folded-chips')).toBeInTheDocument(); + cleanup(); + layout.row = 900; + render(
); + expect(screen.queryByTestId('studio-detail-more')).toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/views/studio-detail/StudioDetailHeader.tsx b/ui/packages/app-shell/src/views/studio-detail/StudioDetailHeader.tsx new file mode 100644 index 00000000000..55430ad21a7 --- /dev/null +++ b/ui/packages/app-shell/src/views/studio-detail/StudioDetailHeader.tsx @@ -0,0 +1,305 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * StudioDetailHeader — the one header of every full-screen Studio detail + * (objectstack#36892, epic objectstack#36890). + * + * A thin composition of `StudioItemHeader`'s slots, nothing more: × (back to + * the list) in `leading`; the type and the source package as identity chips + * after the label and the api name; the status as the header's status chip; + * then, in `actions`, ‹ › with "index / total", the page's primary button and + * a ⋯ menu. Every width rule is `StudioItemHeader`'s own: the identity chips + * fold into the ⋯ menu first, then labelled actions (the position text here) + * show without their label, and the title truncates last. This file adds no + * measurement of its own. + * + * Settled by the epic: no switcher dropdown and no "open in app" button — to + * change item the user closes back to the list, steps with ‹ ›, or uses ⌘K. + * + * ‹ › take the current list's names in order and the current name + * ({@link detailSequence}); the page supplies the order (the list's filter + * and sort carried in the detail address, or by name without a list). + * + * × and ‹ › leave the page, so each goes through the leave guard + * (`confirmUnsavedLeave`): a page holding unsaved edits asks first. Browser + * Back is not intercepted, the platform's convention under `BrowserRouter` + * (`chrome/unsavedEdits.ts` says why). + * + * Esc triggers × unless something else answered it first: an open menu or + * dialog dismisses on Esc and marks the event handled, and a key aimed at a + * text field is left to the field. + */ + +import * as React from 'react'; +import { ChevronLeft, ChevronRight, MoreHorizontal, Package, X } from 'lucide-react'; +import { cn, DropdownMenu, DropdownMenuContent, DropdownMenuTrigger } from '@object-ui/components'; +import { + StudioItemHeader, + StudioItemHeaderFoldedItems, + type StudioItemStatus, +} from '../studio-design/StudioItemHeader.js'; +import { STUDIO_FOLD_LABEL, STUDIO_HEADER_ICON_BUTTON, STUDIO_KIND_CHIP } from '../studio-design/studio-tokens.js'; +import { confirmUnsavedLeave } from '../../chrome/unsavedEdits.js'; +import { t, tFormat } from '../metadata-admin/i18n.js'; + +/** Where the current item sits in the list ‹ › step through. */ +export interface DetailSequence { + /** 1-based position of the current name; `null` when the list does not hold it. */ + index: number | null; + /** How many names the list holds. */ + total: number; + /** The name ‹ opens; `null` on the first item or outside the list. */ + previous: string | null; + /** The name › opens; `null` on the last item or outside the list. */ + next: string | null; +} + +/** + * The position of `current` in `names` and its neighbours. The ends do not + * wrap: ‹ is off on the first item and › on the last. A name the list does + * not hold (an item filtered out since, a direct address) has no position and + * no neighbours. + */ +export function detailSequence(names: readonly string[], current: string): DetailSequence { + const at = names.indexOf(current); + if (at < 0) return { index: null, total: names.length, previous: null, next: null }; + return { + index: at + 1, + total: names.length, + previous: at > 0 ? names[at - 1] : null, + next: at < names.length - 1 ? names[at + 1] : null, + }; +} + +/** A keydown aimed at something the user types into, which keeps its own Esc. */ +function isTypingTarget(target: EventTarget | null): boolean { + if (!(target instanceof Element)) return false; + if (target instanceof HTMLElement && target.isContentEditable) return true; + return target.closest('input, textarea, select, [contenteditable]:not([contenteditable="false"]), [role="textbox"]') !== null; +} + +export interface StudioDetailHeaderProps { + /** The display locale for the header's own strings. */ + locale: string; + /** The item type's icon. */ + icon?: React.ElementType; + /** Set for an object: its tile in the object's palette colour (`StudioItemHeader.objectTile`). */ + objectTile?: { color?: string }; + /** The item's label. */ + label: React.ReactNode; + /** The item's machine name. */ + apiName?: string; + /** The item type, already translated ("Object", "Flow"). */ + typeLabel?: string; + /** The package the item comes from, as its label. */ + packageLabel?: string; + /** The item's status chip. */ + status?: StudioItemStatus; + /** Muted meta text after the status. */ + meta?: React.ReactNode; + /** + * The list ‹ › step through: its names in order, and the current one. + * Absent: no ‹ ›. + */ + sequence?: { names: readonly string[]; current: string }; + /** Opens another item of the list (‹ ›), once the leave guard lets it. */ + onOpenItem?: (name: string) => void; + /** Back to the list (× and Esc), once the leave guard lets it. */ + onClose: () => void; + /** Esc triggers ×; on by default. */ + closeOnEscape?: boolean; + /** + * The page's primary button. A labelled button marks its label + * `data-studio-fold-label` with `STUDIO_FOLD_LABEL`, so a narrow row shows + * its icon alone, as the header's other labelled actions do. + */ + primaryAction?: React.ReactNode; + /** The ⋯ menu's own items (`DropdownMenuItem`s). The folded chips go above them. */ + menu?: React.ReactNode; + /** The tab row (`StudioTab`s). */ + tabs?: React.ReactNode; + /** One line under the title row. */ + note?: React.ReactNode; + testId?: string; + className?: string; +} + +export function StudioDetailHeader({ + locale, + icon, + objectTile, + label, + apiName, + typeLabel, + packageLabel, + status, + meta, + sequence, + onOpenItem, + onClose, + closeOnEscape = true, + primaryAction, + menu, + tabs, + note, + testId, + className, +}: StudioDetailHeaderProps): React.ReactElement { + const close = () => confirmUnsavedLeave(onClose); + const open = (name: string | null) => { + if (name === null || !onOpenItem) return; + confirmUnsavedLeave(() => onOpenItem(name)); + }; + + // The latest close, for a listener installed once per enablement (keyed on + // the flag, never on a callback's identity). + const closeRef = React.useRef(close); + React.useLayoutEffect(() => { + closeRef.current = close; + }); + React.useEffect(() => { + if (!closeOnEscape) return undefined; + const onKeyDown = (e: KeyboardEvent) => { + if (e.key !== 'Escape' || e.defaultPrevented) return; + if (e.metaKey || e.ctrlKey || e.altKey || e.shiftKey) return; + if (isTypingTarget(e.target)) return; + closeRef.current(); + }; + document.addEventListener('keydown', onKeyDown); + return () => document.removeEventListener('keydown', onKeyDown); + }, [closeOnEscape]); + + const closeLabel = t('engine.studio.detailHeader.close', locale); + const moreLabel = t('engine.studio.detailHeader.more', locale); + const packageTitle = packageLabel ? tFormat('engine.studio.detailHeader.package', locale, { package: packageLabel }) : ''; + + const chips = + typeLabel || packageLabel ? ( + <> + {typeLabel && ( + + {typeLabel} + + )} + {packageLabel && ( + + + )} + + ) : undefined; + + const position = sequence ? detailSequence(sequence.names, sequence.current) : null; + const pager = position && ( +
+ + {position.index !== null && ( + + )} + +
+ ); + + // With items of its own the ⋯ is always there and takes the folded chips + // too; without, the header draws a ⋯ only while something is folded. + const moreMenu = menu ? ( + + + + + + + {menu} + + + ) : null; + + return ( + +