TopoTree.vue 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313
  1. <template>
  2. <div style="position:relative;">
  3. <div :id="topoId" class="container" />
  4. <el-card class="legend">
  5. <div >
  6. <h2 style="margin-top:0">图例</h2>
  7. <!-- <div class="listwrap">
  8. <span class="value" style="color:#31a354">24.88%</span>
  9. <span class="lable">延迟占比</span>
  10. </div> -->
  11. <div class="listwrap">
  12. <span class="value">
  13. <el-progress :percentage="100" status="success" :show-text="false" />
  14. </span>
  15. <span class="lable">请求正常</span>
  16. </div>
  17. <div class="listwrap">
  18. <span class="value">
  19. <el-progress :percentage="100" status="warning" :show-text="false" />
  20. </span>
  21. <span class="lable">高延迟</span>
  22. </div>
  23. <div class="listwrap">
  24. <span class="value">
  25. <el-progress :percentage="100" status="exception" :show-text="false" />
  26. </span>
  27. <span class="lable">存在异常</span>
  28. </div>
  29. </div>
  30. </el-card>
  31. <el-dialog
  32. :visible.sync="networkOpen"
  33. :fullscreen="true"
  34. center
  35. :close-on-press-escape="false"
  36. :append-to-body="true"
  37. @before-close="beforecloseNetwork"
  38. @close="closeNetwork"
  39. >
  40. <div v-if="flag" id="networkContainer" style="width:100%;height:100vh" />
  41. </el-dialog>
  42. </div>
  43. </template>
  44. <script>
  45. import { networkSpans } from '@/api/trace'
  46. import screenfull from 'screenfull'
  47. import G6 from '@antv/g6'
  48. import insertCss from 'insert-css'
  49. // 我们用 insert-css 演示引入自定义样式
  50. // 推荐将样式添加到自己的样式文件中
  51. // 若拷贝官方代码,别忘了 npm install insert-css
  52. insertCss(`
  53. .g6-component-tooltip {
  54. background-color: rgba(0,0,0, 0.65);
  55. padding: 10px;
  56. box-shadow: rgb(174, 174, 174) 0px 0px 10px;
  57. width: fit-content;
  58. color: #fff;
  59. border-radius:4px;
  60. }
  61. `)
  62. const colors = {
  63. B: '#5B8FF9', // 蓝色
  64. R: '#F46649', // 红色
  65. Y: '#EEBC20', // 黄色
  66. G: '#5BD8A6', // 绿色
  67. DI: '#A7A7A7' // 灰色
  68. }
  69. // 组件props
  70. const props = {
  71. config: {
  72. padding: [20, 50],
  73. defaultLevel: 3,
  74. defaultZoom: 0.8,
  75. modes: { default: ['zoom-canvas', 'drag-canvas'] }
  76. }
  77. }
  78. export default {
  79. props: {
  80. // 数据
  81. graphData: {
  82. type: Object,
  83. default() {
  84. return {}
  85. }
  86. },
  87. topoId: {
  88. type: String,
  89. default() {
  90. return ''
  91. }
  92. }
  93. },
  94. data() {
  95. return {
  96. isFull: false,
  97. Visible: false,
  98. networkQuery: {
  99. span_id: '07fe3536fd3d424b',
  100. parent_span_id: '88a432e4c06ea0fd'
  101. },
  102. networkOpen: false,
  103. topoData: {},
  104. firstNode: {},
  105. lastNode: {},
  106. apis: require('../../../assets/apis.jpg'),
  107. apm: require('../../../assets/apm.jpg'),
  108. iconDown: require('../../../assets/icon_down.png'),
  109. flag: false,
  110. globalGraph: null
  111. }
  112. },
  113. mounted() {
  114. this.$nextTick(() => {
  115. if (JSON.stringify(this.graphData) != '{}') {
  116. this.initGraph(this.graphData, this.topoId)
  117. }
  118. })
  119. },
  120. destroy() {
  121. if (screenfull.isEnabled) {
  122. screenfull.off('change', this.change)
  123. }
  124. },
  125. methods: {
  126. closeNetwork() {
  127. this.networkOpen = false
  128. this.flag = false
  129. },
  130. beforecloseNetwork() {
  131. this.networkOpen = false
  132. this.flag = false
  133. },
  134. init() {
  135. if (screenfull.isEnabled) {
  136. screenfull.on('change', this.change) // 开启监听
  137. }
  138. },
  139. change() {
  140. this.isFull = screenfull.isFullscreen // 更新全屏状态
  141. },
  142. buildNestedTree(list) {
  143. const tree = [] // 存储树形结构的数组
  144. const lookup = {} // 用于快速查找节点的对象
  145. // 遍历列表,为每个节点在lookup中创建一个引用
  146. list.forEach((item, index) => {
  147. lookup[item.id] = item
  148. })
  149. // 函数用于递归构建嵌套树形结构
  150. function addChild(parentId) {
  151. const parent = lookup[parentId]
  152. if (parent && parent.childs && parent.childs.length > 0) {
  153. parent.children = parent.childs.map(childId => {
  154. const child = lookup[childId]
  155. if (child) {
  156. addChild(child.id) // 递归添加子节点
  157. return child
  158. }
  159. return null
  160. }).filter(Boolean) // 过滤掉空值
  161. } else {
  162. parent.children = [] // 如果没有子节点,则设置为一个空数组
  163. }
  164. }
  165. // 从根节点开始构建树形结构
  166. list.forEach(item => {
  167. if (item.parent_id === -1) {
  168. addChild(item.id)
  169. tree.push(item)
  170. }
  171. })
  172. return tree
  173. },
  174. addDataToTree(tree, newData) {
  175. tree.forEach((v) => {
  176. if (v.children != undefined && v.children.length == 0) {
  177. v.children.push({ ...newData })
  178. } else {
  179. this.addDataToTree(v.children, newData)
  180. }
  181. })
  182. return tree
  183. },
  184. clearObject() {
  185. // 使用 Object.keys 遍历对象的属性并逐个删除
  186. Object.keys(this.topoData).forEach(key => {
  187. this.$delete(this.topoData, key)
  188. })
  189. },
  190. handleData(data) {
  191. data.forEach((v, k) => {
  192. v.id = v.id.toString()
  193. v.type = 'flow-circle'
  194. v.size = [60],
  195. v.name = (v.flat_duration.toFixed(2)).toString() + 'ms'
  196. v.collapsed = false
  197. // v.name = v['Enum(tap_side)'];
  198. // v.label = (v.duration).toFixed(2);
  199. // v.label = v.duration.toFixed(2);
  200. v.label = (v.flat_duration.toFixed(2)).toString() + 'ms'
  201. v.currency = 'ms'
  202. // v.rate = v.duration_persent;
  203. v.rate = ''
  204. // v.status = (v.status_code == 'STATUS_CODE_ERROR'||v.events_timestamp.length>0||v.http_code>399)?'R':(v.duration>500)?'Y':'G';
  205. // v.variableValue = v.duration_persent;
  206. v.status = 'G'
  207. v.variableValue = ''
  208. // v.status_code = 'UNSET'
  209. // 数形结构时打开
  210. // if (v.children != undefined && v.children.length > 0) {
  211. // v.children = this.handleData(v.children)
  212. // }
  213. })
  214. return data
  215. },
  216. initGraph(data, id) {
  217. const _this = this
  218. let graph = null
  219. const container = document.getElementById(id)
  220. const width = container.scrollWidth
  221. const height = container.scrollHeight || 700
  222. // 默认配置
  223. const defaultConfig = {
  224. width,
  225. height,
  226. modes: {
  227. default: ['zoom-canvas', 'drag-canvas']
  228. // default: ['drag-canvas', 'zoom-canvas', 'drag-node', 'lasso-select'],
  229. },
  230. fitView: true,
  231. maxZoom: 2, // 默认值是10
  232. minZoom: 0.02, // 默认值是0.02
  233. animate: true,
  234. defaultNode: {
  235. type: 'flow-rect'
  236. },
  237. defaultEdge: {
  238. // type: 'cubic-horizontal',
  239. type: 'flow-cubic',
  240. style: {
  241. stroke: '#CED4D9'
  242. }
  243. // labelCfg: {
  244. // autoRotate: true,
  245. // },
  246. },
  247. layout: {
  248. type: 'indented',
  249. direction: 'LR',
  250. dropCap: false,
  251. indent: 300,
  252. getHeight: () => {
  253. return 60
  254. }
  255. }
  256. }
  257. /**
  258. * 自定义节点
  259. */
  260. G6.registerNode(
  261. 'flow-rect',
  262. {
  263. shapeType: 'flow-rect',
  264. draw(cfg, group) {
  265. const {
  266. name = '',
  267. // variableName,
  268. variableValue,
  269. // variableUp,
  270. label,
  271. collapsed,
  272. currency,
  273. status,
  274. rate
  275. } = cfg
  276. const grey = '#CED4D9'
  277. const rectConfig = {
  278. width: 202,
  279. height: 60,
  280. lineWidth: 1,
  281. fontSize: 12,
  282. fill: '#fff',
  283. radius: 4,
  284. stroke: grey,
  285. opacity: 1
  286. }
  287. const nodeOrigin = {
  288. x: -rectConfig.width / 2,
  289. y: -rectConfig.height / 2
  290. }
  291. const textConfig = {
  292. textAlign: 'left',
  293. textBaseline: 'bottom'
  294. }
  295. const rect = group.addShape('rect', {
  296. attrs: {
  297. x: nodeOrigin.x,
  298. y: nodeOrigin.y,
  299. ...rectConfig
  300. }
  301. })
  302. const rectBBox = rect.getBBox()
  303. // label title
  304. group.addShape('text', {
  305. attrs: {
  306. ...textConfig,
  307. x: 12 + nodeOrigin.x,
  308. y: 20 + nodeOrigin.y,
  309. text: name.length > 28 ? name.substr(0, 28) + '...' : name,
  310. fontSize: 12,
  311. opacity: 0.85,
  312. fill: '#000',
  313. cursor: 'pointer'
  314. },
  315. // must be assigned in G6 3.3 and later versions. it can be any string you want, but should be unique in a custom item type
  316. name: 'name-shape'
  317. })
  318. // price
  319. const price = group.addShape('text', {
  320. attrs: {
  321. ...textConfig,
  322. x: 12 + nodeOrigin.x,
  323. y: rectBBox.maxY - 12,
  324. text: label,
  325. fontSize: 16,
  326. fill: '#000',
  327. opacity: 0.85
  328. }
  329. })
  330. // label currency 换成ms
  331. group.addShape('text', {
  332. attrs: {
  333. ...textConfig,
  334. x: price.getBBox().maxX + 5,
  335. y: rectBBox.maxY - 12,
  336. text: currency,
  337. fontSize: 12,
  338. fill: '#000',
  339. opacity: 0.75
  340. }
  341. })
  342. // percentage
  343. const percentText = group.addShape('text', {
  344. attrs: {
  345. ...textConfig,
  346. x: rectBBox.maxX - 8,
  347. y: rectBBox.maxY - 12,
  348. text: `${((variableValue || 0) * 100).toFixed(2)}%`,
  349. // text:variableValue,
  350. fontSize: 12,
  351. textAlign: 'right',
  352. fill: colors[status]
  353. }
  354. })
  355. // bottom line background
  356. const bottomBackRect = group.addShape('rect', {
  357. attrs: {
  358. x: nodeOrigin.x,
  359. y: rectBBox.maxY - 4,
  360. width: rectConfig.width,
  361. height: 4,
  362. radius: [0, 0, rectConfig.radius, rectConfig.radius],
  363. fill: '#E0DFE3'
  364. }
  365. })
  366. // bottom percent
  367. const bottomRect = group.addShape('rect', {
  368. attrs: {
  369. x: nodeOrigin.x,
  370. y: rectBBox.maxY - 4,
  371. width: rate * rectBBox.width,
  372. height: 4,
  373. radius: [0, 0, 0, rectConfig.radius],
  374. fill: colors[status]
  375. }
  376. })
  377. // collapse rect
  378. if (cfg.children && cfg.children.length) {
  379. group.addShape('rect', {
  380. attrs: {
  381. x: rectConfig.width / 2 - 8,
  382. y: -8,
  383. width: 16,
  384. height: 16,
  385. stroke: 'rgba(0, 0, 0, 0.25)',
  386. cursor: 'pointer',
  387. fill: '#fff'
  388. },
  389. // must be assigned in G6 3.3 and later versions. it can be any string you want, but should be unique in a custom item type
  390. name: 'collapse-back',
  391. modelId: cfg.id
  392. })
  393. // collpase text
  394. group.addShape('text', {
  395. attrs: {
  396. x: rectConfig.width / 2,
  397. y: -1,
  398. textAlign: 'center',
  399. textBaseline: 'middle',
  400. text: collapsed ? '+' : '-',
  401. fontSize: 16,
  402. cursor: 'pointer',
  403. fill: 'rgba(0, 0, 0, 0.25)'
  404. },
  405. // must be assigned in G6 3.3 and later versions. it can be any string you want, but should be unique in a custom item type
  406. name: 'collapse-text',
  407. modelId: cfg.id
  408. })
  409. }
  410. this.drawLinkPoints(cfg, group)
  411. return rect
  412. },
  413. update(cfg, item) {
  414. const { level, status, name } = cfg
  415. const group = item.getContainer()
  416. let mask = group.find(ele => ele.get('name') === 'mask-shape')
  417. let maskLabel = group.find(ele => ele.get('name') === 'mask-label-shape')
  418. if (level === 0) {
  419. group.get('children').forEach(child => {
  420. if (child.get('name')?.includes('collapse')) return
  421. child.hide()
  422. })
  423. if (!mask) {
  424. mask = group.addShape('rect', {
  425. attrs: {
  426. x: -101,
  427. y: -30,
  428. width: 202,
  429. height: 60,
  430. opacity: 0,
  431. fill: colors[status]
  432. },
  433. // must be assigned in G6 3.3 and later versions. it can be any string you want, but should be unique in a custom item type
  434. name: 'mask-shape'
  435. })
  436. maskLabel = group.addShape('text', {
  437. attrs: {
  438. fill: '#fff',
  439. fontSize: 20,
  440. x: 0,
  441. y: 10,
  442. text: name.length > 28 ? name.substr(0, 16) + '...' : name,
  443. textAlign: 'center',
  444. opacity: 0
  445. },
  446. // must be assigned in G6 3.3 and later versions. it can be any string you want, but should be unique in a custom item type
  447. name: 'mask-label-shape'
  448. })
  449. const collapseRect = group.find(ele => ele.get('name') === 'collapse-back')
  450. const collapseText = group.find(ele => ele.get('name') === 'collapse-text')
  451. collapseRect?.toFront()
  452. collapseText?.toFront()
  453. } else {
  454. mask.show()
  455. maskLabel.show()
  456. }
  457. mask.animate({ opacity: 1 }, 200)
  458. maskLabel.animate({ opacity: 1 }, 200)
  459. return mask
  460. } else {
  461. group.get('children').forEach(child => {
  462. if (child.get('name')?.includes('collapse')) return
  463. child.show()
  464. })
  465. mask?.animate({ opacity: 0 }, {
  466. duration: 200,
  467. callback: () => mask.hide()
  468. })
  469. maskLabel?.animate({ opacity: 0 }, {
  470. duration: 200,
  471. callback: () => maskLabel.hide()
  472. })
  473. }
  474. this.updateLinkPoints(cfg, group)
  475. },
  476. setState(name, value, item) {
  477. if (name === 'collapse') {
  478. const group = item.getContainer()
  479. const collapseText = group.find((e) => e.get('name') === 'collapse-text')
  480. if (collapseText) {
  481. if (!value) {
  482. collapseText.attr({
  483. text: '-'
  484. })
  485. } else {
  486. collapseText.attr({
  487. text: '+'
  488. })
  489. }
  490. }
  491. }
  492. },
  493. getAnchorPoints() {
  494. return [
  495. [0, 0.5],
  496. [1, 0.5]
  497. ]
  498. }
  499. },
  500. 'rect'
  501. )
  502. G6.registerEdge(
  503. 'flow-cubic',
  504. {
  505. afterDraw(cfg, group) {
  506. const sourceNode = cfg.sourceNode._cfg.model
  507. const sourceNodeServiceName = sourceNode.service_name
  508. const targetNode = cfg.targetNode._cfg.model
  509. const targetNodeServiceName = targetNode.service_name
  510. if (sourceNodeServiceName != targetNodeServiceName) {
  511. // get the first shape in the graphics group of this edge, it is the path of the edge here
  512. // 获取图形组中的第一个图形,在这里就是边的路径图形
  513. const shape = group.get('children')[0]
  514. // get the coordinate of the mid point on the path
  515. // 获取路径图形的中点坐标
  516. const midPoint = shape.getPoint(0.5)
  517. const iconDown = _this.iconDown
  518. const visible = !(cfg.sourceNode._cfg.model.span_id == 'UNKNOWN SPAN ID' || cfg.targetNode._cfg.model.span_id == '')
  519. group.addShape('image', {
  520. attrs: {
  521. x: midPoint.x - 8,
  522. y: midPoint.y - 8,
  523. height: 16,
  524. width: 16,
  525. img: iconDown,
  526. cursor: 'pointer'
  527. // opacity: 1,
  528. },
  529. visible,
  530. name: 'name-edge-button'
  531. })
  532. }
  533. },
  534. update: undefined
  535. },
  536. 'single-line'
  537. )
  538. if (!data) {
  539. return
  540. }
  541. const { onInit, config } = props
  542. const tooltip = new G6.Tooltip({
  543. // offsetX and offsetY include the padding of the parent container
  544. offsetX: 20,
  545. offsetY: 30,
  546. // the types of items that allow the tooltip show up
  547. // 允许出现 tooltip 的 item 类型
  548. itemTypes: ['node'],
  549. // custom the tooltip's content
  550. // 自定义 tooltip 内容
  551. getContent: (e) => {
  552. const outDiv = document.createElement('div')
  553. // outDiv.style.padding = '0px 0px 20px 0px';
  554. const nodeName = e.item.getModel().name
  555. let formatedNodeName = ''
  556. if (nodeName != undefined) {
  557. for (let i = 0; i < nodeName.length; i++) {
  558. formatedNodeName = `${formatedNodeName}${nodeName[i]}`
  559. // if (i !== 0 && i % 20 === 0) formatedNodeName = `${formatedNodeName}<br/>`;
  560. }
  561. outDiv.innerHTML = `${formatedNodeName}`
  562. return outDiv
  563. }
  564. }
  565. })
  566. graph = new G6.TreeGraph({
  567. container: id,
  568. ...defaultConfig,
  569. ...config,
  570. plugins: [tooltip]
  571. })
  572. this.globalGraph = graph
  573. if (typeof onInit === 'function') {
  574. onInit(graph)
  575. }
  576. graph.data(data)
  577. graph.render()
  578. // 让画布内容适应视口
  579. graph.fitView()
  580. // 添加点击事件
  581. graph.on('node:click', (evt) => {
  582. const item = evt.item
  583. const itemData = evt.item._cfg.model
  584. const { level, id } = itemData
  585. this.$emit('changeState', itemData)
  586. })
  587. // 点击线 edge:click
  588. graph.on('name-edge-button:click', (evt) => {
  589. this.networkQuery.parent_span_id = ''
  590. this.networkQuery.span_id = ''
  591. let topoData = {}
  592. const itemData = evt.item._cfg.model
  593. const { source, target } = itemData
  594. // source 是前面一个节点的span_id
  595. // target 是后面一个节点的span_id
  596. const firstNode = evt.item._cfg.sourceNode._cfg.model
  597. const newFirstNode = Object.assign({}, firstNode)
  598. newFirstNode.children = []
  599. const lastNode = evt.item._cfg.targetNode._cfg.model
  600. const newLastNode = Object.assign({}, lastNode)
  601. newLastNode.children = []
  602. this.flag = false
  603. if (source != '') {
  604. this.networkQuery.parent_span_id = source
  605. this.networkQuery.span_id = target
  606. networkSpans(this.networkQuery).then(res => {
  607. if (res.OPT_STATUS.length != 0) {
  608. const optList = this.handleData(res.OPT_STATUS)
  609. const newOptList = this.buildNestedTree(optList)
  610. newFirstNode.children = newOptList
  611. const firstList = [newFirstNode]
  612. const resultList = this.addDataToTree(firstList, newLastNode)
  613. topoData = resultList[0]
  614. this.networkOpen = true
  615. this.flag = true
  616. setTimeout(() => {
  617. this.initGraphNetwork(topoData, 'networkContainer')
  618. }, 300)
  619. } else {
  620. this.$message('暂无数据')
  621. }
  622. })
  623. }
  624. })
  625. const handleCollapse = (e) => {
  626. const target = e.target
  627. const id = target.get('modelId')
  628. const item = graph.findById(id)
  629. const nodeModel = item.getModel()
  630. nodeModel.collapsed = !nodeModel.collapsed
  631. graph.layout()
  632. graph.setItemState(item, 'collapse', nodeModel.collapsed)
  633. }
  634. graph.on('collapse-text:click', (e) => {
  635. e.stopPropagation()
  636. e.preventDefault()
  637. handleCollapse(e)
  638. })
  639. graph.on('collapse-back:click', (e) => {
  640. e.stopPropagation()
  641. e.preventDefault()
  642. handleCollapse(e)
  643. })
  644. let currentLevel = 1
  645. const briefZoomThreshold = Math.max(graph.getZoom(), 0.5)
  646. changeNodeColor()
  647. graph.on('viewportchange', e => {
  648. if (e.action !== 'zoom') return
  649. changeNodeColor()
  650. })
  651. if (typeof window !== 'undefined') {
  652. window.onresize = () => {
  653. if (!graph || graph.get('destroyed')) return
  654. if (!container || !container.scrollWidth || !container.scrollHeight) return
  655. graph.changeSize(container.scrollWidth, container.scrollHeight)
  656. }
  657. }
  658. function changeNodeColor() {
  659. const currentZoom = graph.getZoom()
  660. let toLevel = currentLevel
  661. if (currentZoom < briefZoomThreshold) {
  662. toLevel = 0
  663. } else {
  664. toLevel = 1
  665. }
  666. if (toLevel !== currentLevel) {
  667. currentLevel = toLevel
  668. graph.getNodes().forEach(node => {
  669. graph.updateItem(node, {
  670. level: toLevel
  671. })
  672. })
  673. }
  674. }
  675. },
  676. initGraphNetwork(data, id) {
  677. let graph = null
  678. const container = document.getElementById(id)
  679. // const container = this.$refs['container'];
  680. const width = container.scrollWidth
  681. const height = container.scrollHeight || 700
  682. // 默认配置
  683. const defaultConfig = {
  684. width,
  685. height,
  686. modes: {
  687. default: ['zoom-canvas', 'drag-canvas']
  688. },
  689. fitView: true,
  690. animate: true,
  691. defaultNode: {
  692. type: 'flow-rect'
  693. },
  694. defaultEdge: {
  695. type: 'cubic-horizontal',
  696. style: {
  697. stroke: '#CED4D9'
  698. },
  699. labelCfg: {
  700. autoRotate: true
  701. }
  702. },
  703. layout: {
  704. type: 'indented',
  705. direction: 'LR',
  706. dropCap: false,
  707. indent: 300,
  708. getHeight: () => {
  709. return 60
  710. }
  711. }
  712. }
  713. /**
  714. * 自定义节点
  715. */
  716. G6.registerNode(
  717. 'flow-rect',
  718. {
  719. shapeType: 'flow-rect',
  720. draw(cfg, group) {
  721. const {
  722. name = '',
  723. // variableName,
  724. variableValue,
  725. // variableUp,
  726. label,
  727. collapsed,
  728. currency,
  729. status,
  730. rate
  731. } = cfg
  732. const grey = '#CED4D9'
  733. const rectConfig = {
  734. width: 202,
  735. height: 60,
  736. lineWidth: 1,
  737. fontSize: 12,
  738. fill: '#fff',
  739. radius: 4,
  740. stroke: grey,
  741. opacity: 1
  742. }
  743. const nodeOrigin = {
  744. x: -rectConfig.width / 2,
  745. y: -rectConfig.height / 2
  746. }
  747. const textConfig = {
  748. textAlign: 'left',
  749. textBaseline: 'bottom'
  750. }
  751. const rect = group.addShape('rect', {
  752. attrs: {
  753. x: nodeOrigin.x,
  754. y: nodeOrigin.y,
  755. ...rectConfig
  756. }
  757. })
  758. const rectBBox = rect.getBBox()
  759. // label title
  760. group.addShape('text', {
  761. attrs: {
  762. ...textConfig,
  763. x: 12 + nodeOrigin.x,
  764. y: 20 + nodeOrigin.y,
  765. text: name.length > 28 ? name.substr(0, 28) + '...' : name,
  766. fontSize: 12,
  767. opacity: 0.85,
  768. fill: '#000',
  769. cursor: 'pointer'
  770. },
  771. // must be assigned in G6 3.3 and later versions. it can be any string you want, but should be unique in a custom item type
  772. name: 'name-shape'
  773. })
  774. // price
  775. const price = group.addShape('text', {
  776. attrs: {
  777. ...textConfig,
  778. x: 12 + nodeOrigin.x,
  779. y: rectBBox.maxY - 12,
  780. text: label,
  781. fontSize: 16,
  782. fill: '#000',
  783. opacity: 0.85
  784. }
  785. })
  786. // label currency 换成ms
  787. group.addShape('text', {
  788. attrs: {
  789. ...textConfig,
  790. x: price.getBBox().maxX + 5,
  791. y: rectBBox.maxY - 12,
  792. text: currency,
  793. fontSize: 12,
  794. fill: '#000',
  795. opacity: 0.75
  796. }
  797. })
  798. // percentage
  799. const percentText = group.addShape('text', {
  800. attrs: {
  801. ...textConfig,
  802. x: rectBBox.maxX - 8,
  803. y: rectBBox.maxY - 12,
  804. text: `${((variableValue || 0) * 100).toFixed(2)}%`,
  805. // text:variableValue,
  806. fontSize: 12,
  807. textAlign: 'right',
  808. fill: colors[status]
  809. }
  810. })
  811. // bottom line background
  812. const bottomBackRect = group.addShape('rect', {
  813. attrs: {
  814. x: nodeOrigin.x,
  815. y: rectBBox.maxY - 4,
  816. width: rectConfig.width,
  817. height: 4,
  818. radius: [0, 0, rectConfig.radius, rectConfig.radius],
  819. fill: '#E0DFE3'
  820. }
  821. })
  822. // bottom percent
  823. const bottomRect = group.addShape('rect', {
  824. attrs: {
  825. x: nodeOrigin.x,
  826. y: rectBBox.maxY - 4,
  827. width: rate * rectBBox.width,
  828. height: 4,
  829. radius: [0, 0, 0, rectConfig.radius],
  830. fill: colors[status]
  831. }
  832. })
  833. // collapse rect
  834. if (cfg.children && cfg.children.length) {
  835. group.addShape('rect', {
  836. attrs: {
  837. x: rectConfig.width / 2 - 8,
  838. y: -8,
  839. width: 16,
  840. height: 16,
  841. stroke: 'rgba(0, 0, 0, 0.25)',
  842. cursor: 'pointer',
  843. fill: '#fff'
  844. },
  845. // must be assigned in G6 3.3 and later versions. it can be any string you want, but should be unique in a custom item type
  846. name: 'collapse-back',
  847. modelId: cfg.id
  848. })
  849. // collpase text
  850. group.addShape('text', {
  851. attrs: {
  852. x: rectConfig.width / 2,
  853. y: -1,
  854. textAlign: 'center',
  855. textBaseline: 'middle',
  856. text: collapsed ? '+' : '-',
  857. fontSize: 16,
  858. cursor: 'pointer',
  859. fill: 'rgba(0, 0, 0, 0.25)'
  860. },
  861. // must be assigned in G6 3.3 and later versions. it can be any string you want, but should be unique in a custom item type
  862. name: 'collapse-text',
  863. modelId: cfg.id
  864. })
  865. }
  866. this.drawLinkPoints(cfg, group)
  867. return rect
  868. },
  869. update(cfg, item) {
  870. const { level, status, name } = cfg
  871. const group = item.getContainer()
  872. let mask = group.find(ele => ele.get('name') === 'mask-shape')
  873. let maskLabel = group.find(ele => ele.get('name') === 'mask-label-shape')
  874. if (level === 0) {
  875. group.get('children').forEach(child => {
  876. if (child.get('name')?.includes('collapse')) return
  877. child.hide()
  878. })
  879. if (!mask) {
  880. mask = group.addShape('rect', {
  881. attrs: {
  882. x: -101,
  883. y: -30,
  884. width: 202,
  885. height: 60,
  886. opacity: 0,
  887. fill: colors[status]
  888. },
  889. // must be assigned in G6 3.3 and later versions. it can be any string you want, but should be unique in a custom item type
  890. name: 'mask-shape'
  891. })
  892. maskLabel = group.addShape('text', {
  893. attrs: {
  894. fill: '#fff',
  895. fontSize: 20,
  896. x: 0,
  897. y: 10,
  898. text: name.length > 28 ? name.substr(0, 16) + '...' : name,
  899. textAlign: 'center',
  900. opacity: 0
  901. },
  902. // must be assigned in G6 3.3 and later versions. it can be any string you want, but should be unique in a custom item type
  903. name: 'mask-label-shape'
  904. })
  905. const collapseRect = group.find(ele => ele.get('name') === 'collapse-back')
  906. const collapseText = group.find(ele => ele.get('name') === 'collapse-text')
  907. collapseRect?.toFront()
  908. collapseText?.toFront()
  909. } else {
  910. mask.show()
  911. maskLabel.show()
  912. }
  913. mask.animate({ opacity: 1 }, 200)
  914. maskLabel.animate({ opacity: 1 }, 200)
  915. return mask
  916. } else {
  917. group.get('children').forEach(child => {
  918. if (child.get('name')?.includes('collapse')) return
  919. child.show()
  920. })
  921. mask?.animate({ opacity: 0 }, {
  922. duration: 200,
  923. callback: () => mask.hide()
  924. })
  925. maskLabel?.animate({ opacity: 0 }, {
  926. duration: 200,
  927. callback: () => maskLabel.hide()
  928. })
  929. }
  930. this.updateLinkPoints(cfg, group)
  931. },
  932. setState(name, value, item) {
  933. if (name === 'collapse') {
  934. const group = item.getContainer()
  935. const collapseText = group.find((e) => e.get('name') === 'collapse-text')
  936. if (collapseText) {
  937. if (!value) {
  938. collapseText.attr({
  939. text: '-'
  940. })
  941. } else {
  942. collapseText.attr({
  943. text: '+'
  944. })
  945. }
  946. }
  947. }
  948. },
  949. getAnchorPoints() {
  950. return [
  951. [0, 0.5],
  952. [1, 0.5]
  953. ]
  954. }
  955. },
  956. 'rect'
  957. )
  958. G6.registerNode(
  959. 'flow-circle',
  960. {
  961. shapeType: 'flow-circle',
  962. draw(cfg, group) {
  963. const {
  964. span_name,
  965. label,
  966. span_category
  967. } = cfg
  968. const radius = (60 / 2) - 2
  969. const circleBoxlenght = cfg.size
  970. const circle = group.addShape('circle', {
  971. attrs: {
  972. x: 0,
  973. y: 0,
  974. r: radius,
  975. fill: '#F0F4FE',
  976. stroke: '#6B94F7',
  977. lineWidth: 2
  978. },
  979. name: 'circle-shape'
  980. })
  981. group.addShape('text', {
  982. attrs: {
  983. x: 0,
  984. y: 0,
  985. text: label,
  986. fill: '#333',
  987. fontSize: 12,
  988. textAlign: 'center', // 文本居中
  989. textBaseline: 'middle' // 文本垂直居中
  990. // fill: cfg.color, // 节点颜色
  991. },
  992. name: 'label-shape'
  993. })
  994. group.addShape('text', {
  995. attrs: {
  996. x: 0,
  997. y: radius + 20,
  998. text: span_name,
  999. fill: '#333',
  1000. fontSize: 12,
  1001. textAlign: 'center' // 文本居中
  1002. },
  1003. name: 'span-name-shape'
  1004. })
  1005. group.addShape('text', {
  1006. attrs: {
  1007. x: 0,
  1008. y: radius + 40,
  1009. text: span_category,
  1010. fill: '#333',
  1011. fontSize: 12,
  1012. textAlign: 'center' // 文本居中
  1013. },
  1014. name: 'span-category-shape'
  1015. })
  1016. return circle // 返回创建的圆形
  1017. }
  1018. },
  1019. 'circle'
  1020. )
  1021. G6.registerEdge(
  1022. 'flow-cubic',
  1023. {
  1024. getControlPoints(cfg) {
  1025. let controlPoints = cfg.controlPoints // 指定controlPoints
  1026. if (!controlPoints || !controlPoints.length) {
  1027. const { startPoint, endPoint, sourceNode, targetNode } = cfg
  1028. const { x: startX, y: startY, coefficientX, coefficientY } = sourceNode
  1029. ? sourceNode.getModel()
  1030. : startPoint
  1031. const { x: endX, y: endY } = targetNode ? targetNode.getModel() : endPoint
  1032. let curveStart = (endX - startX) * coefficientX
  1033. let curveEnd = (endY - startY) * coefficientY
  1034. curveStart = curveStart > 40 ? 40 : curveStart
  1035. curveEnd = curveEnd < -30 ? curveEnd : -30
  1036. controlPoints = [
  1037. { x: startPoint.x + curveStart, y: startPoint.y },
  1038. { x: endPoint.x + curveEnd, y: endPoint.y }
  1039. ]
  1040. }
  1041. return controlPoints
  1042. },
  1043. getPath(points) {
  1044. const path = []
  1045. path.push(['M', points[0].x, points[0].y])
  1046. path.push([
  1047. 'C',
  1048. points[1].x,
  1049. points[1].y,
  1050. points[2].x,
  1051. points[2].y,
  1052. points[3].x,
  1053. points[3].y
  1054. ])
  1055. return path
  1056. }
  1057. },
  1058. 'single-line'
  1059. )
  1060. if (!data) {
  1061. return
  1062. }
  1063. const { onInit, config } = props
  1064. const tooltip = new G6.Tooltip({
  1065. // offsetX and offsetY include the padding of the parent container
  1066. offsetX: 20,
  1067. offsetY: 30,
  1068. // the types of items that allow the tooltip show up
  1069. // 允许出现 tooltip 的 item 类型
  1070. itemTypes: ['node'],
  1071. // custom the tooltip's content
  1072. // 自定义 tooltip 内容
  1073. getContent: (e) => {
  1074. const outDiv = document.createElement('div')
  1075. const nodeName = e.item.getModel().name
  1076. const item = e.item.getModel()
  1077. const detail = item.detail
  1078. if (item.detail != undefined) {
  1079. let html = ''
  1080. for (const key in detail) {
  1081. html += `<div class='nodeDetail' style='height:20px;line-height:20px;'>
  1082. <span class='label' style='display: inline-block;vertical-align: middle;width: 120px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;text-align: right;'>${key}:</span>
  1083. <span class='value' style='display: inline-block;vertical-align: middle;'>${detail[key]}</span>
  1084. </div>`
  1085. }
  1086. outDiv.innerHTML = `<div style='margin:-9px;position:relative'>
  1087. <div style='padding:10px;'>
  1088. <div class='nodeDetail' style='height:20px;line-height:20px;'>
  1089. <span class='label' style='display: inline-block;vertical-align: middle;width: 120px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;text-align: right;'>SpanID:</span>
  1090. <span class='value' style='display: inline-block;vertical-align: middle;'>${item.span_id}</span>
  1091. </div>
  1092. <div class='nodeDetail' style='height:20px;line-height:20px;'>
  1093. <span class='label' style='display: inline-block;vertical-align: middle;width: 120px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;text-align: right;'>SpanName:</span>
  1094. <span class='value' style='display: inline-block;vertical-align: middle;'>${item.span_name}</span>
  1095. </div>
  1096. <div class='nodeDetail' style='height:20px;line-height:20px;'>
  1097. <span class='label' style='display: inline-block;vertical-align: middle;width: 120px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;text-align: right;'>SpanCategory:</span>
  1098. <span class='value' style='display: inline-block;vertical-align: middle;'>${item.span_category}</span>
  1099. </div>
  1100. <div class='nodeDetail' style='height:20px;line-height:20px;'>
  1101. <span class='label' style='display: inline-block;vertical-align: middle;width: 120px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;text-align: right;'>Duration:</span>
  1102. <span class='value' style='display: inline-block;vertical-align: middle;'>${item.duration}</span>
  1103. </div>
  1104. <div class='nodeDetail' style='height:20px;line-height:20px;'>
  1105. <span class='label' style='display: inline-block;vertical-align: middle;width: 120px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;text-align: right;'>FlatDuration:</span>
  1106. <span class='value' style='display: inline-block;vertical-align: middle;'>${item.flat_duration}</span>
  1107. </div>
  1108. ${html}
  1109. </div>
  1110. <div style='position:absolute;bottom:10px;right:10px;width:80px;height:80px;z-index: -1;backdrop-filter: blur(10px);background-image:url("${item.span_category == 'apm' ? this.apm : this.apis}");background-size:cover;background-repeat:no-repeat;background-position: center;'>
  1111. </div>
  1112. </div>
  1113. `
  1114. return outDiv
  1115. } else {
  1116. let formatedNodeName = ''
  1117. for (let i = 0; i < nodeName.length; i++) {
  1118. formatedNodeName = `${formatedNodeName}${nodeName[i]}`
  1119. // if (i !== 0 && i % 20 === 0) formatedNodeName = `${formatedNodeName}<br/>`;
  1120. }
  1121. outDiv.innerHTML = `${formatedNodeName}`
  1122. return outDiv
  1123. }
  1124. }
  1125. })
  1126. graph = new G6.TreeGraph({
  1127. container: id,
  1128. ...defaultConfig,
  1129. ...config,
  1130. plugins: [tooltip]
  1131. })
  1132. if (typeof onInit === 'function') {
  1133. onInit(graph)
  1134. }
  1135. graph.data(data)
  1136. graph.render()
  1137. // 让画布内容适应视口
  1138. graph.fitView()
  1139. // 添加点击事件
  1140. graph.on('node:click', (evt) => {
  1141. const itemData = evt.item._cfg.model
  1142. const { level, id } = itemData
  1143. this.$emit('changeState', itemData)
  1144. })
  1145. const handleCollapse = (e) => {
  1146. const target = e.target
  1147. const id = target.get('modelId')
  1148. const item = graph.findById(id)
  1149. const nodeModel = item.getModel()
  1150. nodeModel.collapsed = !nodeModel.collapsed
  1151. graph.layout()
  1152. graph.setItemState(item, 'collapse', nodeModel.collapsed)
  1153. }
  1154. graph.on('collapse-text:click', (e) => {
  1155. e.stopPropagation()
  1156. e.preventDefault()
  1157. handleCollapse(e)
  1158. })
  1159. graph.on('collapse-back:click', (e) => {
  1160. e.stopPropagation()
  1161. e.preventDefault()
  1162. handleCollapse(e)
  1163. })
  1164. let currentLevel = 1
  1165. const briefZoomThreshold = Math.max(graph.getZoom(), 0.5)
  1166. changeNodeColor()
  1167. graph.on('viewportchange', e => {
  1168. if (e.action !== 'zoom') return
  1169. changeNodeColor()
  1170. })
  1171. if (typeof window !== 'undefined') {
  1172. window.onresize = () => {
  1173. if (!graph || graph.get('destroyed')) return
  1174. if (!container || !container.scrollWidth || !container.scrollHeight) return
  1175. graph.changeSize(container.scrollWidth, container.scrollHeight)
  1176. }
  1177. }
  1178. function changeNodeColor () {
  1179. const currentZoom = graph.getZoom()
  1180. let toLevel = currentLevel
  1181. if (currentZoom < briefZoomThreshold) {
  1182. toLevel = 0
  1183. } else {
  1184. toLevel = 1
  1185. }
  1186. if (toLevel !== currentLevel) {
  1187. currentLevel = toLevel
  1188. graph.getNodes().forEach(node => {
  1189. graph.updateItem(node, {
  1190. level: toLevel
  1191. })
  1192. })
  1193. }
  1194. }
  1195. },
  1196. clearGraph() {
  1197. this.globalGraph.clear()
  1198. }
  1199. }
  1200. }
  1201. </script>
  1202. <style lang="scss" scoped>
  1203. .container{
  1204. width:100%;
  1205. height: calc( 100vh - 182px);
  1206. background: #fff;
  1207. }
  1208. .full{
  1209. width:32px;
  1210. height:32px;
  1211. position: absolute;
  1212. top:5px;
  1213. right:0px;
  1214. display: block;
  1215. i{
  1216. font-size: 16px;
  1217. color:#999;
  1218. }
  1219. }
  1220. .nodeDetail{
  1221. margin:4px;
  1222. .label,.value{
  1223. display: inline-block;
  1224. }
  1225. .label{
  1226. display: inline-block;
  1227. width: 120px; /* 限制容器宽度 */
  1228. white-space: nowrap; /* 不换行 */
  1229. overflow: hidden; /* 隐藏溢出内容 */
  1230. text-overflow: ellipsis; /* 使用省略号表示截断 */
  1231. text-align: right;
  1232. }
  1233. }
  1234. .legend{
  1235. position: absolute;
  1236. left:0px;
  1237. bottom:30px;
  1238. z-index: 1001;
  1239. transition: all .3s;
  1240. }
  1241. .listwrap{
  1242. color:#666;
  1243. span{
  1244. display: inline-block;
  1245. padding:4px;
  1246. }
  1247. .value{
  1248. width:80px;
  1249. box-sizing: border-box;
  1250. padding-right: 10px;
  1251. }
  1252. }
  1253. </style>