t23-click-flow.mjs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  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 plan = Vue.computed(() => planPipeEnhancement({ selected: store.selected, visiblePipes: pipes, radiusM: store.radiusM }))
  43. const selectContext = vm.createContext({ PIPE_ENHANCEMENT_KIND, pipeEnhancementStore: store })
  44. vm.runInContext(`${functions(shell.scriptSetup.content, ['selectPipeEnhancement'])}\nglobalThis.select = selectPipeEnhancement`, selectContext)
  45. const context = vm.createContext({
  46. instance: { engine: engineContext.engine, viewer }, resolveOverlapPick,
  47. pipelinePickHandlers: new Set(), pointPickHandlers: new Set(),
  48. overlapExpandedGroup: '', overlapPreviewGroup: '', lastPicked: null,
  49. collapseOverlap() {}, paintPicked() {}, expandOverlap() {},
  50. })
  51. vm.runInContext(`${functions(service, ['onPipelinePick', 'pickPipelineAt', 'pickDeviceOrPointAt'])}\nglobalThis.api = { onPipelinePick, pickPipelineAt, pickDeviceOrPointAt };`, context)
  52. // Execute the actual service registration, preserving its device/point-first branch.
  53. const registration = service.match(/record\.detachPickInput = attachPointPick\(record\.host,[\s\S]*?\n \}\)/)?.[0]
  54. assert.ok(registration, 'map must attach its pointer input')
  55. const host = new EventTarget()
  56. Object.assign(context, { record: { host }, attachPointPick })
  57. vm.runInContext(registration, context)
  58. // Execute the actual MapCanvas forwarding expression, followed by the real shell action.
  59. const forwarding = src('components/MapCanvas.vue').match(/onPipelinePick\(\(hit\) => emit\('pipeline-pick', hit\)\)/)?.[0]
  60. assert.ok(forwarding)
  61. Object.assign(context, { onPipelinePick: context.api.onPipelinePick, emit(event, hit) {
  62. assert.equal(event, 'pipeline-pick')
  63. selectContext.select(hit)
  64. } })
  65. vm.runInContext(forwarding, context)
  66. function click(x = 120, y = 230, upX = x) {
  67. for (const [type, clientX] of [['pointerdown', x], ['pointerup', upX]]) {
  68. const event = new Event(type)
  69. Object.assign(event, { button: 0, pointerId: 1, clientX, clientY: y })
  70. host.dispatchEvent(event)
  71. }
  72. }
  73. // Real Vue render/watch/close path; WebGL is replaced only at its renderer boundary.
  74. const enhancement = parse(src('components/PipeEnhancement.vue')).descriptor
  75. let mounts = 0
  76. let releases = 0
  77. let devicePick
  78. const script = compileScript(enhancement, { id: 't23-click', inlineTemplate: true }).content
  79. 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) {
  80. devicePick = options.onDevicePick
  81. assert.equal(next.object.code, 'P-2')
  82. mounts += 1
  83. return { destroy() { releases += 1 } }
  84. } } }
  85. let compiled = script
  86. for (const node of parseJS(script, { sourceType: 'module' }).program.body.filter((n) => n.type === 'ImportDeclaration').reverse()) {
  87. 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')
  88. compiled = compiled.slice(0, node.start) + declarations + compiled.slice(node.end)
  89. }
  90. const Component = new Function('imports', `${compiled.replace('export default', 'return')}`)(imports)
  91. const element = (tag) => ({ tag, children: [], props: {}, parent: null })
  92. const renderer = Vue.createRenderer({
  93. createElement: element, createText: (text) => ({ text }), createComment: (text) => ({ comment: text }),
  94. setText(n, text) { n.text = text }, setElementText(n, text) { n.text = text },
  95. parentNode: (n) => n.parent, nextSibling: () => null,
  96. insert(n, parent, anchor) { if (n.parent) this.remove(n); n.parent = parent; const i = parent.children.indexOf(anchor); parent.children.splice(i < 0 ? parent.children.length : i, 0, n) },
  97. remove(n) { if (n.parent) n.parent.children.splice(n.parent.children.indexOf(n), 1); n.parent = null },
  98. patchProp(n, key, _old, next) { n.props[key] = next },
  99. })
  100. const root = element('root')
  101. const deviceStore = useEnhancementDevicesStore()
  102. const app = renderer.createApp({ setup: () => () => Vue.h(Component, {
  103. plan: plan.value, deviceState: deviceStore, onRadiusChange: (radius) => store.setRadius(radius),
  104. onClose: () => { store.clear(); deviceStore.clear() },
  105. onDevicePick: (device) => deviceStore.open(device, { fetchDetail: async (code) => ({ state: 'success', data: { deviceCode: code, sections: {} } }) }),
  106. }) })
  107. app.mount(root)
  108. function find(node, key) {
  109. if (Object.hasOwn(node.props || {}, key)) return node
  110. return (node.children || []).map((n) => find(n, key)).find(Boolean)
  111. }
  112. assert.equal(find(root, 'data-pipe-enhancement'), undefined)
  113. click()
  114. await Vue.nextTick(); await Vue.nextTick()
  115. 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}`)
  116. assert.equal(store.selected.code, 'P-2')
  117. assert.equal(mounts, 1)
  118. assert.ok(find(root, 'data-pipe-enhancement'), 'pointer hit must render the enhancement dialog')
  119. devicePick({ code: 'D-real', pointCode: 'MP-real', name: '真实设备', placementText: '邻近设备 · 示意安装' })
  120. await Vue.nextTick(); await Vue.nextTick()
  121. assert.equal(deviceStore.aggregate.data.deviceCode, 'D-real')
  122. assert.equal(find(root, 'data-device-detail').props['data-device-detail'], 'D-real')
  123. assert.equal(mounts, 1, '打开设备详情不能重建三维场景')
  124. assert.equal(store.selected.code, 'P-2')
  125. function findTag(node, tag) { return node.tag === tag ? node : (node.children || []).map((child) => findTag(child, tag)).find(Boolean) }
  126. findTag(root, 'select').props.onChange({ target: { value: '100' } })
  127. await Vue.nextTick(); await Vue.nextTick()
  128. assert.equal(store.radiusM, 100)
  129. assert.equal(plan.value.radiusM, 100)
  130. assert.equal(mounts, 2, '范围切换后重绘邻域')
  131. find(root, 'data-pipe-enhancement-close').props.onClick()
  132. await Vue.nextTick()
  133. assert.equal(store.selected, null)
  134. assert.equal(releases, 2)
  135. assert.equal(find(root, 'data-pipe-enhancement'), undefined)
  136. click(120, 230, 150)
  137. assert.equal(store.selected, null, 'dragging the map must not select a pipe')
  138. console.log('PASS pointer → 设备/点位优先链 → GPU instanceId=1 → MapCanvas emit → Pinia → Vue 弹窗 → 关闭释放;拖拽不选中')
  139. app.unmount()
  140. context.record.detachPickInput()