Skip to content

Commit 00dd362

Browse files
feat(console): one Studio detail header composite (×, package, ‹ › with position, ⋯, primary) (#36924)
<!-- claude-projects-attribution: {"github_login":"os-support-ai"} --> _Requested by **Yibo Wang** · [project thread](https://claude.ai/code/project/chan_01BVUyyPie8gHwoPM18iABwB?thread=cmsg_01BVUyyPie8gHwoPM18iABwBTuMGhLAZx29zwDrayDGZZF)_ repo:objectstack#3 · os-support-ai · session_01WGufziBCAytAzzCu3iPBFR Fixes #36892 Part of #36890 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户无感:这次只做出 Studio 全屏详情共用的头部零件,还没有放进任何页面。 - 属于「Studio 重构」大卡,替后面四张接入卡(对象、流程、通用详情等全屏详情页)先定下头部和「上一个/下一个」的接口。 - 出错也碰不到用户,因为没有页面用它;可以直接撤回。 - 无。 ## What changes - New `StudioDetailHeader` (`ui/packages/app-shell/src/views/studio-detail/StudioDetailHeader.tsx`): a thin composite over `StudioItemHeader`'s slots. × (back to the list) in `leading`; the type and the source package as identity chips after the label and api name; the status as the header's status chip; in `actions`, ‹ › with "index / total", the page's primary button (a slot), and ⋯ (the page's own menu items, with the folded chips above them via `StudioItemHeaderFoldedItems`). No switcher dropdown, no "open in app" (epic decision 7). - The ‹ › data interface is a plain prop: `sequence={{ names, current }}` plus `onOpenItem(name)`. `detailSequence(names, current)` (exported, pure) computes the 1-based index, total, previous and next; the ends do not wrap; a name the list does not hold has no position and both steps are off. The order itself comes later from the list card (decision 10: filter and sort in the detail address, by name without list context). - × , Esc and ‹ › all go through the existing leave-guard seam `confirmUnsavedLeave` in `chrome/unsavedEdits.ts`; browser Back is not intercepted (decision 12). Esc is ignored when a menu or dialog already handled it (Radix marks it `defaultPrevented`), when it is aimed at a text field, or with a modifier; `closeOnEscape={false}` turns it off. - Narrow widths reuse `StudioItemHeader`'s rules unchanged: the identity chips (api name, type, package) fold into ⋯ first; the position text carries `data-studio-fold-label` / `STUDIO_FOLD_LABEL` so it leaves the row at the second stage while ‹ › stay; the title is cut last. The composite does no measuring of its own. - Strings: `engine.studio.detailHeader.*` (close, previous, next, position, notInList, package, more) in the `studio` namespace, en + zh. - Not wired into any page (later cards do that). `StudioItemHeader.tsx`, `StudioDesignSurface.tsx` and `unsavedEdits.ts` are read, not edited. Placement: a new sibling folder `views/studio-detail/` rather than `studio-design/`, so this PR adds nothing under the `studio-design/**` surface another open card holds. ## Tests - `StudioDetailHeader.test.tsx` (24 tests): index math (middle, first, last, lone, outside the list, empty list); first/last disabled; ‹ › open the neighbours; the leave guard on × and › (Cancel keeps the page, OK leaves, nothing unsaved means no prompt); Esc triggers × (through the guard), not from a text field, not while ⋯ is open (that Esc closes the menu, the next one closes the page), not with `closeOnEscape` off or a modifier; ×, ‹, › are native buttons in tab order; the narrow-row fold at stubbed widths (wide 900 px nothing folds; 560 px chips fold into ⋯; 380 px the position label folds too; it follows resizes both ways; without menu items the header draws its own ⋯ only while folded). - Test page `ui/e2e/studio-detail-header-width.spec.ts`: the real component and real Tailwind in Chromium at a 1024 px row (everything whole, nothing folded, every box inside the row) and a 360 px row (chips folded into ⋯, position text out, both fold stages taken, ×, ‹, ›, ⋯ inside the row, no overflow), plus keyboard: Tab from ‹ reaches ›, Enter steps, Esc triggers ×. <details><summary>Readings (head 7a4b4a3)</summary> - `vitest run packages/app-shell/src/views/studio-detail/ packages/i18n/src/namespaces/studio/ packages/i18n/src/__tests__/`: Test Files 110 passed (110), Tests 2038 passed, 13 skipped (lock VERDICT command-exit 0). - Playwright (local scratch config, chromium only, no webServer): 3 passed. Readings: 1024 px `{"title":{"width":205.88,"clipped":false},"inRow":{"type":true,"package":true,"apiName":true},"positionShown":true,"fold":null,"childrenInsideRow":true,"controlsInsideRow":true,"documentOverflowX":0}`; 360 px `{"title":{"width":43.92,"clipped":true},"inRow":{"type":false,"package":false,"apiName":false},"positionShown":false,"fold":"labels","childrenInsideRow":true,"controlsInsideRow":true,"documentOverflowX":0}`. - `pnpm --filter @object-ui/app-shell run type-check`: exit 0 (both programs, the test one included). `pnpm --dir ui type-check:e2e`: exit 0. - `ui` i18n: `check:i18n-keys` exit 0, `check:i18n-drift` exit 0, `check:i18n-dead-keys` exit 0 (no `detailHeader` key reported). - eslint (`--no-inline-config`) on the new files: 0 errors, 1 warning (`react-refresh/only-export-components` for the exported pure `detailSequence`, the same shape `StudioItemHeader.tsx` already has). - Derived gate families (`dispatch-gates.mjs --commands`, 38): all exit 0 on the final tree except `pnpm --dir ui exec vitest run scripts/`, which failed once on `e2e-type-check.test.ts` "imports no workspace package" (the test page imported `@object-ui/components`); fixed in 7a4b4a3 by importing it by source path, and that file re-run green (15/15). `--ran` reconciliation: 38 of 38 accounted. </details> ## Acceptance notes - The test page is a Playwright spec (the repo has no Storybook); it measures geometry, so it follows `e2e/studio-item-header-title-width.spec.ts`'s bundling. - Esc is not advertised in the keyboard-shortcuts dialog: the composite is mounted nowhere yet, and advertising belongs beside the handler once a page mounts it (the wiring cards). - The changeset declares `Clause-②: no` as the claim says; a sibling i18n-only changeset declared `yes (widening)` for added keys, so the seat may want to confirm which reading applies to new keys in the `studio` namespace. - At a 360 px row the title is cut (about 44 px in this container's fallback font) after both fold stages: that is `StudioItemHeader`'s existing last step, not new behaviour. ## Verification Files to read first: `StudioDetailHeader.tsx` (the Esc listener and the ⋯ / `foldMenu` choice are the risk hunks), then `StudioDetailHeader.test.tsx`'s narrow-width block. Two-minute check: `pnpm --filter @object-ui/app-shell exec vitest run --root ../.. packages/app-shell/src/views/studio-detail/` and expect 24 passed. Session: https://claude.ai/code/session_01WGufziBCAytAzzCu3iPBFR 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- signed: repo:objectstack#3 · os-support-ai · session_01WGufziBCAytAzzCu3iPBFR --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 4f19091 commit 00dd362

6 files changed

Lines changed: 1068 additions & 0 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@object-ui/i18n': patch
3+
---
4+
5+
feat(console): the strings of the one Studio detail header (close, previous, next, position, package, more)
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
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.
Lines changed: 313 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,313 @@
1+
import { test, expect, type Page } from '@playwright/test';
2+
import { compile } from 'tailwindcss';
3+
import { build, type Plugin, type Rollup } from 'vite';
4+
import { readFileSync } from 'node:fs';
5+
import { createRequire } from 'node:module';
6+
import os from 'node:os';
7+
import path from 'node:path';
8+
import { pathToFileURL } from 'node:url';
9+
import { uiRoot } from '../scripts/ui-root.mjs';
10+
11+
/**
12+
* TEST PAGE for objectstack#36892: the full-screen Studio detail header
13+
* (`StudioDetailHeader`), mounted at a wide and a narrow content column and
14+
* measured in Chromium.
15+
*
16+
* ## Why a Playwright page and not a vitest test
17+
*
18+
* jsdom has no layout engine. The unit test (`StudioDetailHeader.test.tsx`)
19+
* pins the fold's ORDER against stubbed widths; this page proves the real row
20+
* computes it: on a wide column everything is whole in the row, on a narrow
21+
* one the identity chips (type, package, api name) leave for ⋯ first, then the
22+
* position text, the title keeps its readable width, and no box leaves the
23+
* row. The bundling follows `e2e/studio-item-header-title-width.spec.ts`.
24+
*
25+
* ## What is real here and what is a fixture
26+
*
27+
* REAL: `StudioDetailHeader`, `StudioItemHeader` and everything they import,
28+
* bundled by Vite from source and mounted with React's client renderer, and
29+
* the real Tailwind theme compiled for the classes on the page.
30+
*
31+
* FIXTURES: the props (an object "Lead" from package "CRM", a draft status, a
32+
* five-name list with the current item third, a "Publish" primary button and
33+
* one ⋯ item); the row width is set by the box around the header (its 24 px
34+
* side padding included), not by the console's rail and aside; fonts are
35+
* whatever Chromium falls back to, so the assertions are relations (folded or
36+
* whole, inside the row), never one font's pixels.
37+
*/
38+
39+
const REPO_ROOT = uiRoot();
40+
const source = (rel: string) => path.join(REPO_ROOT, rel);
41+
42+
const DETAIL_HEADER = source('packages/app-shell/src/views/studio-detail/StudioDetailHeader.tsx');
43+
const COMPONENTS = source('packages/components/src/index.ts');
44+
const THEME_CSS = source('packages/components/src/index.css');
45+
46+
/** `px-6` on the header: the row is this much narrower than the header. */
47+
const HEADER_SIDE_PADDING = 48;
48+
49+
const ENTRY = '\0studio-detail-header-width:entry';
50+
51+
function workspaceSources(): Plugin {
52+
return {
53+
name: 'studio-detail-header-width-workspace-src',
54+
enforce: 'pre',
55+
async resolveId(id, importer) {
56+
const m = /^@object-ui\/([a-z0-9-]+)(?:\/(.+))?$/.exec(id);
57+
if (!m) return null;
58+
const [, pkg, sub] = m;
59+
const target =
60+
pkg === 'types' && sub === 'zod'
61+
? source('packages/types/src/zod/index.zod.ts')
62+
: source(`packages/${pkg}/src${sub ? `/${sub}` : ''}`);
63+
const resolved = await this.resolve(target, importer, { skipSelf: true });
64+
if (!resolved) throw new Error(`${id} did not resolve to a source file under ${target}`);
65+
return resolved;
66+
},
67+
};
68+
}
69+
70+
function entry(): Plugin {
71+
const code = `
72+
import * as React from 'react';
73+
import { createRoot } from 'react-dom/client';
74+
import { DropdownMenuItem } from ${JSON.stringify(COMPONENTS)};
75+
import { StudioDetailHeader } from ${JSON.stringify(DETAIL_HEADER)};
76+
77+
const h = React.createElement;
78+
const Icon = (props) => h('svg', { ...props, viewBox: '0 0 16 16', 'aria-hidden': 'true' }, h('rect', { x: 2, y: 2, width: 12, height: 12 }));
79+
80+
createRoot(document.getElementById('root')).render(
81+
h('div', { id: 'frame', className: 'bg-background' },
82+
h(StudioDetailHeader, {
83+
testId: 'hdr',
84+
locale: 'en',
85+
icon: Icon,
86+
label: 'Lead qualification board',
87+
apiName: 'lead_qualification',
88+
typeLabel: 'Object',
89+
packageLabel: 'CRM',
90+
status: { label: 'Unpublished draft' },
91+
sequence: { names: ['account', 'contact', 'lead_qualification', 'opportunity', 'task'], current: 'lead_qualification' },
92+
onOpenItem: (name) => { window.__opened = name; },
93+
onClose: () => { window.__closed = (window.__closed ?? 0) + 1; },
94+
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'),
95+
menu: h(DropdownMenuItem, { 'data-testid': 'probe-delete' }, 'Delete'),
96+
})),
97+
);
98+
`;
99+
return {
100+
name: 'studio-detail-header-width-entry',
101+
resolveId: (id) => (id === 'studio-detail-header-width:entry' ? ENTRY : null),
102+
load: (id) => (id === ENTRY ? code : null),
103+
};
104+
}
105+
106+
async function bundlePage(): Promise<string> {
107+
const result = await build({
108+
configFile: false,
109+
root: REPO_ROOT,
110+
cacheDir: path.join(os.tmpdir(), 'objectui-studio-detail-header-width'),
111+
logLevel: 'error',
112+
mode: 'production',
113+
define: { 'process.env.NODE_ENV': JSON.stringify('production') },
114+
plugins: [workspaceSources(), entry()],
115+
build: {
116+
write: false,
117+
minify: false,
118+
target: 'es2022',
119+
modulePreload: false,
120+
reportCompressedSize: false,
121+
rollupOptions: {
122+
input: 'studio-detail-header-width:entry',
123+
output: { format: 'es', codeSplitting: false },
124+
},
125+
},
126+
});
127+
const outputs = (Array.isArray(result) ? result : [result]) as Rollup.RollupOutput[];
128+
const chunks = outputs.flatMap((o) => o.output).filter((o): o is Rollup.OutputChunk => o.type === 'chunk');
129+
if (chunks.length !== 1) throw new Error(`expected one bundled chunk, got ${chunks.length}`);
130+
return chunks[0].code;
131+
}
132+
133+
async function tailwindFor(candidates: string[]): Promise<string> {
134+
const requireFromComponents = createRequire(source('packages/components/package.json'));
135+
const twEntry = requireFromComponents.resolve('tailwindcss/index.css');
136+
const compiler = await compile(readFileSync(THEME_CSS, 'utf8'), {
137+
base: path.dirname(THEME_CSS),
138+
loadStylesheet: async (id: string, base: string) => {
139+
const file = id === 'tailwindcss' ? twEntry : path.resolve(base, id);
140+
return { path: file, base: path.dirname(file), content: readFileSync(file, 'utf8') };
141+
},
142+
loadModule: async (id: string) => {
143+
const file = requireFromComponents.resolve(id);
144+
const mod = await import(pathToFileURL(file).href);
145+
return { path: file, base: path.dirname(file), module: mod.default ?? mod };
146+
},
147+
});
148+
const css = compiler.build(candidates);
149+
// An unstyled row would measure nothing the console draws.
150+
for (const needle of ['@container', 'text-overflow: ellipsis', '--color-muted']) {
151+
if (!css.includes(needle)) throw new Error(`Tailwind emitted nothing for ${needle}; the row would be unstyled.`);
152+
}
153+
return css;
154+
}
155+
156+
interface Reading {
157+
row: { width: number; scrollWidth: number };
158+
title: { width: number; clipped: boolean };
159+
/** Which identity chips the row holds. */
160+
inRow: { type: boolean; package: boolean; apiName: boolean };
161+
/** The position text ("3 / 5") takes room in the row. */
162+
positionShown: boolean;
163+
/** The actions' fold stage, as the header marks it. */
164+
fold: string | null;
165+
/** Every box of the row lies inside it. */
166+
childrenInsideRow: boolean;
167+
/** ×, ‹, › and ⋯ are drawn inside the row. */
168+
controlsInsideRow: boolean;
169+
documentOverflowX: number;
170+
}
171+
172+
let bundle = '';
173+
174+
/** Mount on a page whose stylesheet is there before the header, as in the console. */
175+
async function mount(page: Page, row: number): Promise<void> {
176+
await page.setViewportSize({ width: row + HEADER_SIDE_PADDING, height: 400 });
177+
// First pass: collect the classes both forms of the header use.
178+
const compiled = new Set<string>();
179+
let css = '';
180+
for (let round = 0; ; round++) {
181+
await page.setContent(
182+
`<!doctype html><html><head><style>html,body{margin:0}</style><style id="tailwind"></style></head><body><div id="root"></div></body></html>`,
183+
);
184+
await page.evaluate((text) => {
185+
document.getElementById('tailwind')!.textContent = text;
186+
}, css);
187+
await page.addScriptTag({ content: bundle, type: 'module' });
188+
await page.waitForSelector('[data-testid="studio-detail-title"]', { state: 'attached', timeout: 30_000 });
189+
await page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))));
190+
const candidates = await page.evaluate(() => [
191+
...new Set(
192+
[...document.querySelectorAll('[class]')].flatMap((el) => (el.getAttribute('class') ?? '').split(/\s+/)).filter(Boolean),
193+
),
194+
]);
195+
if (round > 0 && candidates.every((cls) => compiled.has(cls))) break;
196+
if (round === 5) throw new Error('the page kept adding classes; the stylesheet never caught up');
197+
candidates.forEach((cls) => compiled.add(cls));
198+
css = await tailwindFor([...compiled]);
199+
}
200+
await page.evaluate(() => document.fonts?.ready);
201+
// Settle: two consecutive frames with the same title and actions widths.
202+
await page.waitForFunction(
203+
() => {
204+
const title = document.querySelector('[data-testid="studio-detail-title"]');
205+
const actions = title?.parentElement?.lastElementChild;
206+
if (!title || !actions) return false;
207+
const sig = `${title.getBoundingClientRect().width},${actions.getBoundingClientRect().width},${actions.getAttribute('data-fold')}`;
208+
const w = window as unknown as { __sig?: string };
209+
const prev = w.__sig;
210+
w.__sig = sig;
211+
return prev === sig;
212+
},
213+
null,
214+
{ polling: 'raf', timeout: 10_000 },
215+
);
216+
}
217+
218+
async function measure(page: Page): Promise<Reading> {
219+
return page.evaluate(() => {
220+
const round = (n: number) => Math.round(n * 100) / 100;
221+
const title = document.querySelector<HTMLElement>('[data-testid="studio-detail-title"]')!;
222+
const row = title.parentElement!;
223+
const rowRect = row.getBoundingClientRect();
224+
const actions = row.lastElementChild as HTMLElement;
225+
const inside = (el: Element | null) => {
226+
if (!el) return false;
227+
const r = el.getBoundingClientRect();
228+
return r.width > 0 && r.left >= rowRect.left - 0.5 && r.right <= rowRect.right + 0.5;
229+
};
230+
const inRow = (id: string) => {
231+
const el = row.querySelector(`[data-testid="${id}"]`);
232+
return !!el && el.getBoundingClientRect().width > 0;
233+
};
234+
const boxes = Array.from(row.children)
235+
.flatMap((el) => (getComputedStyle(el).display === 'contents' ? Array.from(el.children) : [el]))
236+
.filter((el) => getComputedStyle(el).display !== 'none');
237+
const position = row.querySelector('[data-testid="studio-detail-position"]');
238+
return {
239+
row: { width: round(rowRect.width), scrollWidth: row.scrollWidth },
240+
title: { width: round(title.getBoundingClientRect().width), clipped: title.scrollWidth > title.clientWidth },
241+
inRow: { type: inRow('studio-detail-type'), package: inRow('studio-detail-package'), apiName: inRow('studio-item-api-name') },
242+
positionShown: !!position && position.getBoundingClientRect().width > 1,
243+
fold: actions.getAttribute('data-fold'),
244+
childrenInsideRow: boxes.every((el) => {
245+
const r = el.getBoundingClientRect();
246+
return r.left >= rowRect.left - 0.5 && r.right <= rowRect.right + 0.5;
247+
}),
248+
controlsInsideRow: ['studio-detail-close', 'studio-detail-previous', 'studio-detail-next', 'studio-detail-more'].every((id) =>
249+
inside(row.querySelector(`[data-testid="${id}"]`)),
250+
),
251+
documentOverflowX: round(document.documentElement.scrollWidth - document.documentElement.clientWidth),
252+
};
253+
});
254+
}
255+
256+
async function read(page: Page, row: number, testInfo: import('@playwright/test').TestInfo): Promise<Reading> {
257+
await mount(page, row);
258+
const r = await measure(page);
259+
testInfo.annotations.push({ type: `studio-detail-header@${row}`, description: JSON.stringify(r) });
260+
process.stdout.write(`[studio-detail-header ${row}] ${JSON.stringify(r)}\n`);
261+
return r;
262+
}
263+
264+
test.beforeAll(async () => {
265+
test.setTimeout(240_000);
266+
bundle = await bundlePage();
267+
});
268+
269+
test.describe('the Studio detail header at a wide and a narrow column (objectstack#36892)', () => {
270+
test('wide (1024 px row): every part is whole in the row, nothing folded', async ({ page }, testInfo) => {
271+
const r = await read(page, 1024, testInfo);
272+
expect(r.row.width).toBe(1024);
273+
expect(r.inRow).toEqual({ type: true, package: true, apiName: true });
274+
expect(r.positionShown).toBe(true);
275+
expect(r.fold).toBeNull();
276+
expect(r.title.clipped).toBe(false);
277+
expect(r.childrenInsideRow).toBe(true);
278+
expect(r.controlsInsideRow).toBe(true);
279+
expect(r.documentOverflowX).toBe(0);
280+
await expect(page.getByTestId('studio-detail-position')).toHaveText('3 / 5');
281+
});
282+
283+
test('narrow (360 px row): the identity chips leave for ⋯, and ×, ‹ ›, ⋯ stay inside the row', async ({ page }, testInfo) => {
284+
const r = await read(page, 360, testInfo);
285+
expect(r.row.width).toBe(360);
286+
expect(r.inRow).toEqual({ type: false, package: false, apiName: false });
287+
// Both of StudioItemHeader's stages are taken before the title is cut:
288+
// the chips are in ⋯ and the position text is out of the row.
289+
expect(r.fold).toBe('labels');
290+
expect(r.positionShown).toBe(false);
291+
expect(r.title.width).toBeGreaterThan(0);
292+
expect(r.childrenInsideRow).toBe(true);
293+
expect(r.controlsInsideRow).toBe(true);
294+
expect(r.row.scrollWidth).toBeLessThanOrEqual(Math.ceil(r.row.width));
295+
expect(r.documentOverflowX).toBe(0);
296+
// The folded chips are in ⋯, above the page's own item.
297+
await page.getByTestId('studio-detail-more').click();
298+
const menu = page.getByRole('menu');
299+
await expect(menu.getByTestId('studio-item-header-folded-chips')).toContainText('CRM');
300+
await expect(menu.getByTestId('probe-delete')).toBeVisible();
301+
});
302+
303+
test('narrow: the keyboard reaches ‹ ›, they step, and Esc triggers ×', async ({ page }, testInfo) => {
304+
await read(page, 360, testInfo);
305+
await page.getByTestId('studio-detail-previous').focus();
306+
await page.keyboard.press('Tab');
307+
await expect(page.getByTestId('studio-detail-next')).toBeFocused();
308+
await page.keyboard.press('Enter');
309+
expect(await page.evaluate(() => (window as unknown as { __opened?: string }).__opened)).toBe('opportunity');
310+
await page.keyboard.press('Escape');
311+
expect(await page.evaluate(() => (window as unknown as { __closed?: number }).__closed)).toBe(1);
312+
});
313+
});

0 commit comments

Comments
 (0)