t23-click-flow.mjs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  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, objectPick
  78. let syncs = 0
  79. const script = compileScript(enhancement, { id: 't23-click', inlineTemplate: true }).content
  80. 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) {
  81. devicePick = options.onDevicePick
  82. objectPick = options.onObjectPick
  83. assert.equal(next.object.code, 'P-2')
  84. mounts += 1
  85. return { sync() { syncs += 1 }, destroy() { releases += 1 } }
  86. } } }
  87. let compiled = script
  88. for (const node of parseJS(script, { sourceType: 'module' }).program.body.filter((n) => n.type === 'ImportDeclaration').reverse()) {
  89. 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')
  90. compiled = compiled.slice(0, node.start) + declarations + compiled.slice(node.end)
  91. }
  92. const Component = new Function('imports', `${compiled.replace('export default', 'return')}`)(imports)
  93. const element = (tag) => ({ tag, children: [], props: {}, parent: null })
  94. const renderer = Vue.createRenderer({
  95. createElement: element, createText: (text) => ({ text }), createComment: (text) => ({ comment: text }),
  96. setText(n, text) { n.text = text }, setElementText(n, text) { n.text = text },
  97. parentNode: (n) => n.parent, nextSibling: () => null,
  98. 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) },
  99. remove(n) { if (n.parent) n.parent.children.splice(n.parent.children.indexOf(n), 1); n.parent = null },
  100. patchProp(n, key, _old, next) { n.props[key] = next },
  101. })
  102. const root = element('root')
  103. const deviceStore = useEnhancementDevicesStore()
  104. const app = renderer.createApp({ setup: () => () => Vue.h(Component, {
  105. plan: plan.value, deviceState: deviceStore, onRadiusChange: (radius) => store.setRadius(radius),
  106. onClose: () => { store.clear(); deviceStore.clear() },
  107. onObjectPick: (hit) => selectContext.select(hit),
  108. onDevicePick: (device) => deviceStore.open(device, { fetchDetail: async (code) => ({ state: 'success', data: { deviceCode: code, sections: {} } }) }),
  109. }) })
  110. app.mount(root)
  111. function find(node, key) {
  112. if (Object.hasOwn(node.props || {}, key)) return node
  113. return (node.children || []).map((n) => find(n, key)).find(Boolean)
  114. }
  115. assert.equal(find(root, 'data-pipe-enhancement'), undefined)
  116. click()
  117. await Vue.nextTick(); await Vue.nextTick()
  118. 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}`)
  119. assert.equal(store.selected.code, 'P-2')
  120. assert.equal(mounts, 1)
  121. assert.ok(find(root, 'data-pipe-enhancement'), 'pointer hit must render the enhancement dialog')
  122. devicePick({ code: 'D-real', pointCode: 'MP-real', name: '真实设备', placementText: '邻近设备 · 示意安装' })
  123. await Vue.nextTick(); await Vue.nextTick()
  124. assert.equal(deviceStore.aggregate.data.deviceCode, 'D-real')
  125. assert.equal(find(root, 'data-device-detail').props['data-device-detail'], 'D-real')
  126. assert.equal(mounts, 1, '打开设备详情不能重建三维场景')
  127. assert.equal(store.selected.code, 'P-2')
  128. function findTag(node, tag) { return node.tag === tag ? node : (node.children || []).map((child) => findTag(child, tag)).find(Boolean) }
  129. findTag(root, 'select').props.onChange({ target: { value: '100' } })
  130. await Vue.nextTick(); await Vue.nextTick()
  131. assert.equal(store.radiusM, 100)
  132. assert.equal(plan.value.radiusM, 100)
  133. assert.equal(mounts, 1, '范围切换复用视口与相机')
  134. assert.ok(syncs > 0)
  135. objectPick({ objectKind: 'pipe', code: 'P-1' })
  136. await Vue.nextTick(); await Vue.nextTick()
  137. assert.equal(store.selected.code, 'P-1')
  138. assert.equal(plan.value.object.code, 'P-1')
  139. assert.equal(find(root, 'data-pipe-enhancement-title').text, '重点管段 P-1')
  140. assert.equal(mounts, 1, '邻管点选通过sync切换完整详情,不重建画布')
  141. find(root, 'data-pipe-enhancement-close').props.onClick()
  142. await Vue.nextTick()
  143. assert.equal(store.selected, null)
  144. assert.equal(releases, 1)
  145. assert.equal(find(root, 'data-pipe-enhancement'), undefined)
  146. click(120, 230, 150)
  147. assert.equal(store.selected, null, 'dragging the map must not select a pipe')
  148. console.log('PASS pointer → 设备/点位优先链 → GPU instanceId=1 → MapCanvas emit → Pinia → Vue 弹窗 → 关闭释放;拖拽不选中')
  149. app.unmount()
  150. context.record.detachPickInput()