@gant-lowcode/plugin-code-generator 1.0.10 → 2.0.1

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.
Files changed (75) hide show
  1. package/LICENSE +21 -0
  2. package/{dist → es}/components/code-gen-action/index.d.ts +2 -1
  3. package/es/components/code-gen-action/index.js +330 -0
  4. package/es/components/code-gen-action/index.less +20 -0
  5. package/es/components/code-gen-preview/fixPreviewCode.js +100 -0
  6. package/{dist → es}/components/code-gen-preview/index.d.ts +3 -2
  7. package/es/components/code-gen-preview/index.js +5 -0
  8. package/es/components/code-gen-preview/index.less +16 -0
  9. package/{dist → es}/components/code-gen-result/index.d.ts +2 -2
  10. package/es/components/code-gen-result/index.js +207 -0
  11. package/es/components/code-gen-result/index.less +20 -0
  12. package/{dist → es}/components/codesandbox-preview/index.d.ts +2 -1
  13. package/es/components/codesandbox-preview/index.js +192 -0
  14. package/es/components/codesandbox-preview/index.less +18 -0
  15. package/{dist → es}/components/file-tree/index.d.ts +3 -2
  16. package/es/components/file-tree/index.js +162 -0
  17. package/es/components/file-tree/index.less +54 -0
  18. package/{dist → es}/components/file-type-icon/index.d.ts +2 -2
  19. package/es/components/file-type-icon/index.js +12 -0
  20. package/es/components/file-type-icon/index.less +77 -0
  21. package/{dist → es}/components/sources-view/index.d.ts +2 -1
  22. package/es/components/sources-view/index.js +128 -0
  23. package/es/components/sources-view/index.less +12 -0
  24. package/{dist → es}/index.d.ts +3 -4
  25. package/es/index.js +67 -0
  26. package/es/style.js +9 -0
  27. package/{dist → es}/types/index.d.ts +3 -3
  28. package/es/types/index.js +1 -0
  29. package/lib/components/code-gen-action/index.d.ts +7 -0
  30. package/lib/components/code-gen-action/index.js +336 -0
  31. package/lib/components/code-gen-action/index.less +20 -0
  32. package/lib/components/code-gen-preview/fixPreviewCode.d.ts +2 -0
  33. package/lib/components/code-gen-preview/fixPreviewCode.js +105 -0
  34. package/lib/components/code-gen-preview/index.d.ts +9 -0
  35. package/lib/components/code-gen-preview/index.js +9 -0
  36. package/lib/components/code-gen-preview/index.less +16 -0
  37. package/lib/components/code-gen-result/index.d.ts +14 -0
  38. package/lib/components/code-gen-result/index.js +215 -0
  39. package/lib/components/code-gen-result/index.less +20 -0
  40. package/lib/components/codesandbox-preview/index.d.ts +4 -0
  41. package/lib/components/codesandbox-preview/index.js +199 -0
  42. package/lib/components/codesandbox-preview/index.less +18 -0
  43. package/lib/components/file-tree/index.d.ts +21 -0
  44. package/lib/components/file-tree/index.js +170 -0
  45. package/lib/components/file-tree/index.less +54 -0
  46. package/lib/components/file-type-icon/index.d.ts +6 -0
  47. package/lib/components/file-type-icon/index.js +17 -0
  48. package/lib/components/file-type-icon/index.less +77 -0
  49. package/lib/components/sources-view/index.d.ts +8 -0
  50. package/lib/components/sources-view/index.js +135 -0
  51. package/lib/components/sources-view/index.less +12 -0
  52. package/lib/index.d.ts +27 -0
  53. package/lib/index.js +74 -0
  54. package/lib/style.js +9 -0
  55. package/lib/types/index.d.ts +17 -0
  56. package/lib/types/index.js +3 -0
  57. package/package.json +27 -19
  58. package/dist/components/code-gen-action/index.css +0 -18
  59. package/dist/components/code-gen-action/index.js +0 -203
  60. package/dist/components/code-gen-preview/fixPreviewCode.js +0 -119
  61. package/dist/components/code-gen-preview/index.css +0 -18
  62. package/dist/components/code-gen-preview/index.js +0 -9
  63. package/dist/components/code-gen-result/index.css +0 -18
  64. package/dist/components/code-gen-result/index.js +0 -147
  65. package/dist/components/codesandbox-preview/index.css +0 -17
  66. package/dist/components/codesandbox-preview/index.js +0 -147
  67. package/dist/components/file-tree/index.css +0 -55
  68. package/dist/components/file-tree/index.js +0 -138
  69. package/dist/components/file-type-icon/index.css +0 -73
  70. package/dist/components/file-type-icon/index.js +0 -10
  71. package/dist/components/sources-view/index.css +0 -11
  72. package/dist/components/sources-view/index.js +0 -128
  73. package/dist/index.js +0 -50
  74. package/dist/types/index.js +0 -1
  75. /package/{dist → es}/components/code-gen-preview/fixPreviewCode.d.ts +0 -0
