diff --git a/packages/core/client/package.json b/packages/core/client/package.json index 3afc5524f6..738e29cd63 100644 --- a/packages/core/client/package.json +++ b/packages/core/client/package.json @@ -10,6 +10,7 @@ "@ant-design/cssinjs": "^1.11.1", "@ant-design/icons": "^5.1.4", "@ant-design/pro-layout": "^7.16.11", + "@antv/g2plot": "^2.4.18", "@budibase/handlebars-helpers": "^0.14.0", "@ctrl/tinycolor": "^3.6.0", "@dnd-kit/core": "^5.0.1", diff --git a/packages/core/client/src/schema-component/antd/AntdSchemaComponentProvider.tsx b/packages/core/client/src/schema-component/antd/AntdSchemaComponentProvider.tsx index 45091a3c26..ba7cd194d7 100644 --- a/packages/core/client/src/schema-component/antd/AntdSchemaComponentProvider.tsx +++ b/packages/core/client/src/schema-component/antd/AntdSchemaComponentProvider.tsx @@ -13,6 +13,7 @@ import { Plugin } from '../../application/Plugin'; import * as common from '../common'; import { SchemaComponentOptions } from '../core'; import { useFilterActionProps } from './filter/useFilterActionProps'; +import { requestChartData } from './g2plot/requestChartData'; import { actionSettings } from './action'; import { formV1Settings } from './form'; @@ -24,7 +25,10 @@ import { pageSettings, pageTabSettings } from './page'; export const AntdSchemaComponentProvider = (props) => { const { children } = props; return ( - + {children} ); @@ -46,6 +50,7 @@ export class AntdSchemaComponentPlugin extends Plugin { addScopes() { this.app.addScopes({ + requestChartData, useFilterActionProps, }); } diff --git a/packages/core/client/src/schema-component/antd/g2plot/G2Plot.tsx b/packages/core/client/src/schema-component/antd/g2plot/G2Plot.tsx new file mode 100644 index 0000000000..1e36cc5b92 --- /dev/null +++ b/packages/core/client/src/schema-component/antd/g2plot/G2Plot.tsx @@ -0,0 +1,192 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + +import { + Area, + Bar, + BidirectionalBar, + Box, + Bullet, + Chord, + CirclePacking, + Column, + DualAxes, + Facet, + Funnel, + Gauge, + Heatmap, + Histogram, + Line, + Liquid, + Mix, + Pie, + Progress, + Radar, + RadialBar, + RingProgress, + Rose, + Sankey, + Scatter, + Stock, + Sunburst, + TinyArea, + TinyColumn, + TinyLine, + Treemap, + Venn, + Violin, + Waterfall, + WordCloud, +} from '@antv/g2plot'; +import { Field } from '@formily/core'; +import { observer, useField } from '@formily/react'; +import { Spin } from 'antd'; +import cls from 'classnames'; +import React, { forwardRef, useEffect, useRef } from 'react'; +import { useTranslation } from 'react-i18next'; +import { useAPIClient } from '../../../api-client'; +import { G2PlotDesigner } from './G2PlotDesigner'; + +export type ReactG2PlotProps = { + readonly className?: string; + readonly plot: any; + readonly config: O; +}; + +const plots = { + Line, + Area, + Column, + Bar, + Pie, + Rose, + WordCloud, + Scatter, + Radar, + DualAxes, + TinyLine, + TinyColumn, + TinyArea, + Histogram, + Progress, + RingProgress, + Heatmap, + Box, + Violin, + Venn, + Stock, + Funnel, + Liquid, + Bullet, + Sunburst, + Gauge, + Waterfall, + RadialBar, + BidirectionalBar, + Treemap, + Sankey, + Chord, + CirclePacking, + Mix, + Facet, +}; + +export const G2PlotRenderer = forwardRef(function (props: ReactG2PlotProps, ref: any) { + const { className, plot, config } = props; + const containerRef = useRef(undefined); + const plotRef = useRef(undefined); + + function syncRef(source, target) { + if (typeof target === 'function') { + target(source.current); + } else if (target) { + target.current = source.current; + } + } + + function renderPlot() { + if (plotRef.current) { + plotRef.current.update(config); + } else { + plotRef.current = new plot(containerRef.current, config); + plotRef?.current?.render(); + } + + syncRef(plotRef, ref); + } + + function destoryPlot() { + if (plotRef.current) { + plotRef.current.destroy(); + plotRef.current = undefined; + } + } + + useEffect(() => { + renderPlot(); + return () => destoryPlot(); + }, [config, plot]); + + return
; +}); +G2PlotRenderer.displayName = 'G2PlotRenderer'; + +export const G2Plot: any = observer( + (props: any) => { + const { plot, config } = props; + const field = useField(); + const { t } = useTranslation(); + const api = useAPIClient(); + useEffect(() => { + field.data = field.data || {}; + field.data.loading = true; + const fn = config?.data; + if (typeof fn === 'function') { + const result = fn.bind({ api })(); + if (result?.then) { + result + .then((data) => { + if (Array.isArray(data)) { + field.componentProps.config.data = data; + } + field.data.loading = false; + }) + .catch(console.error); + } else { + field.data.loading = false; + } + } else { + field.data.loading = false; + } + }, []); + + if (!plot || !config) { + return
{t('In configuration')}...
; + } + if (field?.data?.loading !== false) { + return ; + } + return ( +
+ {field.title &&

{field.title}

} + +
+ ); + }, + { displayName: 'G2Plot' }, +); + +G2Plot.Designer = G2PlotDesigner; +G2Plot.plots = plots; diff --git a/packages/core/client/src/schema-component/antd/g2plot/G2PlotDesigner.tsx b/packages/core/client/src/schema-component/antd/g2plot/G2PlotDesigner.tsx new file mode 100644 index 0000000000..7a03e1fa8c --- /dev/null +++ b/packages/core/client/src/schema-component/antd/g2plot/G2PlotDesigner.tsx @@ -0,0 +1,129 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + +import { ISchema, useField, useFieldSchema } from '@formily/react'; +import React from 'react'; +import { useTranslation } from 'react-i18next'; +import { useAPIClient } from '../../../api-client'; +import { + GeneralSchemaDesigner, + SchemaSettingsDivider, + SchemaSettingsModalItem, + SchemaSettingsRemove, +} from '../../../schema-settings'; +import { useCompile, useDesignable } from '../../hooks'; +import _ from 'lodash'; + +const validateJSON = { + validator: `{{(value, rule)=> { + if (!value) { + return ''; + } + try { + const val = JSON.parse(value); + if(!isNaN(val)) { + return false; + } + return true; + } catch(error) { + console.error(error); + return false; + } + }}}`, + message: '{{t("Invalid JSON format")}}', +}; + +export const G2PlotDesigner = () => { + const { t } = useTranslation(); + const { dn } = useDesignable(); + const fieldSchema = useFieldSchema(); + const field = useField(); + const compile = useCompile(); + const api = useAPIClient(); + return ( + + { + field.title = compile(title); + field.componentProps.plot = plot; + const conf = compile(JSON.parse(config)); + const fn = conf?.data; + if (typeof fn === 'function') { + const result = fn.bind({ api })(); + if (result?.then) { + result + .then((data) => { + if (Array.isArray(data)) { + field.componentProps.config.data = data; + } + }) + .catch(console.error); + } + } else { + field.componentProps.config = conf; + } + _.set(fieldSchema, 'title', title); + _.set(fieldSchema, 'x-component-props.plot', plot); + _.set(fieldSchema, 'x-component-props.config', JSON.parse(config)); + dn.emit('patch', { + schema: { + title, + 'x-uid': fieldSchema['x-uid'], + 'x-component-props': fieldSchema['x-component-props'], + }, + }); + dn.refresh(); + }} + /> + + + + ); +}; diff --git a/packages/core/client/src/schema-component/antd/g2plot/__tests__/g2plot.test.tsx b/packages/core/client/src/schema-component/antd/g2plot/__tests__/g2plot.test.tsx new file mode 100644 index 0000000000..42d2fc2b7d --- /dev/null +++ b/packages/core/client/src/schema-component/antd/g2plot/__tests__/g2plot.test.tsx @@ -0,0 +1,24 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + +import { render, waitFor } from '@nocobase/test/client'; +import React from 'react'; +import App1 from '../demos/demo1'; + +// jsdom does not support canvas, so we need to skip this test +describe.skip('G2Plot', () => { + it('basic', async () => { + render(); + + await waitFor(() => { + const g2plot = document.querySelector('.g2plot') as HTMLDivElement; + expect(g2plot).toBeInTheDocument(); + }); + }); +}); diff --git a/packages/core/client/src/schema-component/antd/g2plot/demos/demo1.tsx b/packages/core/client/src/schema-component/antd/g2plot/demos/demo1.tsx new file mode 100644 index 0000000000..82da7c1ce0 --- /dev/null +++ b/packages/core/client/src/schema-component/antd/g2plot/demos/demo1.tsx @@ -0,0 +1,93 @@ + + +import { + APIClient, + APIClientProvider, + CardItem, + G2Plot, + SchemaComponent, + mockAPIClient, + SchemaComponentProvider, +} from '@nocobase/client'; +import React from 'react'; + +const { apiClient, mockRequest } = mockAPIClient(); + +mockRequest.onGet('/test').reply(200, { + data: [ + { + Date: '2010-01', + scales: 1998, + }, + { + Date: '2010-02', + scales: 1850, + }, + { + Date: '2010-03', + scales: 1720, + }, + { + Date: '2010-04', + scales: 1818, + }, + { + Date: '2010-05', + scales: 1920, + }, + { + Date: '2010-06', + scales: 1802, + }, + { + Date: '2010-07', + scales: 1945, + }, + { + Date: '2010-08', + scales: 1856, + }, + { + Date: '2010-09', + scales: 2107, + }, + ], +}); + +const requestChartData = (options) => { + return async function (this: { api: APIClient }) { + const response = await this.api.request(options); + return response?.data?.data; + }; +}; + +const schema = { + type: 'void', + name: 'line', + 'x-designer': 'G2Plot.Designer', + 'x-decorator': 'CardItem', + 'x-component': 'G2Plot', + 'x-component-props': { + plot: 'Line', + config: { + data: '{{ requestChartData({ url: "/test" }) }}', + padding: 'auto', + xField: 'Date', + yField: 'scales', + xAxis: { + // type: 'timeCat', + tickCount: 5, + }, + }, + }, +}; + +export default () => { + return ( + + + + + + ); +}; diff --git a/packages/core/client/src/schema-component/antd/g2plot/index.en-US.md b/packages/core/client/src/schema-component/antd/g2plot/index.en-US.md new file mode 100644 index 0000000000..5a2cffc72e --- /dev/null +++ b/packages/core/client/src/schema-component/antd/g2plot/index.en-US.md @@ -0,0 +1,5 @@ +# G2Plot + +G2 chart. + + diff --git a/packages/core/client/src/schema-component/antd/g2plot/index.md b/packages/core/client/src/schema-component/antd/g2plot/index.md new file mode 100644 index 0000000000..7850c43764 --- /dev/null +++ b/packages/core/client/src/schema-component/antd/g2plot/index.md @@ -0,0 +1,5 @@ +# G2Plot + +G2 图表。 + + diff --git a/packages/core/client/src/schema-component/antd/g2plot/index.ts b/packages/core/client/src/schema-component/antd/g2plot/index.ts new file mode 100644 index 0000000000..2742a5549c --- /dev/null +++ b/packages/core/client/src/schema-component/antd/g2plot/index.ts @@ -0,0 +1,10 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + +export * from './G2Plot'; diff --git a/packages/core/client/src/schema-component/antd/g2plot/requestChartData.ts b/packages/core/client/src/schema-component/antd/g2plot/requestChartData.ts new file mode 100644 index 0000000000..0354ee40d7 --- /dev/null +++ b/packages/core/client/src/schema-component/antd/g2plot/requestChartData.ts @@ -0,0 +1,21 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + +import { APIClient } from '../../../api-client'; + +export const requestChartData = (options) => { + return async function (this: { api: APIClient }) { + try { + const response = await this.api.request(options); + return response?.data?.data; + } catch (error) { + return []; + } + }; +}; diff --git a/packages/core/client/src/schema-component/antd/index.ts b/packages/core/client/src/schema-component/antd/index.ts index d1082b9c80..3dc50cb58e 100644 --- a/packages/core/client/src/schema-component/antd/index.ts +++ b/packages/core/client/src/schema-component/antd/index.ts @@ -7,9 +7,9 @@ * For more information, please refer to: https://www.nocobase.com/agreement. */ +export * from './AntdSchemaComponentProvider'; export { genStyleHook } from './__builtins__'; export * from './action'; -export * from './AntdSchemaComponentProvider'; export * from './appends-tree-select'; export * from './association-field'; export * from './association-select'; @@ -24,15 +24,13 @@ export * from './color-select'; export * from './cron'; export * from './date-picker'; export * from './details'; -export * from './divider'; -export * from './error-fallback'; export * from './expand-action'; -export * from './expiresRadio'; export * from './filter'; export * from './form'; export * from './form-dialog'; export * from './form-item'; export * from './form-v2'; +export * from './g2plot'; export * from './grid'; export * from './grid-card'; export * from './icon-picker'; @@ -41,7 +39,6 @@ export * from './input-number'; export * from './list'; export * from './markdown'; export * from './menu'; -export * from './nanoid-input'; export * from './page'; export * from './pagination'; export * from './password'; @@ -60,8 +57,12 @@ export * from './table-v2'; export * from './tabs'; export * from './time-picker'; export * from './tree-select'; -export * from './unix-timestamp'; export * from './upload'; export * from './variable'; +export * from './unix-timestamp'; +export * from './nanoid-input'; +export * from './error-fallback'; +export * from './expiresRadio'; +export * from './divider'; import './index.less'; diff --git a/packages/core/server/src/plugin-manager/findPackageNames.ts b/packages/core/server/src/plugin-manager/findPackageNames.ts index 6f2d710ca6..573d53dd8e 100644 --- a/packages/core/server/src/plugin-manager/findPackageNames.ts +++ b/packages/core/server/src/plugin-manager/findPackageNames.ts @@ -35,6 +35,7 @@ async function trim(packageNames: string[]) { const excludes = [ '@nocobase/plugin-audit-logs', '@nocobase/plugin-backup-restore', + '@nocobase/plugin-charts', '@nocobase/plugin-disable-pm-add', '@nocobase/plugin-mobile-client', '@nocobase/plugin-mock-collections', diff --git a/packages/plugins/@nocobase/plugin-charts/.npmignore b/packages/plugins/@nocobase/plugin-charts/.npmignore new file mode 100644 index 0000000000..c593fe9df7 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/.npmignore @@ -0,0 +1,2 @@ +/node_modules +/src \ No newline at end of file diff --git a/packages/plugins/@nocobase/plugin-charts/LICENSE b/packages/plugins/@nocobase/plugin-charts/LICENSE new file mode 100644 index 0000000000..0ad25db4bd --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/packages/plugins/@nocobase/plugin-charts/client.d.ts b/packages/plugins/@nocobase/plugin-charts/client.d.ts new file mode 100644 index 0000000000..6c459cbac4 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/client.d.ts @@ -0,0 +1,2 @@ +export * from './dist/client'; +export { default } from './dist/client'; diff --git a/packages/plugins/@nocobase/plugin-charts/client.js b/packages/plugins/@nocobase/plugin-charts/client.js new file mode 100644 index 0000000000..b6e3be70e6 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/client.js @@ -0,0 +1 @@ +module.exports = require('./dist/client/index.js'); diff --git a/packages/plugins/@nocobase/plugin-charts/package.json b/packages/plugins/@nocobase/plugin-charts/package.json new file mode 100644 index 0000000000..ed95936698 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/package.json @@ -0,0 +1,30 @@ +{ + "name": "@nocobase/plugin-charts", + "displayName": "Charts (deprecated)", + "displayName.zh-CN": "图表(废弃)", + "description": "The plugin has been deprecated, please use the data visualization plugin instead.", + "description.zh-CN": "已废弃插件,请使用数据可视化插件代替。", + "version": "1.5.0-alpha.5", + "main": "./dist/server/index.js", + "license": "AGPL-3.0", + "devDependencies": { + "@ant-design/icons": "5.x", + "@formily/antd-v5": "1.x", + "@formily/core": "2.x", + "@formily/react": "2.x", + "@formily/shared": "2.x", + "antd": "5.x", + "json5": "^2.2.3", + "react": "^18.2.0", + "react-i18next": "^11.15.1", + "react-router-dom": "^6.11.2" + }, + "peerDependencies": { + "@nocobase/client": "1.x", + "@nocobase/database": "1.x", + "@nocobase/server": "1.x", + "@nocobase/test": "1.x", + "@nocobase/utils": "1.x" + }, + "gitHead": "d0b4efe4be55f8c79a98a331d99d9f8cf99021a1" +} diff --git a/packages/plugins/@nocobase/plugin-charts/server.d.ts b/packages/plugins/@nocobase/plugin-charts/server.d.ts new file mode 100644 index 0000000000..c41081ddc6 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/server.d.ts @@ -0,0 +1,2 @@ +export * from './dist/server'; +export { default } from './dist/server'; diff --git a/packages/plugins/@nocobase/plugin-charts/server.js b/packages/plugins/@nocobase/plugin-charts/server.js new file mode 100644 index 0000000000..972842039a --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/server.js @@ -0,0 +1 @@ +module.exports = require('./dist/server/index.js'); diff --git a/packages/plugins/@nocobase/plugin-charts/src/client/ChartBlockEngine.tsx b/packages/plugins/@nocobase/plugin-charts/src/client/ChartBlockEngine.tsx new file mode 100644 index 0000000000..9ab66b8ab6 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/client/ChartBlockEngine.tsx @@ -0,0 +1,130 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + +import { useCompile, useRequest } from '@nocobase/client'; +import { Empty, Spin } from 'antd'; +import JSON5 from 'json5'; +import React, { useEffect, useState } from 'react'; +import { ChartBlockEngineDesigner } from './ChartBlockEngineDesigner'; +import chartRenderComponentsMap from './chartRenderComponents'; +import { lang } from './locale'; +import { templates } from './templates'; + +export interface IQueryConfig { + id: number; +} +export interface IChartConfig { + type: string; + template: string; + metric: string; + dimension: string; + category?: string; + [key: string]: any; +} + +export interface ChartBlockEngineMetaData { + query: IQueryConfig; + chart: IChartConfig; +} + +const ChartRenderComponent = ({ + chartBlockEngineMetaData, +}: { + chartBlockEngineMetaData: ChartBlockEngineMetaData; +}): JSX.Element => { + const compile = useCompile(); + const chartType = chartBlockEngineMetaData.chart.type; + const renderComponent = templates.get(chartType)?.renderComponent; + const RenderComponent = chartRenderComponentsMap.get(renderComponent); //G2Plot | Echarts | D3 |Table + const chartConfig = chartBlockEngineMetaData.chart; + const { loading, dataSet, error } = useGetDataSet(chartBlockEngineMetaData.query.id); + + const [currentConfig, setCurrentConfig] = useState({} as any); + + useEffect(() => { + setCurrentConfig(chartConfig); + }, [JSON.stringify(chartConfig)]); + + if (error) { + return ( + <> + {`May be this chart block's query data has been deleted,please check!`}} /> + + ); + } + + if (currentConfig.type !== chartConfig.type) { + return <>; + } + + switch (renderComponent) { + case 'G2Plot': { + const finalChartOptions = templates.get(chartType)?.defaultChartOptions; + let template; + try { + template = JSON5.parse(chartConfig?.template); + } catch (e) { + template = {}; + } + const config = compile( + { + ...finalChartOptions, + ...template, + data: dataSet, + }, + { ...chartConfig, category: chartConfig?.category ?? '' }, + ); + if (config && chartConfig) { + const { dimension, metric, category } = chartConfig; + if (!metric || !dimension) { + return <>{lang('Please check the chart config')}; + } + } + return <>{loading ? : }; + } + } + return <>; +}; + +export const useGetDataSet = (chartQueryId: number) => { + const { data, loading, error } = useRequest<{ + data: any; + }>({ + url: `/chartsQueries:getData/${chartQueryId}`, + }); + const dataSet = data?.data; + return { + loading, + dataSet: dataSet, + error, + }; +}; + +const ChartBlockEngine = ({ chartBlockEngineMetaData }: { chartBlockEngineMetaData: ChartBlockEngineMetaData }) => { + let renderComponent; + const chartType = chartBlockEngineMetaData?.chart?.type; + + if (chartType) { + renderComponent = templates.get(chartType)?.renderComponent; + } + + if (!chartType || !renderComponent) { + return <>{lang('Please check the chart config')}; + } + + return ( + <> + + + ); +}; + +ChartBlockEngine.Designer = ChartBlockEngineDesigner; + +export { ChartBlockEngine }; diff --git a/packages/plugins/@nocobase/plugin-charts/src/client/ChartBlockEngineDesigner.tsx b/packages/plugins/@nocobase/plugin-charts/src/client/ChartBlockEngineDesigner.tsx new file mode 100644 index 0000000000..22f314b3b6 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/client/ChartBlockEngineDesigner.tsx @@ -0,0 +1,261 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + +import { FormLayout } from '@formily/antd-v5'; +import { SchemaOptionsContext, useField, useFieldSchema } from '@formily/react'; +import { + APIClientProvider, + FormDialog, + GeneralSchemaDesigner, + SchemaComponent, + SchemaComponentOptions, + SchemaSettingsDivider, + SchemaSettingsItem, + SchemaSettingsRemove, + css, + i18n, + useAPIClient, + useCompile, + useDesignable, + useGlobalTheme, +} from '@nocobase/client'; +import { error } from '@nocobase/utils/client'; +import { Card } from 'antd'; +import JSON5 from 'json5'; +import React, { useContext, useEffect, useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { ChartBlockEngineMetaData } from './ChartBlockEngine'; +import { Options } from './ChartBlockInitializer'; +import DataSetPreviewTable from './DataSetPreviewTable'; +import { useFieldsById } from './hooks'; +import { lang } from './locale'; +import { templates } from './templates'; +import _ from 'lodash'; + +export const jsonConfigDesc = (title: string, link: string) => { + return ( + + {lang('Json config references: ')} + + {lang(title)} + + + ); +}; + +const validateJSON = { + validator: `{{(value, rule)=> { + if (!value) { + return ''; + } + try { + const val = JSON.parse(value); + if(!isNaN(val)) { + return false; + } + return true; + } catch(error) { + console.error(error); + return false; + } + }}}`, + message: '{{t("Invalid JSON format",{ ns: "charts" })}}', +}; + +export const ChartBlockEngineDesigner = () => { + const fieldSchema = useFieldSchema(); + const { chartBlockEngineMetaData } = fieldSchema?.['x-component-props'] || {}; + return ( + + + + + + ); +}; + +export const ChartBlockEngineDesignerInitializer = (props) => { + const { chartBlockEngineMetaData }: { chartBlockEngineMetaData: ChartBlockEngineMetaData } = props; + const { t } = useTranslation(); + const options = useContext(SchemaOptionsContext); + const { dn } = useDesignable(); + const fieldSchema = useFieldSchema(); + const api = useAPIClient(); + const field = useField(); + const compile = useCompile(); + const { chart, query } = chartBlockEngineMetaData; + const { fields } = useFieldsById(query.id); + const { theme } = useGlobalTheme(); + + const dataSource = fields.map((field) => { + return { + label: field.name, + value: field.name, + }; + }); + + return ( + { + FormDialog( + { + okText: compile('{{t("Submit")}}'), + title: lang('Edit chart block'), + width: 1200, + bodyStyle: { background: 'var(--nb-box-bg)', maxHeight: '65vh', overflow: 'auto' }, + }, + function Com(form) { + const [chartBlockEngineMetaData, setChartBlockEngineMetaData] = useState(null); + useEffect(() => { + const chartBlockEngineMetaData = { + query: { + id: query?.id, + }, + chart: form.values, //TODO + }; + setChartBlockEngineMetaData(chartBlockEngineMetaData); + }, [form.values.type]); + return ( + + +
+ {/* left*/} + + + { + return { + title: template.title, + key: template.type, + description: template.description, + group: template.group, + iconId: template.iconId, + }; + }), + }, + options: { + type: 'void', + 'x-component': 'Options', + }, + }, + }} + /> + + + {/* right*/} +
+ + {/* Chart Preview*/} + {chartBlockEngineMetaData && ( + <> + + + )} + + + {/*Data preview*/} + {chartBlockEngineMetaData?.query?.id && ( + + )} + +
+
+
+
+ ); + }, + theme, + ) + .open({ + initialValues: { ...chart }, //reset before chartBlockMetaData + }) + .then((values) => { + //patch updates + values = { + query, + chart: values, + }; + field.title = values.chart.title; + fieldSchema['title'] = values.chart.title; + field.componentProps.chartBlockEngineMetaData = values; + _.set(fieldSchema, 'x-component-props.chartBlockEngineMetaData', values); + dn.emit('patch', { + schema: { + 'x-uid': fieldSchema['x-uid'], + 'x-component-props': fieldSchema['x-component-props'], + }, + }); + dn.refresh(); + }) + .catch((err) => { + error(err); + }); + }} + > + {props.children || props.title || lang('Edit chart block')} +
+ ); +}; diff --git a/packages/plugins/@nocobase/plugin-charts/src/client/ChartBlockInitializer.tsx b/packages/plugins/@nocobase/plugin-charts/src/client/ChartBlockInitializer.tsx new file mode 100644 index 0000000000..f37c66f88d --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/client/ChartBlockInitializer.tsx @@ -0,0 +1,233 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + +import { FormLayout } from '@formily/antd-v5'; +import { Field } from '@formily/core'; +import { RecursionField, Schema, SchemaOptionsContext, observer, useField, useForm } from '@formily/react'; +import { + APIClientProvider, + FormDialog, + FormProvider, + SchemaComponent, + SchemaComponentOptions, + css, + useAPIClient, + useCompile, + useGlobalTheme, + useSchemaInitializer, +} from '@nocobase/client'; +import { Card } from 'antd'; +import JSON5 from 'json5'; +import React, { useContext, useEffect, useState } from 'react'; +import { ChartBlockEngineMetaData } from './ChartBlockEngine'; +import { jsonConfigDesc } from './ChartBlockEngineDesigner'; +import { ChartQueryBlockInitializer, ChartQueryMetadata } from './ChartQueryBlockInitializer'; +import DataSetPreviewTable from './DataSetPreviewTable'; +import { lang } from './locale'; +import { templates } from './templates'; + +export const Options = observer( + (props) => { + const form = useForm(); + const field = useField(); + const [s, setSchema] = useState(new Schema({})); + const [chartType, setChartType] = useState(form.values.type); + useEffect(() => { + // form.clearFormGraph('options.*'); + setChartType(form?.values?.type); + if (chartType !== form?.values?.type) { + form.clearFormGraph('options.*'); + } + if (form.values.type) { + const template = templates.get(form.values.type); + setSchema(new Schema(template.configurableProperties || {})); + } + }, [form.values.type]); + return ; + }, + { displayName: 'Options' }, +); + +interface ChartFormInterface { + type: string; + template: string; + metric: string; + dimension: string; + category?: string; + + [key: string]: string; +} + +export const ChartBlockInitializer = (props) => { + const { insert } = useSchemaInitializer(); + const options = useContext(SchemaOptionsContext); + const api = useAPIClient(); + const compile = useCompile(); + const { theme } = useGlobalTheme(); + + return ( + { + const dataSource = chartQueryMetadata?.fields.map((field) => { + return { + label: field.name, + value: field.name, + }; + }); + const values = await FormDialog( + { + okText: compile('{{t("Submit")}}'), + title: lang('Create chart block'), + width: 1200, + bodyStyle: { background: 'var(--nb-box-bg)', maxHeight: '65vh', overflow: 'auto' }, + }, + function Com() { + const form = useForm(); + const [chartBlockEngineMetaData, setChartBlockEngineMetaData] = useState(null); + useEffect(() => { + const chartBlockEngineMetaData = { + query: { + id: chartQueryMetadata?.id, + }, + chart: form.values, //TODO + }; + setChartBlockEngineMetaData(chartBlockEngineMetaData); + }, [form.values.type]); + return ( + + +
+ {/* left*/} + + + + { + return { + title: template.title, + key: template.type, + description: template.description, + group: template.group, + iconId: template.iconId, + }; + }), + }, + options: { + type: 'void', + 'x-component': 'Options', + }, + }, + }} + /> + + + + {/* right*/} +
+ + {/* Chart Preview*/} + {chartBlockEngineMetaData && ( + <> + + + )} + + + {/*Data preview*/} + {chartBlockEngineMetaData?.query?.id && ( + + )} + +
+
+
+
+ ); + }, + theme, + ).open({ + initialValues: {}, + }); + if (values) { + const chartBlockEngineMetaData: ChartBlockEngineMetaData = { + query: { + id: chartQueryMetadata.id, + }, + chart: values, + }; + insert({ + type: 'void', + title: values?.title, + 'x-designer': 'ChartBlockEngine.Designer', + 'x-decorator': 'CardItem', + 'x-component': 'ChartBlockEngine', + 'x-component-props': { + chartBlockEngineMetaData, + }, + }); + } + }} + /> + ); +}; diff --git a/packages/plugins/@nocobase/plugin-charts/src/client/ChartQueryBlockInitializer.tsx b/packages/plugins/@nocobase/plugin-charts/src/client/ChartQueryBlockInitializer.tsx new file mode 100644 index 0000000000..374c0eb01c --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/client/ChartQueryBlockInitializer.tsx @@ -0,0 +1,165 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + +import { TableOutlined } from '@ant-design/icons'; +import { FormLayout } from '@formily/antd-v5'; +import { SchemaOptionsContext } from '@formily/react'; +import { + FormDialog, + SchemaInitializerItem, + SchemaComponent, + SchemaComponentOptions, + useAPIClient, + useGlobalTheme, + useSchemaInitializer, +} from '@nocobase/client'; +import { error } from '@nocobase/utils/client'; +import React, { useCallback, useContext, useMemo } from 'react'; +import { useChartQueryMetadataContext } from './ChartQueryMetadataProvider'; +import { lang } from './locale'; +import { getQueryTypeSchema } from './settings/queryTypes'; + +export interface ChartQueryMetadata { + id: number; + title: string; + type: string; + fields: { name: string }[]; +} + +export const ChartQueryBlockInitializer = (props) => { + const { templateWrap, onCreateBlockSchema, componentType, createBlockSchema, ...others } = props; + const { setVisible } = useSchemaInitializer(); + const apiClient = useAPIClient(); + const ctx = useChartQueryMetadataContext(); + const options = useContext(SchemaOptionsContext); + const { theme } = useGlobalTheme(); + + const onAddQuery = useCallback( + (info) => { + FormDialog( + { + sql: lang('Add SQL query'), + json: lang('Add JSON query'), + }[info.key], + () => { + return ( +
+ + + + + +
+ ); + }, + theme, + ) + .open({ + initialValues: { + type: info.key, + }, + }) + .then(async (values) => { + try { + if (apiClient.resource('chartsQueries')?.create) { + const { data } = await apiClient.resource('chartsQueries').create({ values }); + const items = (await ctx.refresh()) as any; + const item = items.find((item) => item.id === data?.data?.id); + onCreateBlockSchema({ item }); + } + setVisible(false); + } catch (err) { + error(err); + } + }) + .catch((err) => { + error(err); + }); + }, + [apiClient, ctx, onCreateBlockSchema, options.components, options.scope, setVisible], + ); + + const items = useMemo(() => { + const defaultItems: any = [ + { + type: 'itemGroup', + title: lang('Select query data'), + children: [], + }, + ]; + const chartQueryMetadata = ctx.data; + if (chartQueryMetadata && Array.isArray(chartQueryMetadata)) { + const item1 = + chartQueryMetadata.length > 0 + ? { + type: 'itemGroup', + title: '{{t("Select chart query", {ns: "charts"})}}', + children: chartQueryMetadata, + } + : null; + const item2 = + chartQueryMetadata.length > 0 + ? { + type: 'divider', + } + : null; + + return [ + item1, + item2, + { + type: 'subMenu', + title: lang('Add chart query'), + // component: AddChartQuery, + children: [ + { + key: 'sql', + type: 'item', + title: 'SQL', + onClick: onAddQuery, + }, + { + key: 'json', + type: 'item', + title: 'JSON', + onClick: onAddQuery, + }, + ], + }, + ].filter(Boolean); + } + + return defaultItems; + }, [ctx.data, onAddQuery]); + + return ( + } + {...others} + onClick={async ({ item }) => { + onCreateBlockSchema({ item }); + setVisible(false); + }} + items={items} + /> + ); +}; diff --git a/packages/plugins/@nocobase/plugin-charts/src/client/ChartQueryMetadataProvider.tsx b/packages/plugins/@nocobase/plugin-charts/src/client/ChartQueryMetadataProvider.tsx new file mode 100644 index 0000000000..7033fe6f84 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/client/ChartQueryMetadataProvider.tsx @@ -0,0 +1,69 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + +import { useAPIClient, useRequest } from '@nocobase/client'; +import { Spin } from 'antd'; +import React, { createContext, useCallback, useContext, useMemo } from 'react'; +import { useLocation } from 'react-router-dom'; + +export const ChartQueryMetadataContext = createContext({ + refresh: () => {}, + data: [] as any[], +}); +ChartQueryMetadataContext.displayName = 'ChartQueryMetadataContext'; + +const options = { + resource: 'chartsQueries', + action: 'listMetadata', + params: { + paginate: false, + sort: ['-id'], + }, +}; + +export const ChartQueryMetadataProvider: React.FC = (props) => { + // TODO:旧版插件已弃用,待删除 + return <>{props.children}; + + const api = useAPIClient(); + const location = useLocation(); + + const isAdminPage = location.pathname.startsWith('/admin'); + const token = api.auth.getToken() || ''; + + const service = useRequest<{ + data: any; + }>(options, { + refreshDeps: [isAdminPage, token], + ready: !!(isAdminPage && token), + }); + + const refresh = useCallback(async () => { + const { data } = await api.request(options); + service.mutate(data); + return data?.data || []; + }, [options, service]); + + const value = useMemo(() => { + return { + refresh, + data: service.data?.data, + }; + }, [service.data?.data, refresh]); + + if (service.loading) { + return ; + } + + return {props.children}; +}; + +export const useChartQueryMetadataContext = () => { + return useContext(ChartQueryMetadataContext); +}; diff --git a/packages/plugins/@nocobase/plugin-charts/src/client/DataSetPreviewTable.tsx b/packages/plugins/@nocobase/plugin-charts/src/client/DataSetPreviewTable.tsx new file mode 100644 index 0000000000..a26f25e910 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/client/DataSetPreviewTable.tsx @@ -0,0 +1,80 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + +import { ISchema } from '@formily/react'; +import { FormItem, Input, SchemaComponent, SchemaComponentProvider, TableV2 } from '@nocobase/client'; +import { Empty, Spin } from 'antd'; +import React from 'react'; +import { useGetDataSet } from './ChartBlockEngine'; + +export default ({ queryId, fields }: { queryId: number; fields }) => { + const { dataSet, loading, error } = useGetDataSet(queryId); + const columns = {}; + if (fields) { + for (const field of fields) { + columns[field.name] = { + type: 'void', + title: field.name, + 'x-component': 'TableV2.Column', + 'x-component-props': { + // width: 200, + }, + properties: { + [field.name]: { + type: 'string', + 'x-component': 'Input', + 'x-read-pretty': true, + }, + }, + }; + } + } + const schema: ISchema = { + type: 'void', + properties: { + input: { + type: 'array', + 'x-component': 'TableV2', + 'x-component-props': { + scroll: { y: 300 }, + }, + default: dataSet, + properties: columns, + }, + }, + }; + + if (error) { + return ( + <> + May be this chart block's query data has been deleted,please check!} /> + + ); + } + + if (loading) + return ( + <> + + + ); + //对dataset中引用类型数据类型进行序列化处理 + dataSet.forEach((item) => { + for (const key in item) { + if (item[key] && item[key] instanceof Object) { + item[key] = JSON.stringify(item[key]); + } + } + }); + return ( + + + + ); +}; diff --git a/packages/plugins/@nocobase/plugin-charts/src/client/Icons.tsx b/packages/plugins/@nocobase/plugin-charts/src/client/Icons.tsx new file mode 100644 index 0000000000..37e251289b --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/client/Icons.tsx @@ -0,0 +1,108 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + +import { Icon } from '@nocobase/client'; +import React from 'react'; + +const RadarChart = () => ( + +); +const FunnelChart = () => ( + +); +const ScatterChart = () => ( + +); +const ColumnChart = () => ( + +); + +const BarChart = () => ( + +); + +const LineChart = () => ( + +); + +const PieChart = () => ( + +); + +const AreaChart = () => ( + +); + +Icon.register({ + 'icon-area': (props) => , + 'icon-pie': (props) => , + 'icon-radar': (props) => , + 'icon-funnel': (props) => , + 'icon-line': (props) => , + 'icon-bar': (props) => , + 'icon-column': (props) => , + 'icon-scatter': (props) => , +}); diff --git a/packages/plugins/@nocobase/plugin-charts/src/client/chartRenderComponents/index.ts b/packages/plugins/@nocobase/plugin-charts/src/client/chartRenderComponents/index.ts new file mode 100644 index 0000000000..43a85d13cb --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/client/chartRenderComponents/index.ts @@ -0,0 +1,16 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + +import { G2Plot } from '@nocobase/client'; +import DataSetPreviewTable from '../DataSetPreviewTable'; + +const chartRenderComponentsMap = new Map(); +chartRenderComponentsMap.set('G2Plot', G2Plot); +chartRenderComponentsMap.set('DataSetPreviewTable', DataSetPreviewTable); +export default chartRenderComponentsMap; diff --git a/packages/plugins/@nocobase/plugin-charts/src/client/hooks/index.ts b/packages/plugins/@nocobase/plugin-charts/src/client/hooks/index.ts new file mode 100644 index 0000000000..08899e4fe8 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/client/hooks/index.ts @@ -0,0 +1,28 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + +import { useChartQueryMetadataContext } from '../ChartQueryMetadataProvider'; +import { useEffect, useState } from 'react'; + +const useFieldsById = (queryId: number) => { + const [fields, setFields] = useState([]); + const ctx = useChartQueryMetadataContext(); + useEffect(() => { + const chartQueryList = ctx?.data; + if (chartQueryList && Array.isArray(chartQueryList)) { + const currentQuery = chartQueryList.find((chartQuery) => chartQuery.id === queryId); + setFields(currentQuery?.fields || []); + } + }, [queryId]); + return { + fields, + }; +}; + +export { useFieldsById }; diff --git a/packages/plugins/@nocobase/plugin-charts/src/client/index.tsx b/packages/plugins/@nocobase/plugin-charts/src/client/index.tsx new file mode 100644 index 0000000000..0e67605f17 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/client/index.tsx @@ -0,0 +1,101 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + +import { registerValidateRules } from '@formily/core'; +import { BlockSchemaComponentPlugin, Plugin, SchemaComponentOptions, useAPIClient } from '@nocobase/client'; +import JSON5 from 'json5'; +import React from 'react'; +import { ChartBlockEngine } from './ChartBlockEngine'; +import { ChartBlockInitializer } from './ChartBlockInitializer'; +import { ChartQueryMetadataProvider } from './ChartQueryMetadataProvider'; +import './Icons'; +import { NAMESPACE, lang } from './locale'; +import { CustomSelect } from './select'; +import { QueriesTable } from './settings/QueriesTable'; + +registerValidateRules({ + json5: (value, rule) => { + if (!value) { + return ''; + } + try { + const val = JSON5.parse(value); + if (!isNaN(val)) { + return { + type: 'error', + message: lang('Invalid JSON format'), + }; + } + return ''; + } catch (error) { + console.error(error); + return { + type: 'error', + message: lang('Invalid JSON format'), + }; + } + }, +}); + +const ChartsProvider = React.memo((props) => { + const api = useAPIClient(); + const validateSQL = (sql) => { + return new Promise((resolve) => { + api + .request({ + url: 'chartsQueries:validate', + method: 'post', + data: { + sql, + }, + }) + .then(({ data }) => { + resolve(data?.data?.errorMessage); + }) + .catch(() => { + resolve('Invalid SQL'); + }); + }); + }; + return ( + + + {props.children} + + + ); +}); +ChartsProvider.displayName = 'ChartsProvider'; + +export class ChartsPlugin extends Plugin { + async afterAdd() { + this.app.pm.add(BlockSchemaComponentPlugin); + } + async load() { + // Chart (Old) 老的不需要了 + // const blockInitializers = this.app.schemaInitializerManager.get('page:addBlock'); + // blockInitializers?.add('data-blocks.chart-old', { + // icon: 'PieChartOutlined', + // title: '{{t("Chart (Old)",{ns:"charts"})}}', + // Component: 'ChartBlockInitializer', + // }); + this.app.use(ChartsProvider); + this.app.pluginSettingsManager.add(NAMESPACE, { + title: `{{t("Charts", { ns: "${NAMESPACE}" })}}`, + icon: 'PieChartOutlined', + Component: QueriesTable, + aclSnippet: 'pm.charts.queries', + }); + } +} + +export default ChartsPlugin; diff --git a/packages/plugins/@nocobase/plugin-charts/src/client/locale/index.ts b/packages/plugins/@nocobase/plugin-charts/src/client/locale/index.ts new file mode 100644 index 0000000000..49a6e33c35 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/client/locale/index.ts @@ -0,0 +1,27 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + +import { i18n } from '@nocobase/client'; +import { useTranslation } from 'react-i18next'; + +export const NAMESPACE = 'charts'; + +// i18n.addResources('zh-CN', NAMESPACE, zhCN); +// i18n.addResources('en-US', NAMESPACE, enUS); +// i18n.addResources('ja-JP', NAMESPACE, jaJP); +// i18n.addResources('ru-RU', NAMESPACE, ruRU); +// i18n.addResources('tr-TR', NAMESPACE, trTR); + +export function lang(key: string) { + return i18n.t(key, { ns: NAMESPACE }); +} + +export function useChartsTranslation() { + return useTranslation(NAMESPACE); +} diff --git a/packages/plugins/@nocobase/plugin-charts/src/client/select/CustomSelect.tsx b/packages/plugins/@nocobase/plugin-charts/src/client/select/CustomSelect.tsx new file mode 100644 index 0000000000..a9917789b4 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/client/select/CustomSelect.tsx @@ -0,0 +1,128 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + +import { LoadingOutlined } from '@ant-design/icons'; +import { connect, mapProps, mapReadPretty } from '@formily/react'; +import { Icon, StablePopover, css } from '@nocobase/client'; +import type { SelectProps } from 'antd'; +import { Select as AntdSelect } from 'antd'; +import React from 'react'; +import { lang } from '../locale'; +import { ReadPretty } from './ReadPretty'; + +type Props = SelectProps & { objectValue?: boolean; onChange?: (v: any) => void; multiple: boolean }; + +const { Option, OptGroup } = AntdSelect; +const filterOption = (input, option) => (option?.label ?? '').toLowerCase().includes((input || '').toLowerCase()); + +const InternalSelect = connect( + (props: Props) => { + const { ...others } = props; + const { options, ...othersProps } = { ...others }; + const mode = props.mode || props.multiple ? 'multiple' : undefined; + const group1 = options.filter((option) => option.group === 2); + const group2 = options.filter((option) => option.group === 1); + return ( + { + props.onChange?.(changed === undefined ? null : changed); + }} + mode={mode} + > + + {group1.map((option) => ( + + ))} + + + {group2.map((option) => ( + + ))} + + + ); + }, + mapProps( + { + dataSource: 'options', + loading: true, + }, + (props, field) => { + return { + ...props, + suffixIcon: field?.['loading'] || field?.['validating'] ? : props?.suffixIcon, + }; + }, + ), + mapReadPretty(ReadPretty), +); + +export const CustomSelect = InternalSelect as unknown as typeof InternalSelect & { + ReadPretty: typeof ReadPretty; +}; + +CustomSelect.ReadPretty = ReadPretty; + +export default CustomSelect; diff --git a/packages/plugins/@nocobase/plugin-charts/src/client/select/ReadPretty.tsx b/packages/plugins/@nocobase/plugin-charts/src/client/select/ReadPretty.tsx new file mode 100644 index 0000000000..bd58edc68b --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/client/select/ReadPretty.tsx @@ -0,0 +1,48 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + +import { isArrayField } from '@formily/core'; +import { observer, useField } from '@formily/react'; +import { isValid } from '@formily/shared'; +import { Tag } from 'antd'; +import React from 'react'; +import { defaultFieldNames, getCurrentOptions } from './shared'; +import { useCompile } from '@nocobase/client'; + +type Composed = { + Select?: React.FC; + Object?: React.FC; +}; + +export const ReadPretty = observer( + (props: any) => { + const fieldNames = { ...defaultFieldNames, ...props.fieldNames }; + const field = useField(); + const compile = useCompile(); + + if (!isValid(props.value)) { + return
; + } + if (isArrayField(field) && field?.value?.length === 0) { + return
; + } + const dataSource = field.dataSource || props.options || []; + const options = getCurrentOptions(field.value, dataSource, fieldNames); + return ( +
+ {options.map((option, key) => ( + + {compile(option[fieldNames.label])} + + ))} +
+ ); + }, + { displayName: 'ReadPretty' }, +); diff --git a/packages/plugins/@nocobase/plugin-charts/src/client/select/index.md b/packages/plugins/@nocobase/plugin-charts/src/client/select/index.md new file mode 100644 index 0000000000..99230b2d75 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/client/select/index.md @@ -0,0 +1,31 @@ +# Select + +## Examples + +### 单选 + + + +### 多选 + + + +### 值为 Object 类型的 Select + + + +## API + +基于 Ant Design 的 [Select](https://ant.design/components/select/#API),相关扩展属性有: + +- `objectValue` 值为 object 类型 +- `fieldNames` 默认值有区别 + +```ts +export const defaultFieldNames = { + label: 'label', + value: 'value', + color: 'color', + options: 'children', +}; +``` diff --git a/packages/plugins/@nocobase/plugin-charts/src/client/select/index.ts b/packages/plugins/@nocobase/plugin-charts/src/client/select/index.ts new file mode 100644 index 0000000000..9960ca8d38 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/client/select/index.ts @@ -0,0 +1,11 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + +export * from './CustomSelect'; +export * from './shared'; diff --git a/packages/plugins/@nocobase/plugin-charts/src/client/select/shared.ts b/packages/plugins/@nocobase/plugin-charts/src/client/select/shared.ts new file mode 100644 index 0000000000..b5e4a3ae51 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/client/select/shared.ts @@ -0,0 +1,46 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + +import lodash from 'lodash'; + +export const defaultFieldNames = { + label: 'label', + value: 'value', + color: 'color', + options: 'children', +}; + +export const getCurrentOptions = (values, dataSource, fieldNames) => { + function flatData(data) { + const newArr = []; + for (let i = 0; i < data.length; i++) { + const children = data[i][fieldNames.options]; + if (Array.isArray(children)) { + newArr.push(...flatData(children)); + } + newArr.push({ ...data[i] }); + } + return newArr; + } + const result = flatData(dataSource); + values = lodash + .castArray(values) + .filter((item) => item != null) + .map((val) => (typeof val === 'object' ? val[fieldNames.value] : val)); + const findOptions = (options: any[]) => { + if (!options) return []; + const current = []; + for (const value of values) { + const option = options.find((v) => v[fieldNames.value] === value) || { value: value, label: value }; + current.push(option); + } + return current; + }; + return findOptions(result); +}; diff --git a/packages/plugins/@nocobase/plugin-charts/src/client/settings/AddNewQuery.tsx b/packages/plugins/@nocobase/plugin-charts/src/client/settings/AddNewQuery.tsx new file mode 100644 index 0000000000..f51c189ac7 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/client/settings/AddNewQuery.tsx @@ -0,0 +1,185 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + +import { DownOutlined, PlusOutlined } from '@ant-design/icons'; +import { createForm } from '@formily/core'; +import { ISchema, useForm } from '@formily/react'; +import { uid } from '@formily/shared'; +import { + ActionContextProvider, + SchemaComponent, + useActionContext, + useRecord, + useResourceActionContext, + useResourceContext, +} from '@nocobase/client'; +import { Button, Dropdown, MenuProps } from 'antd'; +import React, { useMemo, useState } from 'react'; +import { useChartQueryMetadataContext } from '../ChartQueryMetadataProvider'; +import { lang } from '../locale'; +import { getQueryTypeSchema } from './queryTypes'; + +const useCreateAction = () => { + const { setVisible } = useActionContext(); + const form = useForm(); + const { refresh } = useResourceActionContext(); + const { resource } = useResourceContext(); + const ctx = useChartQueryMetadataContext(); + return { + async run() { + await form.submit(); + await resource.create({ values: form.values }); + setVisible(false); + await form.reset(); + refresh(); + ctx.refresh(); + }, + }; +}; + +const useUpdateAction = () => { + const { setVisible } = useActionContext(); + const form = useForm(); + const { refresh } = useResourceActionContext(); + const { resource, targetKey } = useResourceContext(); + const { [targetKey]: filterByTk } = useRecord(); + const ctx = useChartQueryMetadataContext(); + return { + async run() { + await form.submit(); + await resource.update({ filterByTk, values: form.values }); + setVisible(false); + await form.reset(); + refresh(); + ctx.refresh(); + }, + }; +}; + +const useCloseAction = () => { + const { setVisible } = useActionContext(); + return { + async run() { + setVisible(false); + }, + }; +}; + +const getSchema = (initialValue, { form, isNewRecord }) => { + const type = initialValue.type; + const schema: ISchema = { + type: 'void', + name: uid(), + 'x-component': 'Action.Drawer', + 'x-decorator': 'Form', + 'x-decorator-props': { + form, + // initialValue: JSON.parse(JSON.stringify(initialValue)), + }, + title: isNewRecord ? lang('Add query') : lang('Edit query'), + properties: { + title: { + title: lang('Title'), + required: true, + 'x-component': 'Input', + 'x-decorator': 'FormItem', + }, + options: getQueryTypeSchema(type), + footer: { + type: 'void', + 'x-component': 'Action.Drawer.Footer', + properties: { + cancel: { + 'x-component': 'Action', + title: lang('Cancel'), + 'x-component-props': { + useAction: '{{ useCloseAction }}', + }, + }, + submit: { + 'x-component': 'Action', + title: lang('Submit'), + 'x-component-props': { + type: 'primary', + useAction: '{{ useSubmitAction }}', + }, + }, + }, + }, + }, + }; + return schema; +}; + +export const AddNewQuery = () => { + const [visible, setVisible] = useState(false); + const [schema, setSchema] = useState({}); + const form = useMemo(() => createForm(), []); + + const menu = useMemo(() => { + return { + onClick: (info) => { + setVisible(true); + form.setValues({ type: info.key }); + setSchema(getSchema({ type: info.key }, { form, isNewRecord: true })); + }, + items: [ + { + key: 'json', + label: 'JSON', + }, + { + key: 'sql', + label: 'SQL', + }, + { + key: 'api', + label: 'API', + disabled: true, + }, + { + key: 'collection', + label: 'Collection', + disabled: true, + }, + ], + }; + }, [form]); + + return ( + + + + + + + ); +}; + +export const EditQuery = () => { + const [visible, setVisible] = useState(false); + const record = useRecord(); + const form = useMemo(() => createForm(), []); + const schema = getSchema(record, { form, isNewRecord: false }); + return ( + + { + form.setValues(record); + setVisible(true); + }} + > + {lang('Edit')} + + + + ); +}; diff --git a/packages/plugins/@nocobase/plugin-charts/src/client/settings/ConfigureFields.tsx b/packages/plugins/@nocobase/plugin-charts/src/client/settings/ConfigureFields.tsx new file mode 100644 index 0000000000..a4d91c994f --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/client/settings/ConfigureFields.tsx @@ -0,0 +1,27 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + +import { useRecord } from '@nocobase/client'; +import { Table } from 'antd'; +import React from 'react'; + +export const ConfigureFields = () => { + const record = useRecord(); + return ( + + ); +}; diff --git a/packages/plugins/@nocobase/plugin-charts/src/client/settings/QueriesTable.tsx b/packages/plugins/@nocobase/plugin-charts/src/client/settings/QueriesTable.tsx new file mode 100644 index 0000000000..14f7c25572 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/client/settings/QueriesTable.tsx @@ -0,0 +1,35 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + +import { SchemaComponent } from '@nocobase/client'; +import { Card } from 'antd'; +import React, { useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { AddNewQuery, EditQuery } from './AddNewQuery'; +import { ConfigureFields } from './ConfigureFields'; +import { + chartsQueriesSchema, + useDestroyAllSelectedQueriesAction, + useDestroyQueryItemAction, +} from './schemas/chartsQueries'; +import JSON5 from 'json5'; + +export const QueriesTable = () => { + const [visible, setVisible] = useState(false); + const { t } = useTranslation(); + return ( + + + + ); +}; diff --git a/packages/plugins/@nocobase/plugin-charts/src/client/settings/queryTypes.ts b/packages/plugins/@nocobase/plugin-charts/src/client/settings/queryTypes.ts new file mode 100644 index 0000000000..c39669b362 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/client/settings/queryTypes.ts @@ -0,0 +1,74 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + +import { ISchema } from '@formily/react'; +import lodash from 'lodash'; + +export const json: ISchema = { + type: 'object', + properties: { + data: { + title: 'JSON', + required: true, + 'x-component': 'Input.TextArea', + 'x-validator': { json5: true }, + 'x-component-props': { + autoSize: { + maxRows: 20, + minRows: 10, + }, + }, + 'x-decorator': 'FormItem', + }, + }, +}; + +export const sql: ISchema = { + type: 'object', + properties: { + sql: { + title: 'SQL', + required: true, + 'x-component': 'Input.TextArea', + 'x-decorator': 'FormItem', + 'x-validator': { + triggerType: 'onBlur', + validator: '{{validateSQL}}', + }, + 'x-component-props': { + autoSize: { + maxRows: 20, + minRows: 10, + }, + }, + }, + }, +}; + +export const api: ISchema = { + type: 'object', + properties: { + api: { + title: 'API', + required: true, + 'x-component': 'Input', + 'x-decorator': 'FormItem', + }, + }, +}; + +const types = { + json, + sql, + api, +}; + +export const getQueryTypeSchema = (type) => { + return lodash.cloneDeep(types[type]); +}; diff --git a/packages/plugins/@nocobase/plugin-charts/src/client/settings/schemas/chartsQueries.ts b/packages/plugins/@nocobase/plugin-charts/src/client/settings/schemas/chartsQueries.ts new file mode 100644 index 0000000000..922b1449ac --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/client/settings/schemas/chartsQueries.ts @@ -0,0 +1,328 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + +import { ISchema } from '@formily/react'; +import { uid } from '@formily/shared'; +import { + useActionContext, + useRecord, + useRequest, + useResourceActionContext, + useResourceContext, +} from '@nocobase/client'; +import { useChartQueryMetadataContext } from '../../ChartQueryMetadataProvider'; + +const collection = { + name: 'chartsQueries', + fields: [ + { + type: 'integer', + name: 'title', + interface: 'input', + uiSchema: { + title: '{{t("Title",{ns:"charts"})}}', + type: 'string', + 'x-component': 'Input', + required: true, + } as ISchema, + }, + { + type: 'string', + name: 'type', + interface: 'select', + uiSchema: { + title: '{{t("Type",{ns:"charts"})}}', + type: 'string', + 'x-component': 'Select', + required: true, + enum: [ + { label: '{{t("API")}}', value: 'api' }, + { label: '{{t("SQL")}}', value: 'sql' }, + { label: '{{t("JSON")}}', value: 'json' }, + ], + } as ISchema, + }, + ], +}; + +export const useDestroyQueryItemAction = () => { + const ctx = useChartQueryMetadataContext(); + const { refresh } = useResourceActionContext(); + const { resource, targetKey } = useResourceContext(); + const { [targetKey]: filterByTk } = useRecord(); + return { + async run() { + await resource.destroy({ filterByTk }); + refresh(); + ctx.refresh(); + }, + }; +}; + +export const useDestroyAllSelectedQueriesAction = () => { + const ctx = useChartQueryMetadataContext(); + const { state, setState, refresh } = useResourceActionContext(); + const { resource, targetKey } = useResourceContext(); + return { + async run() { + await resource.destroy({ + filterByTk: state?.selectedRowKeys || [], + }); + setState?.({ selectedRowKeys: [] }); + refresh(); + ctx.refresh(); + }, + }; +}; + +export const chartsQueriesSchema: ISchema = { + type: 'object', + properties: { + [uid()]: { + type: 'void', + 'x-decorator': 'ResourceActionProvider', + 'x-decorator-props': { + collection, + resourceName: 'chartsQueries', + request: { + resource: 'chartsQueries', + action: 'list', + params: { + pageSize: 50, + sort: ['-id'], + appends: [], + }, + }, + }, + 'x-component': 'CollectionProvider_deprecated', + 'x-component-props': { + collection, + }, + properties: { + actions: { + type: 'void', + 'x-component': 'ActionBar', + 'x-component-props': { + style: { + marginBottom: 16, + }, + }, + properties: { + delete: { + type: 'void', + title: '{{ t("Delete") }}', + 'x-component': 'Action', + 'x-component-props': { + useAction: '{{ useDestroyAllSelectedQueriesAction }}', + confirm: { + title: '{{t("Delete queries",{ns:"charts"})}}', + content: "{{t('Are you sure you want to delete it?')}}", + }, + }, + }, + create: { + type: 'void', + title: '{{t("Add query")}}', + 'x-component': 'AddNewQuery', + 'x-component-props': { + type: 'primary', + }, + properties: { + drawer: { + type: 'void', + 'x-component': 'Action.Drawer', + 'x-decorator': 'Form', + 'x-decorator-props': { + useValues(options) { + const ctx = useActionContext(); + return useRequest( + () => + Promise.resolve({ + data: { + name: `s_${uid()}`, + }, + }), + { ...options, refreshDeps: [ctx.visible] }, + ); + }, + }, + title: '{{t("Add query",{ns:"charts"})}}', + properties: { + title: { + 'x-component': 'CollectionField', + 'x-decorator': 'FormItem', + }, + type: { + 'x-component': 'CollectionField', + 'x-decorator': 'FormItem', + }, + footer: { + type: 'void', + 'x-component': 'Action.Drawer.Footer', + properties: { + cancel: { + title: '{{t("Cancel",{ns:"charts"})}}', + 'x-component': 'Action', + 'x-component-props': { + useAction: '{{ cm.useCancelAction }}', + }, + }, + submit: { + title: '{{t("Submit",{ns:"charts"})}}', + 'x-component': 'Action', + 'x-component-props': { + type: 'primary', + useAction: '{{ cm.useCreateAction }}', + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + table: { + type: 'void', + 'x-uid': 'input', + 'x-component': 'Table.Void', + 'x-component-props': { + rowKey: 'id', + rowSelection: { + type: 'checkbox', + }, + useDataSource: '{{ cm.useDataSourceFromRAC }}', + }, + properties: { + title: { + type: 'void', + 'x-decorator': 'Table.Column.Decorator', + 'x-component': 'Table.Column', + properties: { + title: { + type: 'number', + 'x-component': 'CollectionField', + 'x-read-pretty': true, + }, + }, + }, + type: { + type: 'void', + 'x-decorator': 'Table.Column.Decorator', + 'x-component': 'Table.Column', + properties: { + type: { + type: 'string', + 'x-component': 'CollectionField', + 'x-read-pretty': true, + }, + }, + }, + actions: { + type: 'void', + title: '{{t("Actions")}}', + 'x-component': 'Table.Column', + properties: { + actions: { + type: 'void', + 'x-component': 'Space', + 'x-component-props': { + split: '|', + }, + properties: { + fields: { + type: 'void', + title: '{{t("Configure fields")}}', + 'x-component': 'Action.Link', + 'x-component-props': { + type: 'primary', + }, + properties: { + drawer: { + type: 'void', + 'x-component': 'Action.Drawer', + title: '{{t("Configure fields")}}', + properties: { + configure: { + type: 'void', + 'x-component': 'ConfigureFields', + }, + }, + }, + }, + }, + update: { + type: 'void', + title: '{{t("Edit")}}', + 'x-component': 'EditQuery', + 'x-component-props': { + type: 'primary', + }, + properties: { + drawer: { + type: 'void', + 'x-component': 'Action.Drawer', + 'x-decorator': 'Form', + 'x-decorator-props': { + useValues: '{{ cm.useValuesFromRecord }}', + }, + title: '{{t("Edit")}}', + properties: { + title: { + 'x-component': 'CollectionField', + 'x-decorator': 'FormItem', + }, + footer: { + type: 'void', + 'x-component': 'Action.Drawer.Footer', + properties: { + cancel: { + title: '{{t("Cancel",{ns:"charts"})}}', + 'x-component': 'Action', + 'x-component-props': { + useAction: '{{ cm.useCancelAction }}', + }, + }, + submit: { + title: '{{t("Submit",{ns:"charts"})}}', + 'x-component': 'Action', + 'x-component-props': { + type: 'primary', + useAction: '{{ cm.useUpdateAction }}', + }, + }, + }, + }, + }, + }, + }, + }, + delete: { + type: 'void', + title: '{{ t("Delete") }}', + 'x-component': 'Action.Link', + 'x-component-props': { + confirm: { + title: '{{t("Delete query",{ns:"charts"})}}', + content: "{{t('Are you sure you want to delete it?')}}", + }, + useAction: '{{ useDestroyQueryItemAction }}', + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, +}; diff --git a/packages/plugins/@nocobase/plugin-charts/src/client/templates/AreaTemplate.tsx b/packages/plugins/@nocobase/plugin-charts/src/client/templates/AreaTemplate.tsx new file mode 100644 index 0000000000..d5ddd58c96 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/client/templates/AreaTemplate.tsx @@ -0,0 +1,73 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + +import JSON5 from 'json5'; + +const chartConfig = { + yField: '{{metric}}', + xField: '{{dimension}}', + seriesField: '{{category}}', +}; + +export const areaTemplate = { + description: '1 「time」or 「Ordered Noun」 field,1 「Numerical」 field,1 「Unordered Noun」 field (optional)', + type: 'Area', + title: 'Area', + iconId: 'icon-area', + group: 2, + renderComponent: 'G2Plot', + defaultChartOptions: chartConfig, + configurableProperties: { + type: 'void', + properties: { + dimension: { + required: true, + type: 'string', + title: '{{t("Category axis / Dimension",{ns:"charts"})}}', + 'x-decorator': 'FormItem', + 'x-component': 'Select', + enum: '{{dataSource}}', + }, + metric: { + required: true, + type: 'string', + title: '{{t("Value axis / Metrics",{ns:"charts"})}}', + 'x-decorator': 'FormItem', + 'x-component': 'Select', + enum: '{{dataSource}}', + }, + category: { + type: 'string', + title: '{{t("Color legend / Dimensional",{ns:"charts"})}}', + 'x-decorator': 'FormItem', + 'x-component': 'Select', + enum: '{{dataSource}}', + }, + jsonConfig: { + type: 'void', + 'x-component': 'div', + properties: { + template: { + required: true, + title: '{{t("JSON config",{ns:"charts"})}}', + type: 'string', + default: JSON5.stringify(chartConfig, null, 2), + 'x-decorator': 'FormItem', + 'x-component': 'Input.TextArea', + 'x-component-props': { + autoSize: { minRows: 8, maxRows: 16 }, + }, + description: '{{jsonConfigDesc("Area | G2Plot","https://g2plot.antv.antgroup.com/api/plots/area")}}', + 'x-validator': { json5: true }, + }, + }, + }, + }, + }, +}; diff --git a/packages/plugins/@nocobase/plugin-charts/src/client/templates/BarTemplate.tsx b/packages/plugins/@nocobase/plugin-charts/src/client/templates/BarTemplate.tsx new file mode 100644 index 0000000000..26f9b970ae --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/client/templates/BarTemplate.tsx @@ -0,0 +1,89 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + +import JSON5 from 'json5'; + +const chartConfig = { + appendPadding: 10, + isGroup: true, + yField: '{{dimension}}', + xField: '{{metric}}', + seriesField: '{{category}}', + label: { + // 可手动配置 label 数据标签位置 + position: 'middle', // 'top', 'bottom', 'middle', + // 配置样式 + style: { + fill: '#FFFFFF', + opacity: 0.6, + }, + }, + xAxis: { + label: { + autoHide: true, + autoRotate: false, + }, + }, +}; +export const barTemplate = { + description: '1 「time」 or 「ordered noun」 field, 1 「value」 field, 0~ 1 「unordered noun」', + type: 'Bar', + title: 'Bar', + iconId: 'icon-bar', + group: 2, + renderComponent: 'G2Plot', + defaultChartOptions: chartConfig, + configurableProperties: { + type: 'void', + properties: { + dimension: { + required: true, + type: 'string', + title: '{{t("Category axis / Dimension",{ns:"charts"})}}', + 'x-decorator': 'FormItem', + 'x-component': 'Select', + enum: '{{dataSource}}', + }, + metric: { + required: true, + type: 'string', + title: '{{t("Value axis / Metrics",{ns:"charts"})}}', + 'x-decorator': 'FormItem', + 'x-component': 'Select', + enum: '{{dataSource}}', + }, + category: { + type: 'string', + title: '{{t("Color legend / Dimensional",{ns:"charts"})}}', + 'x-decorator': 'FormItem', + 'x-component': 'Select', + enum: '{{dataSource}}', + }, + jsonConfig: { + type: 'void', + 'x-component': 'div', + properties: { + template: { + required: true, + title: '{{t("JSON config",{ns:"charts"})}}', + type: 'string', + default: JSON5.stringify(chartConfig, null, 2), + 'x-decorator': 'FormItem', + 'x-component': 'Input.TextArea', + 'x-component-props': { + autoSize: { minRows: 8, maxRows: 16 }, + }, + description: '{{jsonConfigDesc("Bar | G2Plot","https://g2plot.antv.antgroup.com/api/plots/bar")}}', + 'x-validator': { json5: true }, + }, + }, + }, + }, + }, +}; diff --git a/packages/plugins/@nocobase/plugin-charts/src/client/templates/ColumnTemplate.tsx b/packages/plugins/@nocobase/plugin-charts/src/client/templates/ColumnTemplate.tsx new file mode 100644 index 0000000000..f9d451efc7 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/client/templates/ColumnTemplate.tsx @@ -0,0 +1,90 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + +import JSON5 from 'json5'; + +const chartConfig = { + appendPadding: 10, + isGroup: true, + yField: '{{metric}}', + xField: '{{dimension}}', + seriesField: '{{category}}', + label: { + // 可手动配置 label 数据标签位置 + position: 'middle', // 'top', 'bottom', 'middle', + // 配置样式 + style: { + fill: '#FFFFFF', + opacity: 0.6, + }, + }, + xAxis: { + label: { + autoHide: true, + autoRotate: false, + }, + }, +}; + +export const columnTemplate = { + description: '1 「time」 or 「ordered noun」 field, 1 「value」 field, 0 to 1 「unordered noun」', + type: 'Column', + title: 'Column', + iconId: 'icon-column', + group: 2, + renderComponent: 'G2Plot', + defaultChartOptions: chartConfig, + configurableProperties: { + type: 'void', + properties: { + dimension: { + required: true, + type: 'string', + title: '{{t("Category axis / Dimension",{ns:"charts"})}}', + 'x-decorator': 'FormItem', + 'x-component': 'Select', + enum: '{{dataSource}}', + }, + metric: { + required: true, + type: 'string', + title: '{{t("Value axis / Metrics",{ns:"charts"})}}', + 'x-decorator': 'FormItem', + 'x-component': 'Select', + enum: '{{dataSource}}', + }, + category: { + type: 'string', + title: '{{t("Color legend / Dimensional",{ns:"charts"})}}', + 'x-decorator': 'FormItem', + 'x-component': 'Select', + enum: '{{dataSource}}', + }, + jsonConfig: { + type: 'void', + 'x-component': 'div', + properties: { + template: { + required: true, + title: '{{t("JSON config",{ns:"charts"})}}', + type: 'string', + default: JSON5.stringify(chartConfig, null, 2), + 'x-decorator': 'FormItem', + 'x-component': 'Input.TextArea', + 'x-component-props': { + autoSize: { minRows: 8, maxRows: 16 }, + }, + description: '{{jsonConfigDesc("Column | G2Plot","https://g2plot.antv.antgroup.com/api/plots/column")}}', + 'x-validator': { json5: true }, + }, + }, + }, + }, + }, +}; diff --git a/packages/plugins/@nocobase/plugin-charts/src/client/templates/FunnelTemplate.tsx b/packages/plugins/@nocobase/plugin-charts/src/client/templates/FunnelTemplate.tsx new file mode 100644 index 0000000000..39d52e1d4a --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/client/templates/FunnelTemplate.tsx @@ -0,0 +1,74 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + +import JSON5 from 'json5'; + +const chartConfig = { + xField: '{{dimension}}', + yField: '{{metric}}', + seriesField: '{{category}}', + legend: false, +}; + +export const funnelTemplate = { + description: '1 「Unordered Noun」 field, 1 「Numeric」 field', + type: 'Funnel', + title: 'Funnel', + iconId: 'icon-funnel', + group: 1, + renderComponent: 'G2Plot', + defaultChartOptions: chartConfig, + configurableProperties: { + type: 'void', + properties: { + dimension: { + required: true, + type: 'string', + title: '{{t("Sector label / Dimensional",{ns:"charts"})}}', + 'x-decorator': 'FormItem', + 'x-component': 'Select', + enum: '{{dataSource}}', + }, + metric: { + required: true, + type: 'string', + title: '{{t("Funnel Layer Width/Metrics",{ns:"charts"})}}', + 'x-decorator': 'FormItem', + 'x-component': 'Select', + enum: '{{dataSource}}', + }, + category: { + type: 'string', + title: '{{t("Color legend / Dimensional",{ns:"charts"})}}', + 'x-decorator': 'FormItem', + 'x-component': 'Select', + enum: '{{dataSource}}', + }, + jsonConfig: { + type: 'void', + 'x-component': 'div', + properties: { + template: { + required: true, + title: '{{t("JSON config",{ns:"charts"})}}', + type: 'string', + default: JSON5.stringify(chartConfig, null, 2), + 'x-decorator': 'FormItem', + 'x-component': 'Input.TextArea', + 'x-component-props': { + autoSize: { minRows: 8, maxRows: 16 }, + }, + description: '{{jsonConfigDesc("Funnel | G2Plot","https://g2plot.antv.antgroup.com/api/plots/funnel")}}', + 'x-validator': { json5: true }, + }, + }, + }, + }, + }, +}; diff --git a/packages/plugins/@nocobase/plugin-charts/src/client/templates/LineTemplate.tsx b/packages/plugins/@nocobase/plugin-charts/src/client/templates/LineTemplate.tsx new file mode 100644 index 0000000000..fae41e0703 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/client/templates/LineTemplate.tsx @@ -0,0 +1,81 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + +import JSON5 from 'json5'; + +const chartConfig = { + yField: '{{metric}}', + xField: '{{dimension}}', + seriesField: '{{category}}', + xAxis: { + //type: 'time', + }, + yAxis: { + // label: { + // formatter: '{{(v) => `${v}`.replace(/\d{1,3}(?=(\d{3})+$)/g, (s) => `${s},`)}}', + // }, + }, +}; + +export const lineTemplate = { + description: '1 「Time」 or 「Order Noun」 field, 1 「Value」 field', + type: 'Line', + title: 'Line', + iconId: 'icon-line', + group: 2, + renderComponent: 'G2Plot', + defaultChartOptions: chartConfig, + configurableProperties: { + type: 'void', + properties: { + dimension: { + required: true, + type: 'string', + title: '{{t("Category axis / Dimension",{ns:"charts"})}}', + 'x-decorator': 'FormItem', + 'x-component': 'Select', + enum: '{{dataSource}}', + }, + metric: { + required: true, + type: 'string', + title: '{{t("Value axis / Metrics",{ns:"charts"})}}', + 'x-decorator': 'FormItem', + 'x-component': 'Select', + enum: '{{dataSource}}', + }, + category: { + type: 'string', + title: '{{t("Color legend / Dimensional",{ns:"charts"})}}', + 'x-decorator': 'FormItem', + 'x-component': 'Select', + enum: '{{dataSource}}', + }, + jsonConfig: { + type: 'void', + 'x-component': 'div', + properties: { + template: { + required: true, + title: '{{t("JSON config",{ns:"charts"})}}', + type: 'string', + default: JSON5.stringify(chartConfig, null, 2), + 'x-decorator': 'FormItem', + 'x-component': 'Input.TextArea', + 'x-component-props': { + autoSize: { minRows: 8, maxRows: 16 }, + }, + description: '{{jsonConfigDesc("Line | G2Plot","https://g2plot.antv.antgroup.com/api/plots/line")}}', + 'x-validator': { json5: true }, + }, + }, + }, + }, + }, +}; diff --git a/packages/plugins/@nocobase/plugin-charts/src/client/templates/PieTemplate.tsx b/packages/plugins/@nocobase/plugin-charts/src/client/templates/PieTemplate.tsx new file mode 100644 index 0000000000..0f0f0cc368 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/client/templates/PieTemplate.tsx @@ -0,0 +1,77 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + +import JSON5 from 'json5'; + +const chartConfig = { + appendPadding: 10, + angleField: '{{metric}}', + colorField: '{{dimension}}', + radius: 0.9, + label: { + type: 'inner', + offset: '-30%', + content: '{{({percent}) => `${(percent * 100).toFixed(0)}%`}}', + style: { + fontSize: 14, + textAlign: 'center', + }, + }, + interactions: [{ type: 'element-active' }], +}; + +export const pieTemplate = { + description: '1 「Time」 or 「Order Noun」 field, 1 「Value」 field', + title: 'Pie', + type: 'Pie', + iconId: 'icon-pie', + group: 2, + renderComponent: 'G2Plot', + defaultChartOptions: chartConfig, + configurableProperties: { + type: 'void', + properties: { + dimension: { + required: true, + type: 'string', + title: '{{t("Sector label / Dimensional",{ns:"charts"})}}', + 'x-decorator': 'FormItem', + 'x-component': 'Select', + enum: '{{dataSource}}', + }, + metric: { + required: true, + type: 'string', + title: '{{t("Sector Angle / Metric",{ns:"charts"})}}', + 'x-decorator': 'FormItem', + 'x-component': 'Select', + enum: '{{dataSource}}', + }, + jsonConfig: { + type: 'void', + 'x-component': 'div', + properties: { + template: { + required: true, + title: '{{t("JSON config",{ns:"charts"})}}', + type: 'string', + default: JSON5.stringify(chartConfig, null, 2), + 'x-decorator': 'FormItem', + 'x-component': 'Input.TextArea', + 'x-component-props': { + autoSize: { minRows: 8, maxRows: 16 }, + }, + description: '{{jsonConfigDesc("Pie | G2Plot","https://g2plot.antv.antgroup.com/api/plots/pie")}}', + 'x-validator': { json5: true }, + }, + }, + }, + }, + }, +}; diff --git a/packages/plugins/@nocobase/plugin-charts/src/client/templates/RadarTemplate.tsx b/packages/plugins/@nocobase/plugin-charts/src/client/templates/RadarTemplate.tsx new file mode 100644 index 0000000000..7a6368d5ae --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/client/templates/RadarTemplate.tsx @@ -0,0 +1,80 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + +import JSON5 from 'json5'; + +const chartConfig = { + xField: '{{dimension}}', + yField: '{{metric}}', + appendPadding: [0, 10, 0, 10], + xAxis: { + tickLine: null, + }, + yAxis: { + label: false, + grid: { + alternateColor: 'rgba(0, 0, 0, 0.04)', + }, + }, + // 开启辅助点 + point: { + size: 2, + }, + area: {}, +}; + +export const radarTemplate = { + description: '1~ 2 「Unordered Noun」 fields, 1 「Numeric」 field', + type: 'Radar', + title: 'Radar', + iconId: 'icon-radar', + group: 1, + renderComponent: 'G2Plot', + defaultChartOptions: chartConfig, + configurableProperties: { + type: 'void', + properties: { + dimension: { + required: true, + type: 'string', + title: '{{t("Branch Tags/Dimensions",{ns:"charts"})}}', + 'x-decorator': 'FormItem', + 'x-component': 'Select', + enum: '{{dataSource}}', + }, + metric: { + required: true, + type: 'string', + title: '{{t("Branch Length/Metrics",{ns:"charts"})}}', + 'x-decorator': 'FormItem', + 'x-component': 'Select', + enum: '{{dataSource}}', + }, + jsonConfig: { + type: 'void', + 'x-component': 'div', + properties: { + template: { + required: true, + title: '{{t("JSON config",{ns:"charts"})}}', + type: 'string', + default: JSON5.stringify(chartConfig, null, 2), + 'x-decorator': 'FormItem', + 'x-component': 'Input.TextArea', + 'x-component-props': { + autoSize: { minRows: 8, maxRows: 16 }, + }, + description: '{{jsonConfigDesc("Radar | G2Plot","https://g2plot.antv.antgroup.com/api/plots/radar")}}', + 'x-validator': { json5: true }, + }, + }, + }, + }, + }, +}; diff --git a/packages/plugins/@nocobase/plugin-charts/src/client/templates/ScatterTemplate.tsx b/packages/plugins/@nocobase/plugin-charts/src/client/templates/ScatterTemplate.tsx new file mode 100644 index 0000000000..964aebd71f --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/client/templates/ScatterTemplate.tsx @@ -0,0 +1,99 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + +import JSON5 from 'json5'; + +const chartConfig = { + appendPadding: 10, + xField: '{{metric}}', + yField: '{{dimension}}', + colorField: '{{category}}', + shape: 'circle', + size: 4, + yAxis: { + nice: true, + line: { + style: { + stroke: '#aaa', + }, + }, + }, + xAxis: { + min: -100, + grid: { + line: { + style: { + stroke: '#eee', + }, + }, + }, + line: { + style: { + stroke: '#aaa', + }, + }, + }, +}; + +export const scatterTemplate = { + description: '1 「Numeric」 field, 0~ 1 「Unordered Noun」 field', + type: 'Scatter', + title: 'Scatter', + iconId: 'icon-scatter', + group: 2, + renderComponent: 'G2Plot', + defaultChartOptions: chartConfig, + configurableProperties: { + type: 'void', + properties: { + dimension: { + required: true, + type: 'string', + title: '{{t("Category axis / Dimension",{ns:"charts"})}}', + 'x-decorator': 'FormItem', + 'x-component': 'Select', + enum: '{{dataSource}}', + }, + metric: { + required: true, + type: 'string', + title: '{{t("Value axis / Metrics",{ns:"charts"})}}', + 'x-decorator': 'FormItem', + 'x-component': 'Select', + enum: '{{dataSource}}', + }, + category: { + type: 'string', + title: '{{t("Color legend / Dimensional",{ns:"charts"})}}', + 'x-decorator': 'FormItem', + 'x-component': 'Select', + enum: '{{dataSource}}', + }, + jsonConfig: { + type: 'void', + 'x-component': 'div', + properties: { + template: { + required: true, + title: '{{t("JSON config",{ns:"charts"})}}', + type: 'string', + default: JSON5.stringify(chartConfig, null, 2), + 'x-decorator': 'FormItem', + 'x-component': 'Input.TextArea', + 'x-component-props': { + autoSize: { minRows: 8, maxRows: 16 }, + }, + description: '{{jsonConfigDesc("Scatter | G2Plot","https://g2plot.antv.antgroup.com/api/plots/scatter")}}', + 'x-validator': { json5: true }, + }, + }, + }, + }, + }, +}; diff --git a/packages/plugins/@nocobase/plugin-charts/src/client/templates/TableTemplate.tsx b/packages/plugins/@nocobase/plugin-charts/src/client/templates/TableTemplate.tsx new file mode 100644 index 0000000000..46eae04b76 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/client/templates/TableTemplate.tsx @@ -0,0 +1,57 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + +import JSON5 from 'json5'; + +const validateJSON = { + validator: `{{(value, rule)=> { + if (!value) { + return ''; + } + try { + const val = JSON5.parse(value); + if(!isNaN(val)) { + return false; + } + return true; + } catch(error) { + console.error(error); + return false; + } + }}}`, + message: '{{t("Invalid JSON format",{ ns: "charts" })}}', +}; + +const chartConfig = { + appendPadding: 10, + angleField: '{{metric}}', + colorField: '{{dimension}}', + radius: 0.9, + label: { + type: 'inner', + offset: '-30%', + content: '{{({percent}) => `${(percent * 100).toFixed(0)}%`}}', + style: { + fontSize: 14, + textAlign: 'center', + }, + }, + interactions: [{ type: 'element-active' }], +}; +export const tableTemplate = { + title: '表格展示', + type: 'DataSetPreviewTable', + group: 2, + renderComponent: 'DataSetPreviewTable', + defaultChartOptions: chartConfig, + configurableProperties: { + type: 'void', + properties: {}, + }, +}; diff --git a/packages/plugins/@nocobase/plugin-charts/src/client/templates/index.ts b/packages/plugins/@nocobase/plugin-charts/src/client/templates/index.ts new file mode 100644 index 0000000000..28c5a3f057 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/client/templates/index.ts @@ -0,0 +1,30 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + +import { pieTemplate } from './PieTemplate'; +import { barTemplate } from './BarTemplate'; +import { columnTemplate } from './ColumnTemplate'; +import { lineTemplate } from './LineTemplate'; +import { areaTemplate } from './AreaTemplate'; +import { tableTemplate } from './TableTemplate'; +import { scatterTemplate } from './ScatterTemplate'; +import { radarTemplate } from './RadarTemplate'; +import { funnelTemplate } from './FunnelTemplate'; + +export const templates = new Map(); + +templates.set('Pie', pieTemplate); +templates.set('Line', lineTemplate); +templates.set('Area', areaTemplate); +templates.set('Bar', barTemplate); +templates.set('Column', columnTemplate); +templates.set('Scatter', scatterTemplate); +templates.set('Radar', radarTemplate); +templates.set('Funnel', funnelTemplate); +// templates.set('DataSetPreviewTable', tableTemplate); diff --git a/packages/plugins/@nocobase/plugin-charts/src/client/utils.ts b/packages/plugins/@nocobase/plugin-charts/src/client/utils.ts new file mode 100644 index 0000000000..4a427244fd --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/client/utils.ts @@ -0,0 +1,48 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + +import JSON5 from 'json5'; +import { uid } from '@formily/shared'; + +const validateArray = (value) => { + try { + value = JSON5.parse(value); + } catch (e) { + return 'Please input validate dataset'; + } + if (Array.isArray(value)) { + if ( + value.every((item) => { + return typeof item === 'object' && Object.keys(item).length > 1; + }) + ) + return true; + } + return 'Please input validate dataset'; +}; + +const parseDataSetString = (str) => { + const dataSetDataArray = JSON5.parse(str); + if (Array.isArray(dataSetDataArray)) { + if ( + dataSetDataArray.every((item) => { + return typeof item === 'object' && Object.keys(item).length > 1; + }) + ) + dataSetDataArray.map((item) => { + if (!item?.id) { + item.id = uid(); + } + return item; + }); + } + return dataSetDataArray; +}; + +export { validateArray, parseDataSetString }; diff --git a/packages/plugins/@nocobase/plugin-charts/src/index.ts b/packages/plugins/@nocobase/plugin-charts/src/index.ts new file mode 100644 index 0000000000..be99a2ff1a --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/index.ts @@ -0,0 +1,11 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + +export * from './server'; +export { default } from './server'; diff --git a/packages/plugins/@nocobase/plugin-charts/src/locale/en-US.json b/packages/plugins/@nocobase/plugin-charts/src/locale/en-US.json new file mode 100644 index 0000000000..7cc9d9b715 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/locale/en-US.json @@ -0,0 +1,22 @@ +{ + "Edit": "Edit", + "Delete": "Delete", + "Cancel": "Cancel", + "Submit": "Submit", + "Actions": "Actions", + "Title": "Title", + "Enable": "Enable", + "SAML manager": "SAML manager", + "SAML Providers": "SAML Providers", + "Redirect url": "Redirect url", + "SP entity id": "SP entity id", + "Add provider": "Add", + "Edit provider": "Edit", + "Client id": "Client id", + "Entity id or issuer": "Entity id or issuer", + "Login Url": "Login Url", + "Public cert": "Public cert", + "Delete provider": "Delete", + "Are you sure you want to delete it?": "Are you sure you want to delete it?", + "Sign in button name, which will be displayed on the sign in page": "Sign in button name, which will be displayed on the sign in page" +} \ No newline at end of file diff --git a/packages/plugins/@nocobase/plugin-charts/src/locale/es-ES.json b/packages/plugins/@nocobase/plugin-charts/src/locale/es-ES.json new file mode 100644 index 0000000000..66340acb07 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/locale/es-ES.json @@ -0,0 +1,52 @@ +{ + "Edit": "Editar", + "Delete": "Borrar", + "Cancel": "Cancelar", + "Submit": "Enviar", + "Actions": "Acciones", + "Title": "Título", + "Enable": "Activar", + "Chart": "Chart", + "Charts": "Charts", + "Queries": "Consultas", + "Select chart query": "Seleccionar consulta de chart", + "Select query data": "Seleccionar datos de consulta", + "Type": "Tipo", + "Chart type": "Tipo de chart", + "Chart title": "Título del chart", + "Basic charts": "Basic charts", + "More charts": "Más charts", + "Chart config": "Chart config", + "Add query": "Añadir consulta", + "Edit query": "Editar consulta", + "Invalid JSON format,must be an object array.": "Formato JSON no válido, debe ser una matriz de objetos.", + "Area": "Área", + "Bar": "Barra", + "Column": "Columna", + "Funnel": "Embudo", + "Line": "Línea", + "Pie": "Tarta", + "Radar": "Radar", + "Scatter": "Dispersión", + "Edit chart block": "Editar bloque de chart", + "Chart preview": "Vista previa de charts", + "Delete queries": "Eliminar consultas", + "Delete query": "Eliminar consulta", + "Add chart query": "Añadir consulta de chart", + "Add SQL query": "Añadir consulta SQL", + "Add JSON query": "Añadir consulta JSON", + "Data preview": "Vista previa de datos", + "Category axis / Dimension": "Eje de categorías / Dimensión", + "Value axis / Metrics": "Eje de valor / Métrica", + "JSON config": "JSON config", + "Create chart block": "Crear bloque de charts", + "Invalid JSON format": "Formato JSON no válido", + "Json config references": "Referencias JSON config", + "Sector Angle / Metric": "Sector Angle / Metric", + "Sector label / Dimensional": "Etiqueta de sector / Dimensional", + "Color legend / Dimensional": "Leyenda de color / Dimensional", + "Funnel Layer Width/Metrics": "Anchura de la capa del embudo / Métrica", + "Branch Tags/Dimensions": "Etiquetas de rama / Dimensión", + "Branch Length/Metrics": "Longitud de rama / Métrica", + "Please check the chart config": "Please check the chart config" +} \ No newline at end of file diff --git a/packages/plugins/@nocobase/plugin-charts/src/locale/fr-FR.json b/packages/plugins/@nocobase/plugin-charts/src/locale/fr-FR.json new file mode 100644 index 0000000000..9e26dfeeb6 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/locale/fr-FR.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/packages/plugins/@nocobase/plugin-charts/src/locale/ja-JP.json b/packages/plugins/@nocobase/plugin-charts/src/locale/ja-JP.json new file mode 100644 index 0000000000..9e26dfeeb6 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/locale/ja-JP.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/packages/plugins/@nocobase/plugin-charts/src/locale/ko-KR.json b/packages/plugins/@nocobase/plugin-charts/src/locale/ko-KR.json new file mode 100644 index 0000000000..724ca10099 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/locale/ko-KR.json @@ -0,0 +1,61 @@ +{ + "Edit": "편집", + "Delete": "삭제", + "Cancel": "취소", + "Submit": "제출", + "Actions": "작업", + "Title": "제목", + "Enable": "사용", + "Chart": "차트", + "Charts": "차트", + "Queries": "쿼리 목록", + "Select chart query": "차트 데이터 선택", + "Select query data": "쿼리 데이터 선택", + "Type": "유형", + "Chart type": "차트 유형", + "Chart title": "차트 제목", + "Basic charts": "기본 차트", + "More charts": "더 많은 차트", + "Chart config": "차트 설정", + "Add query": "쿼리 추가", + "Edit query": "쿼리 편집", + "Invalid JSON format,must be an object array.": "유효하지 않은 JSON 형식, 객체 배열이어야 합니다.", + "Area": "면적 차트", + "Bar": "막대 차트", + "Column": "컬럼 차트", + "Funnel": "퍼널 차트", + "Line": "선형 차트", + "Pie": "파이 차트", + "Radar": "레이더 차트", + "Scatter": "산점도 차트", + "Edit chart block": "차트 블록 편집", + "Chart preview": "차트 미리보기", + "Delete queries": "쿼리 목록 삭제", + "Delete query": "쿼리 삭제", + "Add chart query": "차트 쿼리 추가", + "Add SQL query": "SQL 쿼리 추가", + "Add JSON query": "JSON 쿼리 추가", + "Data preview": "데이터 미리보기", + "Category axis / Dimension": "카테고리 축 / 차원", + "Value axis / Metrics": "값 축 / 메트릭", + "JSON config": "JSON 설정", + "Json config references": "JSON 설정 참조", + "Create chart block": "차트 블록 생성", + "Invalid JSON format": "유효하지 않은 JSON 형식", + "Json config references: ": "JSON 설정 참조: ", + "Sector Angle / Metric": "섹터 각도 / 메트릭", + "Sector label / Dimensional": "섹터 레이블 / 차원", + "Color legend / Dimensional": "색상 범례 / 차원", + "Funnel Layer Width/Metrics": "퍼널 레이어 너비 / 메트릭", + "Branch Tags/Dimensions": "분기 태그 / 차원", + "Branch Length/Metrics": "분기 길이 / 메트릭", + "Please check the chart config": "차트 설정을 확인하십시오", + "1 「time」or 「Ordered Noun」 field,1 「Numerical」 field,1 「Unordered Noun」 field (optional)": "1개의 「time」 또는 「순서가 지정된 명사」 필드, 1개의 「숫자」 필드, 1개의 「순서가 지정되지 않은 명사」 필드 (선택 사항)", + "1 「time」 or 「ordered noun」 field, 1 「value」 field, 0~ 1 「unordered noun」": "1개의 「time」 또는 「순서가 지정된 명사」 필드, 1개의 「value」 필드, 0~1개의 「순서가 지정되지 않은 명사」", + "1 「time」 or 「ordered noun」 field, 1 「value」 field, 0 to 1 「unordered noun」": "1개의 「time」 또는 「순서가 지정된 명사」 필드, 1개의 「value」 필드, 0에서 1개의 「순서가 지정되지 않은 명사」", + "1 「Unordered Noun」 field, 1 「Numeric」 field": "1개의 「순서가 지정되지 않은 명사」 필드, 1개의 「숫자」 필드", + "1 「Time」 or 「Order Noun」 field, 1 「Value」 field": "1개의 「시간」 또는 「순서가 지정된 명사」 필드, 1개의 「값」 필드", + "1~ 2 「Unordered Noun」 fields, 1 「Numeric」 field": "1~2개의 「순서가 지정되지 않은 명사」 필드, 1개의 「숫자」 필드", + "1 「Numeric」 field, 0~ 1 「Unordered Noun」 field": "1개의 「숫자」 필드, 0~1개의 「순서가 지정되지 않은 명사」 필드", + "Chart (Old)": "차트 (이전)" +} \ No newline at end of file diff --git a/packages/plugins/@nocobase/plugin-charts/src/locale/pt-BR.json b/packages/plugins/@nocobase/plugin-charts/src/locale/pt-BR.json new file mode 100644 index 0000000000..e8d1d3cc37 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/locale/pt-BR.json @@ -0,0 +1,22 @@ +{ + "Edit": "Editar", + "Delete": "Delete", + "Cancel": "Cancelar", + "Submit": "Enviar", + "Actions": "Ações", + "Title": "Titulo", + "Enable": "Ativo", + "SAML manager": "Gerenciador SAML", + "SAML Providers": "Provedores SAML", + "Redirect url": "URL de redirecionamento", + "SP entity id": "ID de entidade do provedor de serviço (SP)", + "Add provider": "Adicionar", + "Edit provider": "Editar", + "Client id": "ID do cliente", + "Entity id or issuer": "ID de entidade ou emissor", + "Login Url": "URL de login", + "Public cert": "Certificado público", + "Delete provider": "Excluir", + "Are you sure you want to delete it?": "Tem certeza de que deseja excluí-lo?", + "Sign in button name, which will be displayed on the sign in page": "Nome do botão de login, que será exibido na página de login" +} \ No newline at end of file diff --git a/packages/plugins/@nocobase/plugin-charts/src/locale/ru-RU.json b/packages/plugins/@nocobase/plugin-charts/src/locale/ru-RU.json new file mode 100644 index 0000000000..9e26dfeeb6 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/locale/ru-RU.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/packages/plugins/@nocobase/plugin-charts/src/locale/tr-TR.json b/packages/plugins/@nocobase/plugin-charts/src/locale/tr-TR.json new file mode 100644 index 0000000000..9e26dfeeb6 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/locale/tr-TR.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/packages/plugins/@nocobase/plugin-charts/src/locale/zh-CN.json b/packages/plugins/@nocobase/plugin-charts/src/locale/zh-CN.json new file mode 100644 index 0000000000..d1e38ea407 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/locale/zh-CN.json @@ -0,0 +1,61 @@ +{ + "Edit": "编辑", + "Delete": "删除", + "Cancel": "取消", + "Submit": "提交", + "Actions": "操作", + "Title": "名称", + "Enable": "启用", + "Chart": "图表", + "Charts": "图表", + "Queries": "查询列表", + "Select chart query": "选择图表数据", + "Select query data": "选择查询数据", + "Type": "类型", + "Chart type": "图表类型", + "Chart title": "图表标题", + "Basic charts": "基础图表", + "More charts": "更多图表", + "Chart config": "图表配置", + "Add query": "添加查询", + "Edit query": "编辑查询", + "Invalid JSON format,must be an object array.": "无效的JSON格式,必须是对象数组。", + "Area": "面积图", + "Bar": "条形图", + "Column": "柱状图", + "Funnel": "漏斗图", + "Line": "折线图", + "Pie": "饼图", + "Radar": "雷达图", + "Scatter": "散点图", + "Edit chart block": "编辑图表区块", + "Chart preview": "图表预览", + "Delete queries": "删除查询列表", + "Delete query": "删除查询", + "Add chart query": "添加图表查询", + "Add SQL query": "添加SQL查询", + "Add JSON query": "添加JSON查询", + "Data preview": "数据预览", + "Category axis / Dimension": "类别轴 / 维度", + "Value axis / Metrics": "值轴 / 度量", + "JSON config": "JSON 配置", + "Json config references": "JSON配置参考", + "Create chart block": "创建图表区块", + "Invalid JSON format": "无效的JSON格式", + "Json config references: ": "JSON配置参考: ", + "Sector Angle / Metric": "扇形角 / 度量", + "Sector label / Dimensional": "扇形标签 / 维度", + "Color legend / Dimensional": "颜色系列 / 维度", + "Funnel Layer Width/Metrics": "漏斗层宽度 / 度量", + "Branch Tags/Dimensions": "分支标签 / 维度", + "Branch Length/Metrics": "分支长度 / 度量", + "Please check the chart config": "请检查图表配置", + "1 「time」or 「Ordered Noun」 field,1 「Numerical」 field,1 「Unordered Noun」 field (optional)": "1 个「时间」或「有序名词」字段,1 个「数值」字段,1 个「无序名词」字段(可选)", + "1 「time」 or 「ordered noun」 field, 1 「value」 field, 0~ 1 「unordered noun」": "1 个「时间」或「有序名词」字段,1 个「数值」字段,0 ~ 1 个「无序名词」", + "1 「time」 or 「ordered noun」 field, 1 「value」 field, 0 to 1 「unordered noun」": "1 个「时间」或「有序名词」字段,1 个「数值」字段,0 ~ 1 个「无序名词」", + "1 「Unordered Noun」 field, 1 「Numeric」 field": "1 个「无序名词」字段,1 个「数值」字段", + "1 「Time」 or 「Order Noun」 field, 1 「Value」 field": "1 个「时间」或「有序名词」字段,1 个「数值」字段", + "1~ 2 「Unordered Noun」 fields, 1 「Numeric」 field": "1 ~ 2 个「无序名词」字段,1 个「数值」字段", + "1 「Numeric」 field, 0~ 1 「Unordered Noun」 field": "1 个「数值」字段,0 ~ 1 个「无序名词」字段", + "Chart (Old)": "图表 (旧)" +} \ No newline at end of file diff --git a/packages/plugins/@nocobase/plugin-charts/src/server/actions/chartsQueries.ts b/packages/plugins/@nocobase/plugin-charts/src/server/actions/chartsQueries.ts new file mode 100644 index 0000000000..b743429e8f --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/server/actions/chartsQueries.ts @@ -0,0 +1,58 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + +import JSON5 from 'json5'; +import { query } from '../query'; + +export const getData = async (ctx, next) => { + const { filterByTk } = ctx.action.params; + const r = ctx.db.getRepository('chartsQueries'); + try { + const instance = await r.findOne({ filterByTk }); + const result = await query[instance.type](instance.options, { db: ctx.db, skipError: true }); + if (typeof result === 'string') { + ctx.body = JSON5.parse(result); + } else { + ctx.body = result; + } + } catch (error) { + ctx.body = []; + ctx.logger.info('chartsQueries', error); + } + return next(); +}; + +export const validate = async (ctx, next) => { + const { values } = ctx.action.params; + ctx.body = { + errorMessage: '', + }; + try { + await query.sql(values, { db: ctx.db, validateSQL: true }); + } catch (error) { + ctx.body = { + errorMessage: error.message, + }; + } + return next(); +}; + +export const listMetadata = async (ctx, next) => { + const r = ctx.db.getRepository('chartsQueries'); + const items = await r.find({ sort: '-id' }); + ctx.body = items.map((item) => { + return { + id: item.id, + title: item.title, + type: item.type, + fields: item.fields, + }; + }); + return next(); +}; diff --git a/packages/plugins/@nocobase/plugin-charts/src/server/actions/index.ts b/packages/plugins/@nocobase/plugin-charts/src/server/actions/index.ts new file mode 100644 index 0000000000..d3436f53a5 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/server/actions/index.ts @@ -0,0 +1,9 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + diff --git a/packages/plugins/@nocobase/plugin-charts/src/server/collections/.gitkeep b/packages/plugins/@nocobase/plugin-charts/src/server/collections/.gitkeep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/plugins/@nocobase/plugin-charts/src/server/collections/chartsQueries.ts b/packages/plugins/@nocobase/plugin-charts/src/server/collections/chartsQueries.ts new file mode 100644 index 0000000000..61eb34c3f8 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/server/collections/chartsQueries.ts @@ -0,0 +1,35 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + +import { defineCollection } from '@nocobase/database'; + +export default defineCollection({ + dumpRules: 'required', + name: 'chartsQueries', + shared: true, + fields: [ + { + name: 'title', + type: 'string', + }, + { + name: 'type', + type: 'string', + }, + { + name: 'options', + type: 'json', + }, + { + name: 'fields', + type: 'json', + defaultValue: [], + }, + ], +}); diff --git a/packages/plugins/@nocobase/plugin-charts/src/server/index.ts b/packages/plugins/@nocobase/plugin-charts/src/server/index.ts new file mode 100644 index 0000000000..be989de7c3 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/server/index.ts @@ -0,0 +1,10 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + +export { default } from './plugin'; diff --git a/packages/plugins/@nocobase/plugin-charts/src/server/plugin.ts b/packages/plugins/@nocobase/plugin-charts/src/server/plugin.ts new file mode 100644 index 0000000000..50689fc264 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/server/plugin.ts @@ -0,0 +1,68 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + +import { InstallOptions, Plugin } from '@nocobase/server'; +import JSON5 from 'json5'; +import { resolve } from 'path'; +import { getData, listMetadata, validate } from './actions/chartsQueries'; +import { query } from './query'; + +export class ChartsPlugin extends Plugin { + syncFields = async (instance, { transaction }) => { + const _data = await query[instance.type](instance.options, { db: this.db, transaction, validateSQL: true }); + let data; + if (typeof _data === 'string') { + data = JSON5.parse(_data); + } else { + data = _data; + } + const d = Array.isArray(data) ? data?.[0] : data; + const fields = Object.keys(d || {}).map((f) => { + return { + name: f, + }; + }); + instance.set('fields', fields); + }; + + afterAdd() {} + + beforeLoad() { + this.app.db.on('chartsQueries.beforeCreate', this.syncFields); + this.app.db.on('chartsQueries.beforeUpdate', this.syncFields); + } + + async load() { + await this.importCollections(resolve(__dirname, 'collections')); + + this.app.resourcer.registerActionHandlers({ + 'chartsQueries:getData': getData, + 'chartsQueries:listMetadata': listMetadata, + 'chartsQueries:validate': validate, + }); + + this.app.acl.registerSnippet({ + name: 'pm.charts.queries', + actions: ['chartsQueries:*'], + }); + + this.app.acl.allow('chartsQueries', 'getData', 'loggedIn'); + this.app.acl.allow('chartsQueries', 'listMetadata', 'loggedIn'); + } + + async install(options?: InstallOptions) {} + + async afterEnable() {} + + async afterDisable() {} + + async remove() {} +} + +export default ChartsPlugin; diff --git a/packages/plugins/@nocobase/plugin-charts/src/server/query.ts b/packages/plugins/@nocobase/plugin-charts/src/server/query.ts new file mode 100644 index 0000000000..b3f5196f18 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/server/query.ts @@ -0,0 +1,48 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + +import { Database } from '@nocobase/database'; + +export const query = { + api: async (options) => { + return []; + }, + json: async (options) => { + return options.data || []; + }, + sql: async ( + options, + { + db, + transaction, + skipError, + validateSQL, + }: { db: Database; transaction?: any; skipError?: boolean; validateSQL?: boolean }, + ) => { + try { + // 分号截取,只取第一段 + const sql: string = options.sql.trim().split(';').shift(); + if (!sql) { + throw new Error('SQL is empty'); + } + if (!/^select/i.test(sql) && !/^with([\s\S]+)select([\s\S]+)/i.test(sql)) { + throw new Error('Only select query allowed'); + } + const [data] = await db.sequelize.query(sql, { transaction }); + return data; + } catch (error) { + if (skipError) { + return []; + } + throw error; + } + }, +}; + +export default query; diff --git a/packages/plugins/@nocobase/plugin-charts/src/server/shared/index.ts b/packages/plugins/@nocobase/plugin-charts/src/server/shared/index.ts new file mode 100644 index 0000000000..f9fa60d6d3 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-charts/src/server/shared/index.ts @@ -0,0 +1,11 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + +const choicesTypeInterfaceArray = ['radioGroup', 'select']; +export { choicesTypeInterfaceArray }; diff --git a/packages/presets/nocobase/package.json b/packages/presets/nocobase/package.json index b3ed824b9c..b8e574458e 100644 --- a/packages/presets/nocobase/package.json +++ b/packages/presets/nocobase/package.json @@ -22,6 +22,7 @@ "@nocobase/plugin-block-iframe": "1.5.0-alpha.5", "@nocobase/plugin-block-workbench": "1.5.0-alpha.5", "@nocobase/plugin-calendar": "1.5.0-alpha.5", + "@nocobase/plugin-charts": "1.5.0-alpha.5", "@nocobase/plugin-client": "1.5.0-alpha.5", "@nocobase/plugin-collection-sql": "1.5.0-alpha.5", "@nocobase/plugin-collection-tree": "1.5.0-alpha.5", @@ -76,6 +77,7 @@ }, "deprecated": [ "@nocobase/plugin-audit-logs", + "@nocobase/plugin-charts", "@nocobase/plugin-mobile-client", "@nocobase/plugin-snapshot-field" ],