build: migrate the build tool from vue-cli to vite4 (#208)

This commit is contained in:
Fine0830 2022-12-17 14:07:03 +08:00 committed by GitHub
parent 1e0c253488
commit 44dcb1e7f6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
214 changed files with 27014 additions and 54234 deletions

33
.eslintignore Normal file
View File

@ -0,0 +1,33 @@
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
*.sh
node_modules
*.md
*.woff
*.ttf
.vscode
.idea
dist
/public
/docs
.husky
.local
/bin
Dockerfile

53
.eslintrc.cjs Normal file
View File

@ -0,0 +1,53 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require("@rushstack/eslint-patch/modern-module-resolution");
module.exports = {
root: true,
extends: [
"plugin:vue/vue3-essential",
"eslint:recommended",
"@vue/eslint-config-typescript",
"@vue/eslint-config-prettier",
],
overrides: [
{
files: ["cypress/e2e/**/*.{cy,spec}.{js,ts,jsx,tsx}"],
extends: ["plugin:cypress/recommended"],
},
],
parserOptions: {
ecmaVersion: "latest",
},
env: {
browser: true,
node: true,
},
rules: {
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/explicit-module-boundary-types": "off",
"vue/script-setup-uses-vars": "error",
"@typescript-eslint/ban-ts-ignore'": "off",
"@typescript-eslint/explicit-function-return-type": "off",
"no-use-before-define": "off",
"@typescript-eslint/no-use-before-define": "off",
"@typescript-eslint/no-non-null-assertion": "off",
"@typescript-eslint/no-this-alias": "off",
"vue/multi-word-component-names": "off",
},
};

View File

@ -37,7 +37,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [12.x, 14.x, 16.x]
node-version: [14.x, 16.x, 18.x]
steps:
- uses: actions/checkout@v1
- name: Use Node.js ${{ matrix.node-version }}

33
.gitignore vendored
View File

@ -16,24 +16,39 @@
# specific language governing permissions and limitations
# under the License.
#
.DS_Store
node_modules
/dist
/node
/tests/e2e/videos/
/tests/e2e/screenshots/
# local env files
.env.local
.env.*.local
# Log files
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
.DS_Store
dist
dist-ssr
coverage
*.local
/cypress/videos/
/cypress/screenshots/
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
# Editor directories and files
.idea

27
.husky/commit-msg Executable file
View File

@ -0,0 +1,27 @@
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
#!/bin/sh
# shellcheck source=./_/husky.sh
. "$(dirname "$0")/_/husky.sh"
PATH="/usr/local/bin:$PATH"
npx --no-install commitlint --edit "$1"

27
.husky/common.sh Normal file
View File

@ -0,0 +1,27 @@
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
#!/bin/sh
command_exists () {
command -v "$1" >/dev/null 2>&1
}
if command_exists winpty && test -t 1; then
exec < /dev/tty
fi

29
.husky/pre-commit Executable file
View File

@ -0,0 +1,29 @@
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
. "$(dirname "$0")/common.sh"
[ -n "$CI" ] && exit 0
PATH="/usr/local/bin:$PATH"
# Format and submit code according to lintstagedrc configuration
npm run lint:lint-staged

22
.stylelintignore Normal file
View File

@ -0,0 +1,22 @@
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
/dist/*
/public/*
public/*

50
commitlint.config.js Normal file
View File

@ -0,0 +1,50 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
module.exports = {
ignores: [(commit) => commit.includes("init")],
extends: ["@commitlint/config-conventional"],
rules: {
"body-leading-blank": [2, "always"],
"footer-leading-blank": [1, "always"],
"header-max-length": [2, "always", 108],
"subject-empty": [2, "never"],
"type-empty": [2, "never"],
"subject-case": [0],
"type-enum": [
2,
"always",
[
"feat",
"fix",
"perf",
"style",
"docs",
"test",
"refactor",
"build",
"ci",
"chore",
"revert",
"wip",
"workflow",
"types",
"release",
],
],
},
};

25
cypress.config.ts Normal file
View File

@ -0,0 +1,25 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { defineConfig } from "cypress";
export default defineConfig({
e2e: {
specPattern: "cypress/e2e/**/*.{cy,spec}.{js,jsx,ts,tsx}",
baseUrl: "http://localhost:4173",
},
});

View File

@ -14,6 +14,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
module.exports = {
presets: ["@vue/cli-plugin-babel/preset"],
};
describe("My First Test", () => {
it("visits the app root url", () => {
cy.visit("/");
cy.contains("h1", "You did it!");
});
});

26
cypress/e2e/tsconfig.json Normal file
View File

@ -0,0 +1,26 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
{
"extends": "@vue/tsconfig/tsconfig.web.json",
"include": ["./**/*", "../support/**/*"],
"compilerOptions": {
"isolatedModules": false,
"target": "es5",
"lib": ["es5", "dom"],
"types": ["cypress"]
}
}

View File

@ -14,7 +14,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const requireAll = (requireContext: Recordable) =>
requireContext.keys().map(requireContext);
const req = require.context("./", true, /\.svg$/);
requireAll(req);
{
"name": "Using fixtures to represent data",
"email": "hello@cypress.io",
"body": "Fixtures are a great way to mock data for responses to routes"
}

View File

@ -0,0 +1,55 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <reference types="cypress" />
// ***********************************************
// This example commands.ts shows you how to
// create various custom commands and overwrite
// existing commands.
//
// For more comprehensive examples of custom
// commands please read more here:
// https://on.cypress.io/custom-commands
// ***********************************************
//
//
// -- This is a parent command --
// Cypress.Commands.add('login', (email, password) => { ... })
//
//
// -- This is a child command --
// Cypress.Commands.add('drag', { prevSubject: 'element'}, (subject, options) => { ... })
//
//
// -- This is a dual command --
// Cypress.Commands.add('dismiss', { prevSubject: 'optional'}, (subject, options) => { ... })
//
//
// -- This will overwrite an existing command --
// Cypress.Commands.overwrite('visit', (originalFn, url, options) => { ... })
//
// declare global {
// namespace Cypress {
// interface Chainable {
// login(email: string, password: string): Chainable<void>
// drag(subject: string, options?: Partial<TypeOptions>): Chainable<Element>
// dismiss(subject: string, options?: Partial<TypeOptions>): Chainable<Element>
// visit(originalFn: CommandOriginalFn, url: string, options: Partial<VisitOptions>): Chainable<Element>
// }
// }
// }
export {};

37
cypress/support/e2e.ts Normal file
View File

@ -0,0 +1,37 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// ***********************************************************
// This example support/index.js is processed and
// loaded automatically before your test files.
//
// This is a great place to put global configuration and
// behavior that modifies Cypress.
//
// You can change the location of this file or turn off
// automatically serving support files with the
// 'supportFile' configuration option.
//
// You can read more here:
// https://on.cypress.io/configuration
// ***********************************************************
// Import commands.js using ES2015 syntax:
import "./commands";
// Alternatively you can use CommonJS syntax:
// require('./commands')

26
env.d.ts vendored Normal file
View File

@ -0,0 +1,26 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_SW_PROXY_TARGET: string;
readonly VITE_DROP_CONSOLE: boolean;
}
interface ImportMeta {
readonly env: ImportMetaEnv;
}

View File

@ -15,17 +15,13 @@ limitations under the License. -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<title><%= htmlWebpackPlugin.options.title %></title>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Apache SkyWalking</title>
</head>
<body>
<noscript>
<strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
<script type="module" src="/src/main.ts"></script>
</body>
</html>