@@ -1,203 +0,0 @@
1
- import * as __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__ from "react/jsx-runtime";
2
- import * as __WEBPACK_EXTERNAL_MODULE_react__ from "react";
3
- import * as __WEBPACK_EXTERNAL_MODULE__gant_lowcode_code_generator_standalone_loader__ from "@gant-lowcode/code-generator/standalone-loader";
4
- import * as __WEBPACK_EXTERNAL_MODULE__gant_lowcode_lowcode_types__ from "@gant-lowcode/lowcode-types";
5
- import * as __WEBPACK_EXTERNAL_MODULE_antd__ from "antd";
6
- import * as __WEBPACK_EXTERNAL_MODULE_semver_functions_coerce_js__ from "semver/functions/coerce.js";
7
- import * as __WEBPACK_EXTERNAL_MODULE_semver_functions_compare_js__ from "semver/functions/compare.js";
8
- import * as __WEBPACK_EXTERNAL_MODULE__code_gen_result_index_js__ from "../code-gen-result/index.js";
9
- import "./index.css";
10
- import * as __WEBPACK_EXTERNAL_MODULE__ant_design_icons__ from "@ant-design/icons";
11
- import * as __WEBPACK_EXTERNAL_MODULE_file_saver__ from "file-saver";
12
- import * as __WEBPACK_EXTERNAL_MODULE_ahooks__ from "ahooks";
13
- function CodeGenActionBtn({ ctx }) {
14
- const [state, setState] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)({
15
- open: false,
16
- hasError: false,
17
- error: null,
18
- loading: false,
19
- result: null,
20
- schema: null,
21
- originalSchema: null
22
- });
23
- const codeGenResultRef = (0, __WEBPACK_EXTERNAL_MODULE_react__.useRef)(null);
24
- const handleClick = async ()=>{
25
- try {
26
- // 打开基于 Gravity 的编辑器/出码预览器
27
- setState((prev)=>({
28
- ...prev,
29
- loading: true,
30
- open: true,
31
- hasError: false
32
- }));
33
- console.log("--ctx", ctx);
34
- const getProjectSchema = ctx.config.get("getProjectSchema");
35
- let originalSchema;
36
- originalSchema = getProjectSchema ? await getProjectSchema() : await ctx.project.exportSchema(__WEBPACK_EXTERNAL_MODULE__gant_lowcode_lowcode_types__.IPublicEnumTransformStage.Save);
37
- // 获取 schema,并修正
38
- const schema = await fixSchema(originalSchema);
39
- console.log("got schema: ", schema);
40
- setState((prev)=>({
41
- ...prev,
42
- schema,
43
- originalSchema
44
- }));
45
- // 出码...
46
- const result = await (0, __WEBPACK_EXTERNAL_MODULE__gant_lowcode_code_generator_standalone_loader__.generateCode)({
47
- solution: "gantLegacy",
48
- schema,
49
- flattenResult: true,
50
- builderOptions: {
51
- // mode: 'fully',
52
- rootPaths: [
53
- "packages",
54
- "icost"
55
- ],
56
- pagePaths: [],
57
- configPaths: []
58
- }
59
- });
60
- console.log("generated: ", result);
61
- setState((prev)=>({
62
- ...prev,
63
- loading: false,
64
- result
65
- }));
66
- } catch (e) {
67
- console.error("failed to run code generator: ", e);
68
- setState((prev)=>({
69
- ...prev,
70
- hasError: true,
71
- error: e instanceof Error ? e : new Error(`${e?.message || e}`)
72
- }));
73
- }
74
- };
75
- const { run, loading: downloading } = (0, __WEBPACK_EXTERNAL_MODULE_ahooks__.useRequest)(async ()=>{
76
- try {
77
- const codeGen = codeGenResultRef.current;
78
- if (!codeGen) return;
79
- const content = await codeGen.codeZip();
80
- __WEBPACK_EXTERNAL_MODULE_file_saver__["default"].saveAs(content, "gant-lowcode-generated-sources.zip");
81
- } catch (e) {
82
- console.log("failed to download sources: ", e);
83
- __WEBPACK_EXTERNAL_MODULE_antd__.message.error("下载失败!");
84
- }
85
- }, {
86
- manual: true
87
- });
88
- const handleDownload = async (e)=>{
89
- e.preventDefault();
90
- e.stopPropagation();
91
- run();
92
- };
93
- const { run: handleUpload, loading: uploading } = (0, __WEBPACK_EXTERNAL_MODULE_ahooks__.useRequest)(async ()=>{
94
- const codeGen = codeGenResultRef.current;
95
- if (!codeGen) return;
96
- try {
97
- const blob = await codeGen.codeZip();
98
- const setCodeUpload = ctx.config.get("setCodeUpload");
99
- if (setCodeUpload) await setCodeUpload({
100
- zipFile: blob
101
- });
102
- } catch (error) {
103
- console.log("failed to git push: ", error);
104
- __WEBPACK_EXTERNAL_MODULE_antd__.message.error("上传失败!");
105
- }
106
- }, {
107
- manual: true
108
- });
109
- let drawerChildren = null;
110
- if (state.hasError) drawerChildren = /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Alert, {
111
- type: "error",
112
- message: "出错了",
113
- description: state.error?.message
114
- });
115
- if (state.loading) drawerChildren = /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Spin, {
116
- className: "code-gen-plugin-loading",
117
- spinning: true,
118
- tip: "正在出码..."
119
- });
120
- drawerChildren = /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__code_gen_result_index_js__.CodeGenResult, {
121
- ref: codeGenResultRef,
122
- result: state.result,
123
- schema: state.schema,
124
- originalSchema: state.originalSchema
125
- });
126
- return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsxs)(__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.Fragment, {
127
- children: [
128
- /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Button, {
129
- type: "text",
130
- onClick: handleClick,
131
- children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__ant_design_icons__.CodeOutlined, {})
132
- }),
133
- /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Drawer, {
134
- open: state.open,
135
- title: "出码结果",
136
- width: "95vw",
137
- rootClassName: "code-gen-drawer",
138
- extra: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsxs)(__WEBPACK_EXTERNAL_MODULE_antd__.Space, {
139
- children: [
140
- /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Button, {
141
- type: "link",
142
- onClick: handleUpload,
143
- loading: uploading,
144
- children: "上传git"
145
- }),
146
- /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Button, {
147
- type: "link",
148
- onClick: handleDownload,
149
- loading: downloading,
150
- children: "下载源代码"
151
- })
152
- ]
153
- }),
154
- onClose: ()=>{
155
- setState((prev)=>({
156
- ...prev,
157
- open: false
158
- }));
159
- },
160
- children: drawerChildren
161
- })
162
- ]
163
- });
164
- }
165
- async function fixSchema(schema) {
166
- return deepClone({
167
- ...schema,
168
- componentsMap: schema.componentsMap.filter((c)=>c.package) // 去掉没有 package 的组件
169
- .map((c)=>{
170
- // 修正版本号(对于没有有效版本号的组件,默认使用 latest)
171
- if (!isValidVersion(c.version)) {
172
- console.warn('[WARN] got invalid version "%o" for component "%s", use "latest" as fallback', c.version, c);
173
- return {
174
- ...c,
175
- version: "latest"
176
- };
177
- }
178
- // 修正 gantd-lowcode-materials 的版本,最小为1.0.6
179
- if ('gantd-lowcode-materials' === c.package && (0, __WEBPACK_EXTERNAL_MODULE_semver_functions_compare_js__["default"])((0, __WEBPACK_EXTERNAL_MODULE_semver_functions_coerce_js__["default"])(c.version) || '', '1.1.0') <= 0) return {
180
- ...c,
181
- version: 'latest'
182
- };
183
- return c;
184
- })
185
- });
186
- }
187
- function deepClone(x) {
188
- try {
189
- return JSON.parse(JSON.stringify(x));
190
- } catch (e) {
191
- throw new Error(`failed to clone schema -- ${e}`);
192
- }
193
- }
194
- function isValidVersion(version) {
195
- if (!version) return false;
196
- // 对于一些明显非法的版本号过滤下
197
- if ("{{version}}" === version || "null" === version || "undefined" === version) return false;
198
- // 对于 latest/beta/rc 这样的 tag 版本号要支持下
199
- if (/^[a-z][a-z0-9]+([a-z0-9-]+)?$/i.test(version)) return true;
200
- // 最后支持下所有 semver 能识别的版本
201
- return null !== (0, __WEBPACK_EXTERNAL_MODULE_semver_functions_coerce_js__["default"])(version);
202
- }
203
- export { CodeGenActionBtn, fixSchema };
@@ -1,119 +0,0 @@
1
- // 默认生成的代码不符合在线预览的规则,需要处理下
2
- function fixPreviewCode(code, unused) {
3
- if (!code) return null;
4
- const fixedModules = Object.entries(code.modules || {}) // 去掉隐藏文件和 html 以及 md 等无用文件:
5
- .filter(([fpath])=>!fpath.startsWith("/.") && !fpath.endsWith(".html") && !fpath.endsWith(".md")) // 所有的 jsx 文件改成 js 文件(因为 gravity 不支持 jsx)
6
- .map(([fpath, module])=>[
7
- fpath.replace(/\.jsx$/, ".js"),
8
- module
9
- ]).map(([fpath, module])=>[
10
- fpath.replace(/\.scss$/, ".css"),
11
- module
12
- ]).reduce((acc, [fpath, module])=>({
13
- ...acc,
14
- [fpath]: {
15
- ...module,
16
- fpath,
17
- code: module.code // 所有的 import xxx from '@/yyy' 转换为 import xxx from '/src/yyy'
18
- .replace(/import\s+([^\s]+)\s+from\s+['"]@\/([^'"]+)['"]/g, (_, name, path)=>`import ${name} from '/src/${path}'`) // 所有的 import styles from 'xxx.scss' 转换为 import styles from '/src/xxx.css'
19
- .replace(/import\s+([^\s]+)\s+from\s+['"]([^'"]+)\.scss['"]/g, (_, name, path)=>`import ${name} from '${path}.css'`)
20
- }
21
- }), {});
22
- const fixedCode = {
23
- ...code,
24
- modules: fixedModules
25
- };
26
- fixedCode.modules["/src/app.js"] = {
27
- ...fixedCode.modules["/src/app.js"],
28
- code: `
29
- // 注意:为了方便在浏览器中进行预览,这里简化了一些内容
30
- import './shims';
31
- import './global.css';
32
-
33
- import React from 'react';
34
- import ReactDOM from 'react-dom';
35
-
36
- import Page from '${Object.keys(fixedModules).find((fpath)=>fpath.startsWith("/src/pages/"))}';
37
-
38
- ReactDOM.render(<Page/>, document.getElementById('root'));
39
- `
40
- };
41
- // 一些垫片
42
- fixedCode.modules["/src/shims.js"] = {
43
- fpath: "/src/shims.js",
44
- code: ""
45
- };
46
- fixedCode.modules["/package.json"] = {
47
- ...fixedCode.modules["/package.json"],
48
- code: JSON.stringify({
49
- name: "demo",
50
- version: "1.0.0",
51
- dependencies: {
52
- react: "^16.8.3",
53
- "react-dom": "^16.8.3",
54
- ...JSON.parse(fixedCode.modules["/package.json"]?.code || "{}")?.dependencies
55
- }
56
- })
57
- };
58
- fixedCode.modules = pickKeys(fixedCode.modules, [
59
- // '/tsconfig.json',
60
- // '/jsconfig.json',
61
- // '/build.json',
62
- // '/abc.json',
63
- "/package.json",
64
- "/src/routes.js",
65
- "/src/app.js",
66
- "/src/constants.js",
67
- "/src/utils.js",
68
- "/src/i18n.js",
69
- "/src/global.css",
70
- "/src/index.js",
71
- "/src/shims.js",
72
- // layouts 暂时先不加载吧
73
- // '/src/layouts/BasicLayout/index.js',
74
- // '/src/layouts/BasicLayout/menuConfig.js',
75
- // '/src/layouts/BasicLayout/components/Footer/index.js',
76
- // '/src/layouts/BasicLayout/components/Footer/index.module.css',
77
- // '/src/layouts/BasicLayout/components/Logo/index.js',
78
- // '/src/layouts/BasicLayout/components/Logo/index.module.css',
79
- // '/src/layouts/BasicLayout/components/PageNav/index.js',
80
- ...Object.keys(fixedModules).filter((fpath)=>fpath.startsWith("/src/pages/"))
81
- ]);
82
- fixedCode.modules["/src/routes.js"] = {
83
- ...fixedCode.modules["/src/routes.js"],
84
- code: `
85
- `
86
- };
87
- fixedCode.modules["/src/global.css"] = {
88
- fpath: "/src/global.css",
89
- code: `
90
- body {
91
- -webkit-font-smoothing: antialiased;
92
- }
93
- `
94
- };
95
- Object.assign(fixedCode.modules, {
96
- "/src/index.html": {
97
- code: '<div id="root"></div>',
98
- fpath: "/src/index.html"
99
- },
100
- "/src/index.less": {
101
- fpath: "/src/index.less",
102
- code: `
103
-
104
- `
105
- }
106
- });
107
- fixedCode.type = "riddle";
108
- return fixedCode;
109
- }
110
- function pickKeys(data, keys) {
111
- return keys.reduce((acc, key)=>{
112
- if (data[key]) return {
113
- ...acc,
114
- [key]: data[key]
115
- };
116
- return acc;
117
- }, {});
118
- }
119
- export { fixPreviewCode };
@@ -1,18 +0,0 @@
1
- .code-gen-preview-tabs {
2
- flex-direction: column;
3
- height: 100%;
4
- display: flex;
5
- }
6
-
7
- .code-gen-preview-tabs .next-tabs-bar {
8
- flex-shrink: 0;
9
- }
10
-
11
- .code-gen-preview-tabs .next-tabs-content {
12
- flex: 1;
13
- }
14
-
15
- .code-gen-preview-tabs .next-tabs-content .next-tabs-tabpane {
16
- height: 100%;
17
- }
18
-
@@ -1,9 +0,0 @@
1
- import * as __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__ from "react/jsx-runtime";
2
- import * as __WEBPACK_EXTERNAL_MODULE__codesandbox_preview_index_js__ from "../codesandbox-preview/index.js";
3
- import "./index.css";
4
- function CodeGenPreview(props) {
5
- return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__codesandbox_preview_index_js__.CodeSandboxPreview, {
6
- ...props
7
- });
8
- }
9
- export { CodeGenPreview };
@@ -1,18 +0,0 @@
1
- .code-gen-tabs {
2
- height: 100%;
3
- }
4
-
5
- .code-gen-tabs .ant-tabs-nav {
6
- margin: 0;
7
- }
8
-
9
- .code-gen-tabs .ant-tabs-content, .code-gen-tabs .ant-tabs-tabpane, .code-gen-source-view {
10
- height: 100%;
11
- }
12
-
13
- .source-view-header {
14
- position: absolute;
15
- top: 18px;
16
- right: 20px;
17
- }
18
-
@@ -1,147 +0,0 @@
1
- import * as __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__ from "react/jsx-runtime";
2
- import * as __WEBPACK_EXTERNAL_MODULE_react__ from "react";
3
- import * as __WEBPACK_EXTERNAL_MODULE_antd__ from "antd";
4
- import "file-saver";
5
- import * as __WEBPACK_EXTERNAL_MODULE_jszip__ from "jszip";
6
- import * as __WEBPACK_EXTERNAL_MODULE__sources_view_index_js__ from "../sources-view/index.js";
7
- import "./index.css";
8
- // import { CodeGenPreview } from "../code-gen-preview/index";
9
- const code_gen_result_rslib_entry_CodeGenResult = /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react__.forwardRef)(function({ result, schema }, ref) {
10
- const [paneState, setPaneState] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)({
11
- expandedKeys: [
12
- "sources",
13
- "preview"
14
- ]
15
- });
16
- const [gravityCode, setGravityCode] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)(null);
17
- const [refresh, setRefresh] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)(0);
18
- (0, __WEBPACK_EXTERNAL_MODULE_react__.useEffect)(()=>{
19
- console.log("--result, schema", result, schema);
20
- setGravityCode(convertCodeGenResult(result, schema));
21
- }, [
22
- result
23
- ]);
24
- const codeZip = async ()=>{
25
- const zip = new __WEBPACK_EXTERNAL_MODULE_jszip__["default"]();
26
- Object.values(gravityCode?.modules || {}).forEach((file)=>{
27
- zip.file(file.fpath.replace(/^\/+/, ""), file.code);
28
- });
29
- return await zip.generateAsync({
30
- type: "blob"
31
- });
32
- };
33
- (0, __WEBPACK_EXTERNAL_MODULE_react__.useImperativeHandle)(ref, ()=>({
34
- codeZip
35
- }));
36
- if (!result) return null;
37
- console.log("--gravityCode", gravityCode);
38
- // const items: TabsProps["items"] = [
39
- // {
40
- // key: "sources",
41
- // label: (
42
- // <span>
43
- // 出码生成的源代码{" "}
44
- // <a href="javascript:void(0)" onClick={handleDownloadSources}>
45
- // 导出/下载 zip 包
46
- // </a>
47
- // </span>
48
- // ),
49
- // children: gravityCode != null && (
50
- // <SourcesView code={gravityCode} onCodeChange={setGravityCode} />
51
- // ),
52
- // },
53
- // {
54
- // key: "preview",
55
- // label: (
56
- // <span>
57
- // 在线预览{" "}
58
- // <a
59
- // href="#refresh"
60
- // onClick={(e) => {
61
- // e.preventDefault();
62
- // e.stopPropagation();
63
- // setRefresh(Date.now());
64
- // }}
65
- // >
66
- // 刷新
67
- // </a>
68
- // </span>
69
- // ),
70
- // children: (
71
- // <div
72
- // className="code-gen-result-gravity-demo"
73
- // style={{ height: "100%" }}
74
- // >
75
- // <CodeGenPreview
76
- // code={gravityCode}
77
- // height={"100%"}
78
- // refresh={refresh}
79
- // />
80
- // </div>
81
- // ),
82
- // },
83
- // ];
84
- // return <Tabs className="code-gen-tabs" items={items} />;
85
- if (!gravityCode) return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Empty, {});
86
- return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)("div", {
87
- className: "code-gen-source-view",
88
- children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__sources_view_index_js__.SourcesView, {
89
- code: gravityCode,
90
- onCodeChange: setGravityCode
91
- })
92
- });
93
- });
94
- function convertCodeGenResult(result, schema) {
95
- const schemaFiles = {
96
- "/.project-schema.json": {
97
- fpath: "/.project-schema.json",
98
- code: `${JSON.stringify(schema, null, 2)}\n`
99
- }
100
- };
101
- if (!result || !Array.isArray(result) || !result.length) return {
102
- type: "demo",
103
- modules: schemaFiles
104
- };
105
- const code = {
106
- type: "demo",
107
- modules: result.reduce((acc, file)=>({
108
- ...acc,
109
- [`/${file.pathName}`]: {
110
- fpath: `/${file.pathName}`,
111
- code: file.content,
112
- entry: void 0,
113
- packagejson: [
114
- "package.json"
115
- ].includes(file.pathName) ? 1 : void 0
116
- }
117
- }), {})
118
- };
119
- let foundEntry = false;
120
- // 设置入口文件
121
- [
122
- "index.js",
123
- "index.ts",
124
- "index.tsx",
125
- "app.js",
126
- "app.ts",
127
- "app.tsx"
128
- ].forEach((fileName)=>{
129
- if (!foundEntry) {
130
- const filePath = `/src/${fileName}`;
131
- if (code.modules[filePath]) {
132
- foundEntry = true;
133
- if ("index.js" === fileName) code.modules[filePath].entry = 1;
134
- else code.modules["/src/index.js"] = {
135
- fpath: "/src/index.js",
136
- entry: 1,
137
- code: `import "./${fileName.replace(/\.\w+$/, "")}"`
138
- };
139
- }
140
- }
141
- });
142
- if (!foundEntry) console.warn("Failed to find entry file for demo.");
143
- // 补充 schema 文件
144
- // Object.assign(code.modules, schemaFiles);
145
- return code;
146
- }
147
- export { code_gen_result_rslib_entry_CodeGenResult as CodeGenResult };
@@ -1,17 +0,0 @@
1
- .code-gen-plugin-code-sandbox-preview {
2
- flex-direction: row;
3
- place-content: center;
4
- place-items: center;
5
- height: 100%;
6
- display: flex;
7
- }
8
-
9
- .code-gen-plugin-code-sandbox-preview iframe {
10
- border: 0;
11
- border-radius: 0;
12
- width: 100%;
13
- height: 100%;
14
- min-height: 300px;
15
- overflow: hidden;
16
- }
17
-
@@ -1,147 +0,0 @@
1
- import * as __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__ from "react/jsx-runtime";
2
- import * as __WEBPACK_EXTERNAL_MODULE_react__ from "react";
3
- import * as __WEBPACK_EXTERNAL_MODULE_antd__ from "antd";
4
- import * as __WEBPACK_EXTERNAL_MODULE__code_gen_preview_fixPreviewCode_js__ from "../code-gen-preview/fixPreviewCode.js";
5
- import "./index.css";
6
- // 使用 CodeSandbox 来进行预览
7
- // @see https://codesandbox.io/docs/api#get-request
8
- function CodeSandboxPreview({ code, height }) {
9
- const parameters = (0, __WEBPACK_EXTERNAL_MODULE_react__.useMemo)(()=>{
10
- const files = {};
11
- if (code && code.modules) {
12
- const fixedCode = (0, __WEBPACK_EXTERNAL_MODULE__code_gen_preview_fixPreviewCode_js__.fixPreviewCode)(code);
13
- if (fixedCode) Object.values(fixedCode.modules).forEach((file)=>{
14
- files[file?.fpath?.slice(1)] = {
15
- isBinary: false,
16
- content: file.code
17
- };
18
- });
19
- // 入口文件需要顺便引入下样式
20
- files["src/index.js"] = {
21
- isBinary: false,
22
- content: `
23
- // 目前需要单独引入下样式文件
24
- import "@alifd/next/dist/next.css";
25
- import "@alifd/pro-layout/dist/AlifdProLayout.css";
26
-
27
- // 引入入口文件
28
- import './app';
29
- `
30
- };
31
- }
32
- return {
33
- files,
34
- template: "create-react-app"
35
- };
36
- }, [
37
- code
38
- ]);
39
- const [state, setState] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)({
40
- parameters,
41
- sandboxId: "",
42
- isCreating: false,
43
- hasError: false,
44
- error: null
45
- });
46
- (0, __WEBPACK_EXTERNAL_MODULE_react__.useEffect)(()=>{
47
- if (state.parameters !== parameters || "retry" === state.sandboxId || !state.sandboxId) {
48
- let hasCanceled = false;
49
- setState((prev)=>({
50
- ...prev,
51
- hasError: false,
52
- code,
53
- parameters,
54
- isCreating: true
55
- }));
56
- (async ()=>{
57
- try {
58
- const sandboxId = await createCodeSandbox(parameters);
59
- if (!hasCanceled) setState((prev)=>({
60
- ...prev,
61
- hasError: false,
62
- isCreating: false,
63
- sandboxId: sandboxId
64
- }));
65
- } catch (error) {
66
- if (!hasCanceled) setState((prev)=>({
67
- ...prev,
68
- hasError: true,
69
- error,
70
- isCreating: false
71
- }));
72
- }
73
- })();
74
- return ()=>{
75
- hasCanceled = true;
76
- };
77
- }
78
- return ()=>{};
79
- }, [
80
- parameters,
81
- state.sandboxId,
82
- state.parameters
83
- ]);
84
- const handleRetry = ()=>{
85
- setState((prev)=>({
86
- ...prev,
87
- hasError: false,
88
- sandboxId: "retry"
89
- }));
90
- };
91
- return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)("div", {
92
- className: "code-gen-plugin-code-sandbox-preview",
93
- style: {
94
- height
95
- },
96
- "data-code-sandbox-id": state.sandboxId,
97
- children: (()=>{
98
- if (state.hasError) return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Alert, {
99
- message: "生成 CodeSandbox 预览应用失败",
100
- description: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsxs)(__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.Fragment, {
101
- children: [
102
- /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsxs)("p", {
103
- children: [
104
- "详细错误:",
105
- `${state.error || "网络开小差了"}`
106
- ]
107
- }),
108
- /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)("p", {
109
- children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Button, {
110
- onClick: handleRetry,
111
- children: "重新尝试下"
112
- })
113
- })
114
- ]
115
- })
116
- });
117
- return state.sandboxId ? /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)("iframe", {
118
- src: `https://codesandbox.io/embed/${state.sandboxId}?autoresize=1&fontsize=14&hidenavigation=1&theme=dark&view=preview`,
119
- title: "CodeSandbox Preview",
120
- allow: "accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking",
121
- sandbox: "allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
122
- }) : /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Spin, {
123
- spinning: true,
124
- tip: "正在生成 CodeSandbox 预览应用..."
125
- });
126
- })()
127
- });
128
- }
129
- async function createCodeSandbox(parameters) {
130
- if (!Object.entries(parameters?.files || {}).length) return "";
131
- const res = await fetch("https://codesandbox.io/api/v1/sandboxes/define?json=1", {
132
- method: "POST",
133
- headers: {
134
- "Content-Type": "application/json",
135
- Accept: "application/json"
136
- },
137
- body: JSON.stringify(parameters)
138
- });
139
- if (!res.ok) throw new Error(`创建 CodeSandbox 失败,错误码:${res.status} ${res.statusText}`);
140
- const json = await res.json().catch((err)=>{
141
- throw new Error(`创建 CodeSandbox 失败,服务异常(${err?.message || err || "未知异常"})`);
142
- });
143
- const { sandbox_id } = json || {};
144
- if (!sandbox_id || "string" != typeof sandbox_id) throw new Error(`创建 CodeSandbox 失败,服务响应异常`);
145
- return sandbox_id;
146
- }
147
- export { CodeSandboxPreview };