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