50669
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,13 +1,20 @@
{
"name": "skywalking-booster-ui",
"version": "9.3.0",
"version": "9.4.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"test:unit": "vue-cli-service test:unit",
"test:e2e": "vue-cli-service test:e2e",
"lint": "vue-cli-service lint"
"dev": "vite",
"build": "run-p type-check build-only",
"preview": "vite preview",
"test:unit": "vitest --environment jsdom --root src/",
"test:e2e:dev": "start-server-and-test 'vite dev --port 4173' :4173 'cypress open --e2e'",
"build-only": "vite build",
"type-check": "vue-tsc --noEmit -p tsconfig.vitest.json --composite false",
"lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --fix --ignore-path .gitignore",
"lint:prettier": "prettier --write \"src/**/*.{js,json,tsx,css,less,scss,vue,html,md}\"",
"lint:stylelint": "stylelint --cache --fix \"**/*.{vue,less,postcss,css,scss}\" --cache --cache-location node_modules/.cache/stylelint/",
"lint:lint-staged": "lint-staged",
"prepare": "husky install"
},
"dependencies": {
"axios": "^0.24.0",
@ -17,132 +24,76 @@
"echarts": "^5.2.2",
"element-plus": "^2.0.2",
"lodash": "^4.17.21",
"monaco-editor": "^0.27.0",
"pinia": "^2.0.5",
"monaco-editor": "^0.34.1",
"pinia": "^2.0.28",
"vis-timeline": "^7.5.1",
"vue": "^3.0.0",
"vue": "^3.2.45",
"vue-grid-layout": "^3.0.0-beta1",
"vue-i18n": "^9.1.9",
"vue-router": "^4.0.0-0",
"vue-router": "^4.1.6",
"vue-types": "^4.1.1"
},
"devDependencies": {
"@commitlint/cli": "^17.3.0",
"@commitlint/config-conventional": "^17.3.0",
"@rushstack/eslint-patch": "^1.1.4",
"@types/d3": "^7.1.0",
"@types/d3-tip": "^3.5.5",
"@types/echarts": "^4.9.12",
"@types/jest": "^24.0.19",
"@types/jsdom": "^20.0.1",
"@types/lodash": "^4.14.179",
"@types/node": "^18.11.12",
"@types/three": "^0.131.0",
"@typescript-eslint/eslint-plugin": "^4.18.0",
"@typescript-eslint/parser": "^4.18.0",
"@vue/cli-plugin-babel": "~4.5.0",
"@vue/cli-plugin-e2e-cypress": "~5.0.8",
"@vue/cli-plugin-eslint": "~4.5.0",
"@vue/cli-plugin-router": "~4.5.0",
"@vue/cli-plugin-typescript": "~4.5.0",
"@vue/cli-plugin-unit-jest": "~4.5.0",
"@vue/cli-plugin-vuex": "~4.5.0",
"@vue/cli-service": "~4.5.0",
"@vue/compiler-sfc": "^3.0.0",
"@vue/eslint-config-prettier": "^6.0.0",
"@vue/eslint-config-typescript": "^7.0.0",
"@vue/test-utils": "^2.0.0-0",
"babel-jest": "^24.9.0",
"eslint": "^6.7.2",
"eslint-plugin-prettier": "^3.3.1",
"eslint-plugin-vue": "^7.0.0",
"husky": "^7.0.4",
"@vitejs/plugin-vue": "^4.0.0",
"@vitejs/plugin-vue-jsx": "^3.0.0",
"@vue/eslint-config-prettier": "^7.0.0",
"@vue/eslint-config-typescript": "^11.0.0",
"@vue/test-utils": "^2.2.6",
"@vue/tsconfig": "^0.1.3",
"@vueuse/core": "^9.6.0",
"cypress": "^12.0.2",
"eslint": "^8.22.0",
"eslint-plugin-cypress": "^2.12.1",
"eslint-plugin-vue": "^9.3.0",
"husky": "^8.0.2",
"jsdom": "^20.0.3",
"lint-staged": "^12.1.3",
"monaco-editor-webpack-plugin": "^4.1.2",
"node-sass": "^6.0.1",
"node-sass": "^8.0.0",
"npm-run-all": "^4.1.5",
"postcss-html": "^1.3.0",
"postcss-scss": "^4.0.2",
"prettier": "^2.2.1",
"sass-loader": "^10.2.0",
"prettier": "^2.7.1",
"sass": "^1.56.1",
"start-server-and-test": "^1.15.2",
"stylelint": "^14.1.0",
"stylelint-config-html": "^1.0.0",
"stylelint-config-prettier": "^9.0.3",
"stylelint-config-standard": "^24.0.0",
"stylelint-order": "^5.0.0",
"svg-sprite-loader": "^6.0.11",
"typescript": "~4.4.4",
"typescript": "~4.7.4",
"unplugin-auto-import": "^0.7.0",
"unplugin-vue-components": "^0.19.2",
"vue-jest": "^5.0.0-0"
"vite": "^4.0.0",
"vite-plugin-monaco-editor": "^1.1.0",
"vite-plugin-svg-icons": "^2.0.1",
"vitest": "^0.25.6",
"vue-tsc": "^1.0.12"
},
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/vue3-essential",
"eslint:recommended",
"@vue/typescript/recommended",
"@vue/prettier",
"@vue/prettier/@typescript-eslint"
],
"parserOptions": {
"ecmaVersion": 2020
},
"rules": {
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/explicit-module-boundary-types": "off",
"vue/script-setup-uses-vars": "error",
"@typescript-eslint/ban-ts-ignore'": "off",
"@typescript-eslint/explicit-function-return-type": "off",
"no-use-before-define": "off",
"@typescript-eslint/no-use-before-define": "off",
"@typescript-eslint/no-non-null-assertion": "off",
"@typescript-eslint/no-this-alias": "off"
},
"overrides": [
{
"files": [
"**/__tests__/*.{j,t}s?(x)",
"**/tests/unit/**/*.spec.{j,t}s?(x)"
],
"env": {
"jest": true
}
}
]
},
"eslintIgnore": [
"vue.config.js"
],
"browserslist": [
"> 1%",
"last 2 versions",
"not dead"
],
"jest": {
"preset": "@vue/cli-plugin-unit-jest/presets/typescript-and-babel",
"transform": {
"^.+\\.vue$": "vue-jest"
}
},
"gitHooks": {
"pre-commit": "lint-staged"
},
"lint-staged": {
"*.{js,jsx,ts,tsx}": [
"eslint --fix",
"prettier --write"
],
"*.vue": [
"eslint --fix",
"prettier --write",
"stylelint --fix --custom-syntax postcss-html"
"*.{js,jsx,ts,tsx,vue,scss,less}": [
"eslint . --ext .vue,.js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --fix --ignore-path .gitignore",
"prettier --write \"src/**/*.{js,tsx,css,less,scss,vue,html,md}\"",
"stylelint --cache --fix \"**/*.{vue,less,postcss,css,scss}\" --cache --cache-location node_modules/.cache/stylelint/"
],
"{!(package)*.json,*.code-snippets,.!(browserslist)*rc}": [
"prettier --write--parser json"
],
"package.json": [
"prettier --write"
],
"*.{scss,less,styl}": [
"stylelint --fix",
"package.json": [
"prettier --write"
],
"*.md": [

View File

@ -14,8 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
module.exports = {
plugins: {
autoprefixer: {},
},
autoprefixer: {},
};

26
prettier.config.js Normal file
View File

@ -0,0 +1,26 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
module.exports = {
printWidth: 120,
semi: true,
vueIndentScriptAndStyle: true,
trailingComma: "all",
proseWrap: "never",
htmlWhitespaceSensitivity: "strict",
endOfLine: "auto",
};

View File

@ -16,10 +16,10 @@ limitations under the License. -->
<router-view />
</template>
<style>
#app {
color: #2c3e50;
height: 100%;
overflow: hidden;
min-width: 1024px;
}
#app {
color: #2c3e50;
height: 100%;
overflow: hidden;
min-width: 1024px;
}
</style>

View File

@ -14,8 +14,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const requireComponent = require.context("./technologies", false, /\.png$/);
const requireTool = require.context("./tools", false, /\.png$/);
const requireComponent = import.meta.glob("./technologies/*.png", { eager: true });
const requireTool = import.meta.glob("./tools/*.png", { eager: true });
const result: { [key: string]: string } = {};
const t: { [key: string]: string } = {};
@ -24,25 +24,19 @@ function capitalizeFirstLetter(str: string) {
}
function validateFileName(str: string): string | undefined {
if (/^\S+\.png$/.test(str)) {
return str.replace(/^\S+\/(\w+)\.png$/, (rs, $1) =>
capitalizeFirstLetter($1)
);
return str.replace(/^\S+\/(\w+)\.png$/, (rs, $1) => capitalizeFirstLetter($1));
}
}
[...requireComponent.keys()].forEach((filePath: string) => {
const componentConfig = requireComponent(filePath);
Object.keys(requireComponent).forEach((filePath: string) => {
const fileName = validateFileName(filePath);
if (fileName) {
result[fileName] = componentConfig;
result[fileName] = (requireComponent as { [key: string]: any })[filePath].default;
}
});
[...requireTool.keys()].forEach((filePath: string) => {
const componentConfig = requireTool(filePath);
Object.keys(requireTool).forEach((filePath: string) => {
const fileName = validateFileName(filePath);
if (fileName) {
t[fileName] = componentConfig;
t[fileName] = (requireTool as { [key: string]: any })[filePath].default;
}
});

File diff suppressed because it is too large Load Diff

View File

@ -19,11 +19,7 @@ limitations under the License. -->
<div class="tools" @click="associateMetrics" v-if="associate.length">
{{ t("associateMetrics") }}
</div>
<div
class="tools"
@click="viewTrace"
v-if="relatedTrace && relatedTrace.enableRelate"
>
<div class="tools" @click="viewTrace" v-if="relatedTrace && relatedTrace.enableRelate">
{{ t("viewTrace") }}
</div>
</div>
@ -40,224 +36,212 @@ limitations under the License. -->
</div>
</template>
<script lang="ts" setup>
import {
watch,
ref,
Ref,
onMounted,
onBeforeUnmount,
unref,
computed,
} from "vue";
import type { PropType } from "vue";
import { useI18n } from "vue-i18n";
import { EventParams } from "@/types/app";
import { Filters, RelatedTrace } from "@/types/dashboard";
import { useECharts } from "@/hooks/useEcharts";
import { addResizeListener, removeResizeListener } from "@/utils/event";
import Trace from "@/views/dashboard/related/trace/Index.vue";
import associateProcessor from "@/hooks/useAssociateProcessor";
import { watch, ref, onMounted, onBeforeUnmount, unref, computed } from "vue";
import type { PropType, Ref } from "vue";
import { useI18n } from "vue-i18n";
import type { EventParams } from "@/types/app";
import type { Filters, RelatedTrace } from "@/types/dashboard";
import { useECharts } from "@/hooks/useEcharts";
import { addResizeListener, removeResizeListener } from "@/utils/event";
import Trace from "@/views/dashboard/related/trace/Index.vue";
import associateProcessor from "@/hooks/useAssociateProcessor";
/*global Nullable, defineProps, defineEmits*/
const emits = defineEmits(["select"]);
const { t } = useI18n();
const chartRef = ref<Nullable<HTMLDivElement>>(null);
const menus = ref<Nullable<HTMLDivElement>>(null);
const visMenus = ref<boolean>(false);
const { setOptions, resize, getInstance } = useECharts(
chartRef as Ref<HTMLDivElement>
);
const currentParams = ref<Nullable<EventParams>>(null);
const showTrace = ref<boolean>(false);
const traceOptions = ref<{ type: string; filters?: unknown }>({
type: "Trace",
});
const props = defineProps({
height: { type: String, default: "100%" },
width: { type: String, default: "100%" },
option: {
type: Object as PropType<{ [key: string]: any }>,
default: () => ({}),
},
filters: {
type: Object as PropType<Filters>,
},
relatedTrace: {
type: Object as PropType<RelatedTrace>,
},
associate: {
type: Array as PropType<{ widgetId: string }[]>,
default: () => [],
},
});
const available = computed(
() =>
(Array.isArray(props.option.series) &&
props.option.series[0] &&
props.option.series[0].data) ||
(Array.isArray(props.option.series.data) && props.option.series.data[0])
);
onMounted(async () => {
await setOptions(props.option);
chartRef.value && addResizeListener(unref(chartRef), resize);
instanceEvent();
});
/*global Nullable, defineProps, defineEmits*/
const emits = defineEmits(["select"]);
const { t } = useI18n();
const chartRef = ref<Nullable<HTMLDivElement>>(null);
const menus = ref<Nullable<HTMLDivElement>>(null);
const visMenus = ref<boolean>(false);
const { setOptions, resize, getInstance } = useECharts(chartRef as Ref<HTMLDivElement>);
const currentParams = ref<Nullable<EventParams>>(null);
const showTrace = ref<boolean>(false);
const traceOptions = ref<{ type: string; filters?: unknown }>({
type: "Trace",
});
const props = defineProps({
height: { type: String, default: "100%" },
width: { type: String, default: "100%" },
option: {
type: Object as PropType<{ [key: string]: any }>,
default: () => ({}),
},
filters: {
type: Object as PropType<Filters>,
},
relatedTrace: {
type: Object as PropType<RelatedTrace>,
},
associate: {
type: Array as PropType<{ widgetId: string }[]>,
default: () => [],
},
});
const available = computed(
() =>
(Array.isArray(props.option.series) && props.option.series[0] && props.option.series[0].data) ||
(Array.isArray(props.option.series.data) && props.option.series.data[0]),
);
onMounted(async () => {
await setOptions(props.option);
chartRef.value && addResizeListener(unref(chartRef), resize);
instanceEvent();
});
function instanceEvent() {
setTimeout(() => {
function instanceEvent() {
setTimeout(() => {
const instance = getInstance();
if (!instance) {
return;
}
instance.on("click", (params: EventParams) => {
currentParams.value = params;
if (!menus.value || !chartRef.value) {
return;
}
visMenus.value = true;
const w = chartRef.value.getBoundingClientRect().width || 0;
const h = chartRef.value.getBoundingClientRect().height || 0;
if (w - params.event.offsetX > 120) {
menus.value.style.left = params.event.offsetX + "px";
} else {
menus.value.style.left = params.event.offsetX - 120 + "px";
}
if (h - params.event.offsetY < 50) {
menus.value.style.top = params.event.offsetY - 40 + "px";
} else {
menus.value.style.top = params.event.offsetY + 2 + "px";
}
});
document.addEventListener(
"click",
() => {
if (instance.isDisposed()) {
return;
}
visMenus.value = false;
instance.dispatchAction({
type: "updateAxisPointer",
currTrigger: "leave",
});
},
true,
);
}, 1000);
}
function associateMetrics() {
emits("select", currentParams.value);
const { dataIndex, seriesIndex } = currentParams.value || {
dataIndex: 0,
seriesIndex: 0,
};
updateOptions({ dataIndex, seriesIndex });
}
function updateOptions(params?: { dataIndex: number; seriesIndex: number }) {
const instance = getInstance();
if (!instance) {
return;
}
instance.on("click", (params: EventParams) => {
currentParams.value = params;
if (!menus.value || !chartRef.value) {
if (!props.filters) {
return;
}
if (props.filters.isRange) {
const { eventAssociate } = associateProcessor(props);
const options = eventAssociate();
setOptions(options || props.option);
} else {
instance.dispatchAction({
type: "updateAxisPointer",
dataIndex: params ? params.dataIndex : props.filters.dataIndex,
seriesIndex: params ? params.seriesIndex : 0,
});
const ids = props.option.series.map((_: unknown, index: number) => index);
instance.dispatchAction({
type: "highlight",
dataIndex: params ? params.dataIndex : props.filters.dataIndex,
seriesIndex: ids,
});
}
}
function viewTrace() {
const item = associateProcessor(props).traceFilters(currentParams.value);
traceOptions.value = {
...traceOptions.value,
filters: item,
};
showTrace.value = true;
visMenus.value = true;
}
watch(
() => props.option,
(newVal, oldVal) => {
if (!available.value) {
return;
}
visMenus.value = true;
const w = chartRef.value.getBoundingClientRect().width || 0;
const h = chartRef.value.getBoundingClientRect().height || 0;
if (w - params.event.offsetX > 120) {
menus.value.style.left = params.event.offsetX + "px";
} else {
menus.value.style.left = params.event.offsetX - 120 + "px";
if (JSON.stringify(newVal) === JSON.stringify(oldVal)) {
return;
}
if (h - params.event.offsetY < 50) {
menus.value.style.top = params.event.offsetY - 40 + "px";
} else {
menus.value.style.top = params.event.offsetY + 2 + "px";
let options;
if (props.filters && props.filters.isRange) {
const { eventAssociate } = associateProcessor(props);
options = eventAssociate();
}
});
document.addEventListener(
"click",
() => {
if (instance.isDisposed()) {
return;
}
visMenus.value = false;
instance.dispatchAction({
type: "updateAxisPointer",
currTrigger: "leave",
});
},
true
);
}, 1000);
}
setOptions(options || props.option);
},
);
watch(
() => props.filters,
() => {
updateOptions();
},
);
function associateMetrics() {
emits("select", currentParams.value);
const { dataIndex, seriesIndex } = currentParams.value || {
dataIndex: 0,
seriesIndex: 0,
};
updateOptions({ dataIndex, seriesIndex });
}
function updateOptions(params?: { dataIndex: number; seriesIndex: number }) {
const instance = getInstance();
if (!instance) {
return;
}
if (!props.filters) {
return;
}
if (props.filters.isRange) {
const { eventAssociate } = associateProcessor(props);
const options = eventAssociate();
setOptions(options || props.option);
} else {
instance.dispatchAction({
type: "updateAxisPointer",
dataIndex: params ? params.dataIndex : props.filters.dataIndex,
seriesIndex: params ? params.seriesIndex : 0,
});
const ids = props.option.series.map((_: unknown, index: number) => index);
instance.dispatchAction({
type: "highlight",
dataIndex: params ? params.dataIndex : props.filters.dataIndex,
seriesIndex: ids,
});
}
}
function viewTrace() {
const item = associateProcessor(props).traceFilters(currentParams.value);
traceOptions.value = {
...traceOptions.value,
filters: item,
};
showTrace.value = true;
visMenus.value = true;
}
watch(
() => props.option,
(newVal, oldVal) => {
if (!available.value) {
return;
}
if (JSON.stringify(newVal) === JSON.stringify(oldVal)) {
return;
}
let options;
if (props.filters && props.filters.isRange) {
const { eventAssociate } = associateProcessor(props);
options = eventAssociate();
}
setOptions(options || props.option);
}
);
watch(
() => props.filters,
() => {
updateOptions();
}
);
onBeforeUnmount(() => {
removeResizeListener(unref(chartRef), resize);
});
onBeforeUnmount(() => {
removeResizeListener(unref(chartRef), resize);
});
</script>
<style lang="scss" scoped>
.no-data {
font-size: 12px;
height: 100%;
box-sizing: border-box;
display: -webkit-box;
-webkit-box-orient: horizontal;
-webkit-box-pack: center;
-webkit-box-align: center;
color: #666;
}
.chart {
overflow: hidden;
flex: 1;
}
.menus {
position: absolute;
display: block;
white-space: nowrap;
z-index: 9999999;
box-shadow: #ddd 1px 2px 10px;
transition: all cubic-bezier(0.075, 0.82, 0.165, 1) linear;
background-color: rgb(255, 255, 255);
border-radius: 4px;
color: rgb(51, 51, 51);
padding: 5px;
}
.tools {
padding: 5px;
color: #999;
cursor: pointer;
&:hover {
color: #409eff;
background-color: #eee;
.no-data {
font-size: 12px;
height: 100%;
box-sizing: border-box;
display: -webkit-box;
-webkit-box-orient: horizontal;
-webkit-box-pack: center;
-webkit-box-align: center;
color: #666;
}
.chart {
overflow: hidden;
flex: 1;
}
.menus {
position: absolute;
display: block;
white-space: nowrap;
z-index: 9999999;
box-shadow: #ddd 1px 2px 10px;
transition: all cubic-bezier(0.075, 0.82, 0.165, 1) linear;
background-color: rgb(255, 255, 255);
border-radius: 4px;
color: rgb(51, 51, 51);
padding: 5px;
}
.tools {
padding: 5px;
color: #999;
cursor: pointer;
&:hover {
color: #409eff;
background-color: #eee;
}
}
}
</style>

View File

@ -24,64 +24,62 @@ limitations under the License. -->
loading,
}"
>
<use :xlink:href="`#${iconName}`"></use>
<use :href="`#${iconName}`"></use>
</svg>
</template>
<script lang="ts" setup>
import "@/assets/icons/index";
/*global defineProps */
defineProps({
iconName: { type: String, default: "" },
size: { type: String, default: "sm" },
loading: { type: Boolean, default: false },
});
/*global defineProps */
defineProps({
iconName: { type: String, default: "" },
size: { type: String, default: "sm" },
loading: { type: Boolean, default: false },
});
</script>
<style lang="scss" scoped>
.icon {
width: 16px;
height: 16px;
vertical-align: middle;
fill: currentColor;
.icon {
width: 16px;
height: 16px;
vertical-align: middle;
fill: currentColor;
&.sm {
width: 14px;
height: 14px;
}
&.sm {
width: 14px;
height: 14px;
}
&.middle {
width: 18px;
height: 18px;
}
&.middle {
width: 18px;
height: 18px;
}
&.lg {
width: 22px;
height: 22px;
}
&.lg {
width: 22px;
height: 22px;
}
&.loading {
animation: loading 1.5s linear infinite;
}
&.loading {
animation: loading 1.5s linear infinite;
}
&.logo {
height: 30px;
width: 110px;
}
&.logo {
height: 30px;
width: 110px;
}
&.xl {
height: 30px;
width: 30px;
}
}
@keyframes loading {
0% {
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
&.xl {
height: 30px;
width: 30px;
}
}
@keyframes loading {
0% {
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
to {
-webkit-transform: rotate(1turn);
transform: rotate(1turn);
to {
-webkit-transform: rotate(1turn);
transform: rotate(1turn);
}
}
}
</style>

View File

@ -20,31 +20,31 @@ limitations under the License. -->
</el-radio-group>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import type { PropType } from "vue";
import { ref } from "vue";
import type { PropType } from "vue";
interface Option {
label: string | number;
value: string | number;
}
/*global defineProps, defineEmits */
const emit = defineEmits(["change"]);
const props = defineProps({
options: {
type: Array as PropType<
{
label: string | number;
value: string | number;
}[]
>,
default: () => [],
},
value: {
type: String as PropType<string>,
default: "",
},
size: { type: null, default: "default" },
});
/*global defineProps, defineEmits */
const emit = defineEmits(["change"]);
const props = defineProps({
options: {
type: Array as PropType<Option[]>,
default: () => [],
},
value: {
type: String as PropType<string>,
default: "",
},
size: { type: null, default: "default" },
});
const selected = ref<string>(props.value);
const selected = ref<string>(props.value);
function checked(opt: unknown) {
emit("change", opt);
}
function checked(opt: unknown) {
emit("change", opt);
}
</script>

View File

@ -19,9 +19,7 @@ limitations under the License. -->
{{ selected.label }}
</span>
<span class="no-data" v-else>Please select a option</span>
<span class="remove-icon" @click="removeSelected" v-if="clearable">
×
</span>
<span class="remove-icon" @click="removeSelected" v-if="clearable"> × </span>
</div>
<div class="opt-wrapper" v-show="visible">
<div
@ -37,141 +35,141 @@ limitations under the License. -->
</div>
</template>
<script lang="ts" setup>
import { ref, watch } from "vue";
import type { PropType } from "vue";
import { Option } from "@/types/app";
import { ref, watch } from "vue";
import type { PropType } from "vue";
import type { Option } from "@/types/app";
/*global defineProps, defineEmits*/
const emit = defineEmits(["change"]);
const props = defineProps({
options: {
type: Array as PropType<Option[]>,
default: () => [],
},
value: {
type: String as PropType<string>,
default: () => "",
},
clearable: { type: Boolean, default: false },
});
const visible = ref<boolean>(false);
const opt = props.options.find((d: Option) => props.value === d.value);
const selected = ref<Option>(opt || { label: "", value: "" });
/*global defineProps, defineEmits*/
const emit = defineEmits(["change"]);
const props = defineProps({
options: {
type: Array as PropType<Option[]>,
default: () => [],
},
value: {
type: String as PropType<string>,
default: () => "",
},
clearable: { type: Boolean, default: false },
});
const visible = ref<boolean>(false);
const opt = props.options.find((d: Option) => props.value === d.value);
const selected = ref<Option>(opt || { label: "", value: "" });
function handleSelect(i: Option) {
selected.value = i;
emit("change", i.value);
}
function removeSelected() {
selected.value = { label: "", value: "" };
emit("change", "");
}
watch(
() => props.value,
(data) => {
const opt = props.options.find((d: Option) => data === d.value);
selected.value = opt || { label: "", value: "" };
function handleSelect(i: Option) {
selected.value = i;
emit("change", i.value);
}
);
document.body.addEventListener("click", handleClick, false);
function removeSelected() {
selected.value = { label: "", value: "" };
emit("change", "");
}
watch(
() => props.value,
(data) => {
const opt = props.options.find((d: Option) => data === d.value);
selected.value = opt || { label: "", value: "" };
},
);
document.body.addEventListener("click", handleClick, false);
function handleClick() {
visible.value = false;
}
function setPopper(event: any) {
event.stopPropagation();
visible.value = !visible.value;
}
function handleClick() {
visible.value = false;
}
function setPopper(event: any) {
event.stopPropagation();
visible.value = !visible.value;
}
</script>
<style lang="scss" scoped>
.bar-select {
position: relative;
justify-content: space-between;
border: 1px solid #ddd;
background: #fff;
border-radius: 3px;
color: #000;
font-size: 12px;
height: 24px;
.selected {
padding: 0 3px;
.bar-select {
position: relative;
justify-content: space-between;
border: 1px solid #ddd;
background: #fff;
border-radius: 3px;
margin: 3px;
color: #409eff;
background-color: #fafafa;
border: 1px solid #e8e8e8;
text-align: center;
}
}
color: #000;
font-size: 12px;
height: 24px;
.no-data {
color: #c0c4cc;
}
.bar-i {
height: 100%;
width: 100%;
padding: 2px 10px;
overflow: auto;
color: #606266;
position: relative;
&:hover {
.remove-icon {
display: block;
.selected {
padding: 0 3px;
border-radius: 3px;
margin: 3px;
color: #409eff;
background-color: #fafafa;
border: 1px solid #e8e8e8;
text-align: center;
}
}
}
.remove-icon {
position: absolute;
right: 5px;
top: 0;
font-size: 14px;
display: none;
color: #aaa;
cursor: pointer;
}
.no-data {
color: #c0c4cc;
}
.opt-wrapper {
color: #606266;
position: absolute;
top: 26px;
left: 0;
background: #fff;
box-shadow: 0 1px 6px rgba(99, 99, 99, 0.2);
border: 1px solid #ddd;
width: 100%;
border-radius: 0 0 3px 3px;
border-right-width: 1px !important;
z-index: 10;
overflow: auto;
max-height: 200px;
padding-bottom: 2px;
.close {
position: absolute;
right: 10px;
top: 12px;
opacity: 0.6;
.bar-i {
height: 100%;
width: 100%;
padding: 2px 10px;
overflow: auto;
color: #606266;
position: relative;
&:hover {
opacity: 1;
.remove-icon {
display: block;
}
}
}
}
.opt {
padding: 7px 15px;
&.select-disabled {
color: #409eff;
cursor: not-allowed;
.remove-icon {
position: absolute;
right: 5px;
top: 0;
font-size: 14px;
display: none;
color: #aaa;
cursor: pointer;
}
&:hover {
background-color: #f5f5f5;
.opt-wrapper {
color: #606266;
position: absolute;
top: 26px;
left: 0;
background: #fff;
box-shadow: 0 1px 6px rgba(99, 99, 99, 0.2);
border: 1px solid #ddd;
width: 100%;
border-radius: 0 0 3px 3px;
border-right-width: 1px !important;
z-index: 10;
overflow: auto;
max-height: 200px;
padding-bottom: 2px;
.close {
position: absolute;
right: 10px;
top: 12px;
opacity: 0.6;
&:hover {
opacity: 1;
}
}
}
.opt {
padding: 7px 15px;
&.select-disabled {
color: #409eff;
cursor: not-allowed;
}
&:hover {
background-color: #f5f5f5;
}
}
}
</style>

View File

@ -27,73 +27,71 @@ limitations under the License. -->
:remote-method="remoteMethod"
:filterable="filterable"
>
<el-option
v-for="item in options"
:key="item.value || ''"
:label="item.label || ''"
:value="item.value || ''"
>
<el-option v-for="item in options" :key="item.value || ''" :label="item.label || ''" :value="item.value || ''">
</el-option>
</el-select>
</template>
<script lang="ts" setup>
import { ref, watch } from "vue";
import type { PropType } from "vue";
import { ref, watch } from "vue";
import type { PropType } from "vue";
interface Option {
label: string | number;
value: string | number;
}
// interface Option {
// label: string | number;
// value: string | number;
// }
/*global defineProps, defineEmits*/
const emit = defineEmits(["change", "query"]);
const props = defineProps({
options: {
type: Array as PropType<(Option & { disabled?: boolean })[]>,
default: () => [],
},
value: {
type: [Array, String, Number, undefined] as PropType<any>,
default: () => [],
},
size: { type: null, default: "default" },
placeholder: {
type: [String, undefined] as PropType<string>,
default: "Select a option",
},
borderRadius: { type: Number, default: 3 },
multiple: { type: Boolean, default: false },
disabled: { type: Boolean, default: false },
clearable: { type: Boolean, default: false },
isRemote: { type: Boolean, default: false },
filterable: { type: Boolean, default: true },
});
/*global defineProps, defineEmits*/
const emit = defineEmits(["change", "query"]);
const props = defineProps({
options: {
type: Array as PropType<
({
label: string | number;
value: string | number;
} & { disabled?: boolean })[]
>,
default: () => [],
},
value: {
type: [Array, String, Number, undefined] as PropType<any>,
default: () => [],
},
size: { type: null, default: "default" },
placeholder: {
type: [String, undefined] as PropType<string>,
default: "Select a option",
},
borderRadius: { type: Number, default: 3 },
multiple: { type: Boolean, default: false },
disabled: { type: Boolean, default: false },
clearable: { type: Boolean, default: false },
isRemote: { type: Boolean, default: false },
filterable: { type: Boolean, default: true },
});
const selected = ref<string[] | string>(props.value);
function changeSelected() {
const options = props.options.filter((d: any) =>
props.multiple
? selected.value.includes(d.value)
: selected.value === d.value
const selected = ref<string[] | string>(props.value);
function changeSelected() {
const options = props.options.filter((d: any) =>
props.multiple ? selected.value.includes(d.value) : selected.value === d.value,
);
emit("change", options);
}
function remoteMethod(query: string) {
if (props.isRemote) {
emit("query", query);
}
}
watch(
() => props.value,
(data) => {
selected.value = data;
},
);
emit("change", options);
}
function remoteMethod(query: string) {
if (props.isRemote) {
emit("query", query);
}
}
watch(
() => props.value,
(data) => {
selected.value = data;
}
);
</script>
<style lang="scss" scoped>
.el-input__inner {
border-radius: unset !important;
}
.el-input__inner {
border-radius: unset !important;
}
</style>

View File

@ -35,56 +35,28 @@ limitations under the License. -->
<transition name="datepicker-anim">
<div
class="datepicker-popup"
:class="[
popupClass,
{ 'datepicker-inline': type === 'inline' },
position,
]"
:class="[popupClass, { 'datepicker-inline': type === 'inline' }, position]"
tabindex="-1"
v-if="show || type === 'inline'"
>
<template v-if="range">
<div class="datepicker-popup__sidebar">
<button
type="button"
class="datepicker-popup__shortcut"
@click="quickPick('quarter')"
>
<button type="button" class="datepicker-popup__shortcut" @click="quickPick('quarter')">
{{ local.quarterHourCutTip }}
</button>
<button
type="button"
class="datepicker-popup__shortcut"
@click="quickPick('half')"
>
<button type="button" class="datepicker-popup__shortcut" @click="quickPick('half')">
{{ local.halfHourCutTip }}
</button>
<button
type="button"
class="datepicker-popup__shortcut"
@click="quickPick('hour')"
>
<button type="button" class="datepicker-popup__shortcut" @click="quickPick('hour')">
{{ local.hourCutTip }}
</button>
<button
type="button"
class="datepicker-popup__shortcut"
@click="quickPick('day')"
>
<button type="button" class="datepicker-popup__shortcut" @click="quickPick('day')">
{{ local.dayCutTip }}
</button>
<button
type="button"
class="datepicker-popup__shortcut"
@click="quickPick('week')"
>
<button type="button" class="datepicker-popup__shortcut" @click="quickPick('week')">
{{ local.weekCutTip }}
</button>
<button
type="button"
class="datepicker-popup__shortcut"
@click="quickPick('month')"
>
<button type="button" class="datepicker-popup__shortcut" @click="quickPick('month')">
{{ local.monthCutTip }}
</button>
</div>
@ -123,16 +95,10 @@ limitations under the License. -->
/>
</template>
<div v-if="showButtons" class="datepicker__buttons">
<button
@click.prevent.stop="cancel"
class="datepicker__button-cancel"
>
<button @click.prevent.stop="cancel" class="datepicker__button-cancel">
{{ local.cancelTip }}
</button>
<button
@click.prevent.stop="submit"
class="datepicker__button-select"
>
<button @click.prevent.stop="submit" class="datepicker__button-select">
{{ local.submitTip }}
</button>
</div>
@ -142,438 +108,431 @@ limitations under the License. -->
</template>
<script lang="ts" setup>
import { ref, computed, onMounted, onBeforeUnmount, watch } from "vue";
import { useI18n } from "vue-i18n";
import DateCalendar from "./DateCalendar.vue";
import { useTimeoutFn } from "@/hooks/useTimeout";
/*global defineProps, defineEmits */
const datepicker = ref(null);
const { t } = useI18n();
const show = ref<boolean>(false);
const dates = ref<Date | string[] | any>([]);
const props = defineProps({
position: { type: String, default: "bottom" },
name: [String],
inputClass: [String],
popupClass: [String],
value: [Date, Array, String],
disabled: [Boolean],
type: {
type: String,
default: "normal",
},
rangeSeparator: {
type: String,
default: "~",
},
clearable: {
type: Boolean,
default: false,
},
placeholder: [String],
disabledDate: {
type: Function,
default: () => false,
},
format: {
type: String,
default: "YYYY-MM-DD",
},
showButtons: {
type: Boolean,
default: false,
},
dateRangeSelect: [Function],
});
const emit = defineEmits(["clear", "input", "confirm", "cancel"]);
const local = computed(() => {
return {
dow: 1, // Monday is the first day of the week
hourTip: t("hourTip"), // tip of select hour
minuteTip: t("minuteTip"), // tip of select minute
secondTip: t("secondTip"), // tip of select second
yearSuffix: t("yearSuffix"), // format of head
monthsHead: t("monthsHead").split("_"), // months of head
months: t("months").split("_"), // months of panel
weeks: t("weeks").split("_"), // weeks
cancelTip: t("cancel"), // default text for cancel button
submitTip: t("confirm"), // default text for submit button
quarterHourCutTip: t("quarterHourCutTip"),
halfHourCutTip: t("halfHourCutTip"),
hourCutTip: t("hourCutTip"),
dayCutTip: t("dayCutTip"),
weekCutTip: t("weekCutTip"),
monthCutTip: t("monthCutTip"),
import { ref, computed, onMounted, onBeforeUnmount, watch } from "vue";
import { useI18n } from "vue-i18n";
import DateCalendar from "./DateCalendar.vue";
import { useTimeoutFn } from "@/hooks/useTimeout";
/*global defineProps, defineEmits */
const datepicker = ref(null);
const { t } = useI18n();
const show = ref<boolean>(false);
const dates = ref<Date | string[] | any>([]);
const props = defineProps({
position: { type: String, default: "bottom" },
name: [String],
inputClass: [String],
popupClass: [String],
value: [Date, Array, String],
disabled: [Boolean],
type: {
type: String,
default: "normal",
},
rangeSeparator: {
type: String,
default: "~",
},
clearable: {
type: Boolean,
default: false,
},
placeholder: [String],
disabledDate: {
type: Function,
default: () => false,
},
format: {
type: String,
default: "YYYY-MM-DD",
},
showButtons: {
type: Boolean,
default: false,
},
dateRangeSelect: [Function],
});
const emit = defineEmits(["clear", "input", "confirm", "cancel"]);
const local = computed(() => {
return {
dow: 1, // Monday is the first day of the week
hourTip: t("hourTip"), // tip of select hour
minuteTip: t("minuteTip"), // tip of select minute
secondTip: t("secondTip"), // tip of select second
yearSuffix: t("yearSuffix"), // format of head
monthsHead: t("monthsHead").split("_"), // months of head
months: t("months").split("_"), // months of panel
weeks: t("weeks").split("_"), // weeks
cancelTip: t("cancel"), // default text for cancel button
submitTip: t("confirm"), // default text for submit button
quarterHourCutTip: t("quarterHourCutTip"),
halfHourCutTip: t("halfHourCutTip"),
hourCutTip: t("hourCutTip"),
dayCutTip: t("dayCutTip"),
weekCutTip: t("weekCutTip"),
monthCutTip: t("monthCutTip"),
};
});
const tf = (time: Date, format?: any): string => {
const year = time.getFullYear();
const month = time.getMonth();
const day = time.getDate();
const hours24 = time.getHours();
const hours = hours24 % 12 === 0 ? 12 : hours24 % 12;
const minutes = time.getMinutes();
const seconds = time.getSeconds();
const milliseconds = time.getMilliseconds();
const dd = (t: number) => `0${t}`.slice(-2);
const map: { [key: string]: string | number } = {
YYYY: year,
MM: dd(month + 1),
MMM: local.value.months[month],
MMMM: local.value.monthsHead[month],
M: month + 1,
DD: dd(day),
D: day,
HH: dd(hours24),
H: hours24,
hh: dd(hours),
h: hours,
mm: dd(minutes),
m: minutes,
ss: dd(seconds),
s: seconds,
S: milliseconds,
};
return (format || props.format).replace(/Y+|M+|D+|H+|h+|m+|s+|S+/g, (str: string) => map[str]);
};
});
const tf = (time: Date, format?: any): string => {
const year = time.getFullYear();
const month = time.getMonth();
const day = time.getDate();
const hours24 = time.getHours();
const hours = hours24 % 12 === 0 ? 12 : hours24 % 12;
const minutes = time.getMinutes();
const seconds = time.getSeconds();
const milliseconds = time.getMilliseconds();
const dd = (t: number) => `0${t}`.slice(-2);
const map: { [key: string]: string | number } = {
YYYY: year,
MM: dd(month + 1),
MMM: local.value.months[month],
MMMM: local.value.monthsHead[month],
M: month + 1,
DD: dd(day),
D: day,
HH: dd(hours24),
H: hours24,
hh: dd(hours),
h: hours,
mm: dd(minutes),
m: minutes,
ss: dd(seconds),
s: seconds,
S: milliseconds,
const range = computed(() => {
return dates.value.length === 2;
});
const text = computed(() => {
const val = props.value;
const txt = dates.value.map((date: Date) => tf(date)).join(` ${props.rangeSeparator} `);
if (Array.isArray(val)) {
return val.length > 1 ? txt : "";
}
return val ? txt : "";
});
const get = () => {
return Array.isArray(props.value) ? dates.value : dates.value[0];
};
return (format || props.format).replace(
/Y+|M+|D+|H+|h+|m+|s+|S+/g,
(str: string) => map[str]
const cls = () => {
emit("clear");
emit("input", range.value ? [] : "");
};
const vi = (val: any) => {
if (Array.isArray(val)) {
return val.length > 1 ? val.map((item) => new Date(item)) : [new Date(), new Date()];
}
return val ? [new Date(val)] : [new Date()];
};
const ok = (leaveOpened: boolean) => {
emit("input", get());
!leaveOpened &&
!props.showButtons &&
useTimeoutFn(() => {
show.value = range.value;
}, 1);
};
const setDates = (d: Date, pos: string) => {
if (pos === "right") {
dates.value[1] = d;
return;
}
dates.value[0] = d;
};
const dc = (e: any) => {
show.value = (datepicker.value as any).contains(e.target) && !props.disabled;
};
const quickPick = (type: string) => {
const end = new Date();
const start = new Date();
switch (type) {
case "quarter":
start.setTime(start.getTime() - 60 * 15 * 1000); //15 mins
break;
case "half":
start.setTime(start.getTime() - 60 * 30 * 1000); //30 mins
break;
case "hour":
start.setTime(start.getTime() - 3600 * 1000); //1 hour
break;
case "day":
start.setTime(start.getTime() - 3600 * 1000 * 24); //1 day
break;
case "week":
start.setTime(start.getTime() - 3600 * 1000 * 24 * 7); //1 week
break;
case "month":
start.setTime(start.getTime() - 3600 * 1000 * 24 * 30); //1 month
break;
default:
break;
}
dates.value = [start, end];
emit("input", get());
};
const submit = () => {
emit("confirm", get());
show.value = false;
};
const cancel = () => {
emit("cancel");
show.value = false;
};
onMounted(() => {
dates.value = vi(props.value);
document.addEventListener("click", dc, true);
});
onBeforeUnmount(() => {
document.removeEventListener("click", dc, true);
});
watch(
() => props.value,
(val: unknown) => {
dates.value = vi(val);
},
);
};
const range = computed(() => {
return dates.value.length === 2;
});
const text = computed(() => {
const val = props.value;
const txt = dates.value
.map((date: Date) => tf(date))
.join(` ${props.rangeSeparator} `);
if (Array.isArray(val)) {
return val.length > 1 ? txt : "";
}
return val ? txt : "";
});
const get = () => {
return Array.isArray(props.value) ? dates.value : dates.value[0];
};
const cls = () => {
emit("clear");
emit("input", range.value ? [] : "");
};
const vi = (val: any) => {
if (Array.isArray(val)) {
return val.length > 1
? val.map((item) => new Date(item))
: [new Date(), new Date()];
}
return val ? [new Date(val)] : [new Date()];
};
const ok = (leaveOpened: boolean) => {
emit("input", get());
!leaveOpened &&
!props.showButtons &&
useTimeoutFn(() => {
show.value = range.value;
}, 1);
};
const setDates = (d: Date, pos: string) => {
if (pos === "right") {
dates.value[1] = d;
return;
}
dates.value[0] = d;
};
const dc = (e: any) => {
show.value = (datepicker.value as any).contains(e.target) && !props.disabled;
};
const quickPick = (type: string) => {
const end = new Date();
const start = new Date();
switch (type) {
case "quarter":
start.setTime(start.getTime() - 60 * 15 * 1000); //15 mins
break;
case "half":
start.setTime(start.getTime() - 60 * 30 * 1000); //30 mins
break;
case "hour":
start.setTime(start.getTime() - 3600 * 1000); //1 hour
break;
case "day":
start.setTime(start.getTime() - 3600 * 1000 * 24); //1 day
break;
case "week":
start.setTime(start.getTime() - 3600 * 1000 * 24 * 7); //1 week
break;
case "month":
start.setTime(start.getTime() - 3600 * 1000 * 24 * 30); //1 month
break;
default:
break;
}
dates.value = [start, end];
emit("input", get());
};
const submit = () => {
emit("confirm", get());
show.value = false;
};
const cancel = () => {
emit("cancel");
show.value = false;
};
onMounted(() => {
dates.value = vi(props.value);
document.addEventListener("click", dc, true);
});
onBeforeUnmount(() => {
document.removeEventListener("click", dc, true);
});
watch(
() => props.value,
(val: unknown) => {
dates.value = vi(val);
}
);
</script>
<style lang="scss" scoped>
@keyframes datepicker-anim-in {
0% {
opacity: 0;
transform: scaleY(0.8);
}
@keyframes datepicker-anim-in {
0% {
opacity: 0;
transform: scaleY(0.8);
}
to {
opacity: 1;
transform: scaleY(1);
}
}
@keyframes datepicker-anim-out {
0% {
opacity: 1;
transform: scaleY(1);
}
to {
opacity: 0;
transform: scaleY(0.8);
}
}
.datepicker {
display: inline-block;
position: relative;
}
.datepicker-icon {
display: block;
position: absolute;
top: 8px;
left: 8px;
color: #515a6ecc;
}
.datepicker-close {
display: none;
position: absolute;
width: 34px;
height: 100%;
top: 0;
right: 0;
cursor: pointer;
}
.datepicker-close:before {
display: block;
content: "";
position: absolute;
width: 16px;
height: 16px;
left: 50%;
top: 50%;
margin-left: -8px;
margin-top: -8px;
text-align: center;
color: #fff;
border-radius: 50%;
background: #ccc
url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA3IDciIHdpZHRoPSI3IiBoZWlnaHQ9IjciPjxwYXRoIGZpbGw9IiNmZmYiIGQ9Ik01LjU4LDVsMi44LTIuODFBLjQxLjQxLDAsMSwwLDcuOCwxLjZMNSw0LjQxLDIuMiwxLjZhLjQxLjQxLDAsMCwwLS41OC41OGgwTDQuNDIsNSwxLjYyLDcuOGEuNDEuNDEsMCwwLDAsLjU4LjU4TDUsNS41OCw3LjgsOC4zOWEuNDEuNDEsMCwwLDAsLjU4LS41OGgwWiIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoLTEuNSAtMS40OCkiIHN0eWxlPSJmaWxsOiNmZmYiLz48L3N2Zz4NCg==")
no-repeat 50% 50%;
}
.datepicker__clearable:hover:before {
display: none;
}
.datepicker__clearable:hover .datepicker-close {
display: block;
}
.datepicker-close:hover:before {
background-color: #afafaf;
}
.datepicker > input {
color: inherit;
// transition: all 200ms ease;
border-radius: 4px;
border: 0;
background: none;
height: 28px;
box-sizing: border-box;
outline: none;
padding: 0 5px;
width: 100%;
user-select: none;
font-family: "Monaco";
letter-spacing: -0.7px;
}
// .datepicker > input.focus {
// border-color: #3f97e3;
// -webkit-box-shadow: 0 0 5px rgba(59, 180, 242, 0.3);
// box-shadow: 0 0 5px rgba(59, 180, 242, 0.3);
// }
.datepicker > input:disabled {
cursor: not-allowed;
background-color: #ebebe4;
border-color: #e5e5e5;
-webkit-box-shadow: none;
box-shadow: none;
}
.datepicker-popup {
border-radius: 4px;
position: absolute;
transition: all 200ms ease;
opacity: 1;
transform: scaleY(1);
font-size: 12px;
background: #fff;
box-shadow: 0 1px 6px rgba(99, 99, 99, 0.2);
margin-top: 2px;
outline: 0;
padding: 5px;
overflow: hidden;
z-index: 999;
&.top {
bottom: 30px;
right: 0;
transform-origin: center bottom;
}
&.bottom {
top: 30px;
right: 0;
transform-origin: center top;
}
&.left {
top: 30px;
transform-origin: center top;
}
&.right {
right: -80px;
top: 30px;
transform-origin: center top;
}
&__sidebar {
position: absolute;
top: 0;
bottom: 0;
width: 100px;
height: 100%;
padding: 5px;
border-right: solid 1px #eaeaea;
}
&__shortcut {
display: block;
width: 100%;
border: 0;
background-color: transparent;
line-height: 34px;
font-size: 12px;
color: #666;
text-align: left;
outline: none;
cursor: pointer;
white-space: nowrap;
&:hover {
color: #3f97e3;
to {
opacity: 1;
transform: scaleY(1);
}
}
&__body {
margin-left: 100px;
padding-left: 5px;
@keyframes datepicker-anim-out {
0% {
opacity: 1;
transform: scaleY(1);
}
to {
opacity: 0;
transform: scaleY(0.8);
}
}
}
.datepicker-inline {
position: relative;
margin-top: 0;
}
.datepicker {
display: inline-block;
position: relative;
}
.datepicker-range {
min-width: 238px;
}
.datepicker-icon {
display: block;
position: absolute;
top: 8px;
left: 8px;
color: #515a6ecc;
}
.datepicker-range .datepicker-popup {
width: 520px;
}
.datepicker-close {
display: none;
position: absolute;
width: 34px;
height: 100%;
top: 0;
right: 0;
cursor: pointer;
}
.datepicker-bottom {
float: left;
width: 100%;
text-align: right;
}
.datepicker-close:before {
display: block;
content: "";
position: absolute;
width: 16px;
height: 16px;
left: 50%;
top: 50%;
margin-left: -8px;
margin-top: -8px;
text-align: center;
color: #fff;
border-radius: 50%;
background: #ccc
url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA3IDciIHdpZHRoPSI3IiBoZWlnaHQ9IjciPjxwYXRoIGZpbGw9IiNmZmYiIGQ9Ik01LjU4LDVsMi44LTIuODFBLjQxLjQxLDAsMSwwLDcuOCwxLjZMNSw0LjQxLDIuMiwxLjZhLjQxLjQxLDAsMCwwLS41OC41OGgwTDQuNDIsNSwxLjYyLDcuOGEuNDEuNDEsMCwwLDAsLjU4LjU4TDUsNS41OCw3LjgsOC4zOWEuNDEuNDEsMCwwLDAsLjU4LS41OGgwWiIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoLTEuNSAtMS40OCkiIHN0eWxlPSJmaWxsOiNmZmYiLz48L3N2Zz4NCg==")
no-repeat 50% 50%;
}
.datepicker-btn {
padding: 5px 10px;
background: #3f97e3;
color: #fff;
border-radius: 2px;
display: inline-block;
cursor: pointer;
}
.datepicker__clearable:hover:before {
display: none;
}
.datepicker-anim-enter-active {
transform-origin: 0 0;
animation: datepicker-anim-in 0.2s cubic-bezier(0.23, 1, 0.32, 1);
}
.datepicker__clearable:hover .datepicker-close {
display: block;
}
.datepicker-anim-leave-active {
transform-origin: 0 0;
animation: datepicker-anim-out 0.2s cubic-bezier(0.755, 0.05, 0.855, 0.06);
}
.datepicker-close:hover:before {
background-color: #afafaf;
}
.datepicker__buttons {
display: block;
text-align: right;
}
.datepicker > input {
color: inherit;
// transition: all 200ms ease;
border-radius: 4px;
border: 0;
background: none;
height: 28px;
box-sizing: border-box;
outline: none;
padding: 0 5px;
width: 100%;
user-select: none;
font-family: "Monaco";
letter-spacing: -0.7px;
}
.datepicker__buttons button {
display: inline-block;
font-size: 13px;
border: none;
cursor: pointer;
margin: 10px 0 0 5px;
padding: 5px 15px;
color: #ffffff;
}
// .datepicker > input.focus {
// border-color: #3f97e3;
// -webkit-box-shadow: 0 0 5px rgba(59, 180, 242, 0.3);
// box-shadow: 0 0 5px rgba(59, 180, 242, 0.3);
// }
.datepicker__buttons .datepicker__button-select {
background: #3f97e3;
}
.datepicker > input:disabled {
cursor: not-allowed;
background-color: #ebebe4;
border-color: #e5e5e5;
-webkit-box-shadow: none;
box-shadow: none;
}
.datepicker__buttons .datepicker__button-cancel {
background: #666;
}
.datepicker-popup {
border-radius: 4px;
position: absolute;
transition: all 200ms ease;
opacity: 1;
transform: scaleY(1);
font-size: 12px;
background: #fff;
box-shadow: 0 1px 6px rgba(99, 99, 99, 0.2);
margin-top: 2px;
outline: 0;
padding: 5px;
overflow: hidden;
z-index: 999;
&.top {
bottom: 30px;
right: 0;
transform-origin: center bottom;
}
&.bottom {
top: 30px;
right: 0;
transform-origin: center top;
}
&.left {
top: 30px;
transform-origin: center top;
}
&.right {
right: -80px;
top: 30px;
transform-origin: center top;
}
&__sidebar {
position: absolute;
top: 0;
bottom: 0;
width: 100px;
height: 100%;
padding: 5px;
border-right: solid 1px #eaeaea;
}
&__shortcut {
display: block;
width: 100%;
border: 0;
background-color: transparent;
line-height: 34px;
font-size: 12px;
color: #666;
text-align: left;
outline: none;
cursor: pointer;
white-space: nowrap;
&:hover {
color: #3f97e3;
}
}
&__body {
margin-left: 100px;
padding-left: 5px;
}
}
.datepicker-inline {
position: relative;
margin-top: 0;
}
.datepicker-range {
min-width: 238px;
}
.datepicker-range .datepicker-popup {
width: 520px;
}
.datepicker-bottom {
float: left;
width: 100%;
text-align: right;
}
.datepicker-btn {
padding: 5px 10px;
background: #3f97e3;
color: #fff;
border-radius: 2px;
display: inline-block;
cursor: pointer;
}
.datepicker-anim-enter-active {
transform-origin: 0 0;
animation: datepicker-anim-in 0.2s cubic-bezier(0.23, 1, 0.32, 1);
}
.datepicker-anim-leave-active {
transform-origin: 0 0;
animation: datepicker-anim-out 0.2s cubic-bezier(0.755, 0.05, 0.855, 0.06);
}
.datepicker__buttons {
display: block;
text-align: right;
}
.datepicker__buttons button {
display: inline-block;
font-size: 13px;
border: none;
cursor: pointer;
margin: 10px 0 0 5px;
padding: 5px 15px;
color: #ffffff;
}
.datepicker__buttons .datepicker__button-select {
background: #3f97e3;
}
.datepicker__buttons .datepicker__button-cancel {
background: #666;
}
</style>

View File

@ -0,0 +1,33 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { describe, it } from "vitest";
// import { mount } from '@vue/test-utils'
// import HelloWorld from '../HelloWorld.vue'
// describe('HelloWorld', () => {
// it('renders properly', () => {
// const wrapper = mount(HelloWorld, { props: { msg: 'Hello Vitest' } })
// expect(wrapper.text()).toContain('Hello Vitest')
// })
// })
describe("My First Test", () => {
it("renders props.msg when passed", () => {
const msg = "new message";
console.log(msg);
});
});

View File

@ -14,22 +14,18 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import axios, { AxiosResponse } from "axios";
import type { AxiosResponse } from "axios";
import axios from "axios";
import { cancelToken } from "@/utils/cancelToken";
async function query(param: {
queryStr: string;
conditions: { [key: string]: unknown };
}) {
async function query(param: { queryStr: string; conditions: { [key: string]: unknown } }) {
const res: AxiosResponse = await axios.post(
"/graphql",
{ query: param.queryStr, variables: { ...param.conditions } },
{ cancelToken: cancelToken() }
{ cancelToken: cancelToken() },
);
if (res.data.errors) {
res.data.errors = res.data.errors
.map((e: { message: string }) => e.message)
.join(" ");
res.data.errors = res.data.errors.map((e: { message: string }) => e.message).join(" ");
}
return res;
}

View File

@ -16,8 +16,7 @@
*/
export const Alarm = {
variable:
"$keyword: String, $scope: Scope, $duration:Duration!, $tags:[AlarmTag], $paging: Pagination!",
variable: "$keyword: String, $scope: Scope, $duration:Duration!, $tags:[AlarmTag], $paging: Pagination!",
query: `
getAlarm(keyword: $keyword, scope: $scope, duration: $duration, paging: $paging, tags: $tags) {
items: msgs {

View File

@ -33,8 +33,7 @@ export const createEBPFTask = {
}`,
};
export const queryEBPFTasks = {
variable:
"$serviceId: ID, $serviceInstanceId: ID, $targets: [EBPFProfilingTargetType!]",
variable: "$serviceId: ID, $serviceInstanceId: ID, $targets: [EBPFProfilingTargetType!]",
query: `
queryEBPFTasks: queryEBPFProfilingTasks(serviceId: $serviceId, serviceInstanceId: $serviceInstanceId, targets: $targets) {
taskId

View File

@ -53,8 +53,7 @@ export const EndpointTopology = {
}`,
};
export const InstanceTopology = {
variable:
"$clientServiceId: ID!, $serverServiceId: ID!, $duration: Duration!",
variable: "$clientServiceId: ID!, $serverServiceId: ID!, $duration: Duration!",
query: `
topology: getServiceInstanceTopology(clientServiceId: $clientServiceId,
serverServiceId: $serverServiceId, duration: $duration) {

View File

@ -14,7 +14,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import axios, { AxiosPromise, AxiosResponse } from "axios";
import type { AxiosPromise, AxiosResponse } from "axios";
import axios from "axios";
import { cancelToken } from "@/utils/cancelToken";
import * as app from "./query/app";
import * as selector from "./query/selector";
@ -55,13 +56,11 @@ class Graphql {
query: query[this.queryData],
variables: variablesData,
},
{ cancelToken: cancelToken() }
{ cancelToken: cancelToken() },
)
.then((res: AxiosResponse) => {
if (res.data.errors) {
res.data.errors = res.data.errors
.map((e: { message: string }) => e.message)
.join(" ");
res.data.errors = res.data.errors.map((e: { message: string }) => e.message).join(" ");
}
return res;
})

View File

@ -14,12 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {
InstanceTopology,
EndpointTopology,
ServicesTopology,
ProcessTopology,
} from "../fragments/topology";
import { InstanceTopology, EndpointTopology, ServicesTopology, ProcessTopology } from "../fragments/topology";
export const getInstanceTopology = `query queryData(${InstanceTopology.variable}) {${InstanceTopology.query}}`;
export const getEndpointTopology = `query queryData(${EndpointTopology.variable}) {${EndpointTopology.query}}`;

View File

@ -15,12 +15,7 @@
* limitations under the License.
*/
import {
Traces,
TraceSpans,
TraceTagKeys,
TraceTagValues,
} from "../fragments/trace";
import { Traces, TraceSpans, TraceTagKeys, TraceTagValues } from "../fragments/trace";
export const queryTraces = `query queryTraces(${Traces.variable}) {${Traces.query}}`;

View File

@ -17,7 +17,7 @@
import { useAppStoreWithOut } from "@/store/modules/app";
import dateFormatStep from "@/utils/dateFormat";
import getLocalTime from "@/utils/localtime";
import { EventParams } from "@/types/app";
import type { EventParams } from "@/types/app";
export default function associateProcessor(props: any) {
function eventAssociate() {
@ -30,9 +30,7 @@ export default function associateProcessor(props: any) {
if (!props.option.series[0]) {
return;
}
const list = props.option.series[0].data.map(
(d: (number | string)[]) => d[0]
);
const list = props.option.series[0].data.map((d: (number | string)[]) => d[0]);
if (!list.includes(props.filters.duration.endTime)) {
return;
}
@ -77,16 +75,8 @@ export default function associateProcessor(props: any) {
if (start) {
const end = start;
duration = {
start: dateFormatStep(
getLocalTime(appStore.utc, new Date(start)),
step,
true
),
end: dateFormatStep(
getLocalTime(appStore.utc, new Date(end)),
step,
true
),
start: dateFormatStep(getLocalTime(appStore.utc, new Date(start)), step, true),
end: dateFormatStep(getLocalTime(appStore.utc, new Date(end)), step, true),
step,
};
}
@ -101,36 +91,27 @@ export default function associateProcessor(props: any) {
status,
};
if (latency) {
const latencyList = series.map(
(d: { name: string; data: number[][] }, index: number) => {
const data = [
d.data[currentParams.dataIndex][1],
series[index + 1]
? series[index + 1].data[currentParams.dataIndex][1]
: Infinity,
];
return {
label:
d.name +
"--" +
(series[index + 1] ? series[index + 1].name : "Infinity"),
value: String(index),
data,
};
}
);
const latencyList = series.map((d: { name: string; data: number[][] }, index: number) => {
const data = [
d.data[currentParams.dataIndex][1],
series[index + 1] ? series[index + 1].data[currentParams.dataIndex][1] : Infinity,
];
return {
label: d.name + "--" + (series[index + 1] ? series[index + 1].name : "Infinity"),
value: String(index),
data,
};
});
item.latency = latencyList;
}
const value = series.map(
(d: { name: string; data: number[][] }, index: number) => {
return {
label: d.name,
value: String(index),
data: d.data[currentParams.dataIndex][1],
date: d.data[currentParams.dataIndex][0],
};
}
);
const value = series.map((d: { name: string; data: number[][] }, index: number) => {
return {
label: d.name,
value: String(index),
data: d.data[currentParams.dataIndex][1],
date: d.data[currentParams.dataIndex][0],
};
});
item.metricValue = value;
return item;
}

View File

@ -14,7 +14,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { ref, computed, ComputedRef, unref } from "vue";
import type { ComputedRef } from "vue";
import { ref, computed, unref } from "vue";
import { useEventListener } from "./useEventListener";
import { screenMap, sizeEnum, screenEnum } from "./data";
@ -40,9 +41,7 @@ export function useBreakpoint(): any {
};
}
export function createBreakpointListen(
fn?: (opt: CreateCallbackParams) => void
): any {
export function createBreakpointListen(fn?: (opt: CreateCallbackParams) => void): any {
const screenRef = ref<sizeEnum>(sizeEnum.XL || "");
const realWidthRef = ref(window.innerWidth);

View File

@ -16,19 +16,15 @@
*/
import { ElMessage } from "element-plus";
import { useDashboardStore } from "@/store/modules/dashboard";
import { LayoutConfig } from "@/types/dashboard";
import type { LayoutConfig } from "@/types/dashboard";
export default function getDashboard(param?: {
name: string;
layer: string;
entity: string;
}) {
export default function getDashboard(param?: { name: string; layer: string; entity: string }) {
const dashboardStore = useDashboardStore();
const opt = param || dashboardStore.currentDashboard;
const list = JSON.parse(sessionStorage.getItem("dashboards") || "[]");
const dashboard = list.find(
(d: { name: string; layer: string; entity: string }) =>
d.name === opt.name && d.entity === opt.entity && d.layer === opt.layer
d.name === opt.name && d.entity === opt.entity && d.layer === opt.layer,
);
const all = dashboardStore.layout;
const widgets: LayoutConfig[] = [];

View File

@ -14,13 +14,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {
BarSeriesOption,
LineSeriesOption,
HeatmapSeriesOption,
SankeySeriesOption,
} from "echarts/charts";
import {
import type { BarSeriesOption, LineSeriesOption, HeatmapSeriesOption, SankeySeriesOption } from "echarts/charts";
import type {
TitleComponentOption,
TooltipComponentOption,
GridComponentOption,
@ -48,10 +43,7 @@ export type ECOption = echarts.ComposeOption<
| SankeySeriesOption
>;
export function useECharts(
elRef: Ref<HTMLDivElement>,
theme: "light" | "dark" | "default" = "default"
): any {
export function useECharts(elRef: Ref<HTMLDivElement>, theme: "light" | "dark" | "default" = "default"): any {
const getDarkMode = computed(() => {
return theme === "default" ? "light" : theme;
});
@ -131,7 +123,7 @@ export function useECharts(
initCharts(theme as "default");
setOptions(cacheOptions.value);
}
}
},
);
tryOnUnmounted(() => {

View File

@ -43,16 +43,13 @@ export function useEventListener({
if (el) {
const element = ref(el as Element) as Ref<Element>;
const handler = isDebounce
? useDebounceFn(listener, wait)
: useThrottleFn(listener, wait);
const handler = isDebounce ? useDebounceFn(listener, wait) : useThrottleFn(listener, wait);
const realHandler = wait ? handler : listener;
const removeEventListener = (e: Element) => {
isAddRef.value = true;
e.removeEventListener(name, realHandler, options);
};
const addEventListener = (e: Element) =>
e.addEventListener(name, realHandler, options);
const addEventListener = (e: Element) => e.addEventListener(name, realHandler, options);
const removeWatch = watch(
element,
@ -64,7 +61,7 @@ export function useEventListener({
});
}
},
{ immediate: true }
{ immediate: true },
);
remove = () => {

View File

@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { LegendOptions } from "@/types/dashboard";
import type { LegendOptions } from "@/types/dashboard";
import { isDef } from "@/utils/is";
export default function useLegendProcess(legend?: LegendOptions) {
@ -37,14 +37,9 @@ export default function useLegendProcess(legend?: LegendOptions) {
}
return true;
}
function aggregations(
data: { [key: string]: number[] },
intervalTime: string[]
) {
function aggregations(data: { [key: string]: number[] }, intervalTime: string[]) {
const source: { [key: string]: unknown }[] = [];
const keys = Object.keys(data || {}).filter(
(i: any) => Array.isArray(data[i]) && data[i].length
);
const keys = Object.keys(data || {}).filter((i: any) => Array.isArray(data[i]) && data[i].length);
const headers = [];
for (const [key, value] of keys.entries()) {
@ -58,12 +53,7 @@ export default function useLegendProcess(legend?: LegendOptions) {
value: d,
};
})
.sort(
(
a: { key: string; value: number },
b: { key: string; value: number }
) => b.value - a.value
)
.sort((a: { key: string; value: number }, b: { key: string; value: number }) => b.value - a.value)
.filter((_: unknown, index: number) => index < 10),
};
if (legend) {

View File

@ -17,25 +17,14 @@
import { MetricQueryTypes, Calculations } from "./data";
export function useListConfig(config: any, index: string) {
const i = Number(index);
const types = [
Calculations.Average,
Calculations.ApdexAvg,
Calculations.PercentageAvg,
];
const calculation =
config.metricConfig &&
config.metricConfig[i] &&
config.metricConfig[i].calculation;
const types = [Calculations.Average, Calculations.ApdexAvg, Calculations.PercentageAvg];
const calculation = config.metricConfig && config.metricConfig[i] && config.metricConfig[i].calculation;
const isLinear =
[
MetricQueryTypes.ReadMetricsValues,
MetricQueryTypes.ReadLabeledMetricsValues,
].includes(config.metricTypes[i]) && !types.includes(calculation);
[MetricQueryTypes.ReadMetricsValues, MetricQueryTypes.ReadLabeledMetricsValues].includes(config.metricTypes[i]) &&
!types.includes(calculation);
const isAvg =
[
MetricQueryTypes.ReadMetricsValues,
MetricQueryTypes.ReadLabeledMetricsValues,
].includes(config.metricTypes[i]) && types.includes(calculation);
[MetricQueryTypes.ReadMetricsValues, MetricQueryTypes.ReadLabeledMetricsValues].includes(config.metricTypes[i]) &&
types.includes(calculation);
return {
isLinear,
isAvg,

View File

@ -20,8 +20,8 @@ import { ElMessage } from "element-plus";
import { useDashboardStore } from "@/store/modules/dashboard";
import { useSelectorStore } from "@/store/modules/selectors";
import { useAppStoreWithOut } from "@/store/modules/app";
import { Instance, Endpoint, Service } from "@/types/selector";
import { MetricConfigOpt } from "@/types/dashboard";
import type { Instance, Endpoint, Service } from "@/types/selector";
import type { MetricConfigOpt } from "@/types/dashboard";
import { MetricCatalog } from "@/views/dashboard/data";
export function useQueryProcessor(config: any) {
@ -42,33 +42,21 @@ export function useQueryProcessor(config: any) {
duration: appStore.durationTime,
};
const variables: string[] = [`$duration: Duration!`];
const isRelation = [
"ServiceRelation",
"ServiceInstanceRelation",
"EndpointRelation",
"ProcessRelation",
].includes(dashboardStore.entity);
const isRelation = ["ServiceRelation", "ServiceInstanceRelation", "EndpointRelation", "ProcessRelation"].includes(
dashboardStore.entity,
);
if (isRelation && !selectorStore.currentDestService) {
return;
}
const fragment = config.metrics.map((name: string, index: number) => {
const metricType = config.metricTypes[index] || "";
const c = (config.metricConfig && config.metricConfig[index]) || {};
if (
[
MetricQueryTypes.ReadSampledRecords,
MetricQueryTypes.SortMetrics,
].includes(metricType)
) {
if ([MetricQueryTypes.ReadSampledRecords, MetricQueryTypes.SortMetrics].includes(metricType)) {
variables.push(`$condition${index}: TopNCondition!`);
conditions[`condition${index}`] = {
name,
parentService: ["All"].includes(dashboardStore.entity)
? null
: selectorStore.currentService.value,
normal: selectorStore.currentService
? selectorStore.currentService.normal
: true,
parentService: ["All"].includes(dashboardStore.entity) ? null : selectorStore.currentService.value,
normal: selectorStore.currentService ? selectorStore.currentService.normal : true,
scope: config.catalog,
topN: c.topN || 10,
order: c.sortOrder || "DES",
@ -76,19 +64,11 @@ export function useQueryProcessor(config: any) {
} else {
const entity = {
scope: config.catalog,
serviceName:
dashboardStore.entity === "All"
? undefined
: selectorStore.currentService.value,
normal:
dashboardStore.entity === "All"
? undefined
: selectorStore.currentService.normal,
serviceInstanceName: [
"ServiceInstance",
"ServiceInstanceRelation",
"ProcessRelation",
].includes(dashboardStore.entity)
serviceName: dashboardStore.entity === "All" ? undefined : selectorStore.currentService.value,
normal: dashboardStore.entity === "All" ? undefined : selectorStore.currentService.normal,
serviceInstanceName: ["ServiceInstance", "ServiceInstanceRelation", "ProcessRelation"].includes(
dashboardStore.entity,
)
? selectorStore.currentPod && selectorStore.currentPod.value
: undefined,
endpointName: dashboardStore.entity.includes("Endpoint")
@ -97,16 +77,9 @@ export function useQueryProcessor(config: any) {
processName: dashboardStore.entity.includes("Process")
? selectorStore.currentProcess && selectorStore.currentProcess.value
: undefined,
destNormal: isRelation
? selectorStore.currentDestService.normal
: undefined,
destServiceName: isRelation
? selectorStore.currentDestService.value
: undefined,
destServiceInstanceName: [
"ServiceInstanceRelation",
"ProcessRelation",
].includes(dashboardStore.entity)
destNormal: isRelation ? selectorStore.currentDestService.normal : undefined,
destServiceName: isRelation ? selectorStore.currentDestService.value : undefined,
destServiceInstanceName: ["ServiceInstanceRelation", "ProcessRelation"].includes(dashboardStore.entity)
? selectorStore.currentDestPod && selectorStore.currentDestPod.value
: undefined,
destEndpointName:
@ -114,8 +87,7 @@ export function useQueryProcessor(config: any) {
? selectorStore.currentDestPod && selectorStore.currentDestPod.value
: undefined,
destProcessName: dashboardStore.entity.includes("ProcessRelation")
? selectorStore.currentDestProcess &&
selectorStore.currentDestProcess.value
? selectorStore.currentDestProcess && selectorStore.currentDestProcess.value
: undefined,
};
if ([MetricQueryTypes.ReadRecords].includes(metricType)) {
@ -129,9 +101,7 @@ export function useQueryProcessor(config: any) {
} else {
entity.scope = dashboardStore.entity;
if (metricType === MetricQueryTypes.ReadLabeledMetricsValues) {
const labels = (c.labelsIndex || "")
.split(",")
.map((item: string) => item.replace(/^\s*|\s*$/g, ""));
const labels = (c.labelsIndex || "").split(",").map((item: string) => item.replace(/^\s*|\s*$/g, ""));
variables.push(`$labels${index}: [String!]!`);
conditions[`labels${index}`] = labels;
}
@ -161,7 +131,7 @@ export function useSourceProcessor(
metrics: string[];
metricTypes: string[];
metricConfig: MetricConfigOpt[];
}
},
) {
if (resp.errors) {
ElMessage.error(resp.errors);
@ -179,23 +149,14 @@ export function useSourceProcessor(
const c = (config.metricConfig && config.metricConfig[index]) || {};
if (type === MetricQueryTypes.ReadMetricsValues) {
source[c.label || m] =
(resp.data[keys[index]] &&
calculateExp(resp.data[keys[index]].values.values, c)) ||
[];
source[c.label || m] = (resp.data[keys[index]] && calculateExp(resp.data[keys[index]].values.values, c)) || [];
}
if (type === MetricQueryTypes.ReadLabeledMetricsValues) {
const resVal = Object.values(resp.data)[0] || [];
const labels = (c.label || "")
.split(",")
.map((item: string) => item.replace(/^\s*|\s*$/g, ""));
const labelsIdx = (c.labelsIndex || "")
.split(",")
.map((item: string) => item.replace(/^\s*|\s*$/g, ""));
const labels = (c.label || "").split(",").map((item: string) => item.replace(/^\s*|\s*$/g, ""));
const labelsIdx = (c.labelsIndex || "").split(",").map((item: string) => item.replace(/^\s*|\s*$/g, ""));
for (const item of resVal) {
const values = item.values.values.map((d: { value: number }) =>
aggregation(Number(d.value), c)
);
const values = item.values.values.map((d: { value: number }) => aggregation(Number(d.value), c));
const indexNum = labelsIdx.findIndex((d: string) => d === item.label);
if (labels[indexNum] && indexNum > -1) {
source[labels[indexNum]] = values;
@ -209,20 +170,14 @@ export function useSourceProcessor(
}
if (
(
[
MetricQueryTypes.ReadRecords,
MetricQueryTypes.ReadSampledRecords,
MetricQueryTypes.SortMetrics,
] as string[]
[MetricQueryTypes.ReadRecords, MetricQueryTypes.ReadSampledRecords, MetricQueryTypes.SortMetrics] as string[]
).includes(type)
) {
source[m] = (Object.values(resp.data)[0] || []).map(
(d: { value: unknown; name: string }) => {
d.value = aggregation(Number(d.value), c);
source[m] = (Object.values(resp.data)[0] || []).map((d: { value: unknown; name: string }) => {
d.value = aggregation(Number(d.value), c);
return d;
}
);
return d;
});
}
if (type === MetricQueryTypes.READHEATMAP) {
const resVal = Object.values(resp.data)[0] || {};
@ -238,12 +193,7 @@ export function useSourceProcessor(
});
let buckets = [] as any;
if (resVal.buckets.length) {
buckets = [
resVal.buckets[0].min,
...resVal.buckets.map(
(item: { min: string; max: string }) => item.max
),
];
buckets = [resVal.buckets[0].min, ...resVal.buckets.map((item: { min: string; max: string }) => item.max)];
}
source[m] = { nodes, buckets }; // nodes: number[][]
@ -260,7 +210,7 @@ export function useQueryPodsMetrics(
metricTypes: string[];
metricConfig: MetricConfigOpt[];
},
scope: string
scope: string,
) {
const metricTypes = (config.metricTypes || []).filter((m: string) => m);
if (!metricTypes.length) {
@ -277,40 +227,33 @@ export function useQueryPodsMetrics(
};
const variables: string[] = [`$duration: Duration!`];
const currentService = selectorStore.currentService || {};
const fragmentList = pods.map(
(
d: (Instance | Endpoint | Service) & { normal: boolean },
index: number
) => {
const param = {
scope,
serviceName: scope === "Service" ? d.label : currentService.label,
serviceInstanceName: scope === "ServiceInstance" ? d.label : undefined,
endpointName: scope === "Endpoint" ? d.label : undefined,
normal: scope === "Service" ? d.normal : currentService.normal,
const fragmentList = pods.map((d: (Instance | Endpoint | Service) & { normal: boolean }, index: number) => {
const param = {
scope,
serviceName: scope === "Service" ? d.label : currentService.label,
serviceInstanceName: scope === "ServiceInstance" ? d.label : undefined,
endpointName: scope === "Endpoint" ? d.label : undefined,
normal: scope === "Service" ? d.normal : currentService.normal,
};
const f = metrics.map((name: string, idx: number) => {
const metricType = metricTypes[idx] || "";
variables.push(`$condition${index}${idx}: MetricsCondition!`);
conditions[`condition${index}${idx}`] = {
name,
entity: param,
};
const f = metrics.map((name: string, idx: number) => {
const metricType = metricTypes[idx] || "";
variables.push(`$condition${index}${idx}: MetricsCondition!`);
conditions[`condition${index}${idx}`] = {
name,
entity: param,
};
let labelStr = "";
if (metricType === MetricQueryTypes.ReadLabeledMetricsValues) {
const c = config.metricConfig[idx] || {};
variables.push(`$labels${index}${idx}: [String!]!`);
labelStr = `labels: $labels${index}${idx}, `;
const labels = (c.labelsIndex || "")
.split(",")
.map((item: string) => item.replace(/^\s*|\s*$/g, ""));
conditions[`labels${index}${idx}`] = labels;
}
return `${name}${index}${idx}: ${metricType}(condition: $condition${index}${idx}, ${labelStr}duration: $duration)${RespFields[metricType]}`;
});
return f;
}
);
let labelStr = "";
if (metricType === MetricQueryTypes.ReadLabeledMetricsValues) {
const c = config.metricConfig[idx] || {};
variables.push(`$labels${index}${idx}: [String!]!`);
labelStr = `labels: $labels${index}${idx}, `;
const labels = (c.labelsIndex || "").split(",").map((item: string) => item.replace(/^\s*|\s*$/g, ""));
conditions[`labels${index}${idx}`] = labels;
}
return `${name}${index}${idx}: ${metricType}(condition: $condition${index}${idx}, ${labelStr}duration: $duration)${RespFields[metricType]}`;
});
return f;
});
const fragment = fragmentList.flat(1).join(" ");
const queryStr = `query queryData(${variables}) {${fragment}}`;
@ -324,7 +267,7 @@ export function usePodsSource(
metrics: string[];
metricTypes: string[];
metricConfig: MetricConfigOpt[];
}
},
): any {
if (resp.errors) {
ElMessage.error(resp.errors);
@ -347,39 +290,23 @@ export function usePodsSource(
}
if (config.metricTypes[index] === MetricQueryTypes.ReadMetricsValues) {
d[name] = {};
if (
[
Calculations.Average,
Calculations.ApdexAvg,
Calculations.PercentageAvg,
].includes(c.calculation)
) {
if ([Calculations.Average, Calculations.ApdexAvg, Calculations.PercentageAvg].includes(c.calculation)) {
d[name]["avg"] = calculateExp(resp.data[key].values.values, c);
}
d[name]["values"] = resp.data[key].values.values.map(
(val: { value: number }) => aggregation(val.value, c)
);
d[name]["values"] = resp.data[key].values.values.map((val: { value: number }) => aggregation(val.value, c));
if (idx === 0) {
names.push(name);
metricConfigArr.push(c);
metricTypesArr.push(config.metricTypes[index]);
}
}
if (
config.metricTypes[index] === MetricQueryTypes.ReadLabeledMetricsValues
) {
if (config.metricTypes[index] === MetricQueryTypes.ReadLabeledMetricsValues) {
const resVal = resp.data[key] || [];
const labels = (c.label || "")
.split(",")
.map((item: string) => item.replace(/^\s*|\s*$/g, ""));
const labelsIdx = (c.labelsIndex || "")
.split(",")
.map((item: string) => item.replace(/^\s*|\s*$/g, ""));
const labels = (c.label || "").split(",").map((item: string) => item.replace(/^\s*|\s*$/g, ""));
const labelsIdx = (c.labelsIndex || "").split(",").map((item: string) => item.replace(/^\s*|\s*$/g, ""));
for (let i = 0; i < resVal.length; i++) {
const item = resVal[i];
const values = item.values.values.map((d: { value: number }) =>
aggregation(Number(d.value), c)
);
const values = item.values.values.map((d: { value: number }) => aggregation(Number(d.value), c));
const indexNum = labelsIdx.findIndex((d: string) => d === item.label);
let key = item.label;
if (labels[indexNum] && indexNum > -1) {
@ -388,13 +315,7 @@ export function usePodsSource(
if (!d[key]) {
d[key] = {};
}
if (
[
Calculations.Average,
Calculations.ApdexAvg,
Calculations.PercentageAvg,
].includes(c.calculation)
) {
if ([Calculations.Average, Calculations.ApdexAvg, Calculations.PercentageAvg].includes(c.calculation)) {
d[key]["avg"] = calculateExp(item.values.values, c);
}
d[key]["values"] = values;
@ -435,13 +356,8 @@ export function useQueryTopologyMetrics(metrics: string[], ids: string[]) {
return { queryStr, conditions };
}
function calculateExp(
arr: { value: number }[],
config: { calculation?: string }
): (number | string)[] {
const sum = arr
.map((d: { value: number }) => d.value)
.reduce((a, b) => a + b);
function calculateExp(arr: { value: number }[], config: { calculation?: string }): (number | string)[] {
const sum = arr.map((d: { value: number }) => d.value).reduce((a, b) => a + b);
let data: (number | string)[] = [];
switch (config.calculation) {
case Calculations.Average:
@ -460,10 +376,7 @@ function calculateExp(
return data;
}
export function aggregation(
val: number,
config: { calculation?: string }
): number | string {
export function aggregation(val: number, config: { calculation?: string }): number | string {
let data: number | string = Number(val);
switch (config.calculation) {
@ -518,11 +431,9 @@ export async function useGetMetricEntity(metric: string, metricType: any) {
let catalog = "";
const dashboardStore = useDashboardStore();
if (
[
MetricQueryTypes.ReadSampledRecords,
MetricQueryTypes.SortMetrics,
MetricQueryTypes.ReadRecords,
].includes(metricType)
[MetricQueryTypes.ReadSampledRecords, MetricQueryTypes.SortMetrics, MetricQueryTypes.ReadRecords].includes(
metricType,
)
) {
const res = await dashboardStore.fetchMetricList(metric);
if (res.errors) {

View File

@ -18,11 +18,7 @@ import { ref, watch } from "vue";
import { tryOnUnmounted } from "@vueuse/core";
import { isFunction } from "@/utils/is";
export function useTimeoutFn(
handle: Fn<any>,
wait: number,
native = false
): any {
export function useTimeoutFn(handle: Fn<any>, wait: number, native = false): any {
if (!isFunction(handle)) {
throw new Error("handle is not Function!");
}
@ -36,7 +32,7 @@ export function useTimeoutFn(
(maturity) => {
maturity && handle();
},
{ immediate: false }
{ immediate: false },
);
}
return { readyRef, stop, start };

View File

@ -22,15 +22,15 @@ limitations under the License. -->
</div>
</template>
<script lang="ts" setup>
import { AppMain, SideBar, NavBar } from "./components";
import { AppMain, SideBar, NavBar } from "./components";
</script>
<style lang="scss" scoped>
.app-wrapper {
height: 100%;
}
.app-wrapper {
height: 100%;
}
.main-container {
flex-grow: 2;
height: 100%;
}
.main-container {
flex-grow: 2;
height: 100%;
}
</style>

View File

@ -22,8 +22,8 @@ limitations under the License. -->
</section>
</template>
<style lang="scss" scoped>
.app-main {
height: calc(100% - 40px);
background: #f7f9fa;
}
.app-main {
height: calc(100% - 40px);
background: #f7f9fa;
}
</style>

View File

@ -23,21 +23,12 @@ limitations under the License. -->
format="YYYY-MM-DD HH:mm"
@input="changeTimeRange"
/>
<span>
UTC{{ appStore.utcHour >= 0 ? "+" : ""
}}{{ `${appStore.utcHour}:${appStore.utcMin}` }}
</span>
<span> UTC{{ appStore.utcHour >= 0 ? "+" : "" }}{{ `${appStore.utcHour}:${appStore.utcMin}` }} </span>
<span title="refresh" class="ghost ml-5 cp" @click="handleReload">
<Icon iconName="retry" :loading="appStore.autoRefresh" class="middle" />
</span>
<span class="version ml-5 cp">
<el-popover
trigger="hover"
width="250"
placement="bottom"
effect="light"
:content="appStore.version"
>
<el-popover trigger="hover" width="250" placement="bottom" effect="light" :content="appStore.version">
<template #reference>
<span>
<Icon iconName="info_outline" size="middle" />
@ -49,92 +40,90 @@ limitations under the License. -->
</div>
</template>
<script lang="ts" setup>
import { ref, watch } from "vue";
import { useRoute } from "vue-router";
import { useI18n } from "vue-i18n";
import timeFormat from "@/utils/timeFormat";
import { useAppStoreWithOut } from "@/store/modules/app";
import { ElMessage } from "element-plus";
import { ref, watch } from "vue";
import { useRoute } from "vue-router";
import { useI18n } from "vue-i18n";
import timeFormat from "@/utils/timeFormat";
import { useAppStoreWithOut } from "@/store/modules/app";
import { ElMessage } from "element-plus";
const { t } = useI18n();
const appStore = useAppStoreWithOut();
const route = useRoute();
const pageName = ref<string>("");
const timeRange = ref<number>(0);
const { t } = useI18n();
const appStore = useAppStoreWithOut();
const route = useRoute();
const pageName = ref<string>("");
const timeRange = ref<number>(0);
resetDuration();
getVersion();
const setConfig = (value: string) => {
pageName.value = value || "";
};
resetDuration();
getVersion();
const setConfig = (value: string) => {
pageName.value = value || "";
};
function handleReload() {
const gap =
appStore.duration.end.getTime() - appStore.duration.start.getTime();
const dates: Date[] = [new Date(new Date().getTime() - gap), new Date()];
appStore.setDuration(timeFormat(dates));
}
function changeTimeRange(val: Date[] | any) {
timeRange.value =
val[1].getTime() - val[0].getTime() > 60 * 24 * 60 * 60 * 1000 ? 1 : 0;
if (timeRange.value) {
return;
function handleReload() {
const gap = appStore.duration.end.getTime() - appStore.duration.start.getTime();
const dates: Date[] = [new Date(new Date().getTime() - gap), new Date()];
appStore.setDuration(timeFormat(dates));
}
appStore.setDuration(timeFormat(val));
}
setConfig(String(route.meta.title));
watch(
() => route.meta.title,
(title: unknown) => {
setConfig(String(title));
}
);
async function getVersion() {
const res = await appStore.fetchVersion();
if (res.errors) {
ElMessage.error(res.errors);
}
}
function resetDuration() {
const { duration }: any = route.params;
if (duration) {
const d = JSON.parse(duration);
appStore.updateDurationRow({
start: new Date(d.start),
end: new Date(d.end),
step: d.step,
});
appStore.updateUTC(d.utc);
function changeTimeRange(val: Date[] | any) {
timeRange.value = val[1].getTime() - val[0].getTime() > 60 * 24 * 60 * 60 * 1000 ? 1 : 0;
if (timeRange.value) {
return;
}
appStore.setDuration(timeFormat(val));
}
setConfig(String(route.meta.title));
watch(
() => route.meta.title,
(title: unknown) => {
setConfig(String(title));
},
);
async function getVersion() {
const res = await appStore.fetchVersion();
if (res.errors) {
ElMessage.error(res.errors);
}
}
function resetDuration() {
const { duration }: any = route.params;
if (duration) {
const d = JSON.parse(duration);
appStore.updateDurationRow({
start: new Date(d.start),
end: new Date(d.end),
step: d.step,
});
appStore.updateUTC(d.utc);
}
}
}
</script>
<style lang="scss" scoped>
.nav-bar {
padding: 5px 10px 5px 28px;
text-align: left;
justify-content: space-between;
background-color: #fafbfc;
border-bottom: 1px solid #dfe4e8;
color: #222;
font-size: 12px;
}
.nav-bar {
padding: 5px 10px 5px 28px;
text-align: left;
justify-content: space-between;
background-color: #fafbfc;
border-bottom: 1px solid #dfe4e8;
color: #222;
font-size: 12px;
}
.nav-bar.dark {
background-color: #333840;
border-bottom: 1px solid #252a2f;
color: #fafbfc;
}
.nav-bar.dark {
background-color: #333840;
border-bottom: 1px solid #252a2f;
color: #fafbfc;
}
.title {
font-size: 14px;
font-weight: 500;
height: 28px;
line-height: 28px;
}
.title {
font-size: 14px;
font-weight: 500;
height: 28px;
line-height: 28px;
}
.nav-tabs {
padding: 10px;
}
.nav-tabs {
padding: 10px;
}
</style>

View File

@ -15,10 +15,7 @@ limitations under the License. -->
<template>
<div class="side-bar">
<div :class="isCollapse ? 'logo-icon-collapse' : 'logo-icon'">
<Icon
:size="isCollapse ? 'xl' : 'logo'"
:iconName="isCollapse ? 'logo' : 'logo-sw'"
/>
<Icon :size="isCollapse ? 'xl' : 'logo'" :iconName="isCollapse ? 'logo' : 'logo-sw'" />
</div>
<el-menu
active-text-color="#448dfe"
@ -43,22 +40,14 @@ limitations under the License. -->
</router-link>
</template>
<el-menu-item-group>
<el-menu-item
v-for="(m, idx) in filterMenus(menu.children)"
:index="m.name"
:key="idx"
>
<el-menu-item v-for="(m, idx) in filterMenus(menu.children)" :index="m.name" :key="idx">
<router-link class="items" :to="m.path">
<span class="title">{{ m.meta && t(m.meta.title) }}</span>
</router-link>
</el-menu-item>
</el-menu-item-group>
</el-sub-menu>
<el-menu-item
:index="String(menu.name)"
@click="changePage(menu)"
v-else
>
<el-menu-item :index="String(menu.name)" @click="changePage(menu)" v-else>
<el-icon class="menu-icons" :style="{ marginRight: '12px' }">
<router-link class="items" :to="menu.children[0].path">
<Icon size="lg" :iconName="menu.meta.icon" />
@ -79,124 +68,117 @@ limitations under the License. -->
color: theme === 'light' ? '#eee' : '#252a2f',
}"
>
<Icon
size="middle"
iconName="format_indent_decrease"
@click="controlMenu"
/>
<Icon size="middle" iconName="format_indent_decrease" @click="controlMenu" />
</div>
</div>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import { useRouter, RouteRecordRaw } from "vue-router";
import { useI18n } from "vue-i18n";
import Icon from "@/components/Icon.vue";
import { useAppStoreWithOut } from "@/store/modules/app";
import { ref } from "vue";
import type { RouteRecordRaw } from "vue-router";
import { useRouter } from "vue-router";
import { useI18n } from "vue-i18n";
import Icon from "@/components/Icon.vue";
import { useAppStoreWithOut } from "@/store/modules/app";
const appStore = useAppStoreWithOut();
const { t } = useI18n();
const name = ref<string>(String(useRouter().currentRoute.value.name));
const theme = ["VirtualMachine", "Kubernetes"].includes(name.value || "")
? ref("light")
: ref("black");
const routes = ref<RouteRecordRaw[] | any>(useRouter().options.routes);
if (/Android|webOS|iPhone|iPod|iPad|BlackBerry/i.test(navigator.userAgent)) {
appStore.setIsMobile(true);
} else {
appStore.setIsMobile(false);
}
const isCollapse = ref(false);
const controlMenu = () => {
isCollapse.value = !isCollapse.value;
};
const changePage = (menu: RouteRecordRaw) => {
theme.value = ["VirtualMachine", "Kubernetes"].includes(String(menu.name))
? "light"
: "black";
};
const filterMenus = (menus: any[]) => {
return menus.filter((d) => d.meta && !d.meta.notShow);
};
const appStore = useAppStoreWithOut();
const { t } = useI18n();
const name = ref<string>(String(useRouter().currentRoute.value.name));
const theme = ["VirtualMachine", "Kubernetes"].includes(name.value || "") ? ref("light") : ref("black");
const routes = ref<RouteRecordRaw[] | any>(useRouter().options.routes);
if (/Android|webOS|iPhone|iPod|iPad|BlackBerry/i.test(navigator.userAgent)) {
appStore.setIsMobile(true);
} else {
appStore.setIsMobile(false);
}
const isCollapse = ref(false);
const controlMenu = () => {
isCollapse.value = !isCollapse.value;
};
const changePage = (menu: RouteRecordRaw) => {
theme.value = ["VirtualMachine", "Kubernetes"].includes(String(menu.name)) ? "light" : "black";
};
const filterMenus = (menus: any[]) => {
return menus.filter((d) => d.meta && !d.meta.notShow);
};
</script>
<style lang="scss" scoped>
.side-bar {
background: #252a2f;
height: 100%;
margin-bottom: 100px;
overflow-y: auto;
overflow-x: hidden;
}
.side-bar {
background: #252a2f;
height: 100%;
margin-bottom: 100px;
overflow-y: auto;
overflow-x: hidden;
}
.el-menu-vertical:not(.el-menu--collapse) {
width: 220px;
font-size: 16px;
}
.el-menu-vertical:not(.el-menu--collapse) {
width: 220px;
font-size: 16px;
}
.logo-icon-collapse {
width: 65px;
margin: 15px 0 10px 0;
text-align: center;
}
.logo-icon-collapse {
width: 65px;
margin: 15px 0 10px 0;
text-align: center;
}
span.collapse {
height: 0;
width: 0;
overflow: hidden;
visibility: hidden;
display: inline-block;
}
span.collapse {
height: 0;
width: 0;
overflow: hidden;
visibility: hidden;
display: inline-block;
}
.logo-icon {
margin: 15px 0 10px 20px;
width: 110px;
}
.logo-icon {
margin: 15px 0 10px 20px;
width: 110px;
}
.menu-control {
position: absolute;
top: 7px;
left: 220px;
cursor: pointer;
transition: all 0.2s linear;
z-index: 99;
color: #252a2f;
}
.menu-control {
position: absolute;
top: 7px;
left: 220px;
cursor: pointer;
transition: all 0.2s linear;
z-index: 99;
color: #252a2f;
}
.menu-control.collapse {
left: 70px;
}
.menu-control.collapse {
left: 70px;
}
.el-icon.el-sub-menu__icon-arrow {
height: 12px;
}
.el-icon.el-sub-menu__icon-arrow {
height: 12px;
}
.items {
display: inline-block;
width: 100%;
}
.items {
display: inline-block;
width: 100%;
}
.version {
color: #eee;
font-size: 12px;
cursor: pointer;
padding-left: 23px;
margin-bottom: 10px;
position: absolute;
bottom: 0;
left: 10px;
}
.version {
color: #eee;
font-size: 12px;
cursor: pointer;
padding-left: 23px;
margin-bottom: 10px;
position: absolute;
bottom: 0;
left: 10px;
}
.empty {
width: 100%;
height: 60px;
}
.empty {
width: 100%;
height: 60px;
}
.title {
display: inline-block;
max-width: 110px;
text-overflow: ellipsis;
overflow: hidden;
}
.title {
display: inline-block;
max-width: 110px;
text-overflow: ellipsis;
overflow: hidden;
}
</style>

View File

@ -32,6 +32,7 @@ if (!savedLanguage) {
}
language = savedLanguage ? savedLanguage : language;
const i18n = createI18n({
legacy: false,
locale: language,
messages,
});

View File

@ -176,10 +176,8 @@ const msg = {
toTheRight: "To The Right",
legendValues: "Legend Values",
minDuration: "Minimal Request Duration",
when4xx:
"Sample HTTP requests and responses with tracing when response code between 400 and 499",
when5xx:
"Sample HTTP requests and responses with tracing when response code between 500 and 599",
when4xx: "Sample HTTP requests and responses with tracing when response code between 400 and 499",
when5xx: "Sample HTTP requests and responses with tracing when response code between 500 and 599",
taskTitle: "HTTP request and response collecting rules",
seconds: "Seconds",
hourTip: "Select Hour",
@ -315,8 +313,7 @@ const msg = {
viewLogs: "View Logs",
logsTagsTip: `Only tags defined in the core/default/searchableLogsTags are searchable.
Check more details on the Configuration Vocabulary page`,
keywordsOfContentLogTips:
"Current storage of SkyWalking OAP server does not support this.",
keywordsOfContentLogTips: "Current storage of SkyWalking OAP server does not support this.",
setEvent: "Set Event",
viewAttributes: "View",
serviceEvents: "Service Events",
@ -370,8 +367,7 @@ const msg = {
addKeywordsOfContent: "Please input a keyword of content",
addExcludingKeywordsOfContent: "Please input a keyword of excluding content",
noticeTag: "Please press Enter after inputting a tag(key=value).",
conditionNotice:
"Notice: Please press Enter after inputting a key of content, exclude key of content(key=value).",
conditionNotice: "Notice: Please press Enter after inputting a key of content, exclude key of content(key=value).",
language: "Language",
gateway: "Gateway",
virtualMQ: "Virtual MQ",

View File

@ -77,10 +77,8 @@ const msg = {
editGraph: "Editar Opciones",
dashboardName: "Selecciona Nombre del Panel",
linkDashboard: "Nombre del panel relacionado con llamadas de la topología",
linkServerMetrics:
"Métricas de servidor relacionadas con llamadas de la topología",
linkClientMetrics:
"Métricas de cliente relacionadas con llamadas de la topología",
linkServerMetrics: "Métricas de servidor relacionadas con llamadas de la topología",
linkClientMetrics: "Métricas de cliente relacionadas con llamadas de la topología",
nodeDashboard: "Nombre del panel relacionado con nodos de la topología",
nodeMetrics: "Mêtricas relacionas con nodos de la topología",
instanceDashboard: "Nombre del panel relacionado con instancias de servicio",
@ -180,10 +178,8 @@ const msg = {
asTable: "Como tabla",
toTheRight: "Derecha",
minDuration: "Duración mínima de la solicitud",
when4xx:
"Ejemplo de solicitud y respuesta http con seguimiento cuando el Código de respuesta está entre 400 y 499",
when5xx:
"Ejemplo de solicitud y respuesta http con seguimiento cuando el Código de respuesta está entre 500 y 599",
when4xx: "Ejemplo de solicitud y respuesta http con seguimiento cuando el Código de respuesta está entre 400 y 499",
when5xx: "Ejemplo de solicitud y respuesta http con seguimiento cuando el Código de respuesta está entre 500 y 599",
taskTitle: "Reglas de recolección de peticiones y respuestas HTTP",
second: "s",
yearSuffix: "Año",
@ -315,8 +311,7 @@ const msg = {
viewLogs: "Ver Registro de Datos",
logsTagsTip: `Solamente etiquetas definidas en core/default/searchableLogsTags pueden ser buscadas.
Más información en la página de Vocabulario de Configuración`,
keywordsOfContentLogTips:
"El almacenamiento actual del servidor SkyWalking OAP no lo soporta.",
keywordsOfContentLogTips: "El almacenamiento actual del servidor SkyWalking OAP no lo soporta.",
setEvent: "Establecer Evento",
viewAttributes: "Ver",
serviceEvents: "Eventos Servico",
@ -347,8 +342,7 @@ const msg = {
destEndpoint: "Endpoint Destinación",
eventSource: "Fuente Envento",
modalTitle: "Inspección",
selectRedirectPage:
"Quiere inspeccionar las Trazas or Registros de datos del servicio %s?",
selectRedirectPage: "Quiere inspeccionar las Trazas or Registros de datos del servicio %s?",
logAnalysis: "Lenguaje de Análisis de Registro de Datos",
logDataBody: "Contenido del Registro de Datos",
addType: "Por favor introduzca un tipo",
@ -369,10 +363,8 @@ const msg = {
addTraceID: "Por favor introduzca el ID de la traza",
addTags: "Por favor introduzaca una etiqueta",
addKeywordsOfContent: "Por favor introduzca una clave de contenido",
addExcludingKeywordsOfContent:
"Por favor introduzca una clave excluyente de contenido",
noticeTag:
"Por favor presione Intro después de introducir una etiqueta(clave=valor).",
addExcludingKeywordsOfContent: "Por favor introduzca una clave excluyente de contenido",
noticeTag: "Por favor presione Intro después de introducir una etiqueta(clave=valor).",
conditionNotice:
"Aviso: Por favor presione Intro después de introducir una clave de contenido, excluir clave de contenido(clave=valor).",
language: "Lenguaje",

View File

@ -282,12 +282,9 @@ const msg = {
chartType: "图表类型",
currentDepth: "当前深度",
defaultDepth: "默认深度",
traceTagsTip:
"只有core/default/searchableTracesTags中定义的标记才可搜索。查看配置词汇表页面上的更多详细信息。",
logTagsTip:
"只有core/default/searchableTracesTags中定义的标记才可搜索。查看配置词汇表页面上的更多详细信息。",
alarmTagsTip:
"只有core/default/searchableTracesTags中定义的标记才可搜索。查看配置词汇表页面上的更多详细信息。",
traceTagsTip: "只有core/default/searchableTracesTags中定义的标记才可搜索。查看配置词汇表页面上的更多详细信息。",
logTagsTip: "只有core/default/searchableTracesTags中定义的标记才可搜索。查看配置词汇表页面上的更多详细信息。",
alarmTagsTip: "只有core/default/searchableTracesTags中定义的标记才可搜索。查看配置词汇表页面上的更多详细信息。",
tagsLink: "配置词汇页",
addTag: "请添加标签",
logCategory: "日志类别",
@ -310,8 +307,7 @@ const msg = {
contentType: "内容类型",
content: "内容",
viewLogs: "查看日志",
logsTagsTip:
"只有core/default/searchableLogsTags中定义的标记才可搜索。查看配置词汇表页面上的更多详细信息。",
logsTagsTip: "只有core/default/searchableLogsTags中定义的标记才可搜索。查看配置词汇表页面上的更多详细信息。",
keywordsOfContentLogTips: "SkyWalking OAP服务器的当前存储不支持此操作",
setEvent: "设置事件",
viewAttributes: "查看",
@ -368,8 +364,7 @@ const msg = {
addKeywordsOfContent: "请输入一个内容关键词",
addExcludingKeywordsOfContent: "请输入一个内容不包含的关键词",
noticeTag: "请输入一个标签(key=value)之后回车",
conditionNotice:
"请输入一个内容关键词或者内容不包含的关键词(key=value)之后回车",
conditionNotice: "请输入一个内容关键词或者内容不包含的关键词(key=value)之后回车",
language: "语言",
gateway: "网关",
virtualMQ: "虚拟消息队列",

View File

@ -22,6 +22,7 @@ import components from "@/components";
import i18n from "./locales";
import { useAppStoreWithOut } from "@/store/modules/app";
import "./styles/index.ts";
import "virtual:svg-icons-register";
const app = createApp(App);
const appStore = useAppStoreWithOut();

View File

@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { RouteRecordRaw } from "vue-router";
import type { RouteRecordRaw } from "vue-router";
import Layout from "@/layout/Index.vue";
export const routesAlarm: Array<RouteRecordRaw> = [
@ -31,8 +31,7 @@ export const routesAlarm: Array<RouteRecordRaw> = [
{
path: "/alerting",
name: "Alarm",
component: () =>
import(/* webpackChunkName: "alerting" */ "@/views/Alarm.vue"),
component: () => import("@/views/Alarm.vue"),
},
],
},

View File

@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { RouteRecordRaw } from "vue-router";
import type { RouteRecordRaw } from "vue-router";
import Layout from "@/layout/Index.vue";
export const routesDashboard: Array<RouteRecordRaw> = [
@ -30,10 +30,7 @@ export const routesDashboard: Array<RouteRecordRaw> = [
children: [
{
path: "/dashboard/list",
component: () =>
import(
/* webpackChunkName: "dashboards" */ "@/views/dashboard/List.vue"
),
component: () => import("@/views/dashboard/List.vue"),
name: "List",
meta: {
title: "dashboardList",
@ -41,10 +38,7 @@ export const routesDashboard: Array<RouteRecordRaw> = [
},
{
path: "/dashboard/new",
component: () =>
import(
/* webpackChunkName: "dashboards" */ "@/views/dashboard/New.vue"
),
component: () => import("@/views/dashboard/New.vue"),
name: "New",
meta: {
title: "dashboardNew",
@ -54,38 +48,26 @@ export const routesDashboard: Array<RouteRecordRaw> = [
path: "",
redirect: "/dashboard/:layerId/:entity/:name",
name: "Create",
component: () =>
import(
/* webpackChunkName: "dashboards" */ "@/views/dashboard/Edit.vue"
),
component: () => import("@/views/dashboard/Edit.vue"),
meta: {
notShow: true,
},
children: [
{
path: "/dashboard/:layerId/:entity/:name",
component: () =>
import(
/* webpackChunkName: "dashboards" */ "@/views/dashboard/Edit.vue"
),
component: () => import("@/views/dashboard/Edit.vue"),
name: "CreateChild",
},
{
path: "/dashboard/:layerId/:entity/:name/tab/:activeTabIndex",
component: () =>
import(
/* webpackChunkName: "dashboards" */ "@/views/dashboard/Edit.vue"
),
component: () => import("@/views/dashboard/Edit.vue"),
name: "CreateActiveTabIndex",
},
],
},
{
path: "",
component: () =>
import(
/* webpackChunkName: "dashboards" */ "@/views/dashboard/Edit.vue"
),
component: () => import("@/views/dashboard/Edit.vue"),
name: "View",
redirect: "/dashboard/:layerId/:entity/:serviceId/:name",
meta: {
@ -94,30 +76,20 @@ export const routesDashboard: Array<RouteRecordRaw> = [
children: [
{
path: "/dashboard/:layerId/:entity/:serviceId/:name",
component: () =>
import(
/* webpackChunkName: "dashboards" */ "@/views/dashboard/Edit.vue"
),
component: () => import("@/views/dashboard/Edit.vue"),
name: "ViewChild",
},
{
path: "/dashboard/:layerId/:entity/:serviceId/:name/tab/:activeTabIndex",
component: () =>
import(
/* webpackChunkName: "dashboards" */ "@/views/dashboard/Edit.vue"
),
component: () => import("@/views/dashboard/Edit.vue"),
name: "ViewActiveTabIndex",
},
],
},
{
path: "",
redirect:
"/dashboard/related/:layerId/:entity/:serviceId/:destServiceId/:name",
component: () =>
import(
/* webpackChunkName: "dashboards" */ "@/views/dashboard/Edit.vue"
),
redirect: "/dashboard/related/:layerId/:entity/:serviceId/:destServiceId/:name",
component: () => import("@/views/dashboard/Edit.vue"),
name: "ViewServiceRelation",
meta: {
notShow: true,
@ -125,18 +97,12 @@ export const routesDashboard: Array<RouteRecordRaw> = [
children: [
{
path: "/dashboard/related/:layerId/:entity/:serviceId/:destServiceId/:name",
component: () =>
import(
/* webpackChunkName: "dashboards" */ "@/views/dashboard/Edit.vue"
),
component: () => import("@/views/dashboard/Edit.vue"),
name: "ViewServiceRelation",
},
{
path: "/dashboard/related/:layerId/:entity/:serviceId/:destServiceId/:name/tab/:activeTabIndex",
component: () =>
import(
/* webpackChunkName: "dashboards" */ "@/views/dashboard/Edit.vue"
),
component: () => import("@/views/dashboard/Edit.vue"),
name: "ViewServiceRelationActiveTabIndex",
},
],
@ -144,10 +110,7 @@ export const routesDashboard: Array<RouteRecordRaw> = [
{
path: "",
redirect: "/dashboard/:layerId/:entity/:serviceId/:podId/:name",
component: () =>
import(
/* webpackChunkName: "dashboards" */ "@/views/dashboard/Edit.vue"
),
component: () => import("@/views/dashboard/Edit.vue"),
name: "ViewPod",
meta: {
notShow: true,
@ -155,30 +118,20 @@ export const routesDashboard: Array<RouteRecordRaw> = [
children: [
{
path: "/dashboard/:layerId/:entity/:serviceId/:podId/:name",
component: () =>
import(
/* webpackChunkName: "dashboards" */ "@/views/dashboard/Edit.vue"
),
component: () => import("@/views/dashboard/Edit.vue"),
name: "ViewPod",
},
{
path: "/dashboard/:layerId/:entity/:serviceId/:podId/:name/tab/:activeTabIndex",
component: () =>
import(
/* webpackChunkName: "dashboards" */ "@/views/dashboard/Edit.vue"
),
component: () => import("@/views/dashboard/Edit.vue"),
name: "ViewPodActiveTabIndex",
},
],
},
{
path: "",
redirect:
"/dashboard/:layerId/:entity/:serviceId/:podId/:destServiceId/:destPodId/:name",
component: () =>
import(
/* webpackChunkName: "dashboards" */ "@/views/dashboard/Edit.vue"
),
redirect: "/dashboard/:layerId/:entity/:serviceId/:podId/:destServiceId/:destPodId/:name",
component: () => import("@/views/dashboard/Edit.vue"),
name: "PodRelation",
meta: {
notShow: true,
@ -186,18 +139,12 @@ export const routesDashboard: Array<RouteRecordRaw> = [
children: [
{
path: "/dashboard/:layerId/:entity/:serviceId/:podId/:destServiceId/:destPodId/:name",
component: () =>
import(
/* webpackChunkName: "dashboards" */ "@/views/dashboard/Edit.vue"
),
component: () => import("@/views/dashboard/Edit.vue"),
name: "ViewPodRelation",
},
{
path: "/dashboard/:layerId/:entity/:serviceId/:podId/:destServiceId/:destPodId/:name/tab/:activeTabIndex",
component: () =>
import(
/* webpackChunkName: "dashboards" */ "@/views/dashboard/Edit.vue"
),
component: () => import("@/views/dashboard/Edit.vue"),
name: "ViewPodRelationActiveTabIndex",
},
],
@ -206,10 +153,7 @@ export const routesDashboard: Array<RouteRecordRaw> = [
path: "",
redirect:
"/dashboard/:layerId/:entity/:serviceId/:podId/:processId/:destServiceId/:destPodId/:destProcessId/:name",
component: () =>
import(
/* webpackChunkName: "dashboards" */ "@/views/dashboard/Edit.vue"
),
component: () => import("@/views/dashboard/Edit.vue"),
name: "ProcessRelation",
meta: {
notShow: true,
@ -217,26 +161,17 @@ export const routesDashboard: Array<RouteRecordRaw> = [
children: [
{
path: "/dashboard/:layerId/:entity/:serviceId/:podId/:processId/:destServiceId/:destPodId/:destProcessId/:name",
component: () =>
import(
/* webpackChunkName: "dashboards" */ "@/views/dashboard/Edit.vue"
),
component: () => import("@/views/dashboard/Edit.vue"),
name: "ViewProcessRelation",
},
{
path: "/dashboard/:layerId/:entity/:serviceId/:podId/:processId/:destServiceId/:destPodId/:destProcessId/:name/tab/:activeTabIndex",
component: () =>
import(
/* webpackChunkName: "dashboards" */ "@/views/dashboard/Edit.vue"
),
component: () => import("@/views/dashboard/Edit.vue"),
name: "ViewProcessRelationActiveTabIndex",
},
{
path: "/dashboard/:layerId/:entity/:serviceId/:podId/:processId/:destServiceId/:destPodId/:destProcessId/:name/duration/:duration",
component: () =>
import(
/* webpackChunkName: "dashboards" */ "@/views/dashboard/Edit.vue"
),
component: () => import("@/views/dashboard/Edit.vue"),
name: "ViewProcessRelationDuration",
},
],

View File

@ -14,21 +14,17 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import type { RouteRecordRaw } from "vue-router";
import { createRouter, createWebHistory } from "vue-router";
import { routesDashboard } from "./dashboard";
import { routesSetting } from "./setting";
import { routesAlarm } from "./alarm";
import routesLayers from "./layer";
const routes: Array<RouteRecordRaw> = [
...routesLayers,
...routesDashboard,
...routesAlarm,
...routesSetting,
];
const routes: Array<RouteRecordRaw> = [...routesLayers, ...routesDashboard, ...routesAlarm, ...routesSetting];
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
history: createWebHistory(import.meta.env.BASE_URL),
routes,
});

View File

@ -22,8 +22,7 @@ function layerDashboards() {
item.component = Layout;
if (item.children) {
item.children = item.children.map((d: any) => {
d.component = () =>
import(/* webpackChunkName: "layer" */ "@/views/Layer.vue");
d.component = () => import("@/views/Layer.vue");
return d;
});
}

View File

@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { RouteRecordRaw } from "vue-router";
import type { RouteRecordRaw } from "vue-router";
import Layout from "@/layout/Index.vue";
export const routesSetting: Array<RouteRecordRaw> = [
@ -36,8 +36,7 @@ export const routesSetting: Array<RouteRecordRaw> = [
icon: "settings",
hasGroup: false,
},
component: () =>
import(/* webpackChunkName: "settings" */ "@/views/Settings.vue"),
component: () => import("@/views/Settings.vue"),
},
],
},

View File

@ -17,8 +17,8 @@
import { defineStore } from "pinia";
import { store } from "@/store";
import graphql from "@/graphql";
import { AxiosResponse } from "axios";
import { Alarm } from "@/types/alarm";
import type { AxiosResponse } from "axios";
import type { Alarm } from "@/types/alarm";
interface AlarmState {
loading: boolean;
@ -35,9 +35,7 @@ export const alarmStore = defineStore({
}),
actions: {
async getAlarms(params: any) {
const res: AxiosResponse = await graphql
.query("queryAlarms")
.params(params);
const res: AxiosResponse = await graphql.query("queryAlarms").params(params);
if (res.data.errors) {
return res.data;
}

View File

@ -17,9 +17,9 @@
import { defineStore } from "pinia";
import { store } from "@/store";
import graphql from "@/graphql";
import { Duration, DurationTime } from "@/types/app";
import type { Duration, DurationTime } from "@/types/app";
import getLocalTime from "@/utils/localtime";
import { AxiosResponse } from "axios";
import type { AxiosResponse } from "axios";
import dateFormatStep, { dateFormatTime } from "@/utils/dateFormat";
import { TimeType } from "@/constants/data";
/*global Nullable*/
@ -92,9 +92,7 @@ export const appStore = defineStore({
this.duration.start.getMonth());
break;
}
const utcSpace =
(this.utcHour + new Date().getTimezoneOffset() / 60) * 3600000 +
this.utcMin * 60000;
const utcSpace = (this.utcHour + new Date().getTimezoneOffset() / 60) * 3600000 + this.utcMin * 60000;
const startUnix: number = this.duration.start.getTime();
const endUnix: number = this.duration.end.getTime();
const timeIntervals: number[] = [];
@ -157,13 +155,11 @@ export const appStore = defineStore({
this.eventStack.forEach((event: any) => {
setTimeout(event(), 0);
}),
500
500,
);
},
async queryOAPTimeInfo() {
const res: AxiosResponse = await graphql
.query("queryOAPTimeInfo")
.params({});
const res: AxiosResponse = await graphql.query("queryOAPTimeInfo").params({});
if (res.data.errors) {
this.utc = -(new Date().getTimezoneOffset() / 60) + ":0";
} else {
@ -176,9 +172,7 @@ export const appStore = defineStore({
return res.data;
},
async fetchVersion(): Promise<void> {
const res: AxiosResponse = await graphql
.query("queryOAPVersion")
.params({});
const res: AxiosResponse = await graphql.query("queryOAPVersion").params({});
if (res.data.errors) {
return res.data;
}

View File

@ -16,13 +16,13 @@
*/
import { defineStore } from "pinia";
import { store } from "@/store";
import { LayoutConfig } from "@/types/dashboard";
import type { LayoutConfig } from "@/types/dashboard";
import graphql from "@/graphql";
import query from "@/graphql/fetch";
import { DashboardItem } from "@/types/dashboard";
import type { DashboardItem } from "@/types/dashboard";
import { useSelectorStore } from "@/store/modules/selectors";
import { NewControl, TextConfig, TimeRangeConfig } from "../data";
import { AxiosResponse } from "axios";
import type { AxiosResponse } from "axios";
import { ElMessage } from "element-plus";
import { useI18n } from "vue-i18n";
import { EntityType } from "@/views/dashboard/data";
@ -105,24 +105,10 @@ export const dashboardStore = defineStore({
newItem.h = 36;
newItem.graph = {
showDepth: true,
depth:
this.entity === EntityType[1].value
? 1
: this.entity === EntityType[0].value
? 2
: 3,
depth: this.entity === EntityType[1].value ? 1 : this.entity === EntityType[0].value ? 2 : 3,
};
}
if (
[
"Trace",
"Profile",
"Log",
"DemandLog",
"Ebpf",
"NetworkProfiling",
].includes(type)
) {
if (["Trace", "Profile", "Log", "DemandLog", "Ebpf", "NetworkProfiling"].includes(type)) {
newItem.h = 36;
}
if (type === "Text") {
@ -156,14 +142,12 @@ export const dashboardStore = defineStore({
},
addTabControls(type: string) {
const activedGridItem = this.activedGridItem.split("-")[0];
const idx = this.layout.findIndex(
(d: LayoutConfig) => d.i === activedGridItem
);
const idx = this.layout.findIndex((d: LayoutConfig) => d.i === activedGridItem);
if (idx < 0) {
return;
}
const tabIndex = this.layout[idx].activedTabIndex || 0;
const { children } = this.layout[idx].children[tabIndex];
const { children } = (this.layout[idx].children || [])[tabIndex];
const arr = children.map((d: any) => Number(d.i));
let index = String(Math.max(...arr) + 1);
if (!children.length) {
@ -184,16 +168,7 @@ export const dashboardStore = defineStore({
showDepth: true,
};
}
if (
[
"Trace",
"Profile",
"Log",
"DemandLog",
"Ebpf",
"NetworkProfiling",
].includes(type)
) {
if (["Trace", "Profile", "Log", "DemandLog", "Ebpf", "NetworkProfiling"].includes(type)) {
newItem.h = 32;
}
if (type === "Text") {
@ -211,7 +186,7 @@ export const dashboardStore = defineStore({
return d;
});
items.push(newItem);
this.layout[idx].children[tabIndex].children = items;
(this.layout[idx].children || [])[tabIndex].children = items;
this.currentTabItems = items;
}
},
@ -238,19 +213,15 @@ export const dashboardStore = defineStore({
},
removeControls(item: LayoutConfig) {
const actived = this.activedGridItem.split("-");
const index = this.layout.findIndex(
(d: LayoutConfig) => actived[0] === d.i
);
const index = this.layout.findIndex((d: LayoutConfig) => actived[0] === d.i);
if (this.selectedGrid && this.selectedGrid.i === item.i) {
this.selectedGrid = null;
}
if (actived.length === 3) {
const tabIndex = Number(actived[1]);
this.currentTabItems = this.currentTabItems.filter(
(d: LayoutConfig) => actived[2] !== d.i
);
this.layout[index].children[tabIndex].children = this.currentTabItems;
this.currentTabItems = this.currentTabItems.filter((d: LayoutConfig) => actived[2] !== d.i);
(this.layout[index].children || [])[tabIndex].children = this.currentTabItems;
return;
}
this.layout = this.layout.filter((d: LayoutConfig) => d.i !== item.i);
@ -258,8 +229,8 @@ export const dashboardStore = defineStore({
removeTabItem(item: LayoutConfig, index: number) {
const idx = this.layout.findIndex((d: LayoutConfig) => d.i === item.i);
if (this.selectedGrid) {
for (const item of this.layout[idx].children[index].children) {
if (this.selectedGrid.i === item.i) {
for (const item of (this.layout[idx].children || [])[index].children) {
if (this.selectedGrid?.i === item.i) {
this.selectedGrid = null;
}
}
@ -285,22 +256,19 @@ export const dashboardStore = defineStore({
},
setConfigs(param: { [key: string]: unknown }) {
const actived = this.activedGridItem.split("-");
const index = this.layout.findIndex(
(d: LayoutConfig) => actived[0] === d.i
);
const index = this.layout.findIndex((d: LayoutConfig) => actived[0] === d.i);
if (actived.length === 3) {
const tabIndex = Number(actived[1]);
const itemIndex = this.layout[index].children[
tabIndex
].children.findIndex((d: LayoutConfig) => actived[2] === d.i);
const itemIndex = (this.layout[index].children || [])[tabIndex].children.findIndex(
(d: LayoutConfig) => actived[2] === d.i,
);
this.layout[index].children[tabIndex].children[itemIndex] = {
...this.layout[index].children[tabIndex].children[itemIndex],
(this.layout[index].children || [])[tabIndex].children[itemIndex] = {
...(this.layout[index].children || [])[tabIndex].children[itemIndex],
...param,
};
this.selectedGrid =
this.layout[index].children[tabIndex].children[itemIndex];
this.setCurrentTabItems(this.layout[index].children[tabIndex].children);
this.selectedGrid = (this.layout[index].children || [])[tabIndex].children[itemIndex];
this.setCurrentTabItems((this.layout[index].children || [])[tabIndex].children);
return;
}
this.layout[index] = {
@ -312,8 +280,8 @@ export const dashboardStore = defineStore({
setWidget(param: LayoutConfig) {
for (let i = 0; i < this.layout.length; i++) {
if (this.layout[i].type === "Tab") {
if (this.layout[i].children && this.layout[i].children.length) {
for (const child of this.layout[i].children) {
if ((this.layout[i].children || []).length) {
for (const child of this.layout[i].children || []) {
if (child.children && child.children.length) {
for (let c = 0; c < child.children.length; c++) {
if (child.children[c].id === param.id) {
@ -332,23 +300,16 @@ export const dashboardStore = defineStore({
}
},
async fetchMetricType(item: string) {
const res: AxiosResponse = await graphql
.query("queryTypeOfMetrics")
.params({ name: item });
const res: AxiosResponse = await graphql.query("queryTypeOfMetrics").params({ name: item });
return res.data;
},
async fetchMetricList(regex: string) {
const res: AxiosResponse = await graphql
.query("queryMetrics")
.params({ regex });
const res: AxiosResponse = await graphql.query("queryMetrics").params({ regex });
return res.data;
},
async fetchMetricValue(param: {
queryStr: string;
conditions: { [key: string]: unknown };
}) {
async fetchMetricValue(param: { queryStr: string; conditions: { [key: string]: unknown } }) {
const res: AxiosResponse = await query(param);
return res.data;
},
@ -371,10 +332,7 @@ export const dashboardStore = defineStore({
name: c.name,
isRoot: c.isRoot,
});
sessionStorage.setItem(
key,
JSON.stringify({ id: t.id, configuration: c })
);
sessionStorage.setItem(key, JSON.stringify({ id: t.id, configuration: c }));
}
list = list.sort((a, b) => {
const nameA = a.name.toUpperCase();
@ -399,9 +357,7 @@ export const dashboardStore = defineStore({
return;
}
}
this.dashboards = JSON.parse(
sessionStorage.getItem("dashboards") || "[]"
);
this.dashboards = JSON.parse(sessionStorage.getItem("dashboards") || "[]");
},
async resetTemplates() {
const res = await this.fetchTemplates();
@ -410,9 +366,7 @@ export const dashboardStore = defineStore({
ElMessage.error(res.errors);
return;
}
this.dashboards = JSON.parse(
sessionStorage.getItem("dashboards") || "[]"
);
this.dashboards = JSON.parse(sessionStorage.getItem("dashboards") || "[]");
},
async updateDashboard(setting: { id: string; configuration: string }) {
const res: AxiosResponse = await graphql.query("updateTemplate").params({
@ -431,7 +385,7 @@ export const dashboardStore = defineStore({
return res.data;
},
async saveDashboard() {
if (!this.currentDashboard.name) {
if (!this.currentDashboard?.name) {
ElMessage.error("The dashboard name is needed.");
return;
}
@ -452,18 +406,16 @@ export const dashboardStore = defineStore({
c.isRoot = false;
const index = this.dashboards.findIndex(
(d: DashboardItem) =>
d.name === this.currentDashboard.name &&
d.name === this.currentDashboard?.name &&
d.entity === this.currentDashboard.entity &&
d.layer === this.currentDashboard.layerId
d.layer === this.currentDashboard?.layer,
);
if (index > -1) {
const { t } = useI18n();
ElMessage.error(t("nameError"));
return;
}
res = await graphql
.query("addNewTemplate")
.params({ setting: { configuration: JSON.stringify(c) } });
res = await graphql.query("addNewTemplate").params({ setting: { configuration: JSON.stringify(c) } });
json = res.data.data.addTemplate;
}
@ -478,17 +430,11 @@ export const dashboardStore = defineStore({
if (!this.currentDashboard.id) {
ElMessage.success("Saved successfully");
}
const key = [
this.currentDashboard.layer,
this.currentDashboard.entity,
this.currentDashboard.name,
].join("_");
const key = [this.currentDashboard.layer, this.currentDashboard.entity, this.currentDashboard.name].join("_");
this.currentDashboard.id = json.id;
if (this.currentDashboard.id) {
sessionStorage.removeItem(key);
this.dashboards = this.dashboards.filter(
(d: DashboardItem) => d.id !== this.currentDashboard.id
);
this.dashboards = this.dashboards.filter((d: DashboardItem) => d.id !== this.currentDashboard?.id);
}
this.dashboards.push(this.currentDashboard);
const l = { id: json.id, configuration: c };
@ -498,9 +444,7 @@ export const dashboardStore = defineStore({
return json;
},
async deleteDashboard() {
const res: AxiosResponse = await graphql
.query("removeTemplate")
.params({ id: this.currentDashboard.id });
const res: AxiosResponse = await graphql.query("removeTemplate").params({ id: this.currentDashboard?.id });
if (res.data.errors) {
ElMessage.error(res.data.errors);
@ -511,14 +455,8 @@ export const dashboardStore = defineStore({
ElMessage.error(json.message);
return res.data;
}
this.dashboards = this.dashboards.filter(
(d: any) => d.id !== this.currentDashboard.id
);
const key = [
this.currentDashboard.layer,
this.currentDashboard.entity,
this.currentDashboard.name,
].join("_");
this.dashboards = this.dashboards.filter((d: any) => d.id !== this.currentDashboard?.id);
const key = [this.currentDashboard?.layer, this.currentDashboard?.entity, this.currentDashboard?.name].join("_");
sessionStorage.removeItem(key);
},
},

View File

@ -15,13 +15,13 @@
* limitations under the License.
*/
import { defineStore } from "pinia";
import { Instance } from "@/types/selector";
import type { Instance } from "@/types/selector";
import { store } from "@/store";
import graphql from "@/graphql";
import { AxiosResponse } from "axios";
import type { AxiosResponse } from "axios";
import { useAppStoreWithOut } from "@/store/modules/app";
import { useSelectorStore } from "@/store/modules/selectors";
import { Conditions, Log } from "@/types/demand-log";
import type { Conditions, Log } from "@/types/demand-log";
interface DemandLogState {
containers: Instance[];
@ -59,9 +59,7 @@ export const demandLogStore = defineStore({
this.message = message || "";
},
async getInstances(id: string) {
const serviceId = this.selectorStore.currentService
? this.selectorStore.currentService.id
: id;
const serviceId = this.selectorStore.currentService ? this.selectorStore.currentService.id : id;
const res: AxiosResponse = await graphql.query("queryInstances").params({
serviceId,
duration: useAppStoreWithOut().durationTime,
@ -75,16 +73,12 @@ export const demandLogStore = defineStore({
},
async getContainers(serviceInstanceId: string) {
if (!serviceInstanceId) {
return new Promise((resolve) =>
resolve({ errors: "No service instance" })
);
return new Promise((resolve) => resolve({ errors: "No service instance" }));
}
const condition = {
serviceInstanceId,
};
const res: AxiosResponse = await graphql
.query("fetchContainers")
.params({ condition });
const res: AxiosResponse = await graphql.query("fetchContainers").params({ condition });
if (res.data.errors) {
return res.data;
@ -100,21 +94,17 @@ export const demandLogStore = defineStore({
},
async getDemandLogs() {
this.loadLogs = true;
const res: AxiosResponse = await graphql
.query("fetchDemandPodLogs")
.params({ condition: this.conditions });
const res: AxiosResponse = await graphql.query("fetchDemandPodLogs").params({ condition: this.conditions });
this.loadLogs = false;
if (res.data.errors) {
return res.data;
}
if (res.data.data.logs.errorReason) {
this.setLogs("", res.data.data.logs.errorReason);
this.setLogs([], res.data.data.logs.errorReason);
return res.data;
}
this.total = res.data.data.logs.logs.length;
const logs = res.data.data.logs.logs
.map((d: Log) => d.content)
.join("\n");
const logs = res.data.data.logs.logs.map((d: Log) => d.content).join("\n");
this.setLogs(logs);
return res.data;
},

View File

@ -15,18 +15,13 @@
* limitations under the License.
*/
import { defineStore } from "pinia";
import { Option } from "@/types/app";
import {
EBPFTaskCreationRequest,
EBPFProfilingSchedule,
EBPFTaskList,
AnalyzationTrees,
} from "@/types/ebpf";
import type { Option } from "@/types/app";
import type { EBPFTaskCreationRequest, EBPFProfilingSchedule, EBPFTaskList, AnalyzationTrees } from "@/types/ebpf";
import { store } from "@/store";
import graphql from "@/graphql";
import { AxiosResponse } from "axios";
import type { AxiosResponse } from "axios";
interface EbpfState {
taskList: EBPFTaskList[];
taskList: Array<Recordable<EBPFTaskList>>;
eBPFSchedules: EBPFProfilingSchedule[];
currentSchedule: EBPFProfilingSchedule | Record<string, never>;
analyzeTrees: AnalyzationTrees[];
@ -51,7 +46,7 @@ export const ebpfStore = defineStore({
aggregateType: "COUNT",
}),
actions: {
setSelectedTask(task: EBPFTaskList) {
setSelectedTask(task: Recordable<EBPFTaskList>) {
this.selectedTask = task || {};
},
setCurrentSchedule(s: EBPFProfilingSchedule) {
@ -61,9 +56,7 @@ export const ebpfStore = defineStore({
this.analyzeTrees = tree;
},
async getCreateTaskData(serviceId: string) {
const res: AxiosResponse = await graphql
.query("getCreateTaskData")
.params({ serviceId });
const res: AxiosResponse = await graphql.query("getCreateTaskData").params({ serviceId });
if (res.data.errors) {
return res.data;
@ -76,9 +69,7 @@ export const ebpfStore = defineStore({
return res.data;
},
async createTask(param: EBPFTaskCreationRequest) {
const res: AxiosResponse = await graphql
.query("saveEBPFTask")
.params({ request: param });
const res: AxiosResponse = await graphql.query("saveEBPFTask").params({ request: param });
if (res.data.errors) {
return res.data;
@ -89,17 +80,11 @@ export const ebpfStore = defineStore({
});
return res.data;
},
async getTaskList(params: {
serviceId: string;
serviceInstanceId: string;
targets: string[];
}) {
async getTaskList(params: { serviceId: string; targets: string[] }) {
if (!params.serviceId) {
return new Promise((resolve) => resolve({}));
}
const res: AxiosResponse = await graphql
.query("getEBPFTasks")
.params(params);
const res: AxiosResponse = await graphql.query("getEBPFTasks").params(params);
this.tip = "";
if (res.data.errors) {
@ -111,16 +96,14 @@ export const ebpfStore = defineStore({
if (!this.taskList.length) {
return res.data;
}
this.getEBPFSchedules({ taskId: this.taskList[0].taskId });
this.getEBPFSchedules({ taskId: String(this.taskList[0].taskId) });
return res.data;
},
async getEBPFSchedules(params: { taskId: string }) {
if (!params.taskId) {
return new Promise((resolve) => resolve({}));
}
const res: AxiosResponse = await graphql
.query("getEBPFSchedules")
.params({ ...params });
const res: AxiosResponse = await graphql.query("getEBPFSchedules").params({ ...params });
if (res.data.errors) {
this.eBPFSchedules = [];
@ -148,9 +131,7 @@ export const ebpfStore = defineStore({
if (!params.timeRanges.length) {
return new Promise((resolve) => resolve({}));
}
const res: AxiosResponse = await graphql
.query("getEBPFResult")
.params(params);
const res: AxiosResponse = await graphql.query("getEBPFResult").params(params);
if (res.data.errors) {
this.analyzeTrees = [];

View File

@ -17,9 +17,9 @@
import { defineStore } from "pinia";
import { store } from "@/store";
import graphql from "@/graphql";
import { AxiosResponse } from "axios";
import { Event, QueryEventCondition } from "@/types/events";
import { Instance, Endpoint } from "@/types/selector";
import type { AxiosResponse } from "axios";
import type { Event, QueryEventCondition } from "@/types/events";
import type { Instance, Endpoint } from "@/types/selector";
import { useAppStoreWithOut } from "@/store/modules/app";
import { useSelectorStore } from "@/store/modules/selectors";
@ -45,9 +45,7 @@ export const eventStore = defineStore({
this.condition = data;
},
async getInstances() {
const serviceId = useSelectorStore().currentService
? useSelectorStore().currentService.id
: "";
const serviceId = useSelectorStore().currentService ? useSelectorStore().currentService.id : "";
const res: AxiosResponse = await graphql.query("queryInstances").params({
serviceId,
duration: useAppStoreWithOut().durationTime,
@ -56,15 +54,11 @@ export const eventStore = defineStore({
if (res.data.errors) {
return res.data;
}
this.instances = [{ value: "", label: "All" }, ...res.data.data.pods] || [
{ value: "", label: "All" },
];
this.instances = [{ value: "", label: "All" }, ...res.data.data.pods] || [{ value: "", label: "All" }];
return res.data;
},
async getEndpoints() {
const serviceId = useSelectorStore().currentService
? useSelectorStore().currentService.id
: "";
const serviceId = useSelectorStore().currentService ? useSelectorStore().currentService.id : "";
if (!serviceId) {
return;
}
@ -76,9 +70,7 @@ export const eventStore = defineStore({
if (res.data.errors) {
return res.data;
}
this.endpoints = [{ value: "", label: "All" }, ...res.data.data.pods] || [
{ value: "", label: "All" },
];
this.endpoints = [{ value: "", label: "All" }, ...res.data.data.pods] || [{ value: "", label: "All" }];
return res.data;
},
async getEvents() {
@ -94,22 +86,20 @@ export const eventStore = defineStore({
return res.data;
}
if (res.data.data.fetchEvents) {
this.events = (res.data.data.fetchEvents.events || []).map(
(item: Event) => {
let scope = "Service";
if (item.source.serviceInstance) {
scope = "ServiceInstance";
}
if (item.source.endpoint) {
scope = "Endpoint";
}
item.scope = scope;
if (!item.endTime || item.endTime === item.startTime) {
item.endTime = Number(item.startTime) + 60000;
}
return item;
this.events = (res.data.data.fetchEvents.events || []).map((item: Event) => {
let scope = "Service";
if (item.source.serviceInstance) {
scope = "ServiceInstance";
}
);
if (item.source.endpoint) {
scope = "Endpoint";
}
item.scope = scope;
if (!item.endTime || item.endTime === item.startTime) {
item.endTime = Number(item.startTime) + 60000;
}
return item;
});
}
return res.data;
},

View File

@ -15,10 +15,10 @@
* limitations under the License.
*/
import { defineStore } from "pinia";
import { Instance, Endpoint, Service } from "@/types/selector";
import type { Instance, Endpoint, Service } from "@/types/selector";
import { store } from "@/store";
import graphql from "@/graphql";
import { AxiosResponse } from "axios";
import type { AxiosResponse } from "axios";
import { useAppStoreWithOut } from "@/store/modules/app";
import { useSelectorStore } from "@/store/modules/selectors";
import { useDashboardStore } from "@/store/modules/dashboard";
@ -71,9 +71,7 @@ export const logStore = defineStore({
return res.data;
},
async getInstances(id: string) {
const serviceId = this.selectorStore.currentService
? this.selectorStore.currentService.id
: id;
const serviceId = this.selectorStore.currentService ? this.selectorStore.currentService.id : id;
const res: AxiosResponse = await graphql.query("queryInstances").params({
serviceId,
duration: useAppStoreWithOut().durationTime,
@ -82,16 +80,11 @@ export const logStore = defineStore({
if (res.data.errors) {
return res.data;
}
this.instances = [
{ value: "0", label: "All" },
...res.data.data.pods,
] || [{ value: " 0", label: "All" }];
this.instances = [{ value: "0", label: "All" }, ...res.data.data.pods] || [{ value: " 0", label: "All" }];
return res.data;
},
async getEndpoints(id: string, keyword?: string) {
const serviceId = this.selectorStore.currentService
? this.selectorStore.currentService.id
: id;
const serviceId = this.selectorStore.currentService ? this.selectorStore.currentService.id : id;
const res: AxiosResponse = await graphql.query("queryEndpoints").params({
serviceId,
duration: useAppStoreWithOut().durationTime,
@ -100,16 +93,11 @@ export const logStore = defineStore({
if (res.data.errors) {
return res.data;
}
this.endpoints = [
{ value: "0", label: "All" },
...res.data.data.pods,
] || [{ value: "0", label: "All" }];
this.endpoints = [{ value: "0", label: "All" }, ...res.data.data.pods] || [{ value: "0", label: "All" }];
return res.data;
},
async getLogsByKeywords() {
const res: AxiosResponse = await graphql
.query("queryLogsByKeywords")
.params({});
const res: AxiosResponse = await graphql.query("queryLogsByKeywords").params({});
if (res.data.errors) {
return res.data;
@ -127,9 +115,7 @@ export const logStore = defineStore({
},
async getServiceLogs() {
this.loadLogs = true;
const res: AxiosResponse = await graphql
.query("queryServiceLogs")
.params({ condition: this.conditions });
const res: AxiosResponse = await graphql.query("queryServiceLogs").params({ condition: this.conditions });
this.loadLogs = false;
if (res.data.errors) {
return res.data;
@ -140,9 +126,7 @@ export const logStore = defineStore({
},
async getBrowserLogs() {
this.loadLogs = true;
const res: AxiosResponse = await graphql
.query("queryBrowserErrorLogs")
.params({ condition: this.conditions });
const res: AxiosResponse = await graphql.query("queryBrowserErrorLogs").params({ condition: this.conditions });
this.loadLogs = false;
if (res.data.errors) {

View File

@ -15,16 +15,16 @@
* limitations under the License.
*/
import { defineStore } from "pinia";
import { EBPFTaskList, ProcessNode } from "@/types/ebpf";
import type { EBPFTaskList, ProcessNode } from "@/types/ebpf";
import { store } from "@/store";
import graphql from "@/graphql";
import { AxiosResponse } from "axios";
import { Call } from "@/types/topology";
import { LayoutConfig } from "@/types/dashboard";
import type { AxiosResponse } from "axios";
import type { Call } from "@/types/topology";
import type { LayoutConfig } from "@/types/dashboard";
import { ElMessage } from "element-plus";
interface NetworkProfilingState {
networkTasks: EBPFTaskList[];
networkTasks: Array<Recordable<EBPFTaskList>>;
networkTip: string;
selectedNetworkTask: Recordable<EBPFTaskList>;
nodes: ProcessNode[];
@ -55,10 +55,10 @@ export const networkProfilingStore = defineStore({
loadNodes: false,
}),
actions: {
setSelectedNetworkTask(task: EBPFTaskList) {
setSelectedNetworkTask(task: Recordable<EBPFTaskList>) {
this.selectedNetworkTask = task || {};
},
setNode(node: Node) {
setNode(node: Nullable<ProcessNode>) {
this.node = node;
},
setLink(link: Call) {
@ -117,33 +117,25 @@ export const networkProfilingStore = defineStore({
when4xx: string;
when5xx: string;
minDuration: number;
}[]
}[],
) {
const res: AxiosResponse = await graphql
.query("newNetworkProfiling")
.params({
request: {
instanceId,
samplings: params,
},
});
const res: AxiosResponse = await graphql.query("newNetworkProfiling").params({
request: {
instanceId,
samplings: params,
},
});
if (res.data.errors) {
return res.data;
}
return res.data;
},
async getTaskList(params: {
serviceId: string;
serviceInstanceId: string;
targets: string[];
}) {
async getTaskList(params: { serviceId: string; serviceInstanceId: string; targets: string[] }) {
if (!params.serviceId) {
return new Promise((resolve) => resolve({}));
}
const res: AxiosResponse = await graphql
.query("getEBPFTasks")
.params(params);
const res: AxiosResponse = await graphql.query("getEBPFTasks").params(params);
this.networkTip = "";
if (res.data.errors) {
@ -162,11 +154,8 @@ export const networkProfilingStore = defineStore({
if (!taskId) {
return new Promise((resolve) => resolve({}));
}
const res: AxiosResponse = await graphql
.query("aliveNetworkProfiling")
.params({ taskId });
const res: AxiosResponse = await graphql.query("aliveNetworkProfiling").params({ taskId });
this.aliveMessage = "";
if (res.data.errors) {
return res.data;
}
@ -176,14 +165,9 @@ export const networkProfilingStore = defineStore({
}
return res.data;
},
async getProcessTopology(params: {
duration: any;
serviceInstanceId: string;
}) {
async getProcessTopology(params: { duration: any; serviceInstanceId: string }) {
this.loadNodes = true;
const res: AxiosResponse = await graphql
.query("getProcessTopology")
.params(params);
const res: AxiosResponse = await graphql.query("getProcessTopology").params(params);
this.loadNodes = false;
if (res.data.errors) {
this.nodes = [];

View File

@ -15,18 +15,18 @@
* limitations under the License.
*/
import { defineStore } from "pinia";
import { Endpoint } from "@/types/selector";
import {
import type { Endpoint } from "@/types/selector";
import type {
TaskListItem,
SegmentSpan,
ProfileAnalyzationTrees,
TaskLog,
ProfileTaskCreationRequest,
} from "@/types/profile";
import { Trace, Span } from "@/types/trace";
import type { Trace } from "@/types/trace";
import { store } from "@/store";
import graphql from "@/graphql";
import { AxiosResponse } from "axios";
import type { AxiosResponse } from "axios";
import { useAppStoreWithOut } from "@/store/modules/app";
interface ProfileState {
@ -35,9 +35,9 @@ interface ProfileState {
condition: { serviceId: string; endpointName: string };
taskList: TaskListItem[];
segmentList: Trace[];
currentSegment: Trace | Record<string, never>;
segmentSpans: SegmentSpan[];
currentSpan: SegmentSpan | Record<string, never>;
currentSegment: Recordable<Trace>;
segmentSpans: Array<Recordable<SegmentSpan>>;
currentSpan: Recordable<SegmentSpan>;
analyzeTrees: ProfileAnalyzationTrees;
taskLogs: TaskLog[];
highlightTop: boolean;
@ -65,10 +65,10 @@ export const profileStore = defineStore({
...data,
};
},
setCurrentSpan(span: Span) {
setCurrentSpan(span: Recordable<SegmentSpan>) {
this.currentSpan = span;
},
setCurrentSegment(s: Trace) {
setCurrentSegment(s: Recordable<Trace>) {
this.currentSegment = s;
},
setHighlightTop() {
@ -99,9 +99,7 @@ export const profileStore = defineStore({
return res.data;
},
async getTaskList() {
const res: AxiosResponse = await graphql
.query("getProfileTaskList")
.params(this.condition);
const res: AxiosResponse = await graphql.query("getProfileTaskList").params(this.condition);
if (res.data.errors) {
return res.data;
@ -122,9 +120,7 @@ export const profileStore = defineStore({
if (!params.taskID) {
return new Promise((resolve) => resolve({}));
}
const res: AxiosResponse = await graphql
.query("getProfileTaskSegmentList")
.params(params);
const res: AxiosResponse = await graphql.query("getProfileTaskSegmentList").params(params);
if (res.data.errors) {
this.segmentList = [];
@ -143,7 +139,7 @@ export const profileStore = defineStore({
this.currentSegment = segmentList[0];
this.getSegmentSpans({ segmentId: segmentList[0].segmentId });
} else {
this.currentSegment = null;
this.currentSegment = {};
}
return res.data;
},
@ -151,9 +147,7 @@ export const profileStore = defineStore({
if (!params.segmentId) {
return new Promise((resolve) => resolve({}));
}
const res: AxiosResponse = await graphql
.query("queryProfileSegment")
.params(params);
const res: AxiosResponse = await graphql.query("queryProfileSegment").params(params);
if (res.data.errors) {
this.segmentSpans = [];
return res.data;
@ -167,8 +161,8 @@ export const profileStore = defineStore({
this.segmentSpans = segment.spans.map((d: SegmentSpan) => {
return {
...d,
segmentId: this.currentSegment.segmentId,
traceId: this.currentSegment.traceIds[0],
segmentId: this.currentSegment?.segmentId,
traceId: (this.currentSegment.traceIds as any)[0],
};
});
if (!(segment.spans && segment.spans.length)) {
@ -179,19 +173,14 @@ export const profileStore = defineStore({
this.currentSpan = segment.spans[index];
return res.data;
},
async getProfileAnalyze(params: {
segmentId: string;
timeRanges: Array<{ start: number; end: number }>;
}) {
async getProfileAnalyze(params: { segmentId: string; timeRanges: Array<{ start: number; end: number }> }) {
if (!params.segmentId) {
return new Promise((resolve) => resolve({}));
}
if (!params.timeRanges.length) {
return new Promise((resolve) => resolve({}));
}
const res: AxiosResponse = await graphql
.query("getProfileAnalyze")
.params(params);
const res: AxiosResponse = await graphql.query("getProfileAnalyze").params(params);
if (res.data.errors) {
this.analyzeTrees = [];
@ -211,9 +200,7 @@ export const profileStore = defineStore({
return res.data;
},
async createTask(param: ProfileTaskCreationRequest) {
const res: AxiosResponse = await graphql
.query("saveProfileTask")
.params({ creationRequest: param });
const res: AxiosResponse = await graphql.query("saveProfileTask").params({ creationRequest: param });
if (res.data.errors) {
return res.data;
@ -222,9 +209,7 @@ export const profileStore = defineStore({
return res.data;
},
async getTaskLogs(param: { taskID: string }) {
const res: AxiosResponse = await graphql
.query("getProfileTaskLogs")
.params(param);
const res: AxiosResponse = await graphql.query("getProfileTaskLogs").params(param);
if (res.data.errors) {
return res.data;

View File

@ -15,10 +15,10 @@
* limitations under the License.
*/
import { defineStore } from "pinia";
import { Service, Instance, Endpoint, Process } from "@/types/selector";
import type { Service, Instance, Endpoint, Process } from "@/types/selector";
import { store } from "@/store";
import graphql from "@/graphql";
import { AxiosResponse } from "axios";
import type { AxiosResponse } from "axios";
import { useAppStoreWithOut } from "@/store/modules/app";
interface SelectorState {
services: Service[];
@ -82,9 +82,7 @@ export const selectorStore = defineStore({
return res.data || {};
},
async fetchServices(layer: string): Promise<AxiosResponse> {
const res: AxiosResponse = await graphql
.query("queryServices")
.params({ layer });
const res: AxiosResponse = await graphql.query("queryServices").params({ layer });
if (!res.data.errors) {
this.services = res.data.data.services || [];
@ -92,10 +90,7 @@ export const selectorStore = defineStore({
}
return res.data;
},
async getServiceInstances(param?: {
serviceId: string;
isRelation: boolean;
}): Promise<Nullable<AxiosResponse>> {
async getServiceInstances(param?: { serviceId: string; isRelation: boolean }): Promise<Nullable<AxiosResponse>> {
const serviceId = param ? param.serviceId : this.currentService?.id;
if (!serviceId) {
return null;
@ -113,10 +108,7 @@ export const selectorStore = defineStore({
}
return res.data;
},
async getProcesses(param?: {
instanceId: string;
isRelation: boolean;
}): Promise<Nullable<AxiosResponse>> {
async getProcesses(param?: { instanceId: string; isRelation: boolean }): Promise<Nullable<AxiosResponse>> {
const instanceId = param ? param.instanceId : this.currentPod?.id;
if (!instanceId) {
return null;

View File

@ -16,12 +16,12 @@
*/
import { defineStore } from "pinia";
import { store } from "@/store";
import { Service } from "@/types/selector";
import { Node, Call } from "@/types/topology";
import type { Service } from "@/types/selector";
import type { Node, Call } from "@/types/topology";
import graphql from "@/graphql";
import { useSelectorStore } from "@/store/modules/selectors";
import { useAppStoreWithOut } from "@/store/modules/app";
import { AxiosResponse } from "axios";
import type { AxiosResponse } from "axios";
import query from "@/graphql/fetch";
import { useQueryTopologyMetrics } from "@/hooks/useMetricsProcessor";
import { ElMessage } from "element-plus";
@ -105,21 +105,19 @@ export const topologyStore = defineStore({
this.calls = calls;
this.nodes = nodes;
},
setNodeMetricValue(m: { id: string; value: unknown }[]) {
setNodeMetricValue(m: MetricVal) {
this.nodeMetricValue = m;
},
setLinkServerMetrics(m: { id: string; value: unknown }[]) {
setLinkServerMetrics(m: MetricVal) {
this.linkServerMetrics = m;
},
setLinkClientMetrics(m: { id: string; value: unknown }[]) {
setLinkClientMetrics(m: MetricVal) {
this.linkClientMetrics = m;
},
async getDepthServiceTopology(serviceIds: string[], depth: number) {
const res = await this.getServicesTopology(serviceIds);
if (depth > 1) {
const ids = (res.nodes || [])
.map((item: Node) => item.id)
.filter((d: string) => !serviceIds.includes(d));
const ids = (res.nodes || []).map((item: Node) => item.id).filter((d: string) => !serviceIds.includes(d));
if (!ids.length) {
this.setTopology(res);
return;
@ -139,9 +137,7 @@ export const topologyStore = defineStore({
if (depth > 3) {
const services = topo.nodes
.map((item: Node) => item.id)
.filter(
(d: string) => ![...ids, ...pods, ...serviceIds].includes(d)
);
.filter((d: string) => ![...ids, ...pods, ...serviceIds].includes(d));
if (!services.length) {
const nodes = [...res.nodes, ...json.nodes, ...topo.nodes];
const calls = [...res.calls, ...json.calls, ...topo.calls];
@ -152,55 +148,20 @@ export const topologyStore = defineStore({
if (depth > 4) {
const nodeIds = data.nodes
.map((item: Node) => item.id)
.filter(
(d: string) =>
![...services, ...ids, ...pods, ...serviceIds].includes(d)
);
.filter((d: string) => ![...services, ...ids, ...pods, ...serviceIds].includes(d));
if (!nodeIds.length) {
const nodes = [
...res.nodes,
...json.nodes,
...topo.nodes,
...data.nodes,
];
const calls = [
...res.calls,
...json.calls,
...topo.calls,
...data.calls,
];
const nodes = [...res.nodes, ...json.nodes, ...topo.nodes, ...data.nodes];
const calls = [...res.calls, ...json.calls, ...topo.calls, ...data.calls];
this.setTopology({ nodes, calls });
return;
}
const toposObj = await this.getServicesTopology(nodeIds);
const nodes = [
...res.nodes,
...json.nodes,
...topo.nodes,
...data.nodes,
...toposObj.nodes,
];
const calls = [
...res.calls,
...json.calls,
...topo.calls,
...data.calls,
...toposObj.calls,
];
const nodes = [...res.nodes, ...json.nodes, ...topo.nodes, ...data.nodes, ...toposObj.nodes];
const calls = [...res.calls, ...json.calls, ...topo.calls, ...data.calls, ...toposObj.calls];
this.setTopology({ nodes, calls });
} else {
const nodes = [
...res.nodes,
...json.nodes,
...topo.nodes,
...data.nodes,
];
const calls = [
...res.calls,
...json.calls,
...topo.calls,
...data.calls,
];
const nodes = [...res.nodes, ...json.nodes, ...topo.nodes, ...data.nodes];
const calls = [...res.calls, ...json.calls, ...topo.calls, ...data.calls];
this.setTopology({ nodes, calls });
}
} else {
@ -220,12 +181,10 @@ export const topologyStore = defineStore({
},
async getServicesTopology(serviceIds: string[]) {
const duration = useAppStoreWithOut().durationTime;
const res: AxiosResponse = await graphql
.query("getServicesTopology")
.params({
serviceIds,
duration,
});
const res: AxiosResponse = await graphql.query("getServicesTopology").params({
serviceIds,
duration,
});
if (res.data.errors) {
return res.data;
}
@ -235,13 +194,11 @@ export const topologyStore = defineStore({
const serverServiceId = useSelectorStore().currentService.id;
const clientServiceId = useSelectorStore().currentDestService.id;
const duration = useAppStoreWithOut().durationTime;
const res: AxiosResponse = await graphql
.query("getInstanceTopology")
.params({
clientServiceId,
serverServiceId,
duration,
});
const res: AxiosResponse = await graphql.query("getInstanceTopology").params({
clientServiceId,
serverServiceId,
duration,
});
if (!res.data.errors) {
this.setInstanceTopology(res.data.data.topology);
}
@ -250,9 +207,7 @@ export const topologyStore = defineStore({
async updateEndpointTopology(endpointIds: string[], depth: number) {
const res = await this.getEndpointTopology(endpointIds);
if (depth > 1) {
const ids = res.nodes
.map((item: Node) => item.id)
.filter((d: string) => !endpointIds.includes(d));
const ids = res.nodes.map((item: Node) => item.id).filter((d: string) => !endpointIds.includes(d));
if (!ids.length) {
this.setTopology(res);
return;
@ -272,9 +227,7 @@ export const topologyStore = defineStore({
if (depth > 3) {
const endpoints = topo.nodes
.map((item: Node) => item.id)
.filter(
(d: string) => ![...ids, ...pods, ...endpointIds].includes(d)
);
.filter((d: string) => ![...ids, ...pods, ...endpointIds].includes(d));
if (!endpoints.length) {
const nodes = [...res.nodes, ...json.nodes, ...topo.nodes];
const calls = [...res.calls, ...json.calls, ...topo.calls];
@ -285,55 +238,20 @@ export const topologyStore = defineStore({
if (depth > 4) {
const nodeIds = data.nodes
.map((item: Node) => item.id)
.filter(
(d: string) =>
![...endpoints, ...ids, ...pods, ...endpointIds].includes(d)
);
.filter((d: string) => ![...endpoints, ...ids, ...pods, ...endpointIds].includes(d));
if (!nodeIds.length) {
const nodes = [
...res.nodes,
...json.nodes,
...topo.nodes,
...data.nodes,
];
const calls = [
...res.calls,
...json.calls,
...topo.calls,
...data.calls,
];
const nodes = [...res.nodes, ...json.nodes, ...topo.nodes, ...data.nodes];
const calls = [...res.calls, ...json.calls, ...topo.calls, ...data.calls];
this.setTopology({ nodes, calls });
return;
}
const toposObj = await this.getEndpointTopology(nodeIds);
const nodes = [
...res.nodes,
...json.nodes,
...topo.nodes,
...data.nodes,
...toposObj.nodes,
];
const calls = [
...res.calls,
...json.calls,
...topo.calls,
...data.calls,
...toposObj.calls,
];
const nodes = [...res.nodes, ...json.nodes, ...topo.nodes, ...data.nodes, ...toposObj.nodes];
const calls = [...res.calls, ...json.calls, ...topo.calls, ...data.calls, ...toposObj.calls];
this.setTopology({ nodes, calls });
} else {
const nodes = [
...res.nodes,
...json.nodes,
...topo.nodes,
...data.nodes,
];
const calls = [
...res.calls,
...json.calls,
...topo.calls,
...data.calls,
];
const nodes = [...res.nodes, ...json.nodes, ...topo.nodes, ...data.nodes];
const calls = [...res.calls, ...json.calls, ...topo.calls, ...data.calls];
this.setTopology({ nodes, calls });
}
} else {
@ -390,10 +308,7 @@ export const topologyStore = defineStore({
return { calls, nodes };
},
async getNodeMetricValue(param: {
queryStr: string;
conditions: { [key: string]: unknown };
}) {
async getNodeMetricValue(param: { queryStr: string; conditions: { [key: string]: unknown } }) {
const res: AxiosResponse = await query(param);
if (res.data.errors) {
@ -407,9 +322,7 @@ export const topologyStore = defineStore({
this.setLinkClientMetrics({});
return;
}
const idsC = this.calls
.filter((i: Call) => i.detectPoints.includes("CLIENT"))
.map((b: Call) => b.id);
const idsC = this.calls.filter((i: Call) => i.detectPoints.includes("CLIENT")).map((b: Call) => b.id);
if (!idsC.length) {
return;
}
@ -425,9 +338,7 @@ export const topologyStore = defineStore({
this.setLinkServerMetrics({});
return;
}
const idsS = this.calls
.filter((i: Call) => i.detectPoints.includes("SERVER"))
.map((b: Call) => b.id);
const idsS = this.calls.filter((i: Call) => i.detectPoints.includes("SERVER")).map((b: Call) => b.id);
if (!idsS.length) {
return;
}
@ -454,10 +365,7 @@ export const topologyStore = defineStore({
ElMessage.error(res.errors);
}
},
async getLegendMetrics(param: {
queryStr: string;
conditions: { [key: string]: unknown };
}) {
async getLegendMetrics(param: { queryStr: string; conditions: { [key: string]: unknown } }) {
const res: AxiosResponse = await query(param);
if (res.data.errors) {
@ -477,10 +385,7 @@ export const topologyStore = defineStore({
});
return res.data;
},
async getCallServerMetrics(param: {
queryStr: string;
conditions: { [key: string]: unknown };
}) {
async getCallServerMetrics(param: { queryStr: string; conditions: { [key: string]: unknown } }) {
const res: AxiosResponse = await query(param);
if (res.data.errors) {
@ -489,10 +394,7 @@ export const topologyStore = defineStore({
this.setLinkServerMetrics(res.data.data);
return res.data;
},
async getCallClientMetrics(param: {
queryStr: string;
conditions: { [key: string]: unknown };
}) {
async getCallClientMetrics(param: { queryStr: string; conditions: { [key: string]: unknown } }) {
const res: AxiosResponse = await query(param);
if (res.data.errors) {

View File

@ -15,11 +15,11 @@
* limitations under the License.
*/
import { defineStore } from "pinia";
import { Instance, Endpoint, Service } from "@/types/selector";
import { Trace, Span } from "@/types/trace";
import type { Instance, Endpoint, Service } from "@/types/selector";
import type { Trace, Span } from "@/types/trace";
import { store } from "@/store";
import graphql from "@/graphql";
import { AxiosResponse } from "axios";
import type { AxiosResponse } from "axios";
import { useAppStoreWithOut } from "@/store/modules/app";
import { useSelectorStore } from "@/store/modules/selectors";
import { QueryOrders } from "@/views/dashboard/data";
@ -30,7 +30,7 @@ interface TraceState {
endpoints: Endpoint[];
traceList: Trace[];
traceSpans: Span[];
currentTrace: Trace | any;
currentTrace: Recordable<Trace>;
conditions: any;
traceSpanLogs: any[];
selectorStore: any;
@ -58,10 +58,10 @@ export const traceStore = defineStore({
setTraceCondition(data: any) {
this.conditions = { ...this.conditions, ...data };
},
setCurrentTrace(trace: Trace) {
setCurrentTrace(trace: Recordable<Trace>) {
this.currentTrace = trace;
},
setTraceSpans(spans: Span) {
setTraceSpans(spans: Span[]) {
this.traceSpans = spans;
},
resetState() {
@ -116,9 +116,7 @@ export const traceStore = defineStore({
return res.data;
},
async getInstances(id: string) {
const serviceId = this.selectorStore.currentService
? this.selectorStore.currentService.id
: id;
const serviceId = this.selectorStore.currentService ? this.selectorStore.currentService.id : id;
const res: AxiosResponse = await graphql.query("queryInstances").params({
serviceId: serviceId,
duration: useAppStoreWithOut().durationTime,
@ -131,9 +129,7 @@ export const traceStore = defineStore({
return res.data;
},
async getEndpoints(id: string, keyword?: string) {
const serviceId = this.selectorStore.currentService
? this.selectorStore.currentService.id
: id;
const serviceId = this.selectorStore.currentService ? this.selectorStore.currentService.id : id;
const res: AxiosResponse = await graphql.query("queryEndpoints").params({
serviceId,
duration: useAppStoreWithOut().durationTime,
@ -146,9 +142,7 @@ export const traceStore = defineStore({
return res.data;
},
async getTraces() {
const res: AxiosResponse = await graphql
.query("queryTraces")
.params({ condition: this.conditions });
const res: AxiosResponse = await graphql.query("queryTraces").params({ condition: this.conditions });
if (res.data.errors) {
return res.data;
}
@ -169,9 +163,7 @@ export const traceStore = defineStore({
return res.data;
},
async getTraceSpans(params: { traceId: string }) {
const res: AxiosResponse = await graphql
.query("queryTrace")
.params(params);
const res: AxiosResponse = await graphql.query("queryTrace").params(params);
if (res.data.errors) {
return res.data;
}
@ -180,9 +172,7 @@ export const traceStore = defineStore({
return res.data;
},
async getSpanLogs(params: any) {
const res: AxiosResponse = await graphql
.query("queryServiceLogs")
.params(params);
const res: AxiosResponse = await graphql.query("queryServiceLogs").params(params);
if (res.data.errors) {
this.traceSpanLogs = [];
return res.data;

View File

@ -20,9 +20,8 @@ body {
line-height: 1.5;
font-size: 14px;
color: #3d444f;
font-family: Helvetica, Arial, "Source Han Sans CN", "Microsoft YaHei",
sans-serif;
text-rendering: optimizeLegibility;
font-family: Helvetica, Arial, "Source Han Sans CN", "Microsoft YaHei", sans-serif;
text-rendering: optimizelegibility;
text-size-adjust: 100%;
}

View File

@ -1,6 +1,7 @@
// generated by unplugin-vue-components
// We suggest you to commit this file into source control
// Read more: https://github.com/vuejs/vue-next/pull/3399
// Read more: https://github.com/vuejs/core/pull/3399
import '@vue/runtime-core'
declare module '@vue/runtime-core' {
export interface GlobalComponents {
@ -46,4 +47,4 @@ declare module '@vue/runtime-core' {
}
}
export { }
export {}

View File

@ -1,4 +1,3 @@
import { DurationTime } from "@/types/app";
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with

View File

@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { DurationTime } from "./app";
import type { DurationTime } from "./app";
export interface Conditions {
container: string;

2
src/types/ebpf.d.ts vendored
View File

@ -15,7 +15,7 @@
* limitations under the License.
*/
import { Process } from "./selector";
import type { Process } from "./selector";
export interface EBPFTaskCreationRequest {
serviceId: string;
processLabels: string[];

View File

@ -110,7 +110,5 @@ declare global {
}
declare module "vue" {
export type JSXComponent<Props = any> =
| { new (): ComponentPublicInstance<Props> }
| FunctionalComponent<Props>;
export type JSXComponent<Props = any> = { new (): ComponentPublicInstance<Props> } | FunctionalComponent<Props>;
}

View File

@ -38,7 +38,6 @@ declare interface ComponentElRef<T extends HTMLElement = HTMLDivElement> {
$el: T;
}
declare type ComponentRef<T extends HTMLElement = HTMLDivElement> =
ComponentElRef<T> | null;
declare type ComponentRef<T extends HTMLElement = HTMLDivElement> = ComponentElRef<T> | null;
declare type ElRef<T extends HTMLElement = HTMLDivElement> = Nullable<T>;

View File

@ -15,3 +15,4 @@
* limitations under the License.
*/
declare module "monaco-editor";
export {};

View File

@ -29,6 +29,7 @@ export type Instance = {
language?: string;
instanceUUID?: string;
attributes?: { name: string; value: string }[];
id?: string;
};
export type Endpoint = {

View File

@ -15,11 +15,7 @@
* limitations under the License.
*/
import dayjs from "dayjs";
export default function dateFormatStep(
date: Date,
step: string,
monthDayDiff?: boolean
): string {
export default function dateFormatStep(date: Date, step: string, monthDayDiff?: boolean): string {
const year = date.getFullYear();
const monthTemp = date.getMonth() + 1;
let month = `${monthTemp}`;
@ -101,5 +97,4 @@ export const dateFormatTime = (date: Date, step: string): string => {
return "";
};
export const dateFormat = (date: number, pattern = "YYYY-MM-DD HH:mm:ss") =>
dayjs(new Date(date)).format(pattern);
export const dateFormat = (date: number, pattern = "YYYY-MM-DD HH:mm:ss") => dayjs(new Date(date)).format(pattern);

View File

@ -39,10 +39,7 @@ export function addResizeListener(element: any, fn: () => unknown): void {
export function removeResizeListener(element: any, fn: () => unknown): void {
if (!element || !element.__resizeListeners__) return;
element.__resizeListeners__.splice(
element.__resizeListeners__.indexOf(fn),
1
);
element.__resizeListeners__.splice(element.__resizeListeners__.indexOf(fn), 1);
if (!element.__resizeListeners__.length) {
element.__ro__.disconnect();
}

View File

@ -53,12 +53,7 @@ export function isNumber(val: unknown): val is number {
}
export function isPromise<T = any>(val: unknown): val is Promise<T> {
return (
is(val, "Promise") &&
isObject(val) &&
isFunction(val.then) &&
isFunction(val.catch)
);
return is(val, "Promise") && isObject(val) && isFunction(val.then) && isFunction(val.catch);
}
export function isString(val: unknown): val is string {

View File

@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Duration } from "@/types/app";
import type { Duration } from "@/types/app";
import { TimeType } from "@/constants/data";
const timeFormat = (time: Date[]): Duration => {

View File

@ -17,11 +17,7 @@
class Vec2 extends Float32Array {
constructor(v?: unknown, y?: unknown) {
super(2);
if (
v instanceof Vec2 ||
v instanceof Float32Array ||
(v instanceof Array && v.length == 2)
) {
if (v instanceof Vec2 || v instanceof Float32Array || (v instanceof Array && v.length == 2)) {
this[0] = v[0];
this[1] = v[1];
} else if (typeof v === "number" && typeof y === "number") {

View File

@ -17,19 +17,11 @@
class Vec3 extends Float32Array {
constructor(v?: unknown, y?: unknown, z?: unknown) {
super(3);
if (
v instanceof Vec3 ||
v instanceof Float32Array ||
(v instanceof Array && v.length == 3)
) {
if (v instanceof Vec3 || v instanceof Float32Array || (v instanceof Array && v.length == 3)) {
this[0] = v[0];
this[1] = v[1];
this[2] = v[2];
} else if (
typeof v === "number" &&
typeof y === "number" &&
typeof z === "number"
) {
} else if (typeof v === "number" && typeof y === "number" && typeof z === "number") {
this[0] = v;
this[1] = y;
this[2] = z;
@ -158,17 +150,9 @@ class Vec3 extends Float32Array {
}
static norm(x: unknown, y: unknown, z: unknown): Vec3 {
const rtn = new Vec3();
if (
x instanceof Vec3 ||
x instanceof Float32Array ||
(x instanceof Array && x.length == 3)
) {
if (x instanceof Vec3 || x instanceof Float32Array || (x instanceof Array && x.length == 3)) {
rtn.copy(x);
} else if (
typeof x === "number" &&
typeof y === "number" &&
typeof z === "number"
) {
} else if (typeof x === "number" && typeof y === "number" && typeof z === "number") {
rtn.xyz(x, y, z);
}
return rtn.norm();

View File

@ -19,17 +19,17 @@ limitations under the License. -->
</div>
</template>
<script lang="ts" setup>
import { useAppStoreWithOut } from "@/store/modules/app";
import Header from "./alarm/Header.vue";
import Content from "./alarm/Content.vue";
import { useAppStoreWithOut } from "@/store/modules/app";
import Header from "./alarm/Header.vue";
import Content from "./alarm/Content.vue";
const appStore = useAppStoreWithOut();
appStore.setPageTitle("Alerting");
const appStore = useAppStoreWithOut();
appStore.setPageTitle("Alerting");
</script>
<style lang="scss" scoped>
.alarm {
flex-grow: 1;
height: 100%;
font-size: 12px;
}
.alarm {
flex-grow: 1;
height: 100%;
font-size: 12px;
}
</style>

View File

@ -19,18 +19,18 @@ limitations under the License. -->
</div>
</template>
<script lang="ts" setup>
import { useAppStoreWithOut } from "@/store/modules/app";
import Header from "./event/Header.vue";
import Content from "./event/Content.vue";
import { useAppStoreWithOut } from "@/store/modules/app";
import Header from "./event/Header.vue";
import Content from "./event/Content.vue";
const appStore = useAppStoreWithOut();
const appStore = useAppStoreWithOut();
appStore.setPageTitle("Events");
appStore.setPageTitle("Events");
</script>
<style lang="scss" scoped>
.event {
flex-grow: 1;
height: 100%;
font-size: 12px;
}
.event {
flex-grow: 1;
height: 100%;
font-size: 12px;
}
</style>

View File

@ -14,54 +14,50 @@ See the License for the specific language governing permissions and
limitations under the License. -->
<template>
<Dashboard v-if="dashboardStore.currentDashboard" />
<div v-else class="no-root">
{{ t("noRoot") }} {{ dashboardStore.layerId }}
</div>
<div v-else class="no-root"> {{ t("noRoot") }} {{ dashboardStore.layerId }} </div>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import { useRoute } from "vue-router";
import { EntityType } from "./dashboard/data";
import { useDashboardStore } from "@/store/modules/dashboard";
import Dashboard from "./dashboard/Edit.vue";
import { useI18n } from "vue-i18n";
import { useAppStoreWithOut } from "@/store/modules/app";
import { ref } from "vue";
import { useRoute } from "vue-router";
import { EntityType } from "./dashboard/data";
import { useDashboardStore } from "@/store/modules/dashboard";
import Dashboard from "./dashboard/Edit.vue";
import { useI18n } from "vue-i18n";
import { useAppStoreWithOut } from "@/store/modules/app";
const route = useRoute();
const { t } = useI18n();
const appStore = useAppStoreWithOut();
const dashboardStore = useDashboardStore();
const layer = ref<string>("GENERAL");
const route = useRoute();
const { t } = useI18n();
const appStore = useAppStoreWithOut();
const dashboardStore = useDashboardStore();
const layer = ref<string>("GENERAL");
getDashboard();
getDashboard();
async function getDashboard() {
layer.value = String(route.meta.layer);
dashboardStore.setLayer(layer.value);
dashboardStore.setMode(false);
await dashboardStore.setDashboards();
const item = dashboardStore.dashboards.find(
(d: { name: string; isRoot: boolean; layer: string; entity: string }) =>
d.layer === dashboardStore.layerId &&
[EntityType[0].value, EntityType[1].value].includes(d.entity) &&
d.isRoot
);
if (!item) {
appStore.setPageTitle(dashboardStore.layer);
dashboardStore.setCurrentDashboard(null);
dashboardStore.setEntity(EntityType[1].value);
return;
async function getDashboard() {
layer.value = String(route.meta.layer);
dashboardStore.setLayer(layer.value);
dashboardStore.setMode(false);
await dashboardStore.setDashboards();
const item = dashboardStore.dashboards.find(
(d: { name: string; isRoot: boolean; layer: string; entity: string }) =>
d.layer === dashboardStore.layerId && [EntityType[0].value, EntityType[1].value].includes(d.entity) && d.isRoot,
);
if (!item) {
appStore.setPageTitle(dashboardStore.layer);
dashboardStore.setCurrentDashboard(null);
dashboardStore.setEntity(EntityType[1].value);
return;
}
dashboardStore.setEntity(item.entity);
dashboardStore.setCurrentDashboard(item);
}
dashboardStore.setEntity(item.entity);
dashboardStore.setCurrentDashboard(item);
}
</script>
<style lang="scss" scoped>
.no-root {
padding: 15px;
width: 100%;
text-align: center;
color: #888;
}
.no-root {
padding: 15px;
width: 100%;
text-align: center;
color: #888;
}
</style>

View File

@ -30,24 +30,10 @@ limitations under the License. -->
<div>
<span>UTC</span>
<span class="ml-5 mr-5">{{ utcHour >= 0 ? "+" : "" }}</span>
<input
type="number"
v-model="utcHour"
min="-12"
max="14"
class="utc-input"
@change="setUTCHour"
/>
<input type="number" v-model="utcHour" min="-12" max="14" class="utc-input" @change="setUTCHour" />
<span class="ml-5 mr-5">:</span>
<span class="utc-min">{{ utcMin > 9 || utcMin === 0 ? null : 0 }}</span>
<input
type="number"
v-model="utcMin"
min="0"
max="59"
class="utc-input"
@change="setUTCMin"
/>
<input type="number" v-model="utcMin" min="0" max="59" class="utc-input" @change="setUTCMin" />
</div>
</div>
<div class="flex-h item">
@ -55,12 +41,7 @@ limitations under the License. -->
<el-switch v-model="auto" @change="handleAuto" style="height: 25px" />
<div class="auto-time ml-5">
<span class="auto-select">
<input
type="number"
v-model="autoTime"
@change="changeAutoTime"
min="1"
/>
<input type="number" v-model="autoTime" @change="changeAutoTime" min="1" />
</span>
{{ t("second") }}
<i class="ml-10">{{ t("timeReload") }}</i>
@ -69,137 +50,136 @@ limitations under the License. -->
</div>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import { useI18n } from "vue-i18n";
import { useAppStoreWithOut } from "@/store/modules/app";
import timeFormat from "@/utils/timeFormat";
import { Languages } from "@/constants/data";
import Selector from "@/components/Selector.vue";
import getLocalTime from "@/utils/localtime";
import { ref } from "vue";
import { useI18n } from "vue-i18n";
import { useAppStoreWithOut } from "@/store/modules/app";
import timeFormat from "@/utils/timeFormat";
import { Languages } from "@/constants/data";
import Selector from "@/components/Selector.vue";
import getLocalTime from "@/utils/localtime";
const { t, locale } = useI18n();
const appStore = useAppStoreWithOut();
const lang = ref<string>(locale.value || "en");
const autoTime = ref<number>(6);
const auto = ref<boolean>(appStore.autoRefresh || false);
const utcHour = ref<number>(appStore.utcHour);
const utcMin = ref<number>(appStore.utcMin);
const { t, locale } = useI18n();
const appStore = useAppStoreWithOut();
const lang = ref<string>(locale.value || "en");
const autoTime = ref<number>(6);
const auto = ref<boolean>(appStore.autoRefresh || false);
const utcHour = ref<number>(appStore.utcHour);
const utcMin = ref<number>(appStore.utcMin);
appStore.setPageTitle("Setting");
const handleReload = () => {
const gap =
appStore.duration.end.getTime() - appStore.duration.start.getTime();
const dates: Date[] = [
getLocalTime(appStore.utc, new Date(new Date().getTime() - gap)),
getLocalTime(appStore.utc, new Date()),
];
appStore.setDuration(timeFormat(dates));
};
const handleAuto = () => {
if (autoTime.value < 1) {
return;
}
appStore.setAutoRefresh(auto.value);
if (auto.value) {
handleReload();
appStore.setReloadTimer(setInterval(handleReload, autoTime.value * 1000));
} else {
appStore.setPageTitle("Setting");
const handleReload = () => {
const gap = appStore.duration.end.getTime() - appStore.duration.start.getTime();
const dates: Date[] = [
getLocalTime(appStore.utc, new Date(new Date().getTime() - gap)),
getLocalTime(appStore.utc, new Date()),
];
appStore.setDuration(timeFormat(dates));
};
const handleAuto = () => {
if (autoTime.value < 1) {
return;
}
appStore.setAutoRefresh(auto.value);
if (auto.value) {
handleReload();
appStore.setReloadTimer(setInterval(handleReload, autoTime.value * 1000));
} else {
if (appStore.reloadTimer) {
clearInterval(appStore.reloadTimer);
}
}
};
const changeAutoTime = () => {
if (autoTime.value < 1) {
return;
}
if (appStore.reloadTimer) {
clearInterval(appStore.reloadTimer);
}
}
};
const changeAutoTime = () => {
if (autoTime.value < 1) {
return;
}
if (appStore.reloadTimer) {
clearInterval(appStore.reloadTimer);
}
if (auto.value) {
handleReload();
appStore.setReloadTimer(setInterval(handleReload, autoTime.value * 1000));
}
};
const setLang = (): void => {
locale.value = lang.value;
window.localStorage.setItem("language", lang.value);
};
const setUTCHour = () => {
if (utcHour.value < -12) {
utcHour.value = -12;
}
if (utcHour.value > 14) {
utcHour.value = 14;
}
if (isNaN(utcHour.value)) {
utcHour.value = 0;
}
appStore.setUTC(utcHour.value, utcMin.value);
};
const setUTCMin = () => {
if (utcMin.value < 0) {
utcMin.value = 0;
}
if (utcMin.value > 59) {
utcMin.value = 59;
}
if (isNaN(utcMin.value)) {
utcMin.value = 0;
}
appStore.setUTC(utcHour.value, utcMin.value);
};
if (auto.value) {
handleReload();
appStore.setReloadTimer(setInterval(handleReload, autoTime.value * 1000));
}
};
const setLang = (): void => {
locale.value = lang.value;
window.localStorage.setItem("language", lang.value);
};
const setUTCHour = () => {
if (utcHour.value < -12) {
utcHour.value = -12;
}
if (utcHour.value > 14) {
utcHour.value = 14;
}
if (isNaN(utcHour.value)) {
utcHour.value = 0;
}
appStore.setUTC(utcHour.value, utcMin.value);
};
const setUTCMin = () => {
if (utcMin.value < 0) {
utcMin.value = 0;
}
if (utcMin.value > 59) {
utcMin.value = 59;
}
if (isNaN(utcMin.value)) {
utcMin.value = 0;
}
appStore.setUTC(utcHour.value, utcMin.value);
};
</script>
<style lang="scss" scoped>
.utc-input {
color: inherit;
background: 0;
border: 0;
outline: none;
padding-bottom: 0;
}
.utc-min {
display: inline-block;
padding-top: 2px;
}
.auto-select {
border-radius: 3px;
background-color: #fff;
padding: 1px;
input {
width: 38px;
border-style: unset;
outline: 0;
}
}
.settings {
color: #606266;
font-size: 13px;
padding: 20px;
.item {
margin-top: 10px;
.utc-input {
color: inherit;
background: 0;
border: 0;
outline: none;
padding-bottom: 0;
}
input {
outline: 0;
width: 50px;
border-radius: 3px;
border: 1px solid #ccc;
text-align: center;
height: 25px;
}
.label {
width: 180px;
.utc-min {
display: inline-block;
font-weight: 500;
color: #000;
line-height: 25px;
padding-top: 2px;
}
.auto-select {
border-radius: 3px;
background-color: #fff;
padding: 1px;
input {
width: 38px;
border-style: unset;
outline: 0;
}
}
.settings {
color: #606266;
font-size: 13px;
padding: 20px;
.item {
margin-top: 10px;
}
input {
outline: 0;
width: 50px;
border-radius: 3px;
border: 1px solid #ccc;
text-align: center;
height: 25px;
}
.label {
width: 180px;
display: inline-block;
font-weight: 500;
color: #000;
line-height: 25px;
}
}
}
</style>

View File

@ -14,11 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License. -->
<template>
<div class="timeline-table clear">
<div
v-for="(i, index) in alarmStore.alarms"
:key="index"
class="clear timeline-item"
>
<div v-for="(i, index) in alarmStore.alarms" :key="index" class="clear timeline-item">
<div class="g-sm-3 grey sm hide-xs time-line tr">
{{ dateFormat(parseInt(i.startTime)) }}
</div>
@ -50,11 +46,7 @@ limitations under the License. -->
:destroy-on-close="true"
@closed="isShowDetails = false"
>
<div
class="mb-10 clear alarm-detail"
v-for="(item, index) in AlarmDetailCol"
:key="index"
>
<div class="mb-10 clear alarm-detail" v-for="(item, index) in AlarmDetailCol" :key="index">
<span class="g-sm-2 grey">{{ t(item.value) }}:</span>
<span v-if="item.label === 'startTime'">
{{ dateFormat(currentDetail[item.label]) }}
@ -66,24 +58,12 @@ limitations under the License. -->
<div>
<ul>
<li>
<span
v-for="(i, index) of EventsDetailHeaders"
:class="i.class"
:key="i.class + index"
>
<span v-for="(i, index) of EventsDetailHeaders" :class="i.class" :key="i.class + index">
{{ t(i.text) }}
</span>
</li>
<li
v-for="event in currentEvents"
:key="event.uuid"
@click="viewEventDetail(event)"
>
<span
v-for="(d, index) of EventsDetailHeaders"
:class="d.class"
:key="event.uuid + index"
>
<li v-for="event in currentEvents" :key="event.uuid" @click="viewEventDetail(event)">
<span v-for="(d, index) of EventsDetailHeaders" :class="d.class" :key="event.uuid + index">
<span v-if="d.class === 'startTime' || d.class === 'endTime'">
{{ dateFormat(event[d.class]) }}
</span>
@ -106,29 +86,16 @@ limitations under the License. -->
@closed="showEventDetails = false"
>
<div class="event-detail">
<div
class="mb-10"
v-for="(eventKey, index) in EventsDetailKeys"
:key="index"
>
<div class="mb-10" v-for="(eventKey, index) in EventsDetailKeys" :key="index">
<span class="keys">{{ t(eventKey.text) }}</span>
<span v-if="eventKey.class === 'parameters'">
<span v-for="(d, index) of currentEvent[eventKey.class]" :key="index">
{{ d.key }}={{ d.value }};
</span>
<span v-for="(d, index) of currentEvent[eventKey.class]" :key="index"> {{ d.key }}={{ d.value }}; </span>
</span>
<span
v-else-if="
eventKey.class === 'startTime' || eventKey.class === 'endTime'
"
>
<span v-else-if="eventKey.class === 'startTime' || eventKey.class === 'endTime'">
{{ dateFormat(currentEvent[eventKey.class]) }}
</span>
<span v-else-if="eventKey.class === 'source'" class="source">
<span
>{{ t("service") }}:
{{ currentEvent[eventKey.class].service }}</span
>
<span>{{ t("service") }}: {{ currentEvent[eventKey.class].service }}</span>
<div v-show="currentEvent[eventKey.class].endpoint">
{{ t("endpoint") }}:
{{ currentEvent[eventKey.class].endpoint }}
@ -144,45 +111,43 @@ limitations under the License. -->
</el-dialog>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import { useI18n } from "vue-i18n";
import { Alarm, Event } from "@/types/alarm";
import { useAlarmStore } from "@/store/modules/alarm";
import { EventsDetailHeaders, AlarmDetailCol, EventsDetailKeys } from "./data";
import { dateFormat } from "@/utils/dateFormat";
import { ref } from "vue";
import { useI18n } from "vue-i18n";
import type { Alarm, Event } from "@/types/alarm";
import { useAlarmStore } from "@/store/modules/alarm";
import { EventsDetailHeaders, AlarmDetailCol, EventsDetailKeys } from "./data";
import { dateFormat } from "@/utils/dateFormat";
const { t } = useI18n();
const alarmStore = useAlarmStore();
const isShowDetails = ref<boolean>(false);
const showEventDetails = ref<boolean>(false);
const currentDetail = ref<Alarm | any>({});
const alarmTags = ref<string[]>([]);
const currentEvents = ref<any[]>([]);
const currentEvent = ref<Event | any>({});
const { t } = useI18n();
const alarmStore = useAlarmStore();
const isShowDetails = ref<boolean>(false);
const showEventDetails = ref<boolean>(false);
const currentDetail = ref<Alarm | any>({});
const alarmTags = ref<string[]>([]);
const currentEvents = ref<any[]>([]);
const currentEvent = ref<Event | any>({});
function showDetails(item: Alarm) {
isShowDetails.value = true;
currentDetail.value = item;
currentEvents.value = item.events;
alarmTags.value = currentDetail.value.tags.map(
(d: { key: string; value: string }) => {
function showDetails(item: Alarm) {
isShowDetails.value = true;
currentDetail.value = item;
currentEvents.value = item.events;
alarmTags.value = currentDetail.value.tags.map((d: { key: string; value: string }) => {
return `${d.key} = ${d.value}`;
}
);
}
});
}
function viewEventDetail(event: Event) {
currentEvent.value = event;
showEventDetails.value = true;
}
function viewEventDetail(event: Event) {
currentEvent.value = event;
showEventDetails.value = true;
}
</script>
<style lang="scss" scoped>
@import "../components/style.scss";
@import "../components/style.scss";
.tips {
width: 100%;
margin: 20px 0;
text-align: center;
font-size: 14px;
}
.tips {
width: 100%;
margin: 20px 0;
text-align: center;
font-size: 14px;
}
</style>

View File

@ -28,12 +28,7 @@ limitations under the License. -->
</div>
<div class="mr-10 ml-10">
<span class="grey">{{ t("searchKeyword") }}: </span>
<el-input
size="small"
v-model="keyword"
class="alarm-tool-input"
@change="refreshAlarms({ pageNum: 1 })"
/>
<el-input size="small" v-model="keyword" class="alarm-tool-input" @change="refreshAlarms({ pageNum: 1 })" />
</div>
<div class="pagination">
<el-pagination
@ -48,84 +43,79 @@ limitations under the License. -->
/>
</div>
</div>
<ConditionTags
:type="'ALARM'"
@update="(data) => refreshAlarms({ pageNum: 1, tagsMap: data.tagsMap })"
/>
<ConditionTags :type="'ALARM'" @update="(data) => refreshAlarms({ pageNum: 1, tagsMap: data.tagsMap })" />
</nav>
</template>
<script lang="ts" setup>
import { ref, computed } from "vue";
import { useI18n } from "vue-i18n";
import ConditionTags from "@/views/components/ConditionTags.vue";
import { AlarmOptions } from "./data";
import { useAppStoreWithOut } from "@/store/modules/app";
import { useAlarmStore } from "@/store/modules/alarm";
import { ElMessage } from "element-plus";
import { ref, computed } from "vue";
import { useI18n } from "vue-i18n";
import ConditionTags from "@/views/components/ConditionTags.vue";
import { AlarmOptions } from "./data";
import { useAppStoreWithOut } from "@/store/modules/app";
import { useAlarmStore } from "@/store/modules/alarm";
import { ElMessage } from "element-plus";
const appStore = useAppStoreWithOut();
const alarmStore = useAlarmStore();
const { t } = useI18n();
const pageSize = 20;
const entity = ref<string>("");
const keyword = ref<string>("");
const pageNum = ref<number>(1);
const total = computed(() =>
alarmStore.alarms.length === pageSize
? pageSize * pageNum.value + 1
: pageSize * pageNum.value
);
const appStore = useAppStoreWithOut();
const alarmStore = useAlarmStore();
const { t } = useI18n();
const pageSize = 20;
const entity = ref<string>("");
const keyword = ref<string>("");
const pageNum = ref<number>(1);
const total = computed(() =>
alarmStore.alarms.length === pageSize ? pageSize * pageNum.value + 1 : pageSize * pageNum.value,
);
refreshAlarms({ pageNum: 1 });
async function refreshAlarms(param: { pageNum: number; tagsMap?: any }) {
const params: any = {
duration: appStore.durationTime,
paging: {
pageNum: param.pageNum,
pageSize,
},
tags: param.tagsMap,
};
params.scope = entity.value || undefined;
params.keyword = keyword.value || undefined;
const res = await alarmStore.getAlarms(params);
if (res.errors) {
ElMessage.error(res.errors);
}
}
function changeEntity(param: any) {
entity.value = param[0].value;
refreshAlarms({ pageNum: 1 });
}
function changePage(p: number) {
pageNum.value = p;
refreshAlarms({ pageNum: p });
}
async function refreshAlarms(param: { pageNum: number; tagsMap?: any }) {
const params: any = {
duration: appStore.durationTime,
paging: {
pageNum: param.pageNum,
pageSize,
},
tags: param.tagsMap,
};
params.scope = entity.value || undefined;
params.keyword = keyword.value || undefined;
const res = await alarmStore.getAlarms(params);
if (res.errors) {
ElMessage.error(res.errors);
}
}
function changeEntity(param: any) {
entity.value = param[0].value;
refreshAlarms({ pageNum: 1 });
}
function changePage(p: number) {
pageNum.value = p;
refreshAlarms({ pageNum: p });
}
</script>
<style lang="scss" scoped>
.alarm-tool {
font-size: 12px;
border-bottom: 1px solid #c1c5ca41;
background-color: #f0f2f5;
padding: 10px;
position: relative;
}
.alarm-tool {
font-size: 12px;
border-bottom: 1px solid #c1c5ca41;
background-color: #f0f2f5;
padding: 10px;
position: relative;
}
.alarm-tool-input {
border-style: unset;
outline: 0;
padding: 2px 5px;
width: 250px;
border-radius: 3px;
}
.alarm-tool-input {
border-style: unset;
outline: 0;
padding: 2px 5px;
width: 250px;
border-radius: 3px;
}
.pagination {
position: absolute;
top: 10px;
right: 5px;
}
.pagination {
position: absolute;
top: 10px;
right: 5px;
}
</style>

View File

@ -42,20 +42,12 @@ limitations under the License. -->
/>
</template>
<div class="content">
<span
v-for="(item, index) in tagList"
:key="index"
@click="selectTag(item)"
class="tag-item"
>
<span v-for="(item, index) in tagList" :key="index" @click="selectTag(item)" class="tag-item">
{{ item }}
</span>
</div>
</el-popover>
<span
class="tags-tip"
:class="type !== 'ALARM' && tagArr.length ? 'link-tips' : ''"
>
<span class="tags-tip" :class="type !== 'ALARM' && tagArr.length ? 'link-tips' : ''">
<a
target="blank"
href="https://github.com/apache/skywalking/blob/master/docs/en/setup/backend/configuration-vocabulary.md"
@ -72,219 +64,219 @@ limitations under the License. -->
</div>
</template>
<script lang="ts" setup>
import { ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { useTraceStore } from "@/store/modules/trace";
import { useLogStore } from "@/store/modules/log";
import { ElMessage } from "element-plus";
import { useAppStoreWithOut } from "@/store/modules/app";
import { ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { useTraceStore } from "@/store/modules/trace";
import { useLogStore } from "@/store/modules/log";
import { ElMessage } from "element-plus";
import { useAppStoreWithOut } from "@/store/modules/app";
/*global defineEmits, defineProps */
const emit = defineEmits(["update"]);
const props = defineProps({
type: { type: String, default: "TRACE" },
});
const traceStore = useTraceStore();
const logStore = useLogStore();
const appStore = useAppStoreWithOut();
const { t } = useI18n();
const tags = ref<string>("");
const tagsList = ref<string[]>([]);
const tagArr = ref<string[]>([]);
const tagList = ref<string[]>([]);
const tagKeys = ref<string[]>([]);
const keysList = ref<string[]>([]);
const visible = ref<boolean>(false);
const tipsMap = {
LOG: "logTagsTip",
TRACE: "traceTagsTip",
ALARM: "alarmTagsTip",
};
fetchTagKeys();
function removeTags(index: number) {
tagsList.value.splice(index, 1);
updateTags();
}
function addLabels() {
if (!tags.value) {
return;
}
tagsList.value.push(tags.value);
tags.value = "";
updateTags();
}
function updateTags() {
const tagsMap = tagsList.value.map((item: string) => {
const key = item.substring(0, item.indexOf("="));
return {
key,
value: item.substring(item.indexOf("=") + 1, item.length),
};
/*global defineEmits, defineProps */
const emit = defineEmits(["update"]);
const props = defineProps({
type: { type: String, default: "TRACE" },
});
emit("update", { tagsMap, tagsList: tagsList.value });
}
async function fetchTagKeys() {
let resp: any = {};
if (props.type === "TRACE") {
resp = await traceStore.getTagKeys();
} else {
resp = await logStore.getLogTagKeys();
const traceStore = useTraceStore();
const logStore = useLogStore();
const appStore = useAppStoreWithOut();
const { t } = useI18n();
const tags = ref<string>("");
const tagsList = ref<string[]>([]);
const tagArr = ref<string[]>([]);
const tagList = ref<string[]>([]);
const tagKeys = ref<string[]>([]);
const keysList = ref<string[]>([]);
const visible = ref<boolean>(false);
const tipsMap = {
LOG: "logTagsTip",
TRACE: "traceTagsTip",
ALARM: "alarmTagsTip",
};
fetchTagKeys();
function removeTags(index: number) {
tagsList.value.splice(index, 1);
updateTags();
}
function addLabels() {
if (!tags.value) {
return;
}
tagsList.value.push(tags.value);
tags.value = "";
updateTags();
}
function updateTags() {
const tagsMap = tagsList.value.map((item: string) => {
const key = item.substring(0, item.indexOf("="));
return {
key,
value: item.substring(item.indexOf("=") + 1, item.length),
};
});
emit("update", { tagsMap, tagsList: tagsList.value });
}
async function fetchTagKeys() {
let resp: any = {};
if (props.type === "TRACE") {
resp = await traceStore.getTagKeys();
} else {
resp = await logStore.getLogTagKeys();
}
if (resp.errors) {
ElMessage.error(resp.errors);
return;
}
tagArr.value = resp.data.tagKeys;
tagKeys.value = resp.data.tagKeys;
keysList.value = resp.data.tagKeys;
searchTags();
}
if (resp.errors) {
ElMessage.error(resp.errors);
return;
}
tagArr.value = resp.data.tagKeys;
tagKeys.value = resp.data.tagKeys;
keysList.value = resp.data.tagKeys;
searchTags();
}
async function fetchTagValues() {
const param = tags.value.split("=")[0];
let resp: any = {};
if (props.type === "TRACE") {
resp = await traceStore.getTagValues(param);
} else {
resp = await logStore.getLogTagValues(param);
}
async function fetchTagValues() {
const param = tags.value.split("=")[0];
let resp: any = {};
if (props.type === "TRACE") {
resp = await traceStore.getTagValues(param);
} else {
resp = await logStore.getLogTagValues(param);
if (resp.errors) {
ElMessage.error(resp.errors);
return;
}
tagArr.value = resp.data.tagValues;
searchTags();
}
if (resp.errors) {
ElMessage.error(resp.errors);
return;
function inputTags() {
if (!tags.value) {
tagArr.value = keysList.value;
tagKeys.value = keysList.value;
tagList.value = tagArr.value;
return;
}
let search = "";
if (tags.value.includes("=")) {
search = tags.value.split("=")[1];
fetchTagValues();
} else {
search = tags.value;
}
tagList.value = tagArr.value.filter((d: string) => d.includes(search));
}
tagArr.value = resp.data.tagValues;
searchTags();
}
function inputTags() {
if (!tags.value) {
tagArr.value = keysList.value;
tagKeys.value = keysList.value;
tagList.value = tagArr.value;
return;
function addTags() {
if (!tags.value.includes("=")) {
return;
}
addLabels();
tagArr.value = tagKeys.value;
searchTags();
}
let search = "";
if (tags.value.includes("=")) {
search = tags.value.split("=")[1];
function selectTag(item: string) {
if (tags.value.includes("=")) {
const key = tags.value.split("=")[0];
tags.value = key + "=" + item;
addTags();
return;
}
tags.value = item + "=";
fetchTagValues();
} else {
search = tags.value;
}
tagList.value = tagArr.value.filter((d: string) => d.includes(search));
}
function addTags() {
if (!tags.value.includes("=")) {
return;
function searchTags() {
let search = "";
if (tags.value.includes("=")) {
search = tags.value.split("=")[1];
} else {
search = tags.value;
}
tagList.value = tagArr.value.filter((d: string) => d.includes(search));
}
addLabels();
tagArr.value = tagKeys.value;
searchTags();
}
function selectTag(item: string) {
if (tags.value.includes("=")) {
const key = tags.value.split("=")[0];
tags.value = key + "=" + item;
addTags();
return;
}
tags.value = item + "=";
fetchTagValues();
}
function searchTags() {
let search = "";
if (tags.value.includes("=")) {
search = tags.value.split("=")[1];
} else {
search = tags.value;
}
tagList.value = tagArr.value.filter((d: string) => d.includes(search));
}
watch(
() => appStore.durationTime,
() => {
fetchTagKeys();
}
);
watch(
() => appStore.durationTime,
() => {
fetchTagKeys();
},
);
</script>
<style lang="scss" scoped>
.trace-tags {
padding: 1px 5px 0 0;
border-radius: 3px;
height: 24px;
display: inline-block;
vertical-align: top;
}
.selected {
display: inline-block;
padding: 0 3px;
border-radius: 3px;
overflow: hidden;
border: 1px dashed #aaa;
font-size: 12px;
margin: 3px 2px 0 2px;
}
.trace-new-tag {
border-style: unset;
outline: 0;
padding: 2px 5px;
border-radius: 3px;
width: 250px;
}
.remove-icon {
display: inline-block;
margin-left: 3px;
cursor: pointer;
}
.tag-item {
display: inline-block;
min-width: 210px;
cursor: pointer;
margin-top: 10px;
&:hover {
color: #409eff;
}
}
.tags-tip {
color: #a7aebb;
}
.link-tips {
display: inline-block;
}
.light {
color: #3d444f;
input {
border: 1px solid #ccc;
.trace-tags {
padding: 1px 5px 0 0;
border-radius: 3px;
height: 24px;
display: inline-block;
vertical-align: top;
}
.selected {
color: #3d444f;
display: inline-block;
padding: 0 3px;
border-radius: 3px;
overflow: hidden;
border: 1px dashed #aaa;
font-size: 12px;
margin: 3px 2px 0 2px;
}
}
.icon-help {
cursor: pointer;
}
.trace-new-tag {
border-style: unset;
outline: 0;
padding: 2px 5px;
border-radius: 3px;
width: 250px;
}
.content {
width: 300px;
max-height: 400px;
overflow: auto;
}
.remove-icon {
display: inline-block;
margin-left: 3px;
cursor: pointer;
}
.tag-item {
display: inline-block;
min-width: 210px;
cursor: pointer;
margin-top: 10px;
&:hover {
color: #409eff;
}
}
.tags-tip {
color: #a7aebb;
}
.link-tips {
display: inline-block;
}
.light {
color: #3d444f;
input {
border: 1px solid #ccc;
}
.selected {
color: #3d444f;
}
}
.icon-help {
cursor: pointer;
}
.content {
width: 300px;
max-height: 400px;
overflow: auto;
}
</style>

View File

@ -33,89 +33,87 @@ limitations under the License. -->
</div>
</template>
<script lang="ts">
import { ref, defineComponent } from "vue";
import { useI18n } from "vue-i18n";
import { useRoute } from "vue-router";
import GridLayout from "./panel/Layout.vue";
import Tool from "./panel/Tool.vue";
import { useDashboardStore } from "@/store/modules/dashboard";
import { useAppStoreWithOut } from "@/store/modules/app";
import Configuration from "./configuration";
import { LayoutConfig } from "@/types/dashboard";
import { ref, defineComponent } from "vue";
import { useI18n } from "vue-i18n";
import { useRoute } from "vue-router";
import GridLayout from "./panel/Layout.vue";
import Tool from "./panel/Tool.vue";
import { useDashboardStore } from "@/store/modules/dashboard";
import { useAppStoreWithOut } from "@/store/modules/app";
import Configuration from "./configuration";
import type { LayoutConfig } from "@/types/dashboard";
export default defineComponent({
name: "Dashboard",
components: { ...Configuration, GridLayout, Tool },
setup() {
const dashboardStore = useDashboardStore();
const appStore = useAppStoreWithOut();
const { t } = useI18n();
const p = useRoute().params;
const layoutKey = ref<string>(`${p.layerId}_${p.entity}_${p.name}`);
setTemplate();
async function setTemplate() {
await dashboardStore.setDashboards();
export default defineComponent({
name: "Dashboard",
components: { ...Configuration, GridLayout, Tool },
setup() {
const dashboardStore = useDashboardStore();
const appStore = useAppStoreWithOut();
const { t } = useI18n();
const p = useRoute().params;
const layoutKey = ref<string>(`${p.layerId}_${p.entity}_${p.name}`);
setTemplate();
async function setTemplate() {
await dashboardStore.setDashboards();
if (!p.entity) {
if (!dashboardStore.currentDashboard) {
return;
if (!p.entity) {
if (!dashboardStore.currentDashboard) {
return;
}
const { layer, entity, name } = dashboardStore.currentDashboard;
layoutKey.value = `${layer}_${entity}_${name}`;
}
const { layer, entity, name } = dashboardStore.currentDashboard;
layoutKey.value = `${layer}_${entity}_${name}`;
}
const c: { configuration: string; id: string } = JSON.parse(
sessionStorage.getItem(layoutKey.value) || "{}"
);
const layout: any = c.configuration || {};
const c: { configuration: string; id: string } = JSON.parse(sessionStorage.getItem(layoutKey.value) || "{}");
const layout: any = c.configuration || {};
dashboardStore.setLayout(setWidgetsID(layout.children || []));
appStore.setPageTitle(layout.name);
if (p.entity) {
dashboardStore.setCurrentDashboard({
layer: p.layerId,
entity: p.entity,
name: p.name,
id: c.id,
isRoot: layout.isRoot,
});
dashboardStore.setLayout(setWidgetsID(layout.children || []));
appStore.setPageTitle(layout.name);
if (p.entity) {
dashboardStore.setCurrentDashboard({
layer: p.layerId,
entity: p.entity,
name: p.name,
id: c.id,
isRoot: layout.isRoot,
});
}
}
}
function setWidgetsID(widgets: LayoutConfig[]) {
for (const item of widgets) {
item.id = item.i;
if (item.type === "Tab") {
if (item.children && item.children.length) {
for (const [index, child] of item.children.entries()) {
if (child.children && child.children.length) {
child.children.map((d: { i: string; index: string } | any) => {
d.id = `${item.i}-${index}-${d.i}`;
return d;
});
function setWidgetsID(widgets: LayoutConfig[]) {
for (const item of widgets) {
item.id = item.i;
if (item.type === "Tab") {
if (item.children && item.children.length) {
for (const [index, child] of item.children.entries()) {
if (child.children && child.children.length) {
child.children.map((d: { i: string; index: string } | any) => {
d.id = `${item.i}-${index}-${d.i}`;
return d;
});
}
}
}
}
}
return widgets;
}
return widgets;
}
function handleClick(e: any) {
e.stopPropagation();
if (e.target.className === "ds-main") {
dashboardStore.activeGridItem("");
dashboardStore.selectWidget(null);
function handleClick(e: any) {
e.stopPropagation();
if (e.target.className === "ds-main") {
dashboardStore.activeGridItem("");
dashboardStore.selectWidget(null);
}
}
}
return {
t,
handleClick,
dashboardStore,
};
},
});
return {
t,
handleClick,
dashboardStore,
};
},
});
</script>
<style lang="scss" scoped>
.ds-main {
overflow: auto;
}
.ds-main {
overflow: auto;
}
</style>

View File

@ -33,9 +33,7 @@ limitations under the License. -->
{{ t("reloadDashboards") }}
</el-button>
<router-link to="/dashboard/new">
<el-button size="small" type="primary">
+ {{ t("newDashboard") }}
</el-button>
<el-button size="small" type="primary"> + {{ t("newDashboard") }} </el-button>
</router-link>
</div>
<div class="table">
@ -74,10 +72,7 @@ limitations under the License. -->
<el-button size="small" @click="handleRename(scope.row)">
{{ t("rename") }}
</el-button>
<el-popconfirm
:title="t('deleteTitle')"
@confirm="handleDelete(scope.row)"
>
<el-popconfirm :title="t('deleteTitle')" @confirm="handleDelete(scope.row)">
<template #reference>
<el-button size="small" type="danger">
{{ t("delete") }}
@ -87,11 +82,7 @@ limitations under the License. -->
<el-popconfirm
:title="t('rootTitle')"
@confirm="setRoot(scope.row)"
v-if="
[EntityType[0].value, EntityType[1].value].includes(
scope.row.entity
)
"
v-if="[EntityType[0].value, EntityType[1].value].includes(scope.row.entity)"
>
<template #reference>
<el-button size="small" style="width: 110px" type="danger">
@ -140,228 +131,189 @@ limitations under the License. -->
</div>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import { useI18n } from "vue-i18n";
import { ElMessageBox, ElMessage } from "element-plus";
import type { ElTable } from "element-plus";
import { useAppStoreWithOut } from "@/store/modules/app";
import { useDashboardStore } from "@/store/modules/dashboard";
import router from "@/router";
import { DashboardItem, LayoutConfig } from "@/types/dashboard";
import { saveFile, readFile } from "@/utils/file";
import { EntityType } from "./data";
import { isEmptyObject } from "@/utils/is";
import { ref } from "vue";
import { useI18n } from "vue-i18n";
import { ElMessageBox, ElMessage } from "element-plus";
import { ElTable } from "element-plus";
import { useAppStoreWithOut } from "@/store/modules/app";
import { useDashboardStore } from "@/store/modules/dashboard";
import router from "@/router";
import type { DashboardItem, LayoutConfig } from "@/types/dashboard";
import { saveFile, readFile } from "@/utils/file";
import { EntityType } from "./data";
import { isEmptyObject } from "@/utils/is";
/*global Nullable*/
const { t } = useI18n();
const appStore = useAppStoreWithOut();
const dashboardStore = useDashboardStore();
const pageSize = 20;
const dashboards = ref<DashboardItem[]>([]);
const searchText = ref<string>("");
const loading = ref<boolean>(false);
const currentPage = ref<number>(1);
const total = ref<number>(0);
const multipleTableRef = ref<InstanceType<typeof ElTable>>();
const multipleSelection = ref<DashboardItem[]>([]);
const dashboardFile = ref<Nullable<HTMLDivElement>>(null);
/*global Nullable*/
const { t } = useI18n();
const appStore = useAppStoreWithOut();
const dashboardStore = useDashboardStore();
const pageSize = 20;
const dashboards = ref<DashboardItem[]>([]);
const searchText = ref<string>("");
const loading = ref<boolean>(false);
const currentPage = ref<number>(1);
const total = ref<number>(0);
const multipleTableRef = ref<InstanceType<typeof ElTable>>();
const multipleSelection = ref<DashboardItem[]>([]);
const dashboardFile = ref<Nullable<HTMLDivElement>>(null);
appStore.setPageTitle("Dashboard List");
const handleSelectionChange = (val: DashboardItem[]) => {
multipleSelection.value = val;
};
setList();
async function setList() {
await dashboardStore.setDashboards();
searchDashboards(1);
}
async function importTemplates(event: any) {
const arr: any = await readFile(event);
for (const item of arr) {
const { layer, name, entity } = item.configuration;
const index = dashboardStore.dashboards.findIndex(
(d: DashboardItem) =>
d.name === name && d.entity === entity && d.layer === layer && !item.id
);
if (index > -1) {
return ElMessage.error(t("nameError"));
appStore.setPageTitle("Dashboard List");
const handleSelectionChange = (val: DashboardItem[]) => {
multipleSelection.value = val;
};
setList();
async function setList() {
await dashboardStore.setDashboards();
searchDashboards(1);
}
async function importTemplates(event: any) {
const arr: any = await readFile(event);
for (const item of arr) {
const { layer, name, entity } = item.configuration;
const index = dashboardStore.dashboards.findIndex(
(d: DashboardItem) => d.name === name && d.entity === entity && d.layer === layer && !item.id,
);
if (index > -1) {
return ElMessage.error(t("nameError"));
}
}
}
loading.value = true;
for (const item of arr) {
const { layer, name, entity, isRoot, children } = item.configuration;
const index = dashboardStore.dashboards.findIndex(
(d: DashboardItem) => d.id === item.id
);
const p: DashboardItem = {
name: name.split(" ").join("-"),
layer: layer,
entity: entity,
isRoot: false,
};
if (index > -1) {
p.id = item.id;
p.isRoot = isRoot;
loading.value = true;
for (const item of arr) {
const { layer, name, entity, isRoot, children } = item.configuration;
const index = dashboardStore.dashboards.findIndex((d: DashboardItem) => d.id === item.id);
const p: DashboardItem = {
name: name.split(" ").join("-"),
layer: layer,
entity: entity,
isRoot: false,
};
if (index > -1) {
p.id = item.id;
p.isRoot = isRoot;
}
dashboardStore.setCurrentDashboard(p);
dashboardStore.setLayout(children);
await dashboardStore.saveDashboard();
}
dashboardStore.setCurrentDashboard(p);
dashboardStore.setLayout(children);
await dashboardStore.saveDashboard();
dashboards.value = dashboardStore.dashboards;
loading.value = false;
dashboardFile.value = null;
}
dashboards.value = dashboardStore.dashboards;
loading.value = false;
dashboardFile.value = null;
}
function exportTemplates() {
if (!multipleSelection.value.length) {
return;
}
const arr = multipleSelection.value.sort(
(a: DashboardItem, b: DashboardItem) => {
function exportTemplates() {
if (!multipleSelection.value.length) {
return;
}
const arr = multipleSelection.value.sort((a: DashboardItem, b: DashboardItem) => {
return a.name.localeCompare(b.name);
}
);
const templates = arr.map((d: DashboardItem) => {
const key = [d.layer, d.entity, d.name].join("_");
const layout = JSON.parse(sessionStorage.getItem(key) || "{}");
return layout;
});
for (const item of templates) {
optimizeTemplate(item.configuration.children);
}
const name = `dashboards.json`;
saveFile(templates, name);
setTimeout(() => {
multipleTableRef.value!.clearSelection();
}, 2000);
}
function optimizeTemplate(
children: (LayoutConfig & {
moved?: boolean;
standard?: unknown;
label?: string;
value?: string;
})[]
) {
for (const child of children || []) {
delete child.moved;
delete child.activedTabIndex;
delete child.standard;
delete child.id;
delete child.label;
delete child.value;
if (isEmptyObject(child.graph)) {
delete child.graph;
}
if (child.widget) {
if (child.widget.title === "") {
delete child.widget.title;
}
if (child.widget.tips === "") {
delete child.widget.tips;
}
}
if (isEmptyObject(child.widget)) {
delete child.widget;
}
if (!(child.metrics && child.metrics.length && child.metrics[0])) {
delete child.metrics;
}
if (
!(child.metricTypes && child.metricTypes.length && child.metricTypes[0])
) {
delete child.metricTypes;
}
if (child.metricConfig && child.metricConfig.length) {
child.metricConfig.forEach((c, index) => {
if (!c.calculation) {
delete c.calculation;
}
if (!c.unit) {
delete c.unit;
}
if (!c.label) {
delete c.label;
}
if (isEmptyObject(c)) {
(child.metricConfig || []).splice(index, 1);
}
});
}
if (!(child.metricConfig && child.metricConfig.length)) {
delete child.metricConfig;
}
if (child.type === "Tab") {
for (const item of child.children || []) {
optimizeTemplate(item.children);
}
}
if (
["Trace", "Topology", "Tab", "Profile", "Ebpf", "Log"].includes(
child.type
)
) {
delete child.widget;
}
}
}
function handleEdit(row: DashboardItem) {
dashboardStore.setMode(true);
dashboardStore.setEntity(row.entity);
dashboardStore.setLayer(row.layer);
dashboardStore.setCurrentDashboard(row);
router.push(`/dashboard/${row.layer}/${row.entity}/${row.name}`);
}
function handleView(row: DashboardItem) {
dashboardStore.setMode(false);
dashboardStore.setEntity(row.entity);
dashboardStore.setLayer(row.layer);
dashboardStore.setCurrentDashboard(row);
router.push(`/dashboard/${row.layer}/${row.entity}/${row.name}`);
}
async function setRoot(row: DashboardItem) {
const items: DashboardItem[] = [];
loading.value = true;
for (const d of dashboardStore.dashboards) {
if (d.id === row.id) {
d.isRoot = !row.isRoot;
});
const templates = arr.map((d: DashboardItem) => {
const key = [d.layer, d.entity, d.name].join("_");
const layout = sessionStorage.getItem(key) || "{}";
const c = {
...JSON.parse(layout).configuration,
...d,
};
delete c.id;
const setting = {
id: d.id,
configuration: JSON.stringify(c),
};
const res = await dashboardStore.updateDashboard(setting);
if (res.data.changeTemplate.id) {
sessionStorage.setItem(
key,
JSON.stringify({
id: d.id,
configuration: c,
})
);
const layout = JSON.parse(sessionStorage.getItem(key) || "{}");
return layout;
});
for (const item of templates) {
optimizeTemplate(item.configuration.children);
}
const name = `dashboards.json`;
saveFile(templates, name);
setTimeout(() => {
multipleTableRef.value!.clearSelection();
}, 2000);
}
function optimizeTemplate(
children: (LayoutConfig & {
moved?: boolean;
standard?: unknown;
label?: string;
value?: string;
})[],
) {
for (const child of children || []) {
delete child.moved;
delete child.activedTabIndex;
delete child.standard;
delete child.id;
delete child.label;
delete child.value;
if (isEmptyObject(child.graph)) {
delete child.graph;
}
} else {
if (
d.layer === row.layer &&
[EntityType[0].value, EntityType[1].value].includes(d.entity) &&
row.isRoot === false &&
d.isRoot === true
) {
d.isRoot = false;
if (child.widget) {
if (child.widget.title === "") {
delete child.widget.title;
}
if (child.widget.tips === "") {
delete child.widget.tips;
}
}
if (isEmptyObject(child.widget)) {
delete child.widget;
}
if (!(child.metrics && child.metrics.length && child.metrics[0])) {
delete child.metrics;
}
if (!(child.metricTypes && child.metricTypes.length && child.metricTypes[0])) {
delete child.metricTypes;
}
if (child.metricConfig && child.metricConfig.length) {
child.metricConfig.forEach((c, index) => {
if (!c.calculation) {
delete c.calculation;
}
if (!c.unit) {
delete c.unit;
}
if (!c.label) {
delete c.label;
}
if (isEmptyObject(c)) {
(child.metricConfig || []).splice(index, 1);
}
});
}
if (!(child.metricConfig && child.metricConfig.length)) {
delete child.metricConfig;
}
if (child.type === "Tab") {
for (const item of child.children || []) {
optimizeTemplate(item.children);
}
}
if (["Trace", "Topology", "Tab", "Profile", "Ebpf", "Log"].includes(child.type)) {
delete child.widget;
}
}
}
function handleEdit(row: DashboardItem) {
dashboardStore.setMode(true);
dashboardStore.setEntity(row.entity);
dashboardStore.setLayer(row.layer);
dashboardStore.setCurrentDashboard(row);
router.push(`/dashboard/${row.layer}/${row.entity}/${row.name}`);
}
function handleView(row: DashboardItem) {
dashboardStore.setMode(false);
dashboardStore.setEntity(row.entity);
dashboardStore.setLayer(row.layer);
dashboardStore.setCurrentDashboard(row);
router.push(`/dashboard/${row.layer}/${row.entity}/${row.name}`);
}
async function setRoot(row: DashboardItem) {
const items: DashboardItem[] = [];
loading.value = true;
for (const d of dashboardStore.dashboards) {
if (d.id === row.id) {
d.isRoot = !row.isRoot;
const key = [d.layer, d.entity, d.name].join("_");
const layout = sessionStorage.getItem(key) || "{}";
const c = {
...JSON.parse(layout).configuration,
...d,
};
delete c.id;
const setting = {
id: d.id,
configuration: JSON.stringify(c),
@ -373,177 +325,202 @@ async function setRoot(row: DashboardItem) {
JSON.stringify({
id: d.id,
configuration: c,
})
}),
);
}
} else {
if (
d.layer === row.layer &&
[EntityType[0].value, EntityType[1].value].includes(d.entity) &&
row.isRoot === false &&
d.isRoot === true
) {
d.isRoot = false;
const key = [d.layer, d.entity, d.name].join("_");
const layout = sessionStorage.getItem(key) || "{}";
const c = {
...JSON.parse(layout).configuration,
...d,
};
const setting = {
id: d.id,
configuration: JSON.stringify(c),
};
const res = await dashboardStore.updateDashboard(setting);
if (res.data.changeTemplate.id) {
sessionStorage.setItem(
key,
JSON.stringify({
id: d.id,
configuration: c,
}),
);
}
}
}
items.push(d);
}
items.push(d);
dashboardStore.resetDashboards(items);
searchDashboards(1);
loading.value = false;
}
dashboardStore.resetDashboards(items);
searchDashboards(1);
loading.value = false;
}
function handleRename(row: DashboardItem) {
ElMessageBox.prompt("Please input dashboard name", "Edit", {
confirmButtonText: "OK",
cancelButtonText: "Cancel",
inputValue: row.name,
})
.then(({ value }) => {
updateName(row, value);
function handleRename(row: DashboardItem) {
ElMessageBox.prompt("Please input dashboard name", "Edit", {
confirmButtonText: "OK",
cancelButtonText: "Cancel",
inputValue: row.name,
})
.catch(() => {
ElMessage({
type: "info",
message: "Input canceled",
.then(({ value }) => {
updateName(row, value);
})
.catch(() => {
ElMessage({
type: "info",
message: "Input canceled",
});
});
});
}
async function updateName(d: DashboardItem, value: string) {
if (new RegExp(/\s/).test(value)) {
ElMessage.error("The name cannot contain spaces, carriage returns, etc");
return;
}
const key = [d.layer, d.entity, d.name].join("_");
const layout = sessionStorage.getItem(key) || "{}";
const c = {
...JSON.parse(layout).configuration,
...d,
name: value,
};
delete c.id;
delete c.filters;
const setting = {
id: d.id,
configuration: JSON.stringify(c),
};
loading.value = true;
const res = await dashboardStore.updateDashboard(setting);
loading.value = false;
if (!res.data.changeTemplate.id) {
return;
}
dashboardStore.setCurrentDashboard({
...d,
name: value,
});
dashboards.value = dashboardStore.dashboards.map((item: any) => {
if (dashboardStore.currentDashboard.id === item.id) {
item = dashboardStore.currentDashboard;
async function updateName(d: DashboardItem, value: string) {
if (new RegExp(/\s/).test(value)) {
ElMessage.error("The name cannot contain spaces, carriage returns, etc");
return;
}
return item;
});
dashboardStore.resetDashboards(dashboards.value);
sessionStorage.setItem("dashboards", JSON.stringify(dashboards.value));
sessionStorage.removeItem(key);
const str = [
dashboardStore.currentDashboard.layer,
dashboardStore.currentDashboard.entity,
dashboardStore.currentDashboard.name,
].join("_");
sessionStorage.setItem(
str,
JSON.stringify({
const key = [d.layer, d.entity, d.name].join("_");
const layout = sessionStorage.getItem(key) || "{}";
const c = {
...JSON.parse(layout).configuration,
...d,
name: value,
};
delete c.id;
delete c.filters;
const setting = {
id: d.id,
configuration: c,
})
);
searchText.value = "";
}
async function handleDelete(row: DashboardItem) {
dashboardStore.setCurrentDashboard(row);
loading.value = true;
await dashboardStore.deleteDashboard();
dashboards.value = dashboardStore.dashboards;
loading.value = false;
sessionStorage.setItem("dashboards", JSON.stringify(dashboards.value));
sessionStorage.removeItem(`${row.layer}_${row.entity}_${row.name}`);
}
function searchDashboards(pageIndex?: any) {
const list = JSON.parse(sessionStorage.getItem("dashboards") || "[]");
const arr = list.filter((d: { name: string }) =>
d.name.includes(searchText.value)
);
configuration: JSON.stringify(c),
};
loading.value = true;
const res = await dashboardStore.updateDashboard(setting);
loading.value = false;
if (!res.data.changeTemplate.id) {
return;
}
dashboardStore.setCurrentDashboard({
...d,
name: value,
});
dashboards.value = dashboardStore.dashboards.map((item: any) => {
if (dashboardStore.currentDashboard.id === item.id) {
item = dashboardStore.currentDashboard;
}
return item;
});
dashboardStore.resetDashboards(dashboards.value);
sessionStorage.setItem("dashboards", JSON.stringify(dashboards.value));
sessionStorage.removeItem(key);
const str = [
dashboardStore.currentDashboard.layer,
dashboardStore.currentDashboard.entity,
dashboardStore.currentDashboard.name,
].join("_");
sessionStorage.setItem(
str,
JSON.stringify({
id: d.id,
configuration: c,
}),
);
searchText.value = "";
}
async function handleDelete(row: DashboardItem) {
dashboardStore.setCurrentDashboard(row);
loading.value = true;
await dashboardStore.deleteDashboard();
dashboards.value = dashboardStore.dashboards;
loading.value = false;
sessionStorage.setItem("dashboards", JSON.stringify(dashboards.value));
sessionStorage.removeItem(`${row.layer}_${row.entity}_${row.name}`);
}
function searchDashboards(pageIndex?: any) {
const list = JSON.parse(sessionStorage.getItem("dashboards") || "[]");
const arr = list.filter((d: { name: string }) => d.name.includes(searchText.value));
total.value = arr.length;
dashboards.value = arr.filter(
(d: { name: string }, index: number) =>
index < pageIndex * pageSize && index >= (pageIndex - 1) * pageSize
);
currentPage.value = pageIndex;
}
total.value = arr.length;
dashboards.value = arr.filter(
(d: { name: string }, index: number) => index < pageIndex * pageSize && index >= (pageIndex - 1) * pageSize,
);
currentPage.value = pageIndex;
}
async function reloadTemplates() {
loading.value = true;
await dashboardStore.resetTemplates();
loading.value = false;
}
function changePage(pageIndex: number) {
currentPage.value = pageIndex;
searchDashboards(pageIndex);
}
async function reloadTemplates() {
loading.value = true;
await dashboardStore.resetTemplates();
loading.value = false;
}
function changePage(pageIndex: number) {
currentPage.value = pageIndex;
searchDashboards(pageIndex);
}
</script>
<style lang="scss" scoped>
.header {
flex-direction: row-reverse;
}
.header {
flex-direction: row-reverse;
}
.dashboard-list {
padding: 20px;
width: 100%;
overflow: hidden;
}
.dashboard-list {
padding: 20px;
width: 100%;
overflow: hidden;
}
.input-with-search {
width: 250px;
}
.input-with-search {
width: 250px;
}
.table {
padding: 20px 10px;
background-color: #fff;
box-shadow: 0px 1px 4px 0px #00000029;
border-radius: 5px;
width: 100%;
height: 100%;
overflow: auto;
}
.table {
padding: 20px 10px;
background-color: #fff;
box-shadow: 0px 1px 4px 0px #00000029;
border-radius: 5px;
width: 100%;
height: 100%;
overflow: auto;
}
.toggle-selection {
margin-top: 20px;
background-color: #fff;
}
.toggle-selection {
margin-top: 20px;
background-color: #fff;
}
.pagination {
float: right;
}
.pagination {
float: right;
}
.btn {
width: 220px;
font-size: 13px;
}
.btn {
width: 220px;
font-size: 13px;
}
.import-template {
display: none;
}
.import-template {
display: none;
}
.input-label {
line-height: 30px;
height: 30px;
width: 220px;
cursor: pointer;
}
.input-label {
line-height: 30px;
height: 30px;
width: 220px;
cursor: pointer;
}
.name {
color: #409eff;
}
.name {
color: #409eff;
}
.reload {
margin-right: 3px;
}
.reload {
margin-right: 3px;
}
.reload-btn {
display: inline-block;
margin-left: 10px;
}
.reload-btn {
display: inline-block;
margin-left: 10px;
}
</style>

View File

@ -17,11 +17,7 @@ limitations under the License. -->
<div class="title">{{ t("newDashboard") }}</div>
<div class="item">
<div class="label">{{ t("name") }}</div>
<el-input
size="default"
v-model="states.name"
placeholder="Please input name"
/>
<el-input size="default" v-model="states.name" placeholder="Please input name" />
</div>
<div class="item">
<div class="label">{{ t("layer") }}</div>
@ -51,95 +47,93 @@ limitations under the License. -->
</div>
</template>
<script lang="ts" setup>
import { reactive } from "vue";
import { useI18n } from "vue-i18n";
import router from "@/router";
import { useSelectorStore } from "@/store/modules/selectors";
import { EntityType } from "./data";
import { ElMessage } from "element-plus";
import { useAppStoreWithOut } from "@/store/modules/app";
import { useDashboardStore } from "@/store/modules/dashboard";
import { reactive } from "vue";
import { useI18n } from "vue-i18n";
import router from "@/router";
import { useSelectorStore } from "@/store/modules/selectors";
import { EntityType } from "./data";
import { ElMessage } from "element-plus";
import { useAppStoreWithOut } from "@/store/modules/app";
import { useDashboardStore } from "@/store/modules/dashboard";
const appStore = useAppStoreWithOut();
const dashboardStore = useDashboardStore();
appStore.setPageTitle("Dashboard New");
const { t } = useI18n();
const selectorStore = useSelectorStore();
const states = reactive({
name: "",
selectedLayer: "",
entity: EntityType[0].value,
layers: [],
});
setLayers();
dashboardStore.setDashboards();
const appStore = useAppStoreWithOut();
const dashboardStore = useDashboardStore();
appStore.setPageTitle("Dashboard New");
const { t } = useI18n();
const selectorStore = useSelectorStore();
const states = reactive({
name: "",
selectedLayer: "",
entity: EntityType[0].value,
layers: [],
});
setLayers();
dashboardStore.setDashboards();
const onCreate = () => {
const index = dashboardStore.dashboards.findIndex(
(d: { name: string; entity: string; layer: string }) =>
d.name === states.name &&
states.entity === d.entity &&
states.selectedLayer === d.layer
);
if (!states.name) {
ElMessage.error(t("nameEmptyError"));
return;
const onCreate = () => {
const index = dashboardStore.dashboards.findIndex(
(d: { name: string; entity: string; layer: string }) =>
d.name === states.name && states.entity === d.entity && states.selectedLayer === d.layer,
);
if (!states.name) {
ElMessage.error(t("nameEmptyError"));
return;
}
if (index > -1) {
ElMessage.error(t("nameError"));
return;
}
dashboardStore.setCurrentDashboard({
name: states.name,
entity: states.entity,
layer: states.selectedLayer,
});
const name = states.name;
const path = `/dashboard/${states.selectedLayer}/${states.entity}/${name}`;
router.push(path);
};
async function setLayers() {
const resp = await selectorStore.fetchLayers();
if (resp.errors) {
ElMessage.error(resp.errors);
}
states.selectedLayer = resp.data.layers[0];
states.layers = resp.data.layers.map((d: string) => {
return { label: d, value: d };
});
}
if (index > -1) {
ElMessage.error(t("nameError"));
return;
function changeLayer(opt: { label: string; value: string }[] | any) {
states.selectedLayer = opt[0].value;
}
dashboardStore.setCurrentDashboard({
name: states.name,
entity: states.entity,
layer: states.selectedLayer,
});
const name = states.name;
const path = `/dashboard/${states.selectedLayer}/${states.entity}/${name}`;
router.push(path);
};
async function setLayers() {
const resp = await selectorStore.fetchLayers();
if (resp.errors) {
ElMessage.error(resp.errors);
function changeEntity(opt: { label: string; value: string }[] | any) {
states.entity = opt[0].value;
}
states.selectedLayer = resp.data.layers[0];
states.layers = resp.data.layers.map((d: string) => {
return { label: d, value: d };
});
}
function changeLayer(opt: { label: string; value: string }[] | any) {
states.selectedLayer = opt[0].value;
}
function changeEntity(opt: { label: string; value: string }[] | any) {
states.entity = opt[0].value;
}
</script>
<style lang="scss" scoped>
.title {
font-size: 18px;
font-weight: bold;
padding-top: 20px;
}
.title {
font-size: 18px;
font-weight: bold;
padding-top: 20px;
}
.new-dashboard {
margin: 0 auto;
}
.new-dashboard {
margin: 0 auto;
}
.item {
margin-top: 20px;
}
.item {
margin-top: 20px;
}
.new-dashboard,
.selectors {
width: 600px;
}
.new-dashboard,
.selectors {
width: 600px;
}
.create {
width: 600px;
}
.create {
width: 600px;
}
.btn {
margin-top: 40px;
}
.btn {
margin-top: 40px;
}
</style>

View File

@ -13,12 +13,7 @@ limitations under the License. -->
<template>
<div>
<span class="label">{{ t("enableAssociate") }}</span>
<el-switch
v-model="eventAssociate"
active-text="Yes"
inactive-text="No"
@change="updateConfig"
/>
<el-switch v-model="eventAssociate" active-text="Yes" inactive-text="No" @change="updateConfig" />
</div>
<div class="footer">
<el-button size="small" @click="cancelConfig">
@ -30,53 +25,53 @@ limitations under the License. -->
</div>
</template>
<script lang="ts" setup>
import { useI18n } from "vue-i18n";
import { ref } from "vue";
import { useDashboardStore } from "@/store/modules/dashboard";
import { useI18n } from "vue-i18n";
import { ref } from "vue";
import { useDashboardStore } from "@/store/modules/dashboard";
const { t } = useI18n();
const dashboardStore = useDashboardStore();
const originConfig = dashboardStore.selectedGrid;
const eventAssociate = ref(dashboardStore.selectedGrid.eventAssociate || false);
const { t } = useI18n();
const dashboardStore = useDashboardStore();
const originConfig = dashboardStore.selectedGrid;
const eventAssociate = ref(dashboardStore.selectedGrid.eventAssociate || false);
function updateConfig() {
dashboardStore.selectedGrid = {
...dashboardStore.selectedGrid,
eventAssociate,
};
dashboardStore.selectWidget(dashboardStore.selectedGrid);
}
function updateConfig() {
dashboardStore.selectedGrid = {
...dashboardStore.selectedGrid,
eventAssociate,
};
dashboardStore.selectWidget(dashboardStore.selectedGrid);
}
function applyConfig() {
dashboardStore.setConfigPanel(false);
dashboardStore.setConfigs(dashboardStore.selectedGrid);
}
function applyConfig() {
dashboardStore.setConfigPanel(false);
dashboardStore.setConfigs(dashboardStore.selectedGrid);
}
function cancelConfig() {
dashboardStore.selectWidget(originConfig);
dashboardStore.setConfigPanel(false);
}
function cancelConfig() {
dashboardStore.selectWidget(originConfig);
dashboardStore.setConfigPanel(false);
}
</script>
<style lang="scss" scoped>
.label {
font-size: 13px;
font-weight: 500;
display: block;
margin-bottom: 5px;
}
.label {
font-size: 13px;
font-weight: 500;
display: block;
margin-bottom: 5px;
}
.item {
margin: 10px 0;
}
.item {
margin: 10px 0;
}
.footer {
position: fixed;
bottom: 0;
right: 0;
border-top: 1px solid #eee;
padding: 10px;
text-align: right;
width: 100%;
background-color: #fff;
}
.footer {
position: fixed;
bottom: 0;
right: 0;
border-top: 1px solid #eee;
padding: 10px;
text-align: right;
width: 100%;
background-color: #fff;
}
</style>

View File

@ -13,21 +13,11 @@ limitations under the License. -->
<template>
<div class="item">
<span class="label">{{ t("textUrl") }}</span>
<el-input
class="input"
v-model="url"
size="small"
@change="changeConfig({ url })"
/>
<el-input class="input" v-model="url" size="small" @change="changeConfig({ url })" />
</div>
<div class="item">
<span class="label">{{ t("content") }}</span>
<el-input
class="input"
v-model="content"
size="small"
@change="changeConfig({ content })"
/>
<el-input class="input" v-model="content" size="small" @change="changeConfig({ content })" />
</div>
<div class="item">
<span class="label">{{ t("textAlign") }}</span>
@ -85,86 +75,86 @@ limitations under the License. -->
</div>
</template>
<script lang="ts" setup>
import { useI18n } from "vue-i18n";
import { ref } from "vue";
import { useDashboardStore } from "@/store/modules/dashboard";
const { t } = useI18n();
const dashboardStore = useDashboardStore();
const originConfig = dashboardStore.selectedGrid;
const graph = originConfig.graph || {};
const url = ref(graph.url || "");
const backgroundColor = ref(graph.backgroundColor || "green");
const fontColor = ref(graph.fontColor || "white");
const content = ref<string>(graph.content || "");
const fontSize = ref<number>(graph.fontSize || 12);
const textAlign = ref(graph.textAlign || "left");
const Colors = [
{
label: "Green",
value: "green",
},
{ label: "Blue", value: "blue" },
{ label: "Red", value: "red" },
{ label: "Grey", value: "grey" },
{ label: "White", value: "white" },
{ label: "Black", value: "black" },
{ label: "Orange", value: "orange" },
];
const AlignStyle = [
{
label: "Left",
value: "left",
},
{ label: "Center", value: "center" },
{ label: "Right", value: "right" },
];
function changeConfig(param: { [key: string]: unknown }) {
const { selectedGrid } = dashboardStore;
const graph = {
...selectedGrid.graph,
...param,
};
dashboardStore.selectWidget({ ...selectedGrid, graph });
}
function applyConfig() {
dashboardStore.setConfigPanel(false);
dashboardStore.setConfigs(dashboardStore.selectedGrid);
}
import { useI18n } from "vue-i18n";
import { ref } from "vue";
import { useDashboardStore } from "@/store/modules/dashboard";
const { t } = useI18n();
const dashboardStore = useDashboardStore();
const originConfig = dashboardStore.selectedGrid;
const graph = originConfig.graph || {};
const url = ref(graph.url || "");
const backgroundColor = ref(graph.backgroundColor || "green");
const fontColor = ref(graph.fontColor || "white");
const content = ref<string>(graph.content || "");
const fontSize = ref<number>(graph.fontSize || 12);
const textAlign = ref(graph.textAlign || "left");
const Colors = [
{
label: "Green",
value: "green",
},
{ label: "Blue", value: "blue" },
{ label: "Red", value: "red" },
{ label: "Grey", value: "grey" },
{ label: "White", value: "white" },
{ label: "Black", value: "black" },
{ label: "Orange", value: "orange" },
];
const AlignStyle = [
{
label: "Left",
value: "left",
},
{ label: "Center", value: "center" },
{ label: "Right", value: "right" },
];
function changeConfig(param: { [key: string]: unknown }) {
const { selectedGrid } = dashboardStore;
const graph = {
...selectedGrid.graph,
...param,
};
dashboardStore.selectWidget({ ...selectedGrid, graph });
}
function applyConfig() {
dashboardStore.setConfigPanel(false);
dashboardStore.setConfigs(dashboardStore.selectedGrid);
}
function cancelConfig() {
dashboardStore.selectWidget(originConfig);
dashboardStore.setConfigPanel(false);
}
function cancelConfig() {
dashboardStore.selectWidget(originConfig);
dashboardStore.setConfigPanel(false);
}
</script>
<style lang="scss" scoped>
.slider {
width: 500px;
margin-top: -3px;
}
.slider {
width: 500px;
margin-top: -3px;
}
.label {
font-size: 13px;
font-weight: 500;
display: block;
margin-bottom: 5px;
}
.label {
font-size: 13px;
font-weight: 500;
display: block;
margin-bottom: 5px;
}
.input {
width: 500px;
}
.input {
width: 500px;
}
.item {
margin-bottom: 10px;
}
.item {
margin-bottom: 10px;
}
.footer {
position: fixed;
bottom: 0;
right: 0;
border-top: 1px solid #eee;
padding: 10px;
text-align: right;
width: 100%;
background-color: #fff;
}
.footer {
position: fixed;
bottom: 0;
right: 0;
border-top: 1px solid #eee;
padding: 10px;
text-align: right;
width: 100%;
background-color: #fff;
}
</style>

Some files were not shown because too many files have changed in this diff Show More