feat: 新增动态接口过滤器功能

This commit is contained in:
奔跑的面条 2022-07-05 21:44:16 +08:00
parent 2ee2783a9c
commit 47f6fc87c7
20 changed files with 541 additions and 107 deletions

View File

@ -20,6 +20,7 @@
"highlight.js": "^11.5.0", "highlight.js": "^11.5.0",
"html2canvas": "^1.4.1", "html2canvas": "^1.4.1",
"keymaster": "^1.6.2", "keymaster": "^1.6.2",
"monaco-editor": "^0.33.0",
"naive-ui": "2.30.3", "naive-ui": "2.30.3",
"pinia": "^2.0.13", "pinia": "^2.0.13",
"screenfull": "^6.0.1", "screenfull": "^6.0.1",

6
pnpm-lock.yaml generated
View File

@ -34,6 +34,7 @@ specifiers:
keymaster: ^1.6.2 keymaster: ^1.6.2
lodash: ~4.17.21 lodash: ~4.17.21
mockjs: ^1.1.0 mockjs: ^1.1.0
monaco-editor: ^0.33.0
naive-ui: 2.30.3 naive-ui: 2.30.3
pinia: ^2.0.13 pinia: ^2.0.13
plop: ^3.0.5 plop: ^3.0.5
@ -68,6 +69,7 @@ dependencies:
highlight.js: 11.5.1 highlight.js: 11.5.1
html2canvas: 1.4.1 html2canvas: 1.4.1
keymaster: 1.6.2 keymaster: 1.6.2
monaco-editor: 0.33.0
naive-ui: 2.30.3_vue@3.2.37 naive-ui: 2.30.3_vue@3.2.37
pinia: 2.0.14_vcmyupim4cga7k7f5hngmth5py pinia: 2.0.14_vcmyupim4cga7k7f5hngmth5py
screenfull: 6.0.1 screenfull: 6.0.1
@ -3756,6 +3758,10 @@ packages:
commander: 9.3.0 commander: 9.3.0
dev: true dev: true
/monaco-editor/0.33.0:
resolution: {integrity: sha512-VcRWPSLIUEgQJQIE0pVT8FcGBIgFoxz7jtqctE+IiCxWugD0DwgyQBcZBhdSrdMC84eumoqMZsGl2GTreOzwqw==}
dev: false
/ms/2.0.0: /ms/2.0.0:
resolution: {integrity: sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==} resolution: {integrity: sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==}
dev: true dev: true

View File

@ -0,0 +1,49 @@
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api.js'
export const useMonacoEditor = (language = 'json') => {
let monacoEditor: monaco.editor.IStandaloneCodeEditor | null = null
let initReadOnly = false
const updateVal = async (val: string) => {
monacoEditor?.setValue(val)
setTimeout(async () => {
initReadOnly && monacoEditor?.updateOptions({ readOnly: false })
// await monacoEditor?.getAction('editor.action.formatDocument')?.run()
initReadOnly && monacoEditor?.updateOptions({ readOnly: true })
}, 100)
}
const createEditor = (
el: HTMLElement | null,
editorOption: monaco.editor.IStandaloneEditorConstructionOptions = {}
) => {
if (monacoEditor) {
return
}
initReadOnly = !!editorOption.readOnly
monacoEditor =
el &&
monaco.editor.create(el, {
language,
minimap: { enabled: false },
theme: 'vs-dark',
multiCursorModifier: 'ctrlCmd',
scrollbar: {
verticalScrollbarSize: 8,
horizontalScrollbarSize: 8
},
tabSize: 2,
automaticLayout: true, // 自适应宽高
...editorOption
})
return monacoEditor
}
const onFormatDoc = () => {
monacoEditor?.getAction('editor.action.formatDocument').run()
}
return {
updateVal,
getEditor: () => monacoEditor,
createEditor,
onFormatDoc
}
}

View File

@ -0,0 +1,3 @@
import MonacoEditor from './index.vue';
export { MonacoEditor };

View File

