| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170 |
- import assert from 'node:assert/strict'
- import { readFileSync } from 'node:fs'
- import vm from 'node:vm'
- import { parse as parseJS } from '@babel/parser'
- import { parse, compileScript } from '@vue/compiler-sfc'
- import * as Vue from 'vue'
- import * as Cesium from 'cesium'
- import { createPinia, setActivePinia } from 'pinia'
- import { attachPointPick } from '../../../src/modules/cockpit/services/pointPick.js'
- import { resolveOverlapPick } from '../../../src/modules/cockpit/domain/overlapDevices.js'
- import { PIPE_ENHANCEMENT_KIND, planPipeEnhancement } from '../../../src/modules/cockpit/domain/pipeEnhancement.js'
- import { usePipeEnhancementStore } from '../../../src/modules/cockpit/stores/pipeEnhancementStore.js'
- import { useEnhancementDevicesStore } from '../../../src/modules/cockpit/stores/enhancementDevicesStore.js'
- const src = (name) => readFileSync(new URL(`../../../src/modules/cockpit/${name}`, import.meta.url), 'utf8')
- const service = src('services/mapService.js')
- const shell = parse(src('CockpitShell.vue')).descriptor
- function nodes(source) {
- return parseJS(source, { sourceType: 'module' }).program.body.map((n) => n.declaration || n)
- }
- function functions(source, names) {
- return nodes(source).filter((n) => n.type === 'FunctionDeclaration' && names.includes(n.id.name))
- .map((n) => source.slice(n.start, n.end)).join('\n')
- }
- const engineCode = src('services/cesiumEngine.js')
- .replace(/^import\s+[^]*?from\s+['"][^'"\n]+['"][ \t]*$/gm, '')
- .replace(/^import\s+['"][^'"\n]+['"][ \t]*$/gm, '').replace(/^export /gm, '')
- const engineContext = vm.createContext({ ...Cesium, CesiumMath: Cesium.Math })
- vm.runInContext(`${engineCode}\nglobalThis.engine = { pickDeviceMarkerAt, pickPointMarkerAt, pickPipeObjectAt };`, engineContext)
- const source = new Cesium.CustomDataSource('cockpit-pipelines')
- source.entities.add({ id: 'pipe:P-2', properties: { kind: 'pipe', code: 'P-2' } })
- const batch = { kind: 'pipe-model-batch', instances: ['pipe:P-1', 'pipe:P-2'] }
- let hits = [{ id: batch, instanceId: 1 }]
- const devices = new Cesium.CustomDataSource('cockpit-associated-device-markers')
- const viewer = {
- dataSources: { getByName: (name) => name === source.name ? [source] : name === devices.name ? [devices] : [] },
- canvas: { getBoundingClientRect: () => ({ left: 20, top: 30 }) },
- scene: { pick: () => hits[0], drillPick: () => hits },
- }
- setActivePinia(createPinia())
- const store = usePipeEnhancementStore()
- const pipes = ['P-1', 'P-2'].map((code) => ({ code, positions: [[110.1, 28.4], [110.101, 28.401]] }))
- const demoDevice = { code: 'D-real', pointCode: 'MP-real', name: '真实设备', placement: 'nearby', placementText: '邻近设备 · 示意安装' }
- const plan = Vue.computed(() => ({ ...planPipeEnhancement({ selected: store.selected, visiblePipes: pipes, radiusM: store.radiusM }),
- deviceList: [demoDevice], devices: [demoDevice], deviceCoverage: { loading: false, partial: false } }))
- const selectContext = vm.createContext({ PIPE_ENHANCEMENT_KIND, pipeEnhancementStore: store })
- vm.runInContext(`${functions(shell.scriptSetup.content, ['selectPipeEnhancement'])}\nglobalThis.select = selectPipeEnhancement`, selectContext)
- const context = vm.createContext({
- instance: { engine: engineContext.engine, viewer }, resolveOverlapPick,
- pipelinePickHandlers: new Set(), pointPickHandlers: new Set(),
- overlapExpandedGroup: '', overlapPreviewGroup: '', lastPicked: null,
- collapseOverlap() {}, paintPicked() {}, expandOverlap() {},
- })
- vm.runInContext(`${functions(service, ['onPipelinePick', 'pickPipelineAt', 'pickDeviceOrPointAt'])}\nglobalThis.api = { onPipelinePick, pickPipelineAt, pickDeviceOrPointAt };`, context)
- // Execute the actual service registration, preserving its device/point-first branch.
- const registration = service.match(/record\.detachPickInput = attachPointPick\(record\.host,[\s\S]*?\n \}\)/)?.[0]
- assert.ok(registration, 'map must attach its pointer input')
- const host = new EventTarget()
- Object.assign(context, { record: { host }, attachPointPick })
- vm.runInContext(registration, context)
- // Execute the actual MapCanvas forwarding expression, followed by the real shell action.
- const forwarding = src('components/MapCanvas.vue').match(/onPipelinePick\(\(hit\) => emit\('pipeline-pick', hit\)\)/)?.[0]
- assert.ok(forwarding)
- Object.assign(context, { onPipelinePick: context.api.onPipelinePick, emit(event, hit) {
- assert.equal(event, 'pipeline-pick')
- selectContext.select(hit)
- } })
- vm.runInContext(forwarding, context)
- function click(x = 120, y = 230, upX = x) {
- for (const [type, clientX] of [['pointerdown', x], ['pointerup', upX]]) {
- const event = new Event(type)
- Object.assign(event, { button: 0, pointerId: 1, clientX, clientY: y })
- host.dispatchEvent(event)
- }
- }
- // Real Vue render/watch/close path; WebGL is replaced only at its renderer boundary.
- const enhancement = parse(src('components/PipeEnhancement.vue')).descriptor
- let mounts = 0
- let releases = 0
- let devicePick, objectPick, focusedDevice
- let syncs = 0
- const script = compileScript(enhancement, { id: 't23-click', inlineTemplate: true }).content
- const imports = { vue: Vue, './EquipmentDetailSections.vue': { default: { props: ['deviceCode', 'aggregate'], render() { return Vue.h('div', { 'data-device-detail': this.deviceCode }) } } }, '../services/threePipeEnhancement.js': { mountPipeEnhancement(_host, next, options) {
- devicePick = options.onDevicePick
- objectPick = options.onObjectPick
- assert.equal(next.object.code, 'P-2')
- mounts += 1
- return { sync() { syncs += 1 }, focusDevice(code) { focusedDevice = code; return true }, destroy() { releases += 1 } }
- } } }
- let compiled = script
- for (const node of parseJS(script, { sourceType: 'module' }).program.body.filter((n) => n.type === 'ImportDeclaration').reverse()) {
- const declarations = node.specifiers.map((s) => `const ${s.local.name} = imports[${JSON.stringify(node.source.value)}][${JSON.stringify(s.type === 'ImportDefaultSpecifier' ? 'default' : s.imported.name)}];`).join('\n')
- compiled = compiled.slice(0, node.start) + declarations + compiled.slice(node.end)
- }
- const Component = new Function('imports', `${compiled.replace('export default', 'return')}`)(imports)
- const element = (tag) => ({ tag, children: [], props: {}, parent: null })
- const renderer = Vue.createRenderer({
- createElement: element, createText: (text) => ({ text }), createComment: (text) => ({ comment: text }),
- setText(n, text) { n.text = text }, setElementText(n, text) { n.text = text },
- parentNode: (n) => n.parent, nextSibling: () => null,
- insert(n, parent, anchor) { if (n.parent) n.parent.children.splice(n.parent.children.indexOf(n), 1); n.parent = parent; const i = parent.children.indexOf(anchor); parent.children.splice(i < 0 ? parent.children.length : i, 0, n) },
- remove(n) { if (n.parent) n.parent.children.splice(n.parent.children.indexOf(n), 1); n.parent = null },
- patchProp(n, key, _old, next) { n.props[key] = next },
- })
- const root = element('root')
- const deviceStore = useEnhancementDevicesStore()
- const app = renderer.createApp({ setup: () => () => Vue.h(Component, {
- plan: plan.value, deviceState: deviceStore, onRadiusChange: (radius) => store.setRadius(radius),
- onClose: () => { store.clear(); deviceStore.clear() },
- onObjectPick: (hit) => selectContext.select(hit),
- onDevicePick: (device) => deviceStore.open(device, { fetchDetail: async (code) => ({ state: 'success', data: { deviceCode: code, sections: {} } }) }),
- onDeviceClose: () => deviceStore.closeDetail(),
- }) })
- app.mount(root)
- function find(node, key) {
- if (Object.hasOwn(node.props || {}, key)) return node
- return (node.children || []).map((n) => find(n, key)).find(Boolean)
- }
- assert.equal(find(root, 'data-pipe-enhancement'), undefined)
- click()
- await Vue.nextTick(); await Vue.nextTick()
- assert.ok(store.selected, `点击未派发:device/point=${JSON.stringify(context.api.pickDeviceOrPointAt(120, 230))}, pipe=${JSON.stringify(engineContext.engine.pickPipeObjectAt(viewer, 120, 230))}, subscribers=${context.pipelinePickHandlers.size}`)
- assert.equal(store.selected.code, 'P-2')
- assert.equal(mounts, 1)
- assert.ok(find(root, 'data-pipe-enhancement'), 'pointer hit must render the enhancement dialog')
- assert.ok(find(root, 'data-device-list'))
- assert.ok(find(root, 'data-pipe-status-list'))
- const deviceButton = find(root, 'data-device-code')
- assert.equal(deviceButton.props['data-device-code'], 'D-real')
- deviceButton.props.onClick()
- assert.equal(focusedDevice, 'D-real')
- await Vue.nextTick(); await Vue.nextTick()
- assert.equal(deviceStore.aggregate.data.deviceCode, 'D-real')
- assert.equal(find(root, 'data-device-detail').props['data-device-detail'], 'D-real')
- devicePick(demoDevice)
- await Vue.nextTick(); await Vue.nextTick()
- assert.equal(find(root, 'data-device-detail').props['data-device-detail'], 'D-real', '场景图标射线点击直接打开设备详情')
- assert.equal(find(root, 'data-device-list') !== undefined, true, '详情覆盖层打开时清单仍保留于其下')
- find(root, 'data-enhancement-device-detail').children
- .filter((node) => node.tag === 'header')[0].children
- .find((node) => node.tag === 'button').props.onClick()
- await Vue.nextTick()
- assert.equal(deviceStore.selected, null)
- assert.ok(find(root, 'data-device-list'), '关闭设备详情不关闭设备列表')
- assert.equal(mounts, 1, '设备详情关闭不重建三维场景')
- function findTag(node, tag) { return node.tag === tag ? node : (node.children || []).map((child) => findTag(child, tag)).find(Boolean) }
- findTag(root, 'select').props.onChange({ target: { value: '100' } })
- await Vue.nextTick(); await Vue.nextTick()
- assert.equal(store.radiusM, 100)
- assert.equal(plan.value.radiusM, 100)
- assert.equal(mounts, 1, '范围切换复用视口与相机')
- assert.ok(syncs > 0)
- objectPick({ objectKind: 'pipe', code: 'P-1' })
- await Vue.nextTick(); await Vue.nextTick()
- assert.equal(store.selected.code, 'P-1')
- assert.equal(plan.value.object.code, 'P-1')
- assert.equal(find(root, 'data-pipe-enhancement-title').text, '重点管段 P-1')
- assert.equal(mounts, 1, '邻管点选通过sync切换完整详情,不重建画布')
- find(root, 'data-pipe-enhancement-close').props.onClick()
- await Vue.nextTick()
- assert.equal(store.selected, null)
- assert.equal(releases, 1)
- assert.equal(find(root, 'data-pipe-enhancement'), undefined)
- click(120, 230, 150)
- assert.equal(store.selected, null, 'dragging the map must not select a pipe')
- console.log('PASS pointer → 设备/点位优先链 → GPU instanceId=1 → MapCanvas emit → Pinia → Vue 弹窗 → 关闭释放;拖拽不选中')
- app.unmount()
- context.record.detachPickInput()
|