t23-click-flow.mjs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. import assert from 'node:assert/strict'
  2. import { readFileSync } from 'node:fs'
  3. import vm from 'node:vm'
  4. import { parse as parseJS } from '@babel/parser'
  5. import { parse, compileScript } from '@vue/compiler-sfc'
  6. import * as Vue from 'vue'
  7. import * as Cesium from 'cesium'
  8. import { createPinia, setActivePinia } from 'pinia'
  9. import { attachPointPick } from '../../../src/modules/cockpit/services/pointPick.js'
  10. import { resolveOverlapPick } from '../../../src/modules/cockpit/domain/overlapDevices.js'
  11. import { PIPE_ENHANCEMENT_KIND, planPipeEnhancement } from '../../../src/modules/cockpit/domain/pipeEnhancement.js'
  12. import { usePipeEnhancementStore } from '../../../src/modules/cockpit/stores/pipeEnhancementStore.js'
  13. import { useEnhancementDevicesStore } from '../../../src/modules/cockpit/stores/enhancementDevicesStore.js'
  14. const src = (name) => readFileSync(new URL(`../../../src/modules/cockpit/${name}`, import.meta.url), 'utf8')
  15. const service = src('services/mapService.js')
  16. const shell = parse(src('CockpitShell.vue')).descriptor
  17. function nodes(source) {
  18. return parseJS(source, { sourceType: 'module' }).program.body.map((n) => n.declaration || n)
  19. }
  20. function functions(source, names) {
  21. return nodes(source).filter((n) => n.type === 'FunctionDeclaration' && names.includes(n.id.name))
  22. .map((n) => source.slice(n.start, n.end)).join('\n')
  23. }
  24. const engineCode = src('services/cesiumEngine.js')
  25. .replace(/^import\s+[^]*?from\s+['"][^'"\n]+['"][ \t]*$/gm, '')
  26. .replace(/^import\s+['"][^'"\n]+['"][ \t]*$/gm, '').replace(/^export /gm, '')
  27. const engineContext = vm.createContext({ ...Cesium, CesiumMath: Cesium.Math })
  28. vm.runInContext(`${engineCode}\nglobalThis.engine = { pickDeviceMarkerAt, pickPointMarkerAt, pickPipeObjectAt };`, engineContext)
  29. const source = new Cesium.CustomDataSource('cockpit-pipelines')
  30. source.entities.add({ id: 'pipe:P-2', properties: { kind: 'pipe', code: 'P-2' } })
  31. const batch = { kind: 'pipe-model-batch', instances: ['pipe:P-1', 'pipe:P-2'] }
  32. let hits = [{ id: batch, instanceId: 1 }]
  33. const devices = new Cesium.CustomDataSource('cockpit-associated-device-markers')
  34. const viewer = {
  35. dataSources: { getByName: (name) => name === source.name ? [source] : name === devices.name ? [devices] : [] },
  36. canvas: { getBoundingClientRect: () => ({ left: 20, top: 30 }) },
  37. scene: { pick: () => hits[0], drillPick: () => hits },
  38. }
  39. setActivePinia(createPinia())
  40. const store = usePipeEnhancementStore()
  41. const pipes = ['P-1', 'P-2'].map((code) => ({ code, positions: [[110.1, 28.4], [110.101, 28.401]] }))
  42. const demoDevice = { code: 'D-real', pointCode: 'MP-real', name: '真实设备', placement: 'nearby', placementText: '邻近设备 · 示意安装' }
  43. const plan = Vue.computed(() => ({ ...planPipeEnhancement({ selected: store.selected, visiblePipes: pipes, radiusM: store.radiusM }),
  44. deviceList: [demoDevice], devices: [demoDevice], deviceCoverage: { loading: false, partial: false } }))
  45. const selectContext = vm.createContext({ PIPE_ENHANCEMENT_KIND, pipeEnhancementStore: store })
  46. vm.runInContext(`${functions(shell.scriptSetup.content, ['selectPipeEnhancement'])}\nglobalThis.select = selectPipeEnhancement`, selectContext)
  47. const context = vm.createContext({
  48. instance: { engine: engineContext.engine, viewer }, resolveOverlapPick,
  49. pipelinePickHandlers: new Set(), pointPickHandlers: new Set(),
  50. overlapExpandedGroup: '', overlapPreviewGroup: '', lastPicked: null,
  51. collapseOverlap() {}, paintPicked() {}, expandOverlap() {},
  52. })
  53. vm.runInContext(`${functions(service, ['onPipelinePick', 'pickPipelineAt', 'pickDeviceOrPointAt'])}\nglobalThis.api = { onPipelinePick, pickPipelineAt, pickDeviceOrPointAt };`, context)
  54. // Execute the actual service registration, preserving its device/point-first branch.
  55. const registration = service.match(/record\.detachPickInput = attachPointPick\(record\.host,[\s\S]*?\n \}\)/)?.[0]
  56. assert.ok(registration, 'map must attach its pointer input')
  57. const host = new EventTarget()
  58. Object.assign(context, { record: { host }, attachPointPick })
  59. vm.runInContext(registration, context)
  60. // Execute the actual MapCanvas forwarding expression, followed by the real shell action.
  61. const forwarding = src('components/MapCanvas.vue').match(/onPipelinePick\(\(hit\) => emit\('pipeline-pick', hit\)\)/)?.[0]
  62. assert.ok(forwarding)
  63. Object.assign(context, { onPipelinePick: context.api.onPipelinePick, emit(event, hit) {
  64. assert.equal(event, 'pipeline-pick')
  65. selectContext.select(hit)
  66. } })
  67. vm.runInContext(forwarding, context)
  68. function click(x = 120, y = 230, upX = x) {
  69. for (const [type, clientX] of [['pointerdown', x], ['pointerup', upX]]) {
  70. const event = new Event(type)
  71. Object.assign(event, { button: 0, pointerId: 1, clientX, clientY: y })
  72. host.dispatchEvent(event)
  73. }
  74. }
  75. // Real Vue render/watch/close path; WebGL is replaced only at its renderer boundary.
  76. const enhancement = parse(src('components/PipeEnhancement.vue')).descriptor
  77. let mounts = 0
  78. let releases = 0
  79. let devicePick, objectPick, focusedDevice
  80. let syncs = 0
  81. const script = compileScript(enhancement, { id: 't23-click', inlineTemplate: true }).content
  82. 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) {
  83. devicePick = options.onDevicePick
  84. objectPick = options.onObjectPick
  85. assert.equal(next.object.code, 'P-2')
  86. mounts += 1
  87. return { sync() { syncs += 1 }, focusDevice(code) { focusedDevice = code; return true }, destroy() { releases += 1 } }
  88. } } }
  89. let compiled = script
  90. for (const node of parseJS(script, { sourceType: 'module' }).program.body.filter((n) => n.type === 'ImportDeclaration').reverse()) {
  91. 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')
  92. compiled = compiled.slice(0, node.start) + declarations + compiled.slice(node.end)
  93. }
  94. const Component = new Function('imports', `${compiled.replace('export default', 'return')}`)(imports)
  95. const element = (tag) => ({ tag, children: [], props: {}, parent: null })
  96. const renderer = Vue.createRenderer({
  97. createElement: element, createText: (text) => ({ text }), createComment: (text) => ({ comment: text }),
  98. setText(n, text) { n.text = text }, setElementText(n, text) { n.text = text },
  99. parentNode: (n) => n.parent, nextSibling: () => null,
  100. 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) },
  101. remove(n) { if (n.parent) n.parent.children.splice(n.parent.children.indexOf(n), 1); n.parent = null },
  102. patchProp(n, key, _old, next) { n.props[key] = next },
  103. })
  104. const root = element('root')
  105. const deviceStore = useEnhancementDevicesStore()
  106. const app = renderer.createApp({ setup: () => () => Vue.h(Component, {
  107. plan: plan.value, deviceState: deviceStore, onRadiusChange: (radius) => store.setRadius(radius),
  108. onClose: () => { store.clear(); deviceStore.clear() },
  109. onObjectPick: (hit) => selectContext.select(hit),
  110. onDevicePick: (device) => deviceStore.open(device, { fetchDetail: async (code) => ({ state: 'success', data: { deviceCode: code, sections: {} } }) }),
  111. onDeviceClose: () => deviceStore.closeDetail(),
  112. }) })
  113. app.mount(root)
  114. function find(node, key) {
  115. if (Object.hasOwn(node.props || {}, key)) return node
  116. return (node.children || []).map((n) => find(n, key)).find(Boolean)
  117. }
  118. assert.equal(find(root, 'data-pipe-enhancement'), undefined)
  119. click()
  120. await Vue.nextTick(); await Vue.nextTick()
  121. 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}`)
  122. assert.equal(store.selected.code, 'P-2')
  123. assert.equal(mounts, 1)
  124. assert.ok(find(root, 'data-pipe-enhancement'), 'pointer hit must render the enhancement dialog')
  125. assert.ok(find(root, 'data-device-list'))
  126. assert.ok(find(root, 'data-pipe-status-list'))
  127. const deviceButton = find(root, 'data-device-code')
  128. assert.equal(deviceButton.props['data-device-code'], 'D-real')
  129. deviceButton.props.onClick()
  130. assert.equal(focusedDevice, 'D-real')
  131. await Vue.nextTick(); await Vue.nextTick()
  132. assert.equal(deviceStore.aggregate.data.deviceCode, 'D-real')
  133. assert.equal(find(root, 'data-device-detail').props['data-device-detail'], 'D-real')
  134. devicePick(demoDevice)
  135. await Vue.nextTick(); await Vue.nextTick()
  136. assert.equal(find(root, 'data-device-detail').props['data-device-detail'], 'D-real', '场景图标射线点击直接打开设备详情')
  137. assert.equal(find(root, 'data-device-list') !== undefined, true, '详情覆盖层打开时清单仍保留于其下')
  138. find(root, 'data-enhancement-device-detail').children
  139. .filter((node) => node.tag === 'header')[0].children
  140. .find((node) => node.tag === 'button').props.onClick()
  141. await Vue.nextTick()
  142. assert.equal(deviceStore.selected, null)
  143. assert.ok(find(root, 'data-device-list'), '关闭设备详情不关闭设备列表')
  144. assert.equal(mounts, 1, '设备详情关闭不重建三维场景')
  145. function findTag(node, tag) { return node.tag === tag ? node : (node.children || []).map((child) => findTag(child, tag)).find(Boolean) }
  146. findTag(root, 'select').props.onChange({ target: { value: '100' } })
  147. await Vue.nextTick(); await Vue.nextTick()
  148. assert.equal(store.radiusM, 100)
  149. assert.equal(plan.value.radiusM, 100)
  150. assert.equal(mounts, 1, '范围切换复用视口与相机')
  151. assert.ok(syncs > 0)
  152. objectPick({ objectKind: 'pipe', code: 'P-1' })
  153. await Vue.nextTick(); await Vue.nextTick()
  154. assert.equal(store.selected.code, 'P-1')
  155. assert.equal(plan.value.object.code, 'P-1')
  156. assert.equal(find(root, 'data-pipe-enhancement-title').text, '重点管段 P-1')
  157. assert.equal(mounts, 1, '邻管点选通过sync切换完整详情,不重建画布')
  158. find(root, 'data-pipe-enhancement-close').props.onClick()
  159. await Vue.nextTick()
  160. assert.equal(store.selected, null)
  161. assert.equal(releases, 1)
  162. assert.equal(find(root, 'data-pipe-enhancement'), undefined)
  163. click(120, 230, 150)
  164. assert.equal(store.selected, null, 'dragging the map must not select a pipe')
  165. console.log('PASS pointer → 设备/点位优先链 → GPU instanceId=1 → MapCanvas emit → Pinia → Vue 弹窗 → 关闭释放;拖拽不选中')
  166. app.unmount()
  167. context.record.detachPickInput()