@ -0,0 +1,84 @@
<template>
<div class="editor-area" :style="{ width, height }">
</div>
</template>
<script lang='ts'>
import { defineComponent, ref } from 'vue'
import { useMonacoEditor } from './index.hook'
export default defineComponent({
props: {
width: {
type: String,
default: '100%'
},
height: {
type: String,
default: '90vh'
},
language: {
type: String,
default: 'json'
},
preComment: {
type: String,
default: ''
},
modelValue: {
type: String,
default: ''
},
editorOptions: {
type: Object,
default: () => ({})
},
},
watch: {
modelValue(val) {
val !== this.getEditor()?.getValue() && this.updateMonacoVal(val)
}
},
setup(props) {
const { updateVal, getEditor, createEditor, onFormatDoc } = useMonacoEditor(props.language)
const isFull = ref(false)
return {
isFull,
updateVal,
getEditor,
createEditor,
onFormatDoc
}
},
methods: {
updateMonacoVal(_val?: string) {
const { modelValue, preComment } = this.$props
const val = preComment ? `${preComment}\n${_val || modelValue}` : (_val || modelValue)
this.updateVal(val)
}
},
mounted() {
if (this.$el) {
const monacoEditor = this.createEditor(this.$el, this.$props.editorOptions)
this.updateMonacoVal()
monacoEditor!.onDidChangeModelContent(() => {
this.$emit('update:modelValue', monacoEditor!.getValue())
})
monacoEditor!.onDidBlurEditorText(() => {
this.$emit('blur')
})
}
}
})
</script>
<style lang="scss" scoped>
.editor-area {
position: relative;
border-radius: 4px;
overflow: hidden;
padding: 5px;
padding-left: 0;
box-sizing: border-box;
}
</style>

View File

@ -20,7 +20,7 @@
<div class="content-right"> <div class="content-right">
<div class="color-name-detail"> <div class="color-name-detail">
<n-text v-if="appThemeDetail" class="color-name">{{ appThemeDetail.name }}</n-text> <n-text v-if="appThemeDetail" class="color-name">{{ appThemeDetail.name }}</n-text>
<n-text v-else="appThemeDetail" class="color-name">中国色</n-text> <n-text v-else class="color-name">中国色</n-text>
<n-text <n-text
v-if="appThemeDetail" v-if="appThemeDetail"
class="color-name-Pinyin" class="color-name-Pinyin"

View File

