import fs from 'node:fs'; import { expect, test } from '@playwright/test'; import { strFromU8, unzipSync } from 'fflate'; import type OLMap from 'ol/Map'; import type VectorLayer from 'ol/layer/Vector'; import type VectorSource from 'ol/source/Vector'; test.describe('workbench editing shell', () => { test.beforeEach(async ({ page }) => { await page.goto('/'); await expect(page.getByText('道路编译工作台', { exact: true })).toBeVisible(); }); test('starts in browse mode and persists the edit switch', async ({ page }) => { const mode = page.getByRole('switch', { name: '编辑模式' }); await expect(mode).not.toBeChecked(); await expect(page.getByRole('button', { name: '放弃' })).toHaveCount(0); await mode.check(); await expect(mode).toBeChecked(); await expect(page.getByRole('button', { name: '放弃' })).toBeVisible(); await page.reload(); await expect(page.getByRole('switch', { name: '编辑模式' })).toBeChecked(); }); test('keeps the map mounted while compiling the current edits', async ({ page }) => { const map = page.getByLabel('道路地图'); await expect(map).toBeVisible(); const canvasCount = await map.locator('canvas').count(); expect(canvasCount).toBeGreaterThan(0); await page.getByRole('button', { name: '保存并重新生成' }).click(); await expect(page.getByText('已保存并重新生成')).toBeVisible({ timeout: 30_000 }); await expect(map).toBeVisible(); await expect(map.locator('canvas')).toHaveCount(canvasCount); }); test('supports layer visibility and inspector accordion state', async ({ page }) => { const roads = page.getByLabel('自研道路与路口面'); await expect(roads).toBeChecked(); await roads.uncheck(); await expect(roads).not.toBeChecked(); await roads.check(); const issues = page.getByText(/待检查问题(/).locator('..'); await expect(issues).not.toHaveAttribute('open', ''); await issues.locator('summary').click(); await expect(issues).toHaveAttribute('open', ''); await issues.locator('summary').click(); await expect(issues).not.toHaveAttribute('open', ''); const overview = page.getByText('当前编译概览').locator('..'); await overview.locator('summary').click(); await expect(overview).toHaveAttribute('open', ''); }); test('edits a signal field and can discard the draft', async ({ page }) => { await page.getByRole('switch', { name: '编辑模式' }).check(); await page.getByText('元素', { exact: true }).click(); const signalSelect = page.getByLabel('检查信号灯'); await expect(signalSelect.locator('option')).not.toHaveCount(1); await signalSelect.selectOption({ index: 1 }); const heading = page.getByLabel('横杆方向(度)'); const original = await heading.inputValue(); await heading.fill(String((Number(original) + 15) % 360)); await expect(page.getByText('未保存修改 0 项')).toHaveCount(0); await expect(page.getByRole('button', { name: '放弃' })).toBeEnabled(); await page.getByRole('button', { name: '放弃' }).click(); await expect(page.getByRole('button', { name: '放弃' })).toBeDisabled(); await expect(heading).toHaveValue(original); }); test('sends the compile request through the browser workflow', async ({ page }) => { const compile = page.waitForRequest( (request) => request.method() === 'POST' && request.url().endsWith('/api/compile'), ); await page.getByRole('button', { name: '保存并重新生成' }).click(); await compile; await expect(page.getByText('已保存并重新生成')).toBeVisible({ timeout: 30_000 }); }); test('exports a package that satisfies the native-road contract', async ({ page }) => { const downloadPromise = page.waitForEvent('download'); await page.getByRole('link', { name: '导出道路包' }).click(); const download = await downloadPromise; expect(download.suggestedFilename()).toBe('e2e-fengshu-er-road.native-road.zip'); const archivePath = await download.path(); expect(archivePath).toBeTruthy(); const entries = unzipSync(fs.readFileSync(archivePath!)); const names = Object.keys(entries); const manifest = JSON.parse(strFromU8(entries['manifest.json'])); expect(manifest).toMatchObject({ areaId: 'e2e-fengshu-er-road', contract: 'native-road-package/v1.1' }); expect(names).toContain('compiled.json'); expect(names).toContain('traffic-signal-assemblies.json'); expect(names).toContain('traffic-signals.json'); expect(names.some((name) => name.includes('override') || name.endsWith('.osm'))).toBe(false); expect(JSON.parse(strFromU8(entries['compiled.json']))).not.toHaveProperty('source'); }); test('exposes the edit-only history controls without changing browse controls', async ({ page }) => { await expect(page.getByRole('button', { name: '撤销' })).toHaveCount(0); await page.getByRole('switch', { name: '编辑模式' }).check(); await expect(page.getByRole('button', { name: '撤销' })).toBeVisible(); await expect(page.getByRole('button', { name: '重做' })).toBeVisible(); await expect(page.getByRole('button', { name: '放弃' })).toBeVisible(); await page.getByRole('switch', { name: '编辑模式' }).uncheck(); await expect(page.getByRole('button', { name: '撤销' })).toHaveCount(0); }); test('opens an ordinary junction from a deep link with its workspace context', async ({ page }) => { const state = await page.request.get('/api/state').then((response) => response.json()); const nodeCounts = new Map(); for (const endpoint of state.compiled.model.endpoints) { const nodeId = String(endpoint.nodeId); nodeCounts.set(nodeId, (nodeCounts.get(nodeId) || 0) + 1); } const nodeId = [...nodeCounts].find(([, count]) => count >= 2)?.[0]; expect(nodeId).toBeTruthy(); await page.goto(`/junction/node/${encodeURIComponent(nodeId!)}`); await expect(page.getByLabel('路口编辑工作区')).toBeVisible(); await expect(page.getByLabel('道路地图')).toBeVisible(); expect((await page.getByLabel('道路地图').boundingBox())?.width).toBeGreaterThan(0); await expect(page.getByText('JunctionTools', { exact: true })).toBeVisible(); await expect(page.getByText(nodeId, { exact: true })).toHaveCount(0); await expect(page.getByText('设施与验证', { exact: true })).toBeVisible(); await expect(page.getByText('当前为浏览模式,开启编辑后可调整路口几何参数')).toBeVisible(); await page.getByRole('button', { name: '开启编辑模式' }).click(); await expect(page.getByLabel('路口编辑工作区').getByText('路口参数', { exact: true })).toBeVisible(); await expect(page.getByLabel('路口编辑工作区').getByText('展开单独定制', { exact: true }).first()).toBeVisible(); await expect(page.getByLabel('路口编辑工作区').getByText('进口收口距离', { exact: true })).toBeVisible(); await expect( page .getByLabel('路口编辑工作区') .getByText(/进口宽度/) .first(), ).toBeVisible(); }); test('discards junction drafts and lists each approach road once', async ({ page }) => { const state = await page.request.get('/api/state').then((response) => response.json()); const nodeCounts = new Map(); for (const endpoint of state.compiled.model.endpoints) { const nodeId = String(endpoint.nodeId); nodeCounts.set(nodeId, (nodeCounts.get(nodeId) || 0) + 1); } const nodeId = [...nodeCounts].find(([, count]) => count >= 2)?.[0]; expect(nodeId).toBeTruthy(); await page.goto(`/junction/node/${encodeURIComponent(nodeId!)}`); await page.getByRole('button', { name: '开启编辑模式' }).click(); const roadsText = await page.locator('.junction-workspace__body dd').nth(1).innerText(); const roads = roadsText .split('、') .map((road) => road.trim()) .filter(Boolean); expect(new Set(roads).size).toBe(roads.length); const input = page.getByLabel('路口编辑工作区').locator('input').first(); const original = Number(await input.inputValue()); await input.fill(String(original + 0.1)); await expect(page.getByRole('button', { name: '放弃草稿' })).toBeEnabled(); await page.getByRole('button', { name: '放弃草稿' }).click(); await expect(input).toHaveValue(String(original)); await page.getByRole('button', { name: '展开单独定制' }).first().click(); const detailRows = page.locator('.parameter-group__details .parameter'); await expect(detailRows.first()).toBeVisible(); await expect(detailRows.first().locator('.parameter-label')).toContainText(/进口/); }); test('opens a junction signal from the local facility list without exposing delete', async ({ page }) => { const state = await page.request.get('/api/state').then((response) => response.json()); const nodeCounts = new Map(); for (const endpoint of state.compiled.model.endpoints) { const nodeId = String(endpoint.nodeId); nodeCounts.set(nodeId, (nodeCounts.get(nodeId) || 0) + 1); } const nodeId = [...nodeCounts].find(([, count]) => count >= 2)?.[0]; expect(nodeId).toBeTruthy(); await page.goto(`/junction/node/${encodeURIComponent(nodeId!)}`); await page.getByRole('button', { name: '开启编辑模式' }).click(); const signalItem = page .getByLabel('已有设施') .getByRole('button', { name: /信号灯/ }) .first(); if ((await signalItem.count()) === 0) return; await signalItem.click(); const signalSelect = page.getByLabel('检查信号灯'); await expect(signalSelect).toHaveValue(/.+/); await expect(page.getByRole('button', { name: '删除信号灯' })).toHaveCount(0); await expect(page.getByText('当前选中:信号灯。可在下方参数中调整。')).toBeVisible(); const heading = page.getByLabel('横杆方向(度)'); const original = await heading.inputValue(); await heading.fill(String((Number(original) + 15) % 360)); await expect(page.getByRole('button', { name: '放弃草稿' })).toBeEnabled(); await page.getByRole('button', { name: '放弃草稿' }).click(); await expect(heading).toHaveValue(original); }); test('keeps complex junction structure and map selection linked across reload', async ({ page }) => { test.setTimeout(60_000); const initial = await page.request.get('/api/state').then((response) => response.json()); const candidate = initial.debug.junctionCandidates.find((item: { nodeIds: string[] }) => item.nodeIds.length >= 3); expect(candidate).toBeTruthy(); const acceptedResponse = await page.request.post('/api/junction-clusters', { data: { candidateId: candidate.id, nodeIds: candidate.nodeIds }, }); expect(acceptedResponse.ok()).toBe(true); const accepted = await acceptedResponse.json(); const id = accepted.added.id; const structure = accepted.junctionStructures[`cluster:${id}`]; expect(structure.arms.length).toBeGreaterThanOrEqual(3); await page.goto(`/junction/cluster/${encodeURIComponent(id)}`); const workspace = page.getByLabel('路口编辑工作区'); await expect(workspace).toBeVisible(); const armButtons = workspace.locator('.junction-workspace__object-list').first().getByRole('button'); await expect(armButtons).toHaveCount(structure.arms.length); const map = await page .getByLabel('道路地图') .evaluateHandle((element) => (element as HTMLDivElement & { __roadWorkbenchMap: OLMap }).__roadWorkbenchMap); await armButtons.first().click(); await expect(armButtons.first()).toHaveAttribute('aria-pressed', 'true'); await expect .poll(async () => page.getByLabel('道路地图').evaluate((element) => { const map = (element as HTMLDivElement & { __roadWorkbenchMap: OLMap }).__roadWorkbenchMap; const layer = map .getLayers() .getArray() .find((item) => item.getZIndex() === 89) as VectorLayer | undefined; return layer?.getSource()?.getFeatures().length || 0; }), ) .toBeGreaterThan(0); const sameMap = await page .getByLabel('道路地图') .evaluate( (element, original) => (element as HTMLDivElement & { __roadWorkbenchMap: OLMap }).__roadWorkbenchMap === original, map, ); expect(sameMap).toBe(true); await expect(workspace.getByText('路口参数', { exact: true })).toHaveCount(0); const scoped = await page.request .get(`/api/edit-state?cluster=${encodeURIComponent(id)}`) .then((response) => response.json()); expect(scoped.handles.handles.length).toBeGreaterThan(0); expect( scoped.handles.handles.every( (handle: { kind: string; editable: boolean }) => [ 'cluster-carriageway-width', 'cluster-carriageway-cutback', 'cluster-carriageway-transition-length', 'cluster-carriageway-position', 'cluster-carriageway-direction', 'cluster-carriageway-edge-offset', 'cluster-corner-radius', 'cluster-island-offset', 'cluster-crossing-inset', 'cluster-stop-line-offset', ].includes(handle.kind) && handle.editable, ), ).toBe(true); expect(scoped.junctionStructure.topologyFingerprint).toBe(structure.topologyFingerprint); await page.getByRole('button', { name: '开启编辑模式' }).click(); await expect(workspace.getByText('路口参数', { exact: true })).toBeVisible(); await expect(workspace.getByText(/车行道宽度/).first()).toBeVisible(); await expect(workspace.getByText(/车行道收口距离/).first()).toBeVisible(); await expect(workspace.getByText(/角部圆角/).first()).toBeVisible(); const cornerGroup = workspace.locator('.parameter-group').filter({ hasText: '角部圆角' }); const parameterInput = cornerGroup.locator('.parameter-input').first(); const parameterValue = Number(await parameterInput.inputValue()); const baselinePreview = await page.request .post('/api/edit-preview', { data: { previewSeq: 0, document: scoped.document, selection: { cluster: id } } }) .then((response) => response.json()); const roadGeometry = ( preview: { layers: { roadSurface: { features: Array<{ properties: { native_id?: string }; geometry: unknown }> } }; }, nativeId: string, ) => preview.layers.roadSurface.features.find((feature) => feature.properties.native_id === nativeId)?.geometry; const previewRequest = page.waitForRequest( (request) => request.method() === 'POST' && request.url().endsWith('/api/edit-preview'), ); const previewResponse = page.waitForResponse( (response) => response.request().method() === 'POST' && response.url().endsWith('/api/edit-preview'), ); await parameterInput.fill(String(parameterValue + 2)); await parameterInput.press('Enter'); const request = await previewRequest; const response = await previewResponse; const requestBody = request.postDataJSON() as { constraints: Array<{ kind: string; value: { radiusMeters: number }; anchor: { cornerKey: string } }>; }; expect(requestBody.constraints).toHaveLength(structure.corners.length); expect(requestBody.constraints.every((constraint) => constraint.kind === 'cluster-corner-radius')).toBe(true); expect(requestBody.constraints.every((constraint) => constraint.value.radiusMeters === parameterValue + 2)).toBe( true, ); const cornerKey = requestBody.constraints[0].anchor?.cornerKey; const updatedPreview = await response.json(); const cornerGeometry = (preview: { layers: { roadSurface: { features: Array<{ properties: { corner_key?: string }; geometry: unknown }> } }; }) => preview.layers.roadSurface.features.find((feature) => feature.properties.corner_key === cornerKey)?.geometry; expect(cornerGeometry(updatedPreview)).not.toEqual(cornerGeometry(baselinePreview)); await expect(parameterInput).toHaveValue(String(parameterValue + 2)); for (const edit of [ { kind: 'cluster-carriageway-position', label: '车行道接入位置', delta: 1 }, { kind: 'cluster-carriageway-direction', label: '车行道接入方向', delta: 1 }, { kind: 'cluster-carriageway-edge-offset', label: '车行道左右边界', delta: 0.25 }, ]) { const handle = scoped.handles.handles.find( (candidate: { kind: string; value: { current: number; max: number }; affects: string[] }) => candidate.kind === edit.kind && candidate.value.current + edit.delta <= candidate.value.max, ); expect(handle).toBeTruthy(); const group = workspace.locator('.parameter-group').filter({ hasText: edit.label }).first(); await expect(group).toBeVisible(); const expand = group.getByRole('button', { name: '展开单独定制' }); if (await expand.count()) await expand.click(); const input = group.locator(`[data-handle-id="${handle.handleId}"] .parameter-input`); const nextValue = Math.round((handle.value.current + edit.delta) * 100) / 100; const editResponse = page.waitForResponse( (candidate) => candidate.request().method() === 'POST' && candidate.url().endsWith('/api/edit-preview') && candidate .request() .postDataJSON() ?.constraints?.some((constraint: { kind: string }) => constraint.kind === edit.kind), ); await input.fill(String(nextValue)); await input.press('Enter'); const editResult = await (await editResponse).json(); expect(editResult.constraintStates.every((state: { applied: boolean }) => state.applied)).toBe(true); expect(roadGeometry(editResult, handle.affects[0])).not.toEqual(roadGeometry(baselinePreview, handle.affects[0])); await page.getByRole('button', { name: '撤销', exact: true }).click(); } await page.reload(); await expect(armButtons).toHaveCount(structure.arms.length); await expect(armButtons.first()).toHaveAttribute('aria-pressed', 'false'); const transitionGroup = workspace.locator('.parameter-group').filter({ hasText: '车行道过渡长度' }); await expect(transitionGroup).toBeVisible(); const expandTransition = transitionGroup.getByRole('button', { name: '展开单独定制' }); if (await expandTransition.count()) await expandTransition.click(); const transitionHandle = scoped.handles.handles.find( (handle: { kind: string; value: { min: number; max: number } }) => handle.kind === 'cluster-carriageway-transition-length' && handle.value.max - handle.value.min > 1, ); expect(transitionHandle).toBeTruthy(); const transitionInput = transitionGroup.locator(`[data-handle-id="${transitionHandle.handleId}"] .parameter-input`); const originalTransitionValue = await transitionInput.inputValue(); const transitionValue = Math.round(((transitionHandle.value.min + transitionHandle.value.max) / 2) * 100) / 100; const transitionResponse = page.waitForResponse( (response) => response.request().method() === 'POST' && response.url().endsWith('/api/edit-preview') && response .request() .postDataJSON() ?.constraints?.some( (constraint: { kind: string }) => constraint.kind === 'cluster-carriageway-transition-length', ), ); await transitionInput.fill(String(transitionValue)); await transitionInput.press('Enter'); const transitionResult = await (await transitionResponse).json(); expect(transitionResult.constraintStates.length).toBeGreaterThan(0); expect(transitionResult.constraintStates.every((state: { applied: boolean }) => state.applied)).toBe(true); await expect(transitionInput).toHaveValue(String(transitionValue)); await page.getByRole('button', { name: '撤销', exact: true }).click(); await expect(transitionInput).toHaveValue(originalTransitionValue); await expect(page.getByRole('button', { name: '重做', exact: true })).toBeEnabled(); await page.getByRole('button', { name: '重做', exact: true }).click(); await expect(transitionInput).toHaveValue(String(transitionValue)); await page .getByRole('region', { name: '路口编辑工作区' }) .getByRole('button', { name: '保存', exact: true }) .click(); await expect(page.getByRole('status')).toHaveText('已保存并重新生成', { timeout: 30_000 }); await page.reload(); await expect(transitionGroup).toBeVisible(); if (await expandTransition.count()) await expandTransition.click(); await expect(transitionInput).toHaveValue(String(transitionValue)); const transitionRow = transitionGroup.locator(`[data-handle-id="${transitionHandle.handleId}"]`); await transitionRow.getByRole('button', { name: '重置', exact: true }).click(); await expect(transitionInput).toHaveValue(originalTransitionValue); await workspace.getByRole('button', { name: '放弃草稿', exact: true }).click(); await expect(transitionInput).toHaveValue(String(transitionValue)); await expect(workspace.getByRole('button', { name: '保存', exact: true })).toBeDisabled(); const refreshed = await page.request.get('/api/state').then((response) => response.json()); expect(refreshed.junctionStructures[`cluster:${id}`].arms.map((arm: { key: string }) => arm.key)).toEqual( structure.arms.map((arm: { key: string }) => arm.key), ); }); test('edits and persists every entry control on a three-arm complex junction', async ({ page }) => { test.setTimeout(60_000); const initial = await page.request.get('/api/state').then((response) => response.json()); const candidate = initial.debug.junctionCandidates.find( (item: { nodeIds: string[] }) => item.nodeIds.length === 3 && item.nodeIds.includes('-91001'), ); expect(candidate).toBeTruthy(); const accepted = await page.request .post('/api/junction-clusters', { data: { candidateId: candidate.id, nodeIds: candidate.nodeIds } }) .then((response) => response.json()); const id = accepted.added.id; const structure = accepted.junctionStructures[`cluster:${id}`]; expect(structure.shape.effectiveArmCount).toBe(3); await page.goto(`/junction/cluster/${encodeURIComponent(id)}`); await page.reload(); const workspace = page.getByLabel('路口编辑工作区'); await page.waitForResponse((response) => response.url().includes(`/api/edit-state?cluster=${encodeURIComponent(id)}`), ); const editStateResponse = page.waitForResponse((response) => response.url().includes(`/api/edit-state?cluster=${encodeURIComponent(id)}`), ); await page.getByRole('button', { name: '开启编辑模式' }).click(); const scoped = await (await editStateResponse).json(); const baseline = await page.request .post('/api/edit-preview', { data: { document: scoped.document, selection: { cluster: id } } }) .then((response) => response.json()); const geometry = (preview: typeof baseline, nativeId: string) => preview.layers.roadSurface.features.find( (feature: { properties: { native_id: string } }) => feature.properties.native_id === nativeId, )?.geometry; let persistedHandleId = ''; let persistedValue = ''; for (const edit of [ { kind: 'cluster-carriageway-position', label: '车行道接入位置', delta: 0.5 }, { kind: 'cluster-carriageway-direction', label: '车行道接入方向', delta: 1 }, { kind: 'cluster-carriageway-edge-offset', label: '车行道左右边界', delta: 0.25 }, { kind: 'cluster-carriageway-transition-length', label: '车行道过渡长度', delta: -0.5 }, ]) { const handle = scoped.handles.handles.find( (item: { kind: string; value: { current: number; min: number; max: number } }) => item.kind === edit.kind && item.value.current + edit.delta >= item.value.min && item.value.current + edit.delta <= item.value.max, ); expect(handle).toBeTruthy(); const group = workspace.locator('.parameter-group').filter({ hasText: edit.label }).first(); const expand = group.getByRole('button', { name: '展开单独定制' }); if (await expand.count()) await expand.click(); const input = group.locator(`[data-handle-id="${handle.handleId}"] .parameter-input`); const nextValue = String(Math.round((handle.value.current + edit.delta) * 100) / 100); const response = page.waitForResponse( (item) => item.url().endsWith('/api/edit-preview') && item .request() .postDataJSON() ?.constraints?.some((constraint: { kind: string }) => constraint.kind === edit.kind), ); await input.fill(nextValue); await input.press('Enter'); const preview = await (await response).json(); expect(preview.constraintStates.every((state: { applied: boolean }) => state.applied)).toBe(true); expect(geometry(preview, handle.affects[0])).not.toEqual(geometry(baseline, handle.affects[0])); if (edit.kind === 'cluster-carriageway-transition-length') { persistedHandleId = handle.handleId; persistedValue = nextValue; } else { await page.getByRole('button', { name: '撤销', exact: true }).click(); } } const saveRequest = page.waitForRequest( (request) => request.method() === 'POST' && request.url().endsWith('/api/edits'), ); await workspace.getByRole('button', { name: '保存', exact: true }).click(); const requestedVersion = (await saveRequest).postDataJSON().expectedDocumentVersion; expect(requestedVersion).toBeLessThanOrEqual(scoped.documentVersion); if (requestedVersion < scoped.documentVersion) { await expect(page.getByRole('status')).toContainText(`保存冲突:文档已被改到版本 ${scoped.documentVersion}`); await workspace.getByRole('button', { name: '保存', exact: true }).click(); } await expect(page.getByRole('status')).toHaveText('已保存并重新生成', { timeout: 30_000 }); await page.reload(); const refreshedTransitionGroup = workspace.locator('.parameter-group').filter({ hasText: '车行道过渡长度' }); await expect(refreshedTransitionGroup).toBeVisible(); const expandTransition = refreshedTransitionGroup.getByRole('button', { name: '展开单独定制' }); await expect(expandTransition).toBeVisible(); await expandTransition.click(); await expect( refreshedTransitionGroup.locator(`[data-handle-id="${persistedHandleId}"] .parameter-input`), ).toHaveValue(persistedValue); }); });