plugin-build-visualization-block 0.1.5 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +21 -0
- package/client.d.ts +2 -2
- package/client.js +1 -1
- package/dist/client/59.6bac6ada1dacea82.js +10 -0
- package/dist/client/index.js +1 -1
- package/dist/client-v2/385.1e235c5081822f07.js +10 -0
- package/dist/client-v2/59.cdb723e410dac32b.js +10 -0
- package/dist/client-v2/index.js +37 -1
- package/dist/externalVersion.js +12 -7
- package/dist/locale/en-US.json +77 -37
- package/dist/locale/vi-VN.json +58 -40
- package/dist/locale/zh-CN.json +79 -40
- package/dist/node_modules/zod/index.cjs +1 -1
- package/dist/node_modules/zod/package.json +1 -1
- package/dist/server/actions/build.js +7 -704
- package/dist/server/collections/workflow-runs.js +51 -0
- package/dist/server/pipeline/analyzer.js +18 -4
- package/dist/server/plugin.js +17 -20
- package/dist/server/tools/build-visualization-block.js +9 -26
- package/dist/server/workflow-domain.js +209 -0
- package/dist/server/workflow.js +466 -0
- package/dist/shared/blockSpec.js +1 -1
- package/dist/shared/workflow.js +58 -0
- package/package.json +14 -3
- package/server.d.ts +2 -2
- package/server.js +1 -1
- package/src/client/locale.ts +18 -18
- package/src/client/plugin.tsx +11 -0
- package/src/client/workflow.ts +28 -0
- package/src/client-v2/__tests__/buildApi.test.ts +68 -0
- package/src/client-v2/__tests__/modelOptions.test.ts +190 -0
- package/src/client-v2/__tests__/nativeModels.test.ts +77 -0
- package/src/client-v2/buildApi.ts +93 -0
- package/src/client-v2/components/AISelectors.tsx +85 -0
- package/src/client-v2/components/BuildForm.tsx +186 -0
- package/src/client-v2/components/CollectionMultiSelect.tsx +63 -0
- package/src/client-v2/components/NativePreview.tsx +53 -0
- package/src/client-v2/locale.ts +5 -0
- package/src/client-v2/modelOptions.ts +201 -0
- package/src/client-v2/models/BuildVisualizationBlockModel.tsx +95 -0
- package/src/client-v2/nativeBlock.ts +28 -0
- package/src/client-v2/pages/SettingsPage.tsx +77 -0
- package/src/client-v2/plugin.tsx +17 -4
- package/src/client-v2/workflow-fields.tsx +23 -0
- package/src/client-v2/workflow.ts +28 -0
- package/src/locale/en-US.json +77 -37
- package/src/locale/namespace.ts +6 -6
- package/src/locale/vi-VN.json +58 -40
- package/src/locale/zh-CN.json +79 -40
- package/src/server/__tests__/build-action.test.ts +121 -117
- package/src/server/__tests__/plugin.test.ts +19 -34
- package/src/server/actions/build.ts +15 -1031
- package/src/server/collections/workflow-runs.ts +30 -0
- package/src/server/pipeline/analyzer.ts +395 -368
- package/src/server/plugin.ts +26 -35
- package/src/server/tools/build-visualization-block.ts +18 -28
- package/src/server/workflow-domain.ts +235 -0
- package/src/server/workflow.ts +519 -0
- package/src/shared/blockSpec.ts +10 -1
- package/src/shared/workflow.ts +26 -0
- package/dist/client-v2/812.6b4f5e757b898c82.js +0 -10
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
|
|
3
|
+
import { useApp } from '@nocobase/client-v2';
|
|
4
|
+
import { useFlowContext, type FlowModelContext } from '@nocobase/flow-engine';
|
|
5
|
+
import { useRequest } from 'ahooks';
|
|
6
|
+
import { Alert, App, Button, Form, Input, Space, Spin, Tag, Typography } from 'antd';
|
|
7
|
+
import React, { useEffect, useState } from 'react';
|
|
8
|
+
import { MAX_COLLECTIONS, MAX_REQUIREMENT_CHARS } from '../../shared/constants';
|
|
9
|
+
import { loadSettings, readBuild, retryBuild, startBuild, type BuildResult, type BuildSelection } from '../buildApi';
|
|
10
|
+
import { useT } from '../locale';
|
|
11
|
+
import { ModelSelect, ServiceSelect } from './AISelectors';
|
|
12
|
+
import { CollectionMultiSelect, type CollectionSelection } from './CollectionMultiSelect';
|
|
13
|
+
import { NativePreview } from './NativePreview';
|
|
14
|
+
|
|
15
|
+
type Values = { requirement: string; collections: CollectionSelection; llmService: string; model: string };
|
|
16
|
+
export function BuildForm({
|
|
17
|
+
value,
|
|
18
|
+
onChange,
|
|
19
|
+
context,
|
|
20
|
+
}: {
|
|
21
|
+
value?: BuildSelection;
|
|
22
|
+
onChange?: (value?: BuildSelection) => void;
|
|
23
|
+
context?: FlowModelContext;
|
|
24
|
+
}) {
|
|
25
|
+
const inherited = useFlowContext<FlowModelContext>();
|
|
26
|
+
const ctx = context || inherited;
|
|
27
|
+
const app = useApp();
|
|
28
|
+
const api = app.apiClient;
|
|
29
|
+
const t = useT();
|
|
30
|
+
const { message } = App.useApp();
|
|
31
|
+
const [form] = Form.useForm<Values>();
|
|
32
|
+
const service = Form.useWatch('llmService', form);
|
|
33
|
+
const [buildId, setBuildId] = useState(value?.buildId);
|
|
34
|
+
const [result, setResult] = useState<BuildResult>();
|
|
35
|
+
const [polling, setPolling] = useState(!!value?.buildId);
|
|
36
|
+
const aiAvailable = !!app.pm.get('ai');
|
|
37
|
+
const defaults = useRequest(() => loadSettings(api), {
|
|
38
|
+
onSuccess: (settings) =>
|
|
39
|
+
form.setFieldsValue({
|
|
40
|
+
collections: {
|
|
41
|
+
dataSource: settings.defaultDataSource || 'main',
|
|
42
|
+
collections: settings.defaultCollections || [],
|
|
43
|
+
},
|
|
44
|
+
llmService: settings.defaultLLMService,
|
|
45
|
+
model: settings.defaultModel,
|
|
46
|
+
}),
|
|
47
|
+
});
|
|
48
|
+
const {
|
|
49
|
+
run: poll,
|
|
50
|
+
cancel,
|
|
51
|
+
error: pollError,
|
|
52
|
+
} = useRequest(
|
|
53
|
+
async () => {
|
|
54
|
+
if (!buildId) throw new Error('Invalid build response');
|
|
55
|
+
return readBuild(api, buildId);
|
|
56
|
+
},
|
|
57
|
+
{
|
|
58
|
+
manual: true,
|
|
59
|
+
pollingInterval: 2000,
|
|
60
|
+
pollingWhenHidden: false,
|
|
61
|
+
onSuccess: (next) => {
|
|
62
|
+
setResult(next);
|
|
63
|
+
if (next.buildPhase === 'completed' || next.buildPhase === 'failed') {
|
|
64
|
+
setPolling(false);
|
|
65
|
+
if (next.buildPhase === 'completed' && next.blockSpec) onChange?.({ buildId: next.id, spec: next.blockSpec });
|
|
66
|
+
}
|
|
67
|
+
},
|
|
68
|
+
},
|
|
69
|
+
);
|
|
70
|
+
useEffect(() => {
|
|
71
|
+
if (buildId && polling) poll();
|
|
72
|
+
else cancel();
|
|
73
|
+
return cancel;
|
|
74
|
+
}, [buildId, polling, poll, cancel]);
|
|
75
|
+
|
|
76
|
+
const build = useRequest(
|
|
77
|
+
async (values: Values) => {
|
|
78
|
+
const id = await startBuild(api, {
|
|
79
|
+
requirement: values.requirement.trim(),
|
|
80
|
+
dataSource: values.collections.dataSource || 'main',
|
|
81
|
+
collections: values.collections.collections || [],
|
|
82
|
+
llmService: values.llmService,
|
|
83
|
+
model: values.model,
|
|
84
|
+
});
|
|
85
|
+
onChange?.(undefined);
|
|
86
|
+
setResult(undefined);
|
|
87
|
+
setBuildId(id);
|
|
88
|
+
setPolling(true);
|
|
89
|
+
},
|
|
90
|
+
{ manual: true, onError: () => message.error(t('The requirement could not be saved')) },
|
|
91
|
+
);
|
|
92
|
+
const retry = useRequest(
|
|
93
|
+
async () => {
|
|
94
|
+
if (!buildId) return;
|
|
95
|
+
await retryBuild(api, buildId);
|
|
96
|
+
onChange?.(undefined);
|
|
97
|
+
setResult(undefined);
|
|
98
|
+
setPolling(true);
|
|
99
|
+
},
|
|
100
|
+
{ manual: true, onError: () => message.error(t('The requirement could not be saved')) },
|
|
101
|
+
);
|
|
102
|
+
|
|
103
|
+
return (
|
|
104
|
+
<Space direction="vertical" style={{ width: '100%' }} size="middle">
|
|
105
|
+
{!aiAvailable && <Alert type="warning" showIcon message={t('The AI service is unavailable')} />}
|
|
106
|
+
{defaults.error && <Alert type="warning" showIcon message={t('Failed to load the list')} />}
|
|
107
|
+
{pollError && (
|
|
108
|
+
<Alert
|
|
109
|
+
type="error"
|
|
110
|
+
showIcon
|
|
111
|
+
message={t('Failed to load build status')}
|
|
112
|
+
action={<Button onClick={poll}>{t('Retry')}</Button>}
|
|
113
|
+
/>
|
|
114
|
+
)}
|
|
115
|
+
{polling ? (
|
|
116
|
+
<Space>
|
|
117
|
+
<Spin />
|
|
118
|
+
<Tag>{t(result?.buildPhase || 'queued')}</Tag>
|
|
119
|
+
<Typography.Text>{t('Generating')}</Typography.Text>
|
|
120
|
+
</Space>
|
|
121
|
+
) : null}
|
|
122
|
+
{result?.buildPhase === 'failed' && (
|
|
123
|
+
<Alert type="error" showIcon message={result.errorMessage || t('The requirement could not be saved')} />
|
|
124
|
+
)}
|
|
125
|
+
{result?.buildPhase === 'completed' && result.blockSpec ? (
|
|
126
|
+
<>
|
|
127
|
+
{result.usedFallback && (
|
|
128
|
+
<Alert type="warning" showIcon message={t('Generated using fallback specification')} />
|
|
129
|
+
)}
|
|
130
|
+
{Array.isArray(result.adjustments) && result.adjustments.length > 0 && (
|
|
131
|
+
<details>
|
|
132
|
+
<summary>{t('Adjustments')}</summary>
|
|
133
|
+
<pre style={{ whiteSpace: 'pre-wrap' }}>{JSON.stringify(result.adjustments, null, 2)}</pre>
|
|
134
|
+
</details>
|
|
135
|
+
)}
|
|
136
|
+
<NativePreview ctx={ctx} spec={result.blockSpec} />
|
|
137
|
+
<Typography.Text type="secondary">
|
|
138
|
+
{t('Save this configuration to insert the generated block.')}
|
|
139
|
+
</Typography.Text>
|
|
140
|
+
</>
|
|
141
|
+
) : null}
|
|
142
|
+
{!polling && buildId && (
|
|
143
|
+
<Button loading={retry.loading} onClick={() => retry.run()} disabled={!aiAvailable}>
|
|
144
|
+
{t('Regenerate')}
|
|
145
|
+
</Button>
|
|
146
|
+
)}
|
|
147
|
+
<Form
|
|
148
|
+
form={form}
|
|
149
|
+
layout="vertical"
|
|
150
|
+
disabled={defaults.loading || build.loading || polling || retry.loading}
|
|
151
|
+
onFinish={(values) => build.run(values)}
|
|
152
|
+
>
|
|
153
|
+
<Form.Item
|
|
154
|
+
name="requirement"
|
|
155
|
+
label={t('Requirement')}
|
|
156
|
+
rules={[{ required: true, whitespace: true }, { max: MAX_REQUIREMENT_CHARS }]}
|
|
157
|
+
>
|
|
158
|
+
<Input.TextArea aria-label={t('Requirement')} rows={3} maxLength={MAX_REQUIREMENT_CHARS} showCount />
|
|
159
|
+
</Form.Item>
|
|
160
|
+
<Form.Item
|
|
161
|
+
name="collections"
|
|
162
|
+
label={t('Collections')}
|
|
163
|
+
rules={[
|
|
164
|
+
{
|
|
165
|
+
validator: (_rule, selected?: CollectionSelection) =>
|
|
166
|
+
selected?.dataSource && selected.collections?.length && selected.collections.length <= MAX_COLLECTIONS
|
|
167
|
+
? Promise.resolve()
|
|
168
|
+
: Promise.reject(new Error(t('At least one collection is required'))),
|
|
169
|
+
},
|
|
170
|
+
]}
|
|
171
|
+
>
|
|
172
|
+
<CollectionMultiSelect />
|
|
173
|
+
</Form.Item>
|
|
174
|
+
<Form.Item name="llmService" label={t('AI service')} rules={[{ required: true }]}>
|
|
175
|
+
<ServiceSelect onChange={() => form.setFieldValue('model', undefined)} />
|
|
176
|
+
</Form.Item>
|
|
177
|
+
<Form.Item name="model" label={t('Model')} rules={[{ required: true }]}>
|
|
178
|
+
<ModelSelect service={service} />
|
|
179
|
+
</Form.Item>
|
|
180
|
+
<Button type="primary" htmlType="submit" loading={build.loading} disabled={!aiAvailable}>
|
|
181
|
+
{t('Build')}
|
|
182
|
+
</Button>
|
|
183
|
+
</Form>
|
|
184
|
+
</Space>
|
|
185
|
+
);
|
|
186
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
|
|
3
|
+
import { useFlowContext } from '@nocobase/flow-engine';
|
|
4
|
+
import { Select, Space } from 'antd';
|
|
5
|
+
import React from 'react';
|
|
6
|
+
import { MAX_COLLECTIONS } from '../../shared/constants';
|
|
7
|
+
import { useT } from '../locale';
|
|
8
|
+
|
|
9
|
+
export type CollectionSelection = { dataSource?: string; collections?: string[] };
|
|
10
|
+
export function CollectionMultiSelect({
|
|
11
|
+
value = {},
|
|
12
|
+
onChange,
|
|
13
|
+
disabled,
|
|
14
|
+
}: {
|
|
15
|
+
value?: CollectionSelection;
|
|
16
|
+
onChange?: (value: CollectionSelection) => void;
|
|
17
|
+
disabled?: boolean;
|
|
18
|
+
}) {
|
|
19
|
+
const ctx = useFlowContext();
|
|
20
|
+
const t = useT();
|
|
21
|
+
const sources = ctx.dataSourceManager.getDataSources();
|
|
22
|
+
const collections = value.dataSource
|
|
23
|
+
? ctx.dataSourceManager.getDataSource(value.dataSource)?.getCollections() || []
|
|
24
|
+
: [];
|
|
25
|
+
return (
|
|
26
|
+
<Space direction="vertical" style={{ width: '100%' }}>
|
|
27
|
+
<Select
|
|
28
|
+
aria-label={t('Data source')}
|
|
29
|
+
placeholder={t('Data source')}
|
|
30
|
+
style={{ width: '100%' }}
|
|
31
|
+
disabled={disabled}
|
|
32
|
+
value={value.dataSource}
|
|
33
|
+
showSearch
|
|
34
|
+
optionFilterProp="label"
|
|
35
|
+
options={sources.map((source) => ({ value: source.key, label: ctx.t(source.displayName || source.key) }))}
|
|
36
|
+
onChange={(dataSource: string) => onChange?.({ dataSource, collections: [] })}
|
|
37
|
+
/>
|
|
38
|
+
<Select
|
|
39
|
+
aria-label={t('Collections')}
|
|
40
|
+
placeholder={t('Collections')}
|
|
41
|
+
mode="multiple"
|
|
42
|
+
style={{ width: '100%' }}
|
|
43
|
+
disabled={disabled || !value.dataSource}
|
|
44
|
+
value={value.collections || []}
|
|
45
|
+
showSearch
|
|
46
|
+
optionFilterProp="label"
|
|
47
|
+
maxCount={MAX_COLLECTIONS}
|
|
48
|
+
options={collections
|
|
49
|
+
.filter((collection) =>
|
|
50
|
+
ctx.acl.can({
|
|
51
|
+
dataSourceKey: value.dataSource,
|
|
52
|
+
resourceName: collection.name,
|
|
53
|
+
actionName: 'list',
|
|
54
|
+
}),
|
|
55
|
+
)
|
|
56
|
+
.map((collection) => ({ value: collection.name, label: ctx.t(collection.title || collection.name) }))}
|
|
57
|
+
onChange={(selected: string[]) =>
|
|
58
|
+
onChange?.({ dataSource: value.dataSource, collections: selected.slice(0, MAX_COLLECTIONS) })
|
|
59
|
+
}
|
|
60
|
+
/>
|
|
61
|
+
</Space>
|
|
62
|
+
);
|
|
63
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
createBlockScopedEngine,
|
|
5
|
+
FlowModelRenderer,
|
|
6
|
+
type FlowModel,
|
|
7
|
+
type FlowModelContext,
|
|
8
|
+
} from '@nocobase/flow-engine';
|
|
9
|
+
import { Alert, ConfigProvider, Spin } from 'antd';
|
|
10
|
+
import React, { useEffect, useState } from 'react';
|
|
11
|
+
import type { BlockSpec } from '../../shared/blockSpec';
|
|
12
|
+
import { useT } from '../locale';
|
|
13
|
+
import { buildNativeOptions } from '../nativeBlock';
|
|
14
|
+
|
|
15
|
+
export function NativePreview({ ctx, spec }: { ctx: FlowModelContext; spec: BlockSpec }) {
|
|
16
|
+
const t = useT();
|
|
17
|
+
const [model, setModel] = useState<FlowModel>();
|
|
18
|
+
const [error, setError] = useState('');
|
|
19
|
+
useEffect(() => {
|
|
20
|
+
let cancelled = false;
|
|
21
|
+
const engine = createBlockScopedEngine(ctx.engine);
|
|
22
|
+
let root: FlowModel | undefined;
|
|
23
|
+
setModel(undefined);
|
|
24
|
+
setError('');
|
|
25
|
+
async function prepare() {
|
|
26
|
+
try {
|
|
27
|
+
const options = buildNativeOptions(ctx, spec, false);
|
|
28
|
+
root = await engine.createModelAsync(options);
|
|
29
|
+
if (cancelled) {
|
|
30
|
+
root.remove();
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
root.context.addDelegate(ctx);
|
|
34
|
+
setModel(root);
|
|
35
|
+
} catch (failure) {
|
|
36
|
+
if (!cancelled) setError(failure instanceof Error ? failure.message : t('Preview is unavailable'));
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
prepare();
|
|
40
|
+
return () => {
|
|
41
|
+
cancelled = true;
|
|
42
|
+
root?.remove();
|
|
43
|
+
engine.unlinkFromStack();
|
|
44
|
+
};
|
|
45
|
+
}, [ctx, spec, t]);
|
|
46
|
+
if (error) return <Alert type="error" showIcon message={t(error)} />;
|
|
47
|
+
if (!model) return <Spin />;
|
|
48
|
+
return (
|
|
49
|
+
<ConfigProvider componentDisabled>
|
|
50
|
+
<FlowModelRenderer model={model} showFlowSettings={false} />
|
|
51
|
+
</ConfigProvider>
|
|
52
|
+
);
|
|
53
|
+
}
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
|
|
3
|
+
import type { CreateModelOptions } from '@nocobase/flow-engine';
|
|
4
|
+
import type { BlockSpec, ChartSpecItem } from '../shared/blockSpec';
|
|
5
|
+
|
|
6
|
+
export type FieldRenderer = (field: string, mode: 'display' | 'edit') => CreateModelOptions;
|
|
7
|
+
|
|
8
|
+
const binding = (spec: BlockSpec) => ({ dataSourceKey: spec.dataSource, collectionName: spec.primaryCollection });
|
|
9
|
+
const title = (value: string) => ({ cardSettings: { titleDescription: { title: value } } });
|
|
10
|
+
const grid = (items: CreateModelOptions[]): CreateModelOptions => ({ use: 'BlockGridModel', subModels: { items } });
|
|
11
|
+
|
|
12
|
+
function chartOptions(chart: ChartSpecItem, spec: BlockSpec, hasChart: (name: string) => boolean): CreateModelOptions {
|
|
13
|
+
if (!chart.measures.length) throw new Error('No compatible chart configuration');
|
|
14
|
+
const measures = chart.measures.map((measure) => ({ ...measure, aggregation: measure.aggregation || 'count' }));
|
|
15
|
+
const dimensions = (chart.dimensions || []).map((dimension) => ({
|
|
16
|
+
...dimension,
|
|
17
|
+
alias: dimension.alias || dimension.field,
|
|
18
|
+
}));
|
|
19
|
+
const config = { ...chart.config };
|
|
20
|
+
const column = (value: unknown, fallback?: string) => {
|
|
21
|
+
if (typeof value !== 'string') return fallback;
|
|
22
|
+
return (
|
|
23
|
+
measures.find((item) => item.field === value)?.alias ||
|
|
24
|
+
dimensions.find((item) => item.field === value)?.alias ||
|
|
25
|
+
value
|
|
26
|
+
);
|
|
27
|
+
};
|
|
28
|
+
let option: Record<string, unknown>;
|
|
29
|
+
if (hasChart(chart.chartType)) {
|
|
30
|
+
option = { mode: 'basic', builder: { ...config, type: chart.chartType } };
|
|
31
|
+
} else if (chart.chartType === 'antd.statistic') {
|
|
32
|
+
const field = column(config.field, measures[0].alias);
|
|
33
|
+
option = {
|
|
34
|
+
mode: 'custom',
|
|
35
|
+
raw: `const rows = ctx.data?.objects || [];
|
|
36
|
+
const value = rows[0]?.[${JSON.stringify(field)}] ?? 0;
|
|
37
|
+
return { graphic: { type: 'text', left: 'center', top: 'middle', style: { text: String(value), fontSize: 36 } } };`,
|
|
38
|
+
};
|
|
39
|
+
} else {
|
|
40
|
+
const types: Record<string, string> = {
|
|
41
|
+
'ant-design-charts.line': 'line',
|
|
42
|
+
'ant-design-charts.column': 'bar',
|
|
43
|
+
'ant-design-charts.bar': 'barHorizontal',
|
|
44
|
+
'ant-design-charts.pie': 'pie',
|
|
45
|
+
'ant-design-charts.area': 'area',
|
|
46
|
+
'ant-design-charts.scatter': 'scatter',
|
|
47
|
+
'ant-design-charts.funnel': 'funnel',
|
|
48
|
+
};
|
|
49
|
+
const type = types[chart.chartType];
|
|
50
|
+
if (!type) throw new Error('No compatible chart configuration');
|
|
51
|
+
const x = column(config.xField, dimensions[0]?.alias),
|
|
52
|
+
y = column(config.yField, measures[0].alias);
|
|
53
|
+
option = {
|
|
54
|
+
mode: 'basic',
|
|
55
|
+
builder: {
|
|
56
|
+
...config,
|
|
57
|
+
type,
|
|
58
|
+
xField: x,
|
|
59
|
+
yField: y,
|
|
60
|
+
seriesField: column(config.seriesField, dimensions[1]?.alias),
|
|
61
|
+
pieCategory: column(config.colorField, dimensions[0]?.alias),
|
|
62
|
+
pieValue: column(config.angleField, measures[0].alias),
|
|
63
|
+
pieRadiusInner: typeof config.innerRadius === 'number' ? config.innerRadius * 100 : 0,
|
|
64
|
+
funnelCategory: column(config.xField, dimensions[0]?.alias),
|
|
65
|
+
funnelValue: column(config.yField, measures[0].alias),
|
|
66
|
+
},
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
return {
|
|
70
|
+
use: 'ChartBlockModel',
|
|
71
|
+
stepParams: {
|
|
72
|
+
...title(chart.title),
|
|
73
|
+
chartSettings: {
|
|
74
|
+
configure: {
|
|
75
|
+
query: { mode: 'builder', collectionPath: [spec.dataSource, spec.primaryCollection], measures, dimensions },
|
|
76
|
+
chart: { option },
|
|
77
|
+
},
|
|
78
|
+
},
|
|
79
|
+
},
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function formOptions(
|
|
84
|
+
spec: BlockSpec,
|
|
85
|
+
fields: string[],
|
|
86
|
+
renderField: FieldRenderer,
|
|
87
|
+
mode: 'create' | 'edit' | 'details',
|
|
88
|
+
actions: boolean,
|
|
89
|
+
): CreateModelOptions {
|
|
90
|
+
const init: Record<string, unknown> = binding(spec);
|
|
91
|
+
if (mode !== 'create') init.filterByTk = '{{ctx.view.inputArgs.filterByTk}}';
|
|
92
|
+
return {
|
|
93
|
+
use: mode === 'create' ? 'CreateFormModel' : mode === 'edit' ? 'EditFormModel' : 'DetailsBlockModel',
|
|
94
|
+
stepParams: { ...title(spec.title), resourceSettings: { init } },
|
|
95
|
+
subModels: {
|
|
96
|
+
grid: {
|
|
97
|
+
use: mode === 'details' ? 'DetailsGridModel' : 'FormGridModel',
|
|
98
|
+
subModels: {
|
|
99
|
+
items: fields.map((field) => ({
|
|
100
|
+
use: mode === 'details' ? 'DetailsItemModel' : 'FormItemModel',
|
|
101
|
+
stepParams: { fieldSettings: { init: { ...binding(spec), fieldPath: field } } },
|
|
102
|
+
subModels: { field: renderField(field, mode === 'details' ? 'display' : 'edit') },
|
|
103
|
+
})),
|
|
104
|
+
},
|
|
105
|
+
},
|
|
106
|
+
actions: mode !== 'details' && actions ? [{ use: 'FormSubmitActionModel' }] : [],
|
|
107
|
+
},
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function popupAction(
|
|
112
|
+
spec: BlockSpec,
|
|
113
|
+
fields: string[],
|
|
114
|
+
renderField: FieldRenderer,
|
|
115
|
+
mode: 'create' | 'edit' | 'details',
|
|
116
|
+
): CreateModelOptions {
|
|
117
|
+
return {
|
|
118
|
+
use: mode === 'create' ? 'AddNewActionModel' : mode === 'edit' ? 'EditActionModel' : 'ViewActionModel',
|
|
119
|
+
stepParams: { popupSettings: { openView: binding(spec) } },
|
|
120
|
+
subModels: {
|
|
121
|
+
page: {
|
|
122
|
+
use: 'ChildPageModel',
|
|
123
|
+
stepParams: { pageSettings: { general: { displayTitle: false, enableTabs: false } } },
|
|
124
|
+
subModels: {
|
|
125
|
+
tabs: [
|
|
126
|
+
{
|
|
127
|
+
use: 'ChildPageTabModel',
|
|
128
|
+
subModels: {
|
|
129
|
+
grid: grid([formOptions(spec, fields, renderField, mode, true)]),
|
|
130
|
+
},
|
|
131
|
+
},
|
|
132
|
+
],
|
|
133
|
+
},
|
|
134
|
+
},
|
|
135
|
+
},
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export function createNativeBlockOptions(
|
|
140
|
+
spec: BlockSpec,
|
|
141
|
+
renderField: FieldRenderer,
|
|
142
|
+
hasChart: (name: string) => boolean,
|
|
143
|
+
includeActions = true,
|
|
144
|
+
currentRecord?: { dataSourceKey?: string; collectionName?: string; filterByTk?: unknown },
|
|
145
|
+
): CreateModelOptions {
|
|
146
|
+
if (spec.blockType === 'chart') {
|
|
147
|
+
if (!spec.charts?.length) throw new Error('No compatible chart configuration');
|
|
148
|
+
return grid(spec.charts.map((chart) => chartOptions(chart, spec, hasChart)));
|
|
149
|
+
}
|
|
150
|
+
const fields = [...new Set(spec.blockType === 'table' ? spec.table?.fields : spec.form?.fields)];
|
|
151
|
+
if (!fields.length) throw new Error('No compatible field renderer');
|
|
152
|
+
if (spec.blockType === 'form') {
|
|
153
|
+
const options = formOptions(
|
|
154
|
+
spec,
|
|
155
|
+
fields,
|
|
156
|
+
renderField,
|
|
157
|
+
spec.form?.mode === 'create' ? 'create' : 'edit',
|
|
158
|
+
includeActions,
|
|
159
|
+
);
|
|
160
|
+
const hasCurrentRecord =
|
|
161
|
+
currentRecord?.collectionName === spec.primaryCollection &&
|
|
162
|
+
(currentRecord.dataSourceKey || 'main') === spec.dataSource &&
|
|
163
|
+
currentRecord.filterByTk != null;
|
|
164
|
+
// Matching popups use their record anchor; standalone blocks retain native pagination.
|
|
165
|
+
return grid([
|
|
166
|
+
spec.form?.mode === 'create' || hasCurrentRecord
|
|
167
|
+
? options
|
|
168
|
+
: {
|
|
169
|
+
...options,
|
|
170
|
+
stepParams: { ...options.stepParams, resourceSettings: { init: binding(spec) } },
|
|
171
|
+
},
|
|
172
|
+
]);
|
|
173
|
+
}
|
|
174
|
+
const actions = includeActions ? spec.table?.actions || [] : [];
|
|
175
|
+
const rowActions: CreateModelOptions[] = [];
|
|
176
|
+
if (actions.includes('view')) rowActions.push(popupAction(spec, fields, renderField, 'details'));
|
|
177
|
+
if (actions.includes('edit')) rowActions.push(popupAction(spec, fields, renderField, 'edit'));
|
|
178
|
+
if (actions.includes('delete')) rowActions.push({ use: 'DeleteActionModel' });
|
|
179
|
+
return grid([
|
|
180
|
+
{
|
|
181
|
+
use: 'TableBlockModel',
|
|
182
|
+
stepParams: { ...title(spec.title), resourceSettings: { init: binding(spec) } },
|
|
183
|
+
subModels: {
|
|
184
|
+
columns: [
|
|
185
|
+
...fields.map(
|
|
186
|
+
(field): CreateModelOptions => ({
|
|
187
|
+
use: 'TableColumnModel',
|
|
188
|
+
stepParams: {
|
|
189
|
+
fieldSettings: { init: { ...binding(spec), fieldPath: field } },
|
|
190
|
+
tableColumnSettings: { sorter: { sorter: !!spec.table?.sortable?.includes(field) } },
|
|
191
|
+
},
|
|
192
|
+
subModels: { field: renderField(field, 'display') },
|
|
193
|
+
}),
|
|
194
|
+
),
|
|
195
|
+
...(rowActions.length ? [{ use: 'TableActionsColumnModel', subModels: { actions: rowActions } }] : []),
|
|
196
|
+
],
|
|
197
|
+
actions: actions.includes('add') ? [popupAction(spec, fields, renderField, 'create')] : [],
|
|
198
|
+
},
|
|
199
|
+
},
|
|
200
|
+
]);
|
|
201
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
|
|
3
|
+
import { BlockModel } from '@nocobase/client-v2';
|
|
4
|
+
import { FlowModelRenderer, tExpr, type CreateModelOptions, type FlowModel } from '@nocobase/flow-engine';
|
|
5
|
+
import { Empty } from 'antd';
|
|
6
|
+
import React from 'react';
|
|
7
|
+
import { readBuild, type BuildSelection } from '../buildApi';
|
|
8
|
+
import { BuildForm } from '../components/BuildForm';
|
|
9
|
+
import { NAMESPACE } from '../locale';
|
|
10
|
+
import { buildNativeOptions } from '../nativeBlock';
|
|
11
|
+
|
|
12
|
+
export class BuildVisualizationBlockModel extends BlockModel<{ subModels: { content?: FlowModel } }> {
|
|
13
|
+
pendingOptions?: CreateModelOptions;
|
|
14
|
+
|
|
15
|
+
async installGenerated(selection: BuildSelection) {
|
|
16
|
+
if (!this.pendingOptions) return;
|
|
17
|
+
const next = await this.flowEngine.createModelAsync({
|
|
18
|
+
...this.pendingOptions,
|
|
19
|
+
parentId: this.uid,
|
|
20
|
+
subKey: 'content',
|
|
21
|
+
subType: 'object',
|
|
22
|
+
});
|
|
23
|
+
const previous = this.subModels.content;
|
|
24
|
+
const previousFingerprint = this.props.generationFingerprint;
|
|
25
|
+
this.setSubModel('content', next);
|
|
26
|
+
this.setProps('generationFingerprint', JSON.stringify(selection));
|
|
27
|
+
try {
|
|
28
|
+
await this.save();
|
|
29
|
+
} catch (error) {
|
|
30
|
+
if (previous) this.setSubModel('content', previous);
|
|
31
|
+
else delete this.subModels.content;
|
|
32
|
+
this.setProps('generationFingerprint', previousFingerprint);
|
|
33
|
+
next.remove();
|
|
34
|
+
throw error;
|
|
35
|
+
}
|
|
36
|
+
this.pendingOptions = undefined;
|
|
37
|
+
if (previous) await previous.destroy();
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
renderComponent() {
|
|
41
|
+
return this.subModels.content ? (
|
|
42
|
+
<FlowModelRenderer model={this.subModels.content} showFlowSettings={false} />
|
|
43
|
+
) : (
|
|
44
|
+
<Empty description={this.context.t('Generate a block to get started', { ns: NAMESPACE })} />
|
|
45
|
+
);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
BuildVisualizationBlockModel.define({
|
|
50
|
+
label: tExpr('Build Visualization Block', { ns: NAMESPACE }),
|
|
51
|
+
group: tExpr('AI', { ns: NAMESPACE }),
|
|
52
|
+
createModelOptions: { use: 'BuildVisualizationBlockModel' },
|
|
53
|
+
hide: (ctx) => !ctx.acl.can({ dataSourceKey: 'main', resourceName: 'aiVisualizationBuilds', actionName: 'build' }),
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
BuildVisualizationBlockModel.registerFlow({
|
|
57
|
+
key: 'visualizationBuildSettings',
|
|
58
|
+
title: tExpr('Build Visualization Block', { ns: NAMESPACE }),
|
|
59
|
+
manual: true,
|
|
60
|
+
sort: -100,
|
|
61
|
+
steps: {
|
|
62
|
+
generate: {
|
|
63
|
+
preset: true,
|
|
64
|
+
title: tExpr('Build Visualization Block', { ns: NAMESPACE }),
|
|
65
|
+
uiMode: { type: 'dialog', props: { width: 1000 } },
|
|
66
|
+
uiSchema: (ctx) => ({
|
|
67
|
+
generation: {
|
|
68
|
+
type: 'object',
|
|
69
|
+
required: true,
|
|
70
|
+
'x-decorator': 'FormItem',
|
|
71
|
+
'x-component': BuildForm,
|
|
72
|
+
'x-component-props': { context: ctx },
|
|
73
|
+
},
|
|
74
|
+
}),
|
|
75
|
+
async beforeParamsSave(ctx, params: { generation?: BuildSelection }) {
|
|
76
|
+
const model = ctx.model as BuildVisualizationBlockModel;
|
|
77
|
+
model.pendingOptions = undefined;
|
|
78
|
+
if (!params.generation?.buildId) throw new Error(ctx.t('Generate a block to get started', { ns: NAMESPACE }));
|
|
79
|
+
const result = await readBuild(ctx.api, params.generation.buildId);
|
|
80
|
+
if (result.buildPhase !== 'completed' || !result.blockSpec)
|
|
81
|
+
throw new Error(ctx.t('Build is not completed', { ns: NAMESPACE }));
|
|
82
|
+
params.generation = { buildId: result.id, spec: result.blockSpec };
|
|
83
|
+
model.setStepParams('visualizationBuildSettings', 'generate', { generation: params.generation });
|
|
84
|
+
if (model.subModels.content && model.props.generationFingerprint === JSON.stringify(params.generation)) return;
|
|
85
|
+
if (result.blockSpec.blockType === 'chart' && !(await ctx.engine.getModelClassAsync('ChartBlockModel'))) {
|
|
86
|
+
throw new Error(ctx.t('Data visualization plugin is unavailable', { ns: NAMESPACE }));
|
|
87
|
+
}
|
|
88
|
+
model.pendingOptions = buildNativeOptions(ctx, result.blockSpec);
|
|
89
|
+
},
|
|
90
|
+
async afterParamsSave(ctx, params: { generation: BuildSelection }) {
|
|
91
|
+
await (ctx.model as BuildVisualizationBlockModel).installGenerated(params.generation);
|
|
92
|
+
},
|
|
93
|
+
},
|
|
94
|
+
},
|
|
95
|
+
});
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
|
|
3
|
+
import { DetailsItemModel, FormItemModel, TableColumnModel } from '@nocobase/client-v2';
|
|
4
|
+
import type PluginDataVisualizationClient from '@nocobase/plugin-data-visualization/client-v2';
|
|
5
|
+
import type { FlowModelContext } from '@nocobase/flow-engine';
|
|
6
|
+
import type { BlockSpec } from '../shared/blockSpec';
|
|
7
|
+
import { createNativeBlockOptions } from './modelOptions';
|
|
8
|
+
|
|
9
|
+
export function buildNativeOptions(ctx: FlowModelContext, spec: BlockSpec, includeActions = true) {
|
|
10
|
+
const collection = ctx.dataSourceManager.getCollection(spec.dataSource, spec.primaryCollection);
|
|
11
|
+
if (!collection) throw new Error(ctx.t('Collection is unavailable', { ns: 'plugin-build-visualization-block' }));
|
|
12
|
+
const visualization = ctx.app.pm.get('data-visualization') as PluginDataVisualizationClient | undefined;
|
|
13
|
+
return createNativeBlockOptions(
|
|
14
|
+
spec,
|
|
15
|
+
(fieldPath, mode) => {
|
|
16
|
+
const field = collection.getFieldByPath(fieldPath);
|
|
17
|
+
const Model = mode === 'edit' ? FormItemModel : spec.blockType === 'table' ? TableColumnModel : DetailsItemModel;
|
|
18
|
+
const binding = Model.getDefaultBindingByField(ctx, field, { fallbackToTargetTitleField: mode === 'display' });
|
|
19
|
+
if (!binding) throw new Error(ctx.t('No compatible field renderer', { ns: 'plugin-build-visualization-block' }));
|
|
20
|
+
const props =
|
|
21
|
+
typeof binding.defaultProps === 'function' ? binding.defaultProps(ctx, field) : binding.defaultProps;
|
|
22
|
+
return { use: binding.modelName, props: { ...props } };
|
|
23
|
+
},
|
|
24
|
+
(name) => !!visualization?.charts.getChart(name),
|
|
25
|
+
includeActions,
|
|
26
|
+
ctx.view?.inputArgs,
|
|
27
|
+
);
|
|
28
|
+
}
|