@ -4,11 +4,12 @@ import { http } from '@/api/http'
import { CreateComponentType, ChartFrameEnum } from '@/packages/index.d' import { CreateComponentType, ChartFrameEnum } from '@/packages/index.d'
import { useChartEditStore } from '@/store/modules/chartEditStore/chartEditStore' import { useChartEditStore } from '@/store/modules/chartEditStore/chartEditStore'
import { RequestDataTypeEnum } from '@/enums/httpEnum' import { RequestDataTypeEnum } from '@/enums/httpEnum'
import { isPreview } from '@/utils' import { isPreview, newFunctionHandle } from '@/utils'
// 获取类型 // 获取类型
type ChartEditStoreType = typeof useChartEditStore type ChartEditStoreType = typeof useChartEditStore
/** /**
* setdata * setdata
* @param targetComponent * @param targetComponent
@ -23,26 +24,23 @@ export const useChartDataFetch = (
const vChartRef = ref<typeof VChart | null>(null) const vChartRef = ref<typeof VChart | null>(null)
let fetchInterval: any = 0 let fetchInterval: any = 0
const requestInterval = () => { const requestIntervalFn = () => {
const chartEditStore = useChartEditStore() const chartEditStore = useChartEditStore()
const { requestOriginUrl, requestInterval } = toRefs( const { requestOriginUrl, requestInterval } = toRefs(chartEditStore.getRequestGlobalConfig)
chartEditStore.getRequestGlobalConfig
)
// 组件类型 // 组件类型
const { chartFrame } = targetComponent.chartConfig const { chartFrame } = targetComponent.chartConfig
// 请求配置 // 请求配置
const { requestDataType, requestHttpType, requestUrl } = toRefs( const { requestDataType, requestHttpType, requestUrl } = toRefs(targetComponent.data)
targetComponent.data
)
// 非请求类型 // 非请求类型
if (requestDataType.value !== RequestDataTypeEnum.AJAX) return if (requestDataType.value !== RequestDataTypeEnum.AJAX) return
// 处理地址 // 处理地址
if (requestUrl?.value && requestInterval.value > 0) { if (requestUrl?.value && requestInterval.value > 0) {
// requestOriginUrl 允许为空 // requestOriginUrl 允许为空
const completePath = const completePath = requestOriginUrl && requestOriginUrl.value + requestUrl.value
requestOriginUrl && requestOriginUrl.value + requestUrl.value
if (!completePath) return if (!completePath) return
clearInterval(fetchInterval)
const fetchFn = async () => { const fetchFn = async () => {
const res: any = await http(requestHttpType.value)(completePath || '', {}) const res: any = await http(requestHttpType.value)(completePath || '', {})
if (res.data) { if (res.data) {
@ -54,7 +52,8 @@ export const useChartDataFetch = (
// eCharts 组件配合 vChart 库更新方式 // eCharts 组件配合 vChart 库更新方式
if (chartFrame === ChartFrameEnum.ECHARTS) { if (chartFrame === ChartFrameEnum.ECHARTS) {
if (vChartRef.value) { if (vChartRef.value) {
vChartRef.value.setOption({ dataset: res.data }) const filter = targetComponent.filter
vChartRef.value.setOption({ dataset: newFunctionHandle(res.data, filter) })
} }
} }
} }
@ -63,16 +62,15 @@ export const useChartDataFetch = (
} }
} }
} }
// 立即调用 // 立即调用
fetchFn() fetchFn()
// 开启定时 // 开启定时
setInterval(fetchFn, requestInterval.value * 1000) fetchInterval = setInterval(fetchFn, requestInterval.value * 1000)
} }
} }
isPreview() && requestInterval() isPreview() && requestIntervalFn()
return { vChartRef } return { vChartRef }
} }

View File

@ -74,7 +74,6 @@ const dataHandle = (newData: number) => {
watch( watch(
() => props.chartConfig.option.dataset, () => props.chartConfig.option.dataset,
newData => { newData => {
console.log(dataHandle(newData))
props.chartConfig.option.series[0].data = [dataHandle(newData)] props.chartConfig.option.series[0].data = [dataHandle(newData)]
option.value = props.chartConfig.option option.value = props.chartConfig.option
}, },

View File

@ -2,9 +2,14 @@ import type { GlobalThemeJsonType } from '@/settings/chartThemes/index'
import type { RequestConfigType } from '@/store/modules/chartEditStore/chartEditStore.d' import type { RequestConfigType } from '@/store/modules/chartEditStore/chartEditStore.d'
export enum ChartFrameEnum { export enum ChartFrameEnum {
COMMON = 'common', // echarts 框架
ECHARTS = 'echarts', ECHARTS = 'echarts',
NAIVE_UI = 'naiveUI' // UI 组件框架
NAIVE_UI = 'naiveUI',
// 自定义带数据组件
COMMON = 'common',
// 无数据变更
STATIC = 'static'
} }
// 组件配置 // 组件配置
@ -77,6 +82,7 @@ export interface PublicConfigType extends requestConfig {
// 动画 // 动画
animations: string[] animations: string[]
} }
filter?: string
setPosition: Function setPosition: Function
} }

View File

@ -45,6 +45,8 @@ export class publicConfig implements PublicConfigType {
public data = { ...requestConfig } public data = { ...requestConfig }
// 数据获取 // 数据获取
public requestData = [] public requestData = []
// 数据过滤
public filter = undefined
// 设置坐标 // 设置坐标
public setPosition(x: number, y: number): void { public setPosition(x: number, y: number): void {

View File

@ -52,7 +52,8 @@ import {
ArrowBack as ArrowBackIcon, ArrowBack as ArrowBackIcon,
ArrowForward as ArrowForwardIcon, ArrowForward as ArrowForwardIcon,
Planet as PawIcon, Planet as PawIcon,
Search as SearchIcon Search as SearchIcon,
Filter as FilterIcon
} from '@vicons/ionicons5' } from '@vicons/ionicons5'
import { import {
@ -190,7 +191,9 @@ const ionicons5 = {
// 狗爪 // 狗爪
PawIcon, PawIcon,
// 搜索(放大镜) // 搜索(放大镜)
SearchIcon SearchIcon,
// 过滤器
FilterIcon
} }
const carbon = { const carbon = {

View File

@ -49,7 +49,7 @@ export const backgroundImageSize = 5
export const previewScaleType = PreviewScaleEnum.FIT export const previewScaleType = PreviewScaleEnum.FIT
// 数据请求间隔 // 数据请求间隔
export const requestInterval = 30 export const requestInterval = 5
// 工作区域历史记录存储最大数量 // 工作区域历史记录存储最大数量
export const editHistoryMax = 100 export const editHistoryMax = 100

View File

@ -167,6 +167,9 @@ export const useChartEditStore = defineStore({
}, },
// * 设置目标数据 select // * 设置目标数据 select
setTargetSelectChart(selectId?: string | string[], push: boolean = false) { setTargetSelectChart(selectId?: string | string[], push: boolean = false) {
// 重复选中
if(this.targetChart.selectId.find((e: string) => e === selectId)) return
// 无 id 清空 // 无 id 清空
if(!selectId) { if(!selectId) {
this.targetChart.selectId = [] this.targetChart.selectId = []

View File

@ -5,6 +5,8 @@ import throttle from 'lodash/throttle'
import Image_404 from '../assets/images/exception/image-404.png' import Image_404 from '../assets/images/exception/image-404.png'
import html2canvas from 'html2canvas' import html2canvas from 'html2canvas'
import { downloadByA } from './file' import { downloadByA } from './file'
import { isString } from './type'
import cloneDeep from 'lodash/cloneDeep';
/** /**
* * * *
@ -19,9 +21,7 @@ export const isDev = () => {
* @param { Number } randomLength * @param { Number } randomLength
*/ */
export const getUUID = (randomLength = 10) => { export const getUUID = (randomLength = 10) => {
return Number( return Number(Math.random().toString().substr(2, randomLength) + Date.now()).toString(36)
Math.random().toString().substr(2, randomLength) + Date.now()
).toString(36)
} }
/** /**
@ -90,10 +90,7 @@ export const screenfullFn = (isFullscreen?: boolean, isEnabled?: boolean) => {
* @param key * @param key
* @param value * @param value
*/ */
export const setDomAttribute = < export const setDomAttribute = <K extends keyof CSSStyleDeclaration, V extends CSSStyleDeclaration[K]>(
K extends keyof CSSStyleDeclaration,
V extends CSSStyleDeclaration[K]
>(
HTMLElement: HTMLElement, HTMLElement: HTMLElement,
key: K, key: K,
value: V value: V
@ -149,7 +146,7 @@ export const addEventListener = <K extends keyof WindowEventMap>(
type, type,
throttle(listener, delay || 300, { throttle(listener, delay || 300, {
leading: true, leading: true,
trailing: false, trailing: false
}), }),
options options
) )
@ -186,3 +183,34 @@ export const canvasCut = (html: HTMLElement | null, callback?: Function) => {
if (callback) callback() if (callback) callback()
}) })
} }
/**
* *
* @param data
* @param funcStr
* @param toString
* @param errorCallBack
* @param successCallBack
* @returns
*/
export const newFunctionHandle = (
data: any,
funcStr?: string,
toString?: boolean,
errorCallBack?: Function,
successCallBack?: Function
) => {
try {
if (!funcStr) return data
const fn = new Function('data', funcStr)
const fnRes = fn( cloneDeep(data))
const resHandle = toString && isString(fnRes) ? JSON.stringify(fnRes) : fnRes
// 成功回调
successCallBack && successCallBack(resHandle)
return resHandle
} catch (error) {
// 失败回调
errorCallBack && errorCallBack(error)
return '函数执行错误'
}
}

View File

@ -1,10 +1,7 @@
<template> <template>
<div class="go-chart-configurations-data-ajax"> <div class="go-chart-configurations-data-ajax">
<setting-item-box name="类型" :alone="true"> <setting-item-box name="类型" :alone="true">
<n-select <n-select v-model:value="targetData.data.requestHttpType" :options="selectOptions" />
v-model:value="targetData.data.requestHttpType"
:options="selectOptions"
/>
</setting-item-box> </setting-item-box>
<setting-item-box name="源地址:" :alone="true"> <setting-item-box name="源地址:" :alone="true">
@ -23,19 +20,26 @@
<ul class="go-pl-0"> <ul class="go-pl-0">
开发环境使用 mock 数据请输入 开发环境使用 mock 数据请输入
<li v-for="item in apiList" :key="item.value"> <li v-for="item in apiList" :key="item.value">
<n-text type="info"> {{item.value}} </n-text> <n-text type="info"> {{ item.value }} </n-text>
</li> </li>
</ul> </ul>
</n-tooltip> </n-tooltip>
</template> </template>
<n-input <n-input v-model:value.trim="targetData.data.requestUrl" :min="1" placeholder="请输入地址(去除源)" />
v-model:value.trim="targetData.data.requestUrl"
:min="1"
placeholder="请输入地址(去除源)"
/>
</setting-item-box> </setting-item-box>
<setting-item-box name="测试" :alone="true"> <setting-item-box :alone="true">
<template #name>
测试
<n-tooltip trigger="hover">
<template #trigger>
<n-icon size="21" :depth="3">
<help-outline-icon></help-outline-icon>
</n-icon>
</template>
默认赋值给 dataset 字段
</n-tooltip>
</template>
<n-space> <n-space>
<n-button @click="sendHandle"> <n-button @click="sendHandle">
<template #icon> <template #icon>
@ -48,17 +52,13 @@
</n-space> </n-space>
</setting-item-box> </setting-item-box>
<chart-data-matching-and-show :show="showMatching && !loading" :ajax="true"></chart-data-matching-and-show>
<go-skeleton :load="loading" :repeat="3"></go-skeleton> <go-skeleton :load="loading" :repeat="3"></go-skeleton>
<chart-data-matching-and-show
v-show="showMatching && !loading"
:ajax="true"
></chart-data-matching-and-show>
</div> </div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { ref, toRefs } from 'vue' import { ref, toRefs, onBeforeUnmount, watchEffect } from 'vue'
import { icon } from '@/plugins' import { icon } from '@/plugins'
import { SettingItemBox } from '@/components/Pages/ChartItemSetting' import { SettingItemBox } from '@/components/Pages/ChartItemSetting'
import { RequestHttpEnum, ResultEnum } from '@/enums/httpEnum' import { RequestHttpEnum, ResultEnum } from '@/enums/httpEnum'
@ -67,56 +67,56 @@ import { http } from '@/api/http'
import { SelectHttpType } from '../../index.d' import { SelectHttpType } from '../../index.d'
import { ChartDataMatchingAndShow } from '../ChartDataMatchingAndShow' import { ChartDataMatchingAndShow } from '../ChartDataMatchingAndShow'
import { useTargetData } from '../../../hooks/useTargetData.hook' import { useTargetData } from '../../../hooks/useTargetData.hook'
import { isDev } from '@/utils' import { isDev, newFunctionHandle } from '@/utils'
const { HelpOutlineIcon, FlashIcon } = icon.ionicons5 const { HelpOutlineIcon, FlashIcon } = icon.ionicons5
const { targetData, chartEditStore } = useTargetData() const { targetData, chartEditStore } = useTargetData()
const { requestOriginUrl } = toRefs(chartEditStore.getRequestGlobalConfig) const { requestOriginUrl } = toRefs(chartEditStore.getRequestGlobalConfig)
// //
const loading = ref(false) const loading = ref(false)
const showMatching = ref(false) const showMatching = ref(false)
let lastFilter: any = undefined
const apiList = [ const apiList = [
{ {
value: `【图表】${ chartDataUrl }` value: `【图表】${chartDataUrl}`
}, },
{ {
value: `【文本】${ textUrl }` value: `【文本】${textUrl}`
}, },
{ {
value: `【0~100 整数】${ numberIntUrl }` value: `【0~100 整数】${numberIntUrl}`
}, },
{ {
value: `【0~1小数】${ numberFloatUrl }` value: `【0~1小数】${numberFloatUrl}`
}, },
{ {
value: `【图片地址】${ imageUrl }` value: `【图片地址】${imageUrl}`
}, },
{ {
value: `【排名列表】${ rankListUrl }` value: `【排名列表】${rankListUrl}`
}, },
{ {
value: `【滚动表格】${ scrollBoardUrl }` value: `【滚动表格】${scrollBoardUrl}`
}, }
] ]
// //
const selectOptions: SelectHttpType[] = [ const selectOptions: SelectHttpType[] = [
{ {
label: RequestHttpEnum.GET, label: RequestHttpEnum.GET,
value: RequestHttpEnum.GET, value: RequestHttpEnum.GET
}, },
{ {
label: RequestHttpEnum.POST, label: RequestHttpEnum.POST,
value: RequestHttpEnum.POST, value: RequestHttpEnum.POST
}, }
] ]
// //
const sendHandle = async () => { const sendHandle = async () => {
loading.value = true loading.value = true
if(!targetData.value) return
const { requestUrl, requestHttpType } = targetData.value.data const { requestUrl, requestHttpType } = targetData.value.data
if (!requestUrl) { if (!requestUrl) {
window['$message'].warning('请求参数不正确,请检查!') window['$message'].warning('请求参数不正确,请检查!')
@ -124,17 +124,26 @@ const sendHandle = async () => {
} }
const completePath = requestOriginUrl && requestOriginUrl.value + requestUrl const completePath = requestOriginUrl && requestOriginUrl.value + requestUrl
const res = await http(requestHttpType)(completePath || '', {}) const res = await http(requestHttpType)(completePath || '', {})
setTimeout(() => { loading.value = false
loading.value = false if (res.status === ResultEnum.SUCCESS) {
if (res.status === ResultEnum.SUCCESS) { targetData.value.option.dataset = newFunctionHandle(res.data, targetData.value.filter)
// @ts-ignore showMatching.value = true
targetData.value.option.dataset = res.data return
showMatching.value = true }
return window['$message'].warning('数据异常,请检查接口数据!')
}
window['$message'].warning('数据异常,请检查接口数据!')
}, 500)
} }
watchEffect(() => {
const filter = targetData.value?.filter
if (lastFilter !== filter) {
lastFilter = filter
sendHandle()
}
})
onBeforeUnmount(() => {
lastFilter = null
})
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>

View File

@ -1,6 +1,6 @@
<template> <template>
<n-timeline class="go-chart-configurations-timeline"> <n-timeline class="go-chart-configurations-timeline">
<n-timeline-item v-if="isCharts && dimensionsAndSource" type="info" :title="TimelineTitleEnum.MAPPING"> <n-timeline-item v-show="isCharts && dimensionsAndSource" type="info" :title="TimelineTitleEnum.MAPPING">
<n-table striped> <n-table striped>
<thead> <thead>
<tr> <tr>
@ -25,6 +25,12 @@
</tbody> </tbody>
</n-table> </n-table>
</n-timeline-item> </n-timeline-item>
<n-timeline-item v-show="filterShow" color="#97846c" :title="TimelineTitleEnum.FILTER">
<n-space vertical>
<n-text depth="3">点击{{ targetData.filter ? '「编辑」' : '「新增」' }}查看过滤规则</n-text>
<chart-data-monaco-editor></chart-data-monaco-editor>
</n-space>
</n-timeline-item>
<n-timeline-item type="success" :title="TimelineTitleEnum.CONTENT"> <n-timeline-item type="success" :title="TimelineTitleEnum.CONTENT">
<n-space vertical> <n-space vertical>
<n-text depth="3">ECharts 图表需符合 ECharts-setdata 数据规范</n-text> <n-text depth="3">ECharts 图表需符合 ECharts-setdata 数据规范</n-text>
@ -55,7 +61,7 @@
</template> </template>
下载 下载
</n-button> </n-button>
<n-tooltip trigger="hover"> <n-tooltip trigger="hover">
<template #trigger> <template #trigger>
<n-icon class="go-ml-1" size="21" :depth="3"> <n-icon class="go-ml-1" size="21" :depth="3">
<help-outline-icon></help-outline-icon> <help-outline-icon></help-outline-icon>
@ -65,8 +71,8 @@
</n-tooltip> </n-tooltip>
</div> </div>
</n-space> </n-space>
<n-card> <n-card size="small">
<n-code :code="getSource" language="json"></n-code> <n-code :code="filterRes(getSource)" language="json"></n-code>
</n-card> </n-card>
</n-space> </n-space>
</n-timeline-item> </n-timeline-item>
@ -76,14 +82,21 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref, computed, watch } from 'vue' import { ref, computed, watch } from 'vue'
import { CreateComponentType, PackagesCategoryEnum } from '@/packages/index.d' import { CreateComponentType, PackagesCategoryEnum } from '@/packages/index.d'
import { RequestDataTypeEnum } from '@/enums/httpEnum'
import { icon } from '@/plugins' import { icon } from '@/plugins'
import { DataResultEnum, TimelineTitleEnum } from '../../index.d' import { DataResultEnum, TimelineTitleEnum } from '../../index.d'
import { ChartDataMonacoEditor } from '../ChartDataMonacoEditor'
import { useFile } from '../../hooks/useFile.hooks' import { useFile } from '../../hooks/useFile.hooks'
import { useTargetData } from '../../../hooks/useTargetData.hook' import { useTargetData } from '../../../hooks/useTargetData.hook'
import isObject from 'lodash/isObject' import isObject from 'lodash/isObject'
const { targetData } = useTargetData() import cloneDeep from 'lodash/cloneDeep'
const { targetData } = useTargetData()
const props = defineProps({ const props = defineProps({
show: {
type: Boolean,
required: false
},
ajax: { ajax: {
type: Boolean, type: Boolean,
required: true required: true
@ -102,6 +115,16 @@ const dimensionsAndSource = ref()
const { uploadFileListRef, customRequest, beforeUpload, download } = useFile(targetData) const { uploadFileListRef, customRequest, beforeUpload, download } = useFile(targetData)
//
const filterShow = computed(() => {
return targetData.value.data.requestDataType === RequestDataTypeEnum.AJAX
})
//
const dataToString = (str: any) => {
return isObject(str) ? JSON.stringify(str) : str
}
// //
const isCharts = computed(() => { const isCharts = computed(() => {
return targetData.value.chartConfig.package === PackagesCategoryEnum.CHARTS return targetData.value.chartConfig.package === PackagesCategoryEnum.CHARTS
@ -129,47 +152,68 @@ const dimensionsAndSourceHandle = () => {
try { try {
// //
return dimensions.value.map((dimensionsItem: string, index: number) => { return dimensions.value.map((dimensionsItem: string, index: number) => {
return index === 0 ? return index === 0
{ ? {
// //
field: '通用标识', field: '通用标识',
// //
mapping: dimensionsItem, mapping: dimensionsItem,
// //
result: DataResultEnum.NULL result: DataResultEnum.NULL
} : { }
field: `数据项-${index}`, : {
mapping: dimensionsItem, field: `数据项-${index}`,
result: matchingHandle(dimensionsItem) mapping: dimensionsItem,
} result: matchingHandle(dimensionsItem)
}
}) })
} catch (error) { } catch (error) {
return [] return []
} }
} }
watch(() => targetData.value?.option?.dataset, (newData: { //
source: any, const filterRes = (data: any) => {
dimensions: any try {
} | null) => { if(targetData.value.filter) {
if (newData && isObject(newData)) { const fn = new Function('data', targetData.value.filter)
// Echarts const res = fn(cloneDeep(data))
source.value = isCharts.value ? newData.source : newData return dataToString(res)
if (isCharts.value) {
dimensions.value = newData.dimensions
dimensionsAndSource.value = dimensionsAndSourceHandle()
} }
} else { return data
dimensionsAndSource.value = null } catch (error) {
source.value = newData return '过滤函数错误'
} }
}, { }
immediate: true
}) watch(
() => targetData.value?.option?.dataset,
(
newData: {
source: any
dimensions: any
} | null
) => {
if (newData && isObject(newData)) {
// Echarts
source.value = newData
if (isCharts.value) {
dimensions.value = newData.dimensions
dimensionsAndSource.value = dimensionsAndSourceHandle()
}
} else {
dimensionsAndSource.value = null
source.value = newData
}
},
{
immediate: true
}
)
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
@include go("chart-configurations-timeline") { @include go('chart-configurations-timeline') {
@include deep() { @include deep() {
pre { pre {
white-space: pre-wrap; white-space: pre-wrap;

View File

@ -0,0 +1,3 @@
import ChartDataMonacoEditor from './index.vue'
export { ChartDataMonacoEditor }

View File

@ -0,0 +1,195 @@
<template>
<template v-if="targetData.filter">
<n-card>
<p><span class="func-keyword">function</span>&nbsp;&nbsp;filter(data)&nbsp;&nbsp;{</p>
<!-- 函数体 -->
<div class="go-ml-4">
<n-code :code="targetData.filter" language="typescript"></n-code>
</div>
<p>}</p>
<template #footer>
<n-space justify="end">
<n-button tertiary size="small" @click="delFilter">
<template #icon>
<n-icon>
<trash-icon />
</n-icon>
</template>
删除
</n-button>
<n-button type="info" tertiary size="small" @click="addFilter">
<template #icon>
<n-icon>
<pencil-icon />
</n-icon>
</template>
编辑
</n-button>
</n-space>
</template>
</n-card>
</template>
<template v-else>
<n-space justify="space-around">
<n-button @click="addFilter">
<template #icon>
<n-icon>
<filter-icon />
</n-icon>
</template>
新增过滤器
</n-button>
</n-space>
</template>
<!-- 弹窗 -->
<n-modal class="go-chart-data-monaco-editor" v-model:show="showModal" :mask-closable="false">
<n-card :bordered="false" role="dialog" size="small" aria-modal="true" style="width: 1000px; height: 600px">
<template #header>
<n-space>
<n-text>过滤器函数编辑器</n-text>
</n-space>
</template>
<template #header-extra> </template>
<n-space size="small" vertical>
<n-space justify="space-between">
<div>
<n-space vertical>
<n-text depth="3">// => data </n-text>
<p><span class="func-keyword">function</span>&nbsp;&nbsp;filter(data)&nbsp;&nbsp;{</p>
<monaco-editor width="460px" height="380px" v-model:modelValue="filter" language="json" />
<p>}</p>
</n-space>
</div>
<n-divider vertical style="height: 480px" />
<n-scrollbar style="max-height: 480px">
<n-space :size="15" vertical>
<div class="editor-data-show">
<n-space>
<n-text depth="3">目标数据</n-text>
<n-code
:code="dataToString(targetData.option.dataset)"
language="typescript"
:word-wrap="true"
></n-code>
</n-space>
</div>
<div class="editor-data-show">
<n-space>
<n-text depth="3">过滤器结果</n-text>
<n-code :code="filterRes" language="typescript" :word-wrap="true"></n-code>
</n-space>
</div>
</n-space>
</n-scrollbar>
</n-space>
</n-space>
<template #action>
<n-space justify="space-between">
<div class="go-flex-items-center">
<n-tag :bordered="false" type="success">
<template #icon>
<n-icon :component="DocumentTextIcon" />
</template>
规则
</n-tag>
<n-text class="go-ml-2" depth="3">过滤器将对接口返回值的data字段进行处理</n-text>
</div>
<n-space>
<n-button size="medium" @click="closeFilter">取消</n-button>
<n-button size="medium" type="primary" @click="saveFilter">保存</n-button>
</n-space>
</n-space>
</template>
</n-card>
</n-modal>
</template>
<script lang="ts" setup>
import { ref, computed } from 'vue'
import { MonacoEditor } from '@/components/Pages/MonacoEditor'
import { useTargetData } from '../../../hooks/useTargetData.hook'
import { icon } from '@/plugins'
import { goDialog, isString } from '@/utils'
import cloneDeep from 'lodash/cloneDeep'
const { PencilIcon, TrashIcon, FilterIcon, DocumentTextIcon } = icon.ionicons5
const { targetData, chartEditStore } = useTargetData()
//
const showModal = ref(false)
// filter
const filter = ref(targetData.value.filter || `return data`)
//
const errorFlag = ref(false)
//
const dataToString = (str: any) => {
return isString(str) ? str : JSON.stringify(str)
}
//
const filterRes = computed(() => {
try {
const fn = new Function('data', filter.value)
const res = fn(cloneDeep(targetData.value.option.dataset))
errorFlag.value = false
return JSON.stringify(res)
} catch (error) {
errorFlag.value = true
return '过滤函数错误'
}
})
//
const addFilter = () => {
showModal.value = true
}
//
const delFilter = () => {
goDialog({
message: '是否删除过滤器',
onPositiveCallback: () => {
targetData.value.filter = undefined
}
})
}
//
const closeFilter = () => {
showModal.value = false
}
//
const saveFilter = () => {
if (errorFlag.value) {
window['$message'].error('过滤函数错误,无法进行保存')
return
}
targetData.value.filter = filter.value
closeFilter()
}
//
const filterData = (data: any) => {}
</script>
<style lang="scss" scoped>
.func-keyword {
color: #b478cf;
}
@include go('chart-data-monaco-editor') {
&.n-card.n-modal,
.n-card {
@extend .go-background-filter;
}
.editor-data-show {
@include fetch-bg-color('filter-color');
width: 420px;
padding: 20px;
border-radius: 5px;
}
}
</style>

View File

@ -1,6 +1,6 @@
<template> <template>
<div class="go-chart-configurations-data-static"> <div class="go-chart-configurations-data-static">
<chart-data-matching-and-show :ajax="false"></chart-data-matching-and-show> <chart-data-matching-and-show :show="false" :ajax="false"></chart-data-matching-and-show>
</div> </div>
</template> </template>

View File

@ -8,6 +8,7 @@ export enum DataResultEnum {
} }
export enum TimelineTitleEnum { export enum TimelineTitleEnum {
FILTER = '数据过滤',
MAPPING = '数据映射', MAPPING = '数据映射',
CONTENT = '数据内容', CONTENT = '数据内容',
} }