Compare commits

..

57 Commits

Author SHA1 Message Date
wwsun 8a3ab3c093 chore(release): publish
- @music163/tango-context@1.1.10
 - @music163/tango-core@1.4.4
 - @music163/tango-designer@1.4.6
 - @music163/tango-helpers@1.2.4
 - @music163/tango-sandbox@1.0.13
 - @music163/tango-setting-form@1.2.15
 - @music163/tango-ui@1.4.5
2024-09-09 15:58:16 +08:00
Wells 55602fc961 fix: add classNameSetter and classNameInput (#207)
* feat: add basic classNameInput

* fix: add classNameSetter
2024-09-09 15:50:56 +08:00
864907600cc a3c0e463ca chore: update code editor (#205) 2024-09-09 15:08:02 +08:00
BoBoooooo 79f9a8c179 fix: service support set description field (#206)
* fix: service support set description field

* fix: undefined string bug

* fix: update title display
2024-09-09 15:07:38 +08:00
Wells ea96872261 fix: renderSetter with template (#202)
* fix: renderSetter with template

* fix: update types
2024-09-03 16:52:59 +08:00
wwsun a86e0e049c chore(release): publish
- @music163/tango-context@1.1.9
 - @music163/tango-core@1.4.3
 - @music163/tango-designer@1.4.5
 - @music163/tango-helpers@1.2.3
 - @music163/tango-sandbox@1.0.12
 - @music163/tango-setting-form@1.2.14
 - @music163/tango-ui@1.4.4
2024-09-02 10:50:59 +08:00
Wells c4e1ed67f5 fix: add prop value template & fix components popover (#201)
* fix: clear value in CodeSetter

* fix: update variable path in codesetter

* fix: add prop value template

* fix: update  recommendedList for ComponentsPopover

* fix: update icon size in line mode for ComponentsPanel
2024-08-30 18:09:01 +08:00
wwsun 179de0cc52 chore(release): publish
- @music163/tango-designer@1.4.4
 - @music163/tango-setting-form@1.2.13
 - @music163/tango-ui@1.4.3
2024-08-16 17:50:55 +08:00
BoBoooooo 6de54884b5 fix: CodeInput 支持 jsx css 代码补全 (#198)
* feat: code setter support jsx css completion

* fix: refactor expression css mode

* fix: update story

* fix: revert code
2024-08-16 11:16:39 +08:00
wwsun 55bf417ddf chore(release): publish
- @music163/tango-designer@1.4.3
 - @music163/tango-setting-form@1.2.12
 - @music163/tango-ui@1.4.2
2024-08-09 15:49:28 +08:00
BoBoooooo ca56edd9ae fix: file errors overlay support click to error file & optimize ui (#197) 2024-08-09 13:52:35 +08:00
Wells 65149f1326 fix: update mobile simulator ui (#196)
* fix: update mobile simulator styles

* docs: update

* fix: update icon
2024-08-08 11:20:20 +08:00
864907600cc 939466648d fix: route matching without query string & toggle button wrapping (#195)
* fix: fix route is not matched when url contains query string

* fix: fix mode switch button group wrapping

* fix: fix toggle button text wrapping
2024-08-07 15:51:36 +08:00
wwsun 8fe57333a0 chore(release): publish
- @music163/tango-context@1.1.8
 - @music163/tango-core@1.4.2
 - @music163/tango-designer@1.4.2
 - @music163/tango-sandbox@1.0.11
 - @music163/tango-setting-form@1.2.11
2024-08-06 13:54:27 +08:00
BoBoooooo 269e304d68 fix: view module _nodesTree set init value (#194) 2024-08-06 11:08:42 +08:00
wwsun 8c80255f81 chore: up 2024-08-05 12:31:12 +08:00
wwsun 359aa0b148 chore: update 2024-08-05 12:30:37 +08:00
wwsun 51ca4a72ce chore(release): publish
- @music163/tango-context@1.1.7
 - @music163/tango-core@1.4.1
 - @music163/tango-designer@1.4.1
 - @music163/tango-helpers@1.2.2
 - @music163/tango-sandbox@1.0.10
 - @music163/tango-setting-form@1.2.10
 - @music163/tango-ui@1.4.1
2024-08-05 12:28:43 +08:00
BoBoooooo b83d965955 fix: show right panel when design view select node & optimize editor css (#193) 2024-08-05 11:45:41 +08:00
Wells a1eea02f94 fix: parse template code & update maxRow of TextAreaSetter (#192)
* fix: update templatePattern regex to allow for multiline code wrapping

* fix: update error overlay display to use designer.activeView instead of mode

* fix: update maxRows to 6 in TextAreaSetter
2024-08-05 11:20:41 +08:00
wwsun 0d0479e3e5 chore(release): publish
- @music163/tango-context@1.1.6
 - @music163/tango-core@1.4.0
 - @music163/tango-designer@1.4.0
 - @music163/tango-helpers@1.2.1
 - @music163/tango-sandbox@1.0.9
 - @music163/tango-setting-form@1.2.9
 - @music163/tango-ui@1.4.0
2024-08-01 14:28:53 +08:00
wwsun 67d602a3ec fix: update types 2024-08-01 14:26:37 +08:00
Wells 8dd289cd7d feat: add isError and errorMessage to File & add isAstSynced to Module (#190)
* feat: update file without sync ast

* feat: parse and display file errors

* fix: update

* fix: refactor toolbar

* fix: add activeViews config to toolbarItem

* fix: update icon
2024-07-30 20:54:05 +08:00
wwsun 82bc5db4d8 chore(release): publish
- @music163/tango-context@1.1.5
 - @music163/tango-core@1.3.3
 - @music163/tango-designer@1.3.3
 - @music163/tango-sandbox@1.0.8
 - @music163/tango-setting-form@1.2.8
 - @music163/tango-ui@1.3.3
2024-07-12 13:51:34 +08:00
Wells 85c053b3db fix: update designer config (#186)
* docs: add section to generate local https ca

* fix: support disable format code

* fix: disable autoRemoveUnusedImports in CodeEditor

* fix: update toggle view setting
2024-07-12 10:52:12 +08:00
wwsun 32f5667cae docs: update readme 2024-07-03 15:44:25 +08:00
Wells 1d0fb4f274 fix: selection bug without prototype & update ToggleButton style (#180)
* fix: update toggleButton arrow style

* fix: check if prototype exists in selection tool

* fix: update state tree data
2024-06-26 16:54:38 +08:00
Wells 0011cdca0f chore(release): publish
- @music163/tango-context@1.1.4
 - @music163/tango-core@1.3.2
 - @music163/tango-designer@1.3.2
 - @music163/tango-sandbox@1.0.7
 - @music163/tango-setting-form@1.2.7
 - @music163/tango-ui@1.3.2
2024-06-20 15:45:08 +08:00
Wells 0f3f0afdfa fix: update designer style (#176)
* fix: remove useless codes

* fix: show insert children icon only for hasChildren node

* fix: update dependency

* fix: update styles

* fix: show sibling action for nodes except page & update drag icon for DragPanel

* fix: update ToggleButton style

* fix: add showDropdownIcon to ToggleButton

* fix: update codeSetter style

* fix: add builtin imageSetter

* fix: update PopOut icon
2024-06-20 15:42:49 +08:00
BoBoooooo b53a9f7eef fix: drag-panel add resizeable & height prop (#175)
* fix: drag-panel add resizeable & height prop

* fix: add className
2024-06-18 16:56:00 +08:00
Wells 5336c2ec28 docs: update 2024-06-11 09:17:36 +00:00
Wells cdbd2351a2 docs: update README.zh-CN.md 2024-06-11 17:04:28 +08:00
Wells 1f03977f7d docs: add some examples 2024-06-11 17:01:41 +08:00
864907600cc a2cc418a73 fix: fix global hotkey triggering on content editable elements (#174) 2024-06-06 14:57:41 +08:00
Wells 239c0b0a28 chore(release): publish
- @music163/tango-context@1.1.3
 - @music163/tango-core@1.3.1
 - @music163/tango-designer@1.3.1
 - @music163/tango-sandbox@1.0.6
 - @music163/tango-setting-form@1.2.6
 - @music163/tango-ui@1.3.1
2024-06-05 18:17:02 +08:00
Wells ae04850bb2 fix: set value as jsxElement children (#173) 2024-06-05 18:11:57 +08:00
864907600cc ca740c83ae fix: fix context menu error on macOS (#170)
* fix: fix context menu error on macOS

* fix: adjust context menu icon style
2024-06-03 15:57:58 +08:00
Wells 00bf52a411 chore(release): publish
- @music163/tango-context@1.1.2
 - @music163/tango-core@1.3.0
 - @music163/tango-designer@1.3.0
 - @music163/tango-helpers@1.2.0
 - @music163/tango-sandbox@1.0.5
 - @music163/tango-setting-form@1.2.5
 - @music163/tango-ui@1.3.0
2024-06-03 09:51:00 +08:00
864907600cc c1306e24e0 fix: use addEventListener to bind iframe event handlers (#169)
* feat: use addEventListener to bind iframe event handlers

* fix: types
2024-05-31 17:44:55 +08:00
864907600cc 28040fc006 feat: add context menu (#161)
* feat: add more actions menu on SelectionTools

* feat: add view source context action

* feat: normalize hotkey by platform

* feat: add context menu to components tree

* feat: add context menu to viewport
2024-05-31 17:31:58 +08:00
Wells 3f3981bb9d fix: parse app entry file & pass correct routerType to sandbox (#168)
* fix: parse app entry file & pass correct routerType to sandbox

* fix: export entry module
2024-05-31 14:54:12 +08:00
Wells 253ceca969 chore(release): publish
- @music163/tango-designer@1.2.3
 - @music163/tango-setting-form@1.2.4
 - @music163/tango-ui@1.2.3
2024-05-30 17:05:52 +08:00
BoBoooooo a0ed57ff4f fix: optimize variable panel scroll ui & onCancel bug (#166) 2024-05-30 14:06:12 +08:00
BoBoooooo f83c6bc0f6 fix: popover re-click position bug & drag panel drag bug (#165)
* fix: popover reClick position bug

* fix: drag event lose when drag over iframe
2024-05-29 15:26:00 +08:00
Wells bb92210594 chore(release): publish
- @music163/tango-designer@1.2.2
 - @music163/tango-setting-form@1.2.3
 - @music163/tango-ui@1.2.2
2024-05-27 10:18:03 +08:00
Wells 163ecedff3 fix: export usePreviewSandboxQuery & add builtin sandboxQuery (#163)
* fix: export usePreviewSandboxQuery

* fix: update ui

* fix: update ui
2024-05-24 18:28:04 +08:00
Wells 22a2e9bdd1 chore(release): publish
- @music163/tango-designer@1.2.1
 - @music163/tango-setting-form@1.2.2
 - @music163/tango-ui@1.2.1
2024-05-22 14:53:57 +08:00
Wells 696f82bd26 style: update 2024-05-22 14:52:44 +08:00
BoBoooooo a0484e8f64 fix: check local component prototypes (#160)
* fix: prototype undefined bug

* fix: logic bug

* fix: components grid item ui

* fix: ui bug

* fix: update local file
2024-05-22 11:56:52 +08:00
Wells cf31ef19f4 chore(release): publish
- @music163/tango-context@1.1.1
 - @music163/tango-core@1.2.0
 - @music163/tango-designer@1.2.0
 - @music163/tango-helpers@1.1.1
 - @music163/tango-sandbox@1.0.4
 - @music163/tango-setting-form@1.2.1
 - @music163/tango-ui@1.2.0
2024-05-21 15:06:42 +08:00
864907600cc fe31246483 feat: add select parent node of selected node (#158)
* feat: add select parent node of selected node

* feat: move select parent node to SelectSource

* fix: change icon & order

---------

Co-authored-by: ccloli <8115912+ccloli@users.noreply.github.com>
2024-05-20 20:15:28 +08:00
BoBoooooo 9daf3872e7 feat: event-setter & expression-setter use popover (#159) 2024-05-20 16:57:37 +08:00
BoBoooooo f17ccbb7f6 fix: support add components with popover (#155)
* feat: add drag panel & popover component

* feat: update web ide version to 1.3.11

* feat: add components-popover

* fix: update sidebar default width

* feat: add global components popover

* fix: _menuData default value

* feat: add addComponent event

* revert: remove isCollapsed prop

* fix: update local icon font url
2024-05-20 16:13:34 +08:00
BoBoooooo f854f75b8a feat: supoort set default active view (#157) 2024-05-20 15:27:32 +08:00
BoBoooooo df3021f75e feat: add history forward & back shortcut key (#154) 2024-05-20 15:26:46 +08:00
BoBoooooo 8bf53a76f8 fix: prototype2code & go back history error (#156)
* fix: snippet import bug

* fix: history could back logic bug

* fix: editor add left border when in dual mode

* fix: setting-form title overflow bug
2024-05-20 15:26:07 +08:00
Wells 791fbb162a fix: enhance code value validate in SettingForm (#152)
* fix: update register setter strategy & add getSetter

* fix: handle invalid code to prop value

* fix: add validate logic to code setters

* fix: update code validate

* fix: update ui of settingForm header
2024-05-17 18:20:08 +08:00
147 changed files with 4848 additions and 1369 deletions
+1
View File
@@ -9,3 +9,4 @@ coverage/
.umi-production/
.log
.eslintcache
*.pem
+26 -15
View File
@@ -31,23 +31,17 @@ You can view the detailed usage guide through the following links:
- Out-of-the-box front-end low-code designer, providing flexible and easy-to-use designer React components
- Developed using TypeScript, providing complete type definition files
## 🎯 Milestone
## 💡 Examples
```mermaid
gantt
dateFormat YYYY-MM-DD
title Tango 1.0 Milestones
excludes weekends
%% (`excludes` accepts specific dates in YYYY-MM-DD format, days of the week ("sunday") or "weekends", but not the word "weekdays".)
You can use tango to build lowcode builders, for example:
section Builder Release
1.0 Alpha : m1, 2023-10-01, 2024-01-31
1.0 RC : m2, 2024-02-01, 2024-04-30
1.0 Stable : m3, 2024-04-30, 2024-12-31
```
> [!NOTE]
> Alpha versions will continue to optimize some implementation protocols and continuously integrate new features from the internal version of NetEase; RC versions will provide a stable parsing protocol and implementation; The 1.0 official version is planned to be released in Q2 2024. After the release of the 1.0 official version, we will continue to iterate on versions and gradually incorporate core capabilities such as process design, component library, and AIGC from the internal version.
| Preview | Description |
| ---------------------------------------------------------------------------------------------- | ----------------------- |
| ![image](https://github.com/NetEase/tango/assets/6984035/56a71741-4536-4336-803a-d81d51128a76) | Internal App Builder |
| ![dashboard app](public/dashboard-builder.png) | Dashboard App Builder |
| ![image](https://github.com/NetEase/tango/assets/6984035/790d88e1-d716-4f99-868a-31dda25e9fb1) | Mobile App Builder |
| ![rn app](public/rn-builder.png) | ReactNative App Builder |
| ![mail app](public/mail-builder.png) | Email Builder |
## 🌐 Compatibility
@@ -76,6 +70,23 @@ yarn
yarn start
```
### Local Https certificate
If you need to use https in the local development environment, you can use the following command to generate a certificate:
```bash
brew install mkcert
# install the local certificate
mkcert -install
# enter the playground app directory
cd apps/playground
# generate a certificate
mkcert local.netease.com # or change to your own domain name
```
## 💬 Community
Join NetEase Tango Community to share your ideas, suggestions, or questions and connect with other users and contributors.
+30 -19
View File
@@ -26,28 +26,22 @@
## ✨ 特性
- 经历网易云音乐内网生产环境的实际检验,可灵活集成应用于低代码平台,本地开发工具等
- 基于源码 AST 驱动,无私有 DSL 和协议
- 提供实时出码能力,支持源码进,源码出
- 开箱即用的前端低代码设计器,提供灵活易用的设计器 React 组件
- 使用 TypeScript 开发,提供完整的类型定义文件
- 提供基于源码 AST 驱动的低代码引擎,无私有 DSL 和协议
- 提供实时出码能力,支持源码进,源码出,适配多种源码开发场景
- 提供开箱即用的前端低代码设计器,提供灵活易用的设计器 React 组件
- 使用 TypeScript 开发,提供完整的类型定义文件和完善的文档支持
## 🎯 里程碑
## 💡 例子
```mermaid
gantt
dateFormat YYYY-MM-DD
title Tango 1.0 Milestones
excludes weekends
%% (`excludes` accepts specific dates in YYYY-MM-DD format, days of the week ("sunday") or "weekends", but not the word "weekdays".)
你可以使用 Tango 快速构建多种类型的基于源码的低代码搭建工具,例如:
section Builder Release
1.0 Alpha : m1, 2023-10-01, 2024-01-31
1.0 RC : m2, 2024-02-01, 2024-04-30
1.0 Stable : m3, 2024-04-30, 2024-12-31
```
> [!NOTE]
> Alpha 版本会持续对一些实现协议进行优化,并持续融合网易内网版本中的新增特性;RC 版本将会提供基本稳定的解析协议和实现;1.0 正式版本计划在 2024 年Q2发布。1.0 正式版发布后我们将会持续进行版本迭代,并逐步融入内网版本中的流程设计、组件库、AIGC 等核心基础能力。
| 预览图 | 说明 |
| ---------------------------------------------------------------------------------------------- | -------------------- |
| ![image](https://github.com/NetEase/tango/assets/6984035/56a71741-4536-4336-803a-d81d51128a76) | 中后台系统搭建 |
| ![dashboard app](public/dashboard-builder.png) | 仪表盘应用搭建 |
| ![image](https://github.com/NetEase/tango/assets/6984035/790d88e1-d716-4f99-868a-31dda25e9fb1) | H5活动页面搭建 |
| ![rn app](public/rn-builder.png) | ReactNative 应用搭建 |
| ![mail app](public/mail-builder.png) | 营销类邮件搭建 |
## 🌐 兼容环境
@@ -76,6 +70,23 @@ yarn
yarn start
```
### 本地 https 证书
如果需要在本地开发环境中使用 https,可以使用以下命令生成证书:
```bash
brew install mkcert
# 将 mkcert 添加到本地根 CA,仅在本地生效
mkcert -install
# 进入 playground 应用目录
cd apps/playground
# 为网站生成一个由 mkcert 签名的证书
mkcert local.netease.com
```
## 💬 社区讨论
参与 NetEase Tango 的社区,以分享您的想法、建议或问题,并与其他用户和贡献者建立联系。
-28
View File
@@ -1,28 +0,0 @@
-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC4sAqDE3nhtSWD
YqV4mlglnzIs2AioZr2uxfj/OKrpE1ZML/dflJyc5NGUpOZWV+W1vRc70wWVNFxB
Si8nrYrrseoID7Ehxxe6+J1m/JsEbhZWHwV3M1iGW7JD7VhujaDpSLg67wMTMpSW
3BUS+0NT+MNfCisp+u/ls4fXPCTgXiWcjMULm95oLlTeYwurPHfxwn9f9hh85I5I
K3dI7w8MsQN7EFNrJz3UfrNLpmARMtSUBMwBYqrCitoUxRT0q7KYCru7kHxGPB6A
SQrFpSpOWT79vp8GBSp9g3axhRsK+aEgzQ0QGrFPHBwBP/kWgmdB1URc/K7STSC9
xyMNZOM7AgMBAAECggEATbyDYDKVbaRymr+tyHqmuYctdmSkGEXOdz8LFFoEzj/+
ZekWpVuHJB7H/FoAPb2XiYyCuAKVafz1C+IuwPOx8o0bZbM9KmuDmIZGsm+GzDGO
I0fBZC/vhfYYrbC8NSRV43thWCT8VVtH4cvW7vtllnWxvlIoYu4lhbiwZ68AEpO1
8PlJsOhnagfkFpG8LehSDs9if5L+Ig0geQEcUY3pGUM9LKYsRoxFv6Vh8wQku1XD
YOxLvLWDPqJ75m816t50RARe3e6eDJ+ukzDCoDjmLP8uhf1sk1FcL5aOgUNU3VOi
P6sIH5uzuD0MA3FXx2mItYLOc44r4uaFJZiRUMEXGQKBgQDCjUYblE4rh0nKFkqx
AhgfcRgpgLbP42OwFtD0u20RXdZAEJDRDQ43NdOgjFp2B50k75LBPIoFXYUZdzKj
l7S2FH5O9Cc6hEgZGI4hCiYd+nQVI1mxv820YnzZJN4oooxyL+B5RlnW5cDT7LJN
11Q5PRewkM+XpfbE3lKUjTNcDwKBgQDzBS+j8T9GJSzV2xgA+mpGHe1RjDq6yQtk
Rl5GWpflW4Nr3/58BbmCWNA8WP0NOWutJhrkltwLCqJC8OZX/WHnmcmq2k+UAfQQ
z98p+xcMWOTcl5XIbveuhYoZb2udt9WVJLcpRVxVhEWcBrtHsrpScZXsKYf/TaZ1
JtCjPU5KFQKBgGXj/UqmYkYzxXZ8NEP998pHvcLGsXew/F2VpXv2yQlmXrYQtvd1
YfOSUjJsL1hPZoKYogBoB1UGBJYwsimxYyhVFU2eWwkvjF7wWEd/fDUJHVCQwgHw
lPga+I303BDmCK4o2uRI7vY4P8P92+gelPKhR03mmYIvnky+rvsz9CkLAoGAVerl
du6Z0jDecxUsnVvrKrL17jjHorXlYyRFvFXXEe2SvxbIIAzeEylXJZ7IiF5epS6t
n1d+oCC4UTZeGYmpjXofhFn+fHNcWH1FhtAQy/q5nwuwltY0luz7cBamU3Jk/n+m
id7N0CYdfhYbLDQSD4e822ureyV2zkBUzwGjpikCgYEAoCVbhkxVrQHRmxLC2jDx
pM94W1ij9TqblfGg3OMpPXjpTdlknatWjBw7JkoyxYiYJq5Gi2p4QV6HHUvS1osj
BB+4A99/PD9A0ICoJglz8SXlGe/895zwHwpKT9f0zjizQrEd2KCPf75URa+t2FGY
B2GkXsbChRWVrey5+uMzUD8=
-----END PRIVATE KEY-----
-25
View File
@@ -1,25 +0,0 @@
-----BEGIN CERTIFICATE-----
MIIEQjCCAqqgAwIBAgIRAIeLJ2jwt4MSKycHFmFXL6YwDQYJKoZIhvcNAQELBQAw
fTEeMBwGA1UEChMVbWtjZXJ0IGRldmVsb3BtZW50IENBMSkwJwYDVQQLDCB3d3N1
bkBzdW4tbWJwLmxvY2FsIChTVU4gV2Vpd2VpKTEwMC4GA1UEAwwnbWtjZXJ0IHd3
c3VuQHN1bi1tYnAubG9jYWwgKFNVTiBXZWl3ZWkpMB4XDTIyMDcyODAxNTIxMFoX
DTI0MTAyODAxNTIxMFowVDEnMCUGA1UEChMebWtjZXJ0IGRldmVsb3BtZW50IGNl
cnRpZmljYXRlMSkwJwYDVQQLDCB3d3N1bkBzdW4tbWJwLmxvY2FsIChTVU4gV2Vp
d2VpKTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALiwCoMTeeG1JYNi
pXiaWCWfMizYCKhmva7F+P84qukTVkwv91+UnJzk0ZSk5lZX5bW9FzvTBZU0XEFK
Lyetiuux6ggPsSHHF7r4nWb8mwRuFlYfBXczWIZbskPtWG6NoOlIuDrvAxMylJbc
FRL7Q1P4w18KKyn67+Wzh9c8JOBeJZyMxQub3mguVN5jC6s8d/HCf1/2GHzkjkgr
d0jvDwyxA3sQU2snPdR+s0umYBEy1JQEzAFiqsKK2hTFFPSrspgKu7uQfEY8HoBJ
CsWlKk5ZPv2+nwYFKn2DdrGFGwr5oSDNDRAasU8cHAE/+RaCZ0HVRFz8rtJNIL3H
Iw1k4zsCAwEAAaNmMGQwDgYDVR0PAQH/BAQDAgWgMBMGA1UdJQQMMAoGCCsGAQUF
BwMBMB8GA1UdIwQYMBaAFDILZR+SW32Ug0HkAKrH1KT2a1ttMBwGA1UdEQQVMBOC
EWxvY2FsLm5ldGVhc2UuY29tMA0GCSqGSIb3DQEBCwUAA4IBgQCEdeV2Likl4MUt
wWeN/X3tAR3L7mkl7e4f0CQ4v2lOs8cekOP7p3ZFk5nSyVbxda3usPB0OtbVTibw
qZ1n/TMRb5epHroXIMleqngP82zFZNg+WVyHm/ZAml8gVD0VZjYM1Tb+U9+SrgGw
lvZndbuUXa3h/d0irPH90KsdEeAR1SqwzAzvLO2JgvBuimHRceQWcTiiGWDZOyii
tux4U+pEzh0Dia40uFozFAoYZPDUpZ+gsiQ3MR3HOrAu2OR0a+CfelDXZNLR3C4z
cBKr53ajAbHstnpxKJh9IfeKph44PrbDo6HMe1XPprl7idoEesX3Ma3SBgm4lmId
cfEOUWNIYOgtOT5bflXNNyzXOgYVjpLnjwg4EOASO/XIjhvqdjIyCu7HJMIcZ9oo
Aob2exeluv5LVwic1UJQDl2McDBIgJ8R32oEN4skCKIBSbWlxWyjnxL5I5WkJF4y
vlSx8bKAjVr8map0C3rWISuZdgheJkF96qjwhVSxOv++p6srq6M=
-----END CERTIFICATE-----
+17 -7
View File
@@ -1,10 +1,11 @@
import React from 'react';
import { Box, Group } from 'coral-system';
import { Box, Group, Text } from 'coral-system';
import { Avatar, Space, Switch } from 'antd';
import { BranchesOutlined, MenuOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { registerSetter } from '@music163/tango-designer';
import type { IVariableTreeNode } from '@music163/tango-helpers';
import { FooSetter } from '../components';
import { ToggleButton } from '@music163/tango-ui';
export * from './mock-files';
@@ -46,8 +47,17 @@ registerSetter({
// 平台 Logo
export function Logo() {
return (
<Box width="50px" display="flex" alignItems="center" justifyContent="center" fontSize="20px">
<MenuOutlined />
<Box width="50px" display="flex" alignItems="center" justifyContent="center" fontSize="14px">
<ToggleButton
shape="text"
items={[
{ label: '回到首页', key: 'home' },
{ label: '文档', key: 'doc' },
{ label: '设置', key: 'setting' },
]}
>
<MenuOutlined />
</ToggleButton>
</Box>
);
}
@@ -56,12 +66,12 @@ export function Logo() {
export function ProjectDetail() {
return (
<Box display="flex" alignItems="center" columnGap="l">
<Box className="ProjectName" fontSize="18px" fontWeight="bold">
<Text className="ProjectName" fontSize="18px" fontWeight="bold" truncated>
community-test
</Box>
<Box className="BranchName" as="code" fontSize="14px">
</Text>
<Text className="BranchName" as="code" fontSize="14px" truncated>
<BranchesOutlined /> feature/list
</Box>
</Text>
</Box>
);
}
+2 -3
View File
@@ -2,7 +2,7 @@ const packageJson = {
name: 'demo',
private: true,
dependencies: {
'@music163/tango-mail': '0.1.1',
'@music163/tango-mail': '0.2.4',
'@music163/tango-boot': '0.2.5',
react: '17.0.2',
'react-dom': '17.0.2',
@@ -44,7 +44,7 @@ const tangoConfigJson = {
},
'@music163/tango-mail': {
description: 'TangoMail 基础物料',
version: '0.1.1',
version: '0.2.4',
library: 'TangoMail',
type: 'baseDependency',
resources: ['https://unpkg.com/@music163/tango-mail@{{version}}/dist/index.js'],
@@ -116,7 +116,6 @@ const WelcomeEmail = () => (
</Section>
<Text style={paragraph}>
Best,
<br />
The Koala team
</Text>
<Hr style={hr} />
+25 -5
View File
@@ -3,7 +3,7 @@ const packageJson = {
private: true,
dependencies: {
'@music163/antd': '0.2.5',
'@music163/tango-boot': '0.2.5',
'@music163/tango-boot': '0.3.5',
react: '17.0.2',
'react-dom': '17.0.2',
'prop-types': '15.7.2',
@@ -48,7 +48,7 @@ const tangoConfigJson = {
},
'@music163/tango-boot': {
description: '云音乐低代码运行时框架',
version: '0.2.5',
version: '0.3.5',
library: 'TangoBoot',
type: 'baseDependency',
resources: ['https://unpkg.com/@music163/tango-boot@{{version}}/dist/boot.js'],
@@ -56,7 +56,7 @@ const tangoConfigJson = {
},
'@music163/antd': {
description: '云音乐低代码中后台应用基础物料',
version: '0.2.5',
version: '0.2.6',
library: 'TangoAntd',
type: 'baseDependency',
resources: [
@@ -153,6 +153,7 @@ import { definePage } from "@music163/tango-boot";
import {
Page,
Section,
Box,
Button,
Input,
FormilyForm,
@@ -161,10 +162,15 @@ import {
} from "@music163/antd";
import { Space } from "@music163/antd";
import { LocalButton } from "../components";
import { OutButton } from "../components";
class App extends React.Component {
render() {
return (
<Page title={tango.stores.app.title} subTitle={111}>
<Page title={tango.stores.app.title} subTitle={<><Button>hello</Button></>}>
<Section tid="section0">
<Box></Box>
</Section>
<Section tid="section1" title="Section Title">
your input: <Input tid="input1" defaultValue="hello" />
copy input: <Input value={tango.page.input1?.value} />
@@ -180,6 +186,7 @@ class App extends React.Component {
<Section tid="section2">
<Space tid="space1">
<LocalButton />
<OutButton />
<Button tid="button1">button</Button>
</Space>
</Section>
@@ -191,7 +198,7 @@ class App extends React.Component {
</Section>
<Section title="原生 DOM" tid="section4">
<h1 style={{ ...{ color: "red" }, fontSize: 64 }}>
hello world
hello world
</h1>
<div
style={{
@@ -289,6 +296,14 @@ registerComponentPrototype({
});
`;
const outButtonCode = `
import React from 'react';
export default function OutButton(props) {
return <button {...props}>Out button (from other file)</button>
}
`;
const componentsInputCode = `
import React from 'react';
import { registerComponentPrototype } from '../utils';
@@ -311,6 +326,7 @@ registerComponentPrototype({
const componentsEntryCode = `
export { default as LocalButton } from './button';
export { default as LocalInput } from './input';
export { default as OutButton } from './out-button';
`;
const storeApp = `
@@ -361,13 +377,16 @@ export default defineServices({
add: {
url: 'https://nei.hz.netease.com/api/apimock-v2/c45109399a1d33d83e32a59984b25b00/api/users',
method: 'post',
description: '新增用户'
},
update: {
url: 'https://nei.hz.netease.com/api/apimock-v2/c45109399a1d33d83e32a59984b25b00/api/users',
method: 'post',
description: '更新用户'
},
delete: {
url: 'https://nei.hz.netease.com/api/apimock-v2/c45109399a1d33d83e32a59984b25b00/api/users?id=1',
description: '删除用户'
},
});
`;
@@ -411,6 +430,7 @@ export const sampleFiles = [
{ filename: '/src/pages/list.js', code: viewHomeCode },
{ filename: '/src/pages/detail.js', code: emptyPageCode },
{ filename: '/src/components/button.js', code: componentsButtonCode },
{ filename: '/src/components/out-button.js', code: outButtonCode },
{ filename: '/src/components/input.js', code: componentsInputCode },
{ filename: '/src/components/index.js', code: componentsEntryCode },
{ filename: '/src/routes.js', code: routesCode },
+65 -11
View File
@@ -45,14 +45,17 @@ const Snippet2ColumnLayout: IComponentPrototype = {
const Snippet3ColumnLayout: IComponentPrototype = {
name: 'Snippet3ColumnLayout',
title: '三列布局',
icon: 'icon-column3',
icon: 'icon-column-3',
type: 'snippet',
package: '@music163/antd',
initChildren: `
<Columns columns={12}>
<Column colSpan={4}></Column>
<Column colSpan={4}></Column>
<Column colSpan={4}></Column>
<Column colSpan={4}>
</Column>
<Column colSpan={4}>
</Column>
<Column colSpan={4}>
</Column>
</Columns>
`,
relatedImports: ['Columns', 'Column'],
@@ -76,13 +79,9 @@ const SnippetButtonGroup: IComponentPrototype = {
// hack some prototypes
basePrototypes['Section'].siblingNames = [
'SnippetButtonGroup',
'Section',
'Section',
'Section',
'Section',
'Section',
'Section',
'Section',
'Snippet2ColumnLayout',
'Snippet3ColumnLayout',
'SnippetSuccessResult',
];
export const nativeDomPrototypes = () => {
@@ -132,6 +131,9 @@ export const nativeDomPrototypes = () => {
title: '样式',
group: 'style',
setter: 'expressionSetter',
setterProps: {
expressionType: 'cssObject',
},
},
{
name: 'className',
@@ -166,6 +168,32 @@ const prototypes: Dict<IComponentPrototype> = {
Snippet2ColumnLayout,
Snippet3ColumnLayout,
SnippetButtonGroup,
Section: {
...basePrototypes['Section'],
props: [
// ...(basePrototypes['Section'].props as any),
{
name: 'title',
title: '标题',
setter: 'textSetter',
},
{
name: 'extra',
title: '额外内容',
setter: 'renderSetter',
options: [
{
label: '按钮组',
value: 'ButtonGroup',
renderBody:
'<ButtonGroup><Button>button1</Button><Button>button2</Button></ButtonGroup>',
relatedImports: ['ButtonGroup', 'Button'],
},
],
template: '(v) => {\n return {{content}};\n}',
},
],
},
Box: {
name: 'Box',
title: '盒子',
@@ -197,6 +225,32 @@ const prototypes: Dict<IComponentPrototype> = {
title: 'd',
setter: 'textSetter',
},
{
name: 'onClick',
title: '点击事件',
setter: 'eventSetter',
template: '(e) => {\n {{content}}\n}',
tip: '回调参数说明:e 为事件对象',
},
{
name: 'renderFoo',
title: 'foo自定义渲染',
setter: 'renderSetter',
options: [
{
label: '占位空间',
value: 'Box',
render: '() => <Box>test</Box>',
relatedImports: ['Box'],
},
{
label: '占位文本',
value: 'Text',
render: '() => <Text>text</Text>',
relatedImports: ['Text'],
},
],
},
],
},
Columns: {
+40 -39
View File
@@ -20,42 +20,13 @@ import {
ApiOutlined,
AppstoreAddOutlined,
BuildOutlined,
ClusterOutlined,
FunctionOutlined,
PlusOutlined,
createFromIconfontCN,
} from '@ant-design/icons';
import { Action } from '@music163/tango-ui';
import { Action, PackageOutlined } from '@music163/tango-ui';
import { useState } from 'react';
// 1. 实例化工作区
const workspace = new Workspace({
entry: '/src/index.js',
files: sampleFiles,
prototypes,
});
// inject workspace to window for debug
(window as any).__workspace__ = workspace;
// 2. 引擎初始化
const engine = createEngine({
workspace,
});
// @ts-ignore
window.__workspace__ = workspace;
// 3. 沙箱初始化
const sandboxQuery = new DndQuery({
context: 'iframe',
});
// 4. 图标库初始化(物料面板和组件树使用了 iconfont 里的图标)
createFromIconfontCN({
scriptUrl: '//at.alicdn.com/t/c/font_2891794_6d4hj5u0bjx.js',
});
const menuData = {
common: [
{
@@ -90,6 +61,36 @@ const menuData = {
],
};
// 1. 实例化工作区
const workspace = new Workspace({
entry: '/src/index.js',
files: sampleFiles,
prototypes,
});
// inject workspace to window for debug
(window as any).__workspace__ = workspace;
// 2. 引擎初始化
const engine = createEngine({
workspace,
menuData,
defaultActiveView: 'design', // dual code design
});
// @ts-ignore
window.__workspace__ = workspace;
// 3. 沙箱初始化
const sandboxQuery = new DndQuery({
context: 'iframe',
});
// 4. 图标库初始化(物料面板和组件树使用了 iconfont 里的图标)
createFromIconfontCN({
scriptUrl: '//at.alicdn.com/t/c/font_2891794_151xsllxqd7.js',
});
/**
* 5. 平台初始化,访问 https://local.netease.com:6006/
*/
@@ -112,8 +113,8 @@ export default function App() {
actions={
<Box px="l">
<Toolbar>
<Toolbar.Item key="routeSwitch" placement="left" />
<Toolbar.Item key="addPage" placement="left">
<Toolbar.Item key="routeSwitch" placement="left" activeViews={['design']} />
<Toolbar.Item key="addPage" placement="left" activeViews={['design']}>
<Action
tooltip="添加页面"
shape="outline"
@@ -121,10 +122,10 @@ export default function App() {
onClick={() => setShowNewPageModal(true)}
/>
</Toolbar.Item>
<Toolbar.Item key="history" placement="left" />
<Toolbar.Item key="preview" placement="left" />
<Toolbar.Item key="history" placement="left" activeViews={['design']} />
<Toolbar.Item key="preview" placement="left" activeViews={['design']} />
<Toolbar.Item key="togglePanel" placement="right" activeViews={['design']} />
<Toolbar.Item key="modeSwitch" placement="right" />
<Toolbar.Item key="togglePanel" placement="right" />
<Toolbar.Separator />
<Toolbar.Item placement="right">
<Space>
@@ -180,12 +181,15 @@ export default function App() {
<Sidebar.Item
key="dependency"
label="依赖"
icon={<ClusterOutlined />}
icon={<PackageOutlined />}
isFloat
width={800}
/>
</Sidebar>
<WorkspacePanel>
<WorkspaceView mode="code">
<CodeEditor />
</WorkspaceView>
<WorkspaceView mode="design">
<Sandbox
onMessage={(e) => {
@@ -207,9 +211,6 @@ export default function App() {
navigatorExtra={<Button size="small">hello world</Button>}
/>
</WorkspaceView>
<WorkspaceView mode="code">
<CodeEditor />
</WorkspaceView>
</WorkspacePanel>
<SettingPanel />
</DesignerPanel>
+2 -1
View File
@@ -45,7 +45,7 @@ const sandboxQuery = new DndQuery({
// 4. 图标库初始化(物料面板和组件树使用了 iconfont 里的图标)
createFromIconfontCN({
scriptUrl: '//at.alicdn.com/t/c/font_2891794_cou9i7556tl.js',
scriptUrl: '//at.alicdn.com/t/c/font_2891794_151xsllxqd7.js',
});
/**
@@ -112,6 +112,7 @@ export default function App() {
if (sandboxWindow.TangoMail) {
if (sandboxWindow.TangoMail.menuData) {
setMenuData(sandboxWindow.TangoMail.menuData);
engine.designer.setMenuData(sandboxWindow.TangoMail.menuData);
}
if (sandboxWindow.TangoMail.prototypes) {
workspace.setComponentPrototypes(sandboxWindow.TangoMail.prototypes);
+1 -1
View File
@@ -3,7 +3,7 @@ import { SystemProvider } from 'coral-system';
import 'antd/dist/antd.css';
export const parameters = {
actions: { argTypesRegex: '^on[A-Z].*' },
actions: { argTypesRegex: '^on.*' },
controls: {
matchers: {
color: /(background|color)$/i,
+20 -2
View File
@@ -14,7 +14,7 @@ const BLACK_LIST = ['codeSetter', 'eventSetter', 'modelSetter', 'routerSetter'];
BUILT_IN_SETTERS.filter((setter) => !BLACK_LIST.includes(setter.name)).forEach(register);
createFromIconfontCN({
scriptUrl: '//at.alicdn.com/t/c/font_2891794_cou9i7556tl.js',
scriptUrl: '//at.alicdn.com/t/c/font_2891794_151xsllxqd7.js',
});
export default {
@@ -38,7 +38,7 @@ function SettingFormDemo({ initValues, prototype }: SettingFormDemoProps) {
const model = new FormModel(initValues, { onChange: console.log });
return (
<Box display="flex">
<Box flex="0 0 400px" overflow="hidden">
<Box flex="0 0 320px" overflow="hidden">
<SettingForm
model={model}
prototype={prototype}
@@ -59,14 +59,24 @@ function SettingFormDemo({ initValues, prototype }: SettingFormDemoProps) {
const prototypeHasBasicProps: IComponentPrototype = {
name: 'Sample',
title: '演示组件',
package: 'sample-pkg',
type: 'element',
docs: 'https://4x-ant-design.antgroup.com/components/slider-cn',
props: [
{
name: 'code',
title: 'codeSetter',
setter: 'codeSetter',
},
{
name: 'style',
title: 'codeSetter(cssObject)',
setter: 'codeSetter',
setterProps: {
expressionType: 'cssObject',
},
},
{
name: 'text',
title: 'textSetter',
@@ -77,6 +87,11 @@ const prototypeHasBasicProps: IComponentPrototype = {
title: 'textAreaSetter',
setter: 'textAreaSetter',
},
{
name: 'src',
title: 'imageSetter',
setter: 'imageSetter',
},
{
name: 'number',
title: 'numberSetter',
@@ -261,6 +276,9 @@ export function InitValues() {
name: 'style',
title: 'codeSetter',
setter: 'codeSetter',
setterProps: {
expressionType: 'cssObject',
},
},
{
name: 'object',
@@ -0,0 +1,29 @@
import React from 'react';
import { ActionSelect } from '@music163/tango-ui';
export default {
title: 'UI/ActionSelect',
component: ActionSelect,
};
const options = [
{ label: 'action1', value: 'action1' },
{ label: 'action2', value: 'action2' },
{ label: 'action3', value: 'action3' },
];
export const Basic = {
args: {
defaultText: '选择动作',
options,
onSelect: console.log,
},
};
export const showInput = {
args: {
text: '选择动作',
options,
showInput: true,
},
};
@@ -0,0 +1,15 @@
import React, { useState } from 'react';
import { ClassNameInput } from '@music163/tango-ui';
export default {
title: 'UI/ClassNameInput',
};
export function Basic() {
return <ClassNameInput defaultValue="hello world" onChange={console.log} />;
}
export function Controlled() {
const [value, setValue] = useState('');
return <ClassNameInput value={value} onChange={setValue} />;
}
@@ -0,0 +1,82 @@
import React from 'react';
import { DragPanel } from '@music163/tango-ui';
import { Box, Text } from 'coral-system';
import { Button } from 'antd';
export default {
title: 'UI/DragPanel',
};
export function Basic() {
return (
<>
<DragPanel
title="弹层标题"
extra="右上角内容"
width={350}
body={<Box p="m"></Box>}
footer={<Text></Text>}
>
<Button></Button>
</DragPanel>
<DragPanel
title="弹层标题"
extra="右上角内容"
width={350}
body={<Box p="m"></Box>}
footer={<Text></Text>}
>
<Button
style={{
position: 'absolute',
bottom: 20,
right: 20,
}}
>
</Button>
</DragPanel>
</>
);
}
export function FooterCustom() {
return (
<DragPanel
title="弹层标题"
extra="右上角内容"
width={350}
body={<Box p="m"></Box>}
footer={(close) => (
<Box display="flex" justifyContent="space-between">
<Text></Text>
<Button size="small" onClick={() => close()}>
</Button>
</Box>
)}
>
<Button></Button>
</DragPanel>
);
}
export function ResizeablePanel() {
return (
<DragPanel
title="弹层标题"
resizeable
extra="右上角内容"
width={350}
height={400}
body={
<Box p="m" textAlign="center" background="#fa8484">
</Box>
}
footer={<Text></Text>}
>
<Button></Button>
</DragPanel>
);
}
+5 -1
View File
@@ -1,5 +1,5 @@
import React from 'react';
import { Action, InputCode } from '@music163/tango-ui';
import { Action, InputCode, InputStyleCode } from '@music163/tango-ui';
import { BlockOutlined } from '@ant-design/icons';
export default {
@@ -28,6 +28,10 @@ export function Basic() {
);
}
export function CSS() {
return <InputStyleCode enableESLint suffix={<Action icon={<BlockOutlined />} size="small" />} />;
}
const code = `
function foo() {
console.log("test");
+4 -4
View File
@@ -15,10 +15,10 @@
"test:watch": "jest --watch",
"eslint": "eslint packages/**/src/*.{ts,tsx} --cache",
"publish": "lerna publish",
"ver": "lerna version --no-private",
"release": "yarn eslint && yarn build && lerna version --no-private --conventional-commits && lerna publish from-git",
"release:npm": "yarn eslint && yarn build && yarn run ver && lerna publish from-git",
"release:beta": "yarn eslint && yarn build && yarn run ver && lerna publish from-package --dist-tag beta",
"ver": "lerna version --no-private --conventional-commits",
"release": "yarn eslint && yarn build && yarn ver && lerna publish from-git",
"release:npm": "yarn eslint && yarn build && yarn ver && lerna publish from-package",
"release:beta": "yarn eslint && yarn build && yarn ver && lerna publish from-package --dist-tag beta",
"up": "yarn upgrade-interactive --latest",
"prepare": "husky install"
},
+42
View File
@@ -3,6 +3,48 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.1.10](https://github.com/netease/tango/compare/@music163/tango-context@1.1.9...@music163/tango-context@1.1.10) (2024-09-09)
### Bug Fixes
- service support set description field ([#206](https://github.com/netease/tango/issues/206)) ([79f9a8c](https://github.com/netease/tango/commit/79f9a8c1791424f35f194ab2a9aa7c263ef39f40))
## [1.1.9](https://github.com/netease/tango/compare/@music163/tango-context@1.1.8...@music163/tango-context@1.1.9) (2024-09-02)
**Note:** Version bump only for package @music163/tango-context
## [1.1.8](https://github.com/netease/tango/compare/@music163/tango-context@1.1.7...@music163/tango-context@1.1.8) (2024-08-06)
**Note:** Version bump only for package @music163/tango-context
## [1.1.7](https://github.com/netease/tango/compare/@music163/tango-context@1.1.6...@music163/tango-context@1.1.7) (2024-08-05)
**Note:** Version bump only for package @music163/tango-context
## [1.1.6](https://github.com/netease/tango/compare/@music163/tango-context@1.1.5...@music163/tango-context@1.1.6) (2024-08-01)
**Note:** Version bump only for package @music163/tango-context
## [1.1.5](https://github.com/netease/tango/compare/@music163/tango-context@1.1.4...@music163/tango-context@1.1.5) (2024-07-12)
**Note:** Version bump only for package @music163/tango-context
## [1.1.4](https://github.com/netease/tango/compare/@music163/tango-context@1.1.3...@music163/tango-context@1.1.4) (2024-06-20)
**Note:** Version bump only for package @music163/tango-context
## [1.1.3](https://github.com/netease/tango/compare/@music163/tango-context@1.1.2...@music163/tango-context@1.1.3) (2024-06-05)
**Note:** Version bump only for package @music163/tango-context
## [1.1.2](https://github.com/netease/tango/compare/@music163/tango-context@1.1.1...@music163/tango-context@1.1.2) (2024-06-03)
**Note:** Version bump only for package @music163/tango-context
## [1.1.1](https://github.com/netease/tango/compare/@music163/tango-context@1.1.0...@music163/tango-context@1.1.1) (2024-05-21)
**Note:** Version bump only for package @music163/tango-context
# [1.1.0](https://github.com/netease/tango/compare/@music163/tango-context@1.0.2...@music163/tango-context@1.1.0) (2024-05-17)
### Features
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@music163/tango-context",
"version": "1.1.0",
"version": "1.1.10",
"description": "react context for tango-apps",
"keywords": [
"react",
@@ -31,8 +31,8 @@
"react": ">= 16.8"
},
"dependencies": {
"@music163/tango-core": "^1.1.0",
"@music163/tango-helpers": "^1.1.0",
"@music163/tango-core": "^1.4.4",
"@music163/tango-helpers": "^1.2.4",
"mobx-react-lite": "4.0.7"
},
"publishConfig": {
+9 -6
View File
@@ -90,12 +90,15 @@ export const useWorkspaceData = () => {
key: prefix,
selectable: false,
showAddButton: true,
children: Object.keys(file.serviceFunctions || {}).map((key) => ({
title: key,
key: [prefix, key].join('.'),
type: 'function',
showRemoveButton: true,
})),
children: Object.entries(file.serviceFunctions || {}).map(([key, value]) => {
const title = value.description ? `${key}(${value.description})` : key;
return {
title,
key: [prefix, key].join('.'),
type: 'function',
showRemoveButton: true,
};
}),
});
});
+69
View File
@@ -3,6 +3,75 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.4.4](https://github.com/netease/tango/compare/@music163/tango-core@1.4.3...@music163/tango-core@1.4.4) (2024-09-09)
**Note:** Version bump only for package @music163/tango-core
## [1.4.3](https://github.com/netease/tango/compare/@music163/tango-core@1.4.2...@music163/tango-core@1.4.3) (2024-09-02)
**Note:** Version bump only for package @music163/tango-core
## [1.4.2](https://github.com/netease/tango/compare/@music163/tango-core@1.4.1...@music163/tango-core@1.4.2) (2024-08-06)
### Bug Fixes
- view module \_nodesTree set init value ([#194](https://github.com/netease/tango/issues/194)) ([269e304](https://github.com/netease/tango/commit/269e304d685c4fcc80635b9d04220cda333b80c4))
## [1.4.1](https://github.com/netease/tango/compare/@music163/tango-core@1.4.0...@music163/tango-core@1.4.1) (2024-08-05)
**Note:** Version bump only for package @music163/tango-core
# [1.4.0](https://github.com/netease/tango/compare/@music163/tango-core@1.3.3...@music163/tango-core@1.4.0) (2024-08-01)
### Bug Fixes
- update types ([67d602a](https://github.com/netease/tango/commit/67d602a3ec6b7f74156bb78fda6f3b4bc2676e55))
### Features
- add isError and errorMessage to File & add isAstSynced to Module ([#190](https://github.com/netease/tango/issues/190)) ([8dd289c](https://github.com/netease/tango/commit/8dd289cd7daba628e54dc6b8929f22a1e2245160))
## [1.3.3](https://github.com/netease/tango/compare/@music163/tango-core@1.3.2...@music163/tango-core@1.3.3) (2024-07-12)
### Bug Fixes
- update designer config ([#186](https://github.com/netease/tango/issues/186)) ([85c053b](https://github.com/netease/tango/commit/85c053b3db6d652b41c9873dba1366315174833f))
## [1.3.2](https://github.com/netease/tango/compare/@music163/tango-core@1.3.1...@music163/tango-core@1.3.2) (2024-06-20)
### Bug Fixes
- update designer style ([#176](https://github.com/netease/tango/issues/176)) ([0f3f0af](https://github.com/netease/tango/commit/0f3f0afdfa8aee2532a97c5c2e92ef4230397d86))
## [1.3.1](https://github.com/netease/tango/compare/@music163/tango-core@1.3.0...@music163/tango-core@1.3.1) (2024-06-05)
### Bug Fixes
- set value as jsxElement children ([#173](https://github.com/netease/tango/issues/173)) ([ae04850](https://github.com/netease/tango/commit/ae04850bb251f392575a72ca5fd960249ea9d06b))
# [1.3.0](https://github.com/netease/tango/compare/@music163/tango-core@1.2.0...@music163/tango-core@1.3.0) (2024-06-03)
### Bug Fixes
- parse app entry file & pass correct routerType to sandbox ([#168](https://github.com/netease/tango/issues/168)) ([3f3981b](https://github.com/netease/tango/commit/3f3981bb9db874b738a67fd449c579c35c58d08b))
### Features
- add context menu ([#161](https://github.com/netease/tango/issues/161)) ([28040fc](https://github.com/netease/tango/commit/28040fc00604339a40ad3216b76baf7de93a13e0))
# [1.2.0](https://github.com/netease/tango/compare/@music163/tango-core@1.1.0...@music163/tango-core@1.2.0) (2024-05-21)
### Bug Fixes
- enhance code value validate in SettingForm ([#152](https://github.com/netease/tango/issues/152)) ([791fbb1](https://github.com/netease/tango/commit/791fbb162a7147243924e01f54e9c0b586f14438))
- prototype2code & go back history error ([#156](https://github.com/netease/tango/issues/156)) ([8bf53a7](https://github.com/netease/tango/commit/8bf53a76f8a71eaf261ea68b9ee44e5bf19893aa))
- support add components with popover ([#155](https://github.com/netease/tango/issues/155)) ([f17ccbb](https://github.com/netease/tango/commit/f17ccbb7f645f8047ecd96d9f3f2185048a3b726))
### Features
- add select parent node of selected node ([#158](https://github.com/netease/tango/issues/158)) ([fe31246](https://github.com/netease/tango/commit/fe3124648325e72abfc58da8b2f8ff83301d40b8))
- supoort set default active view ([#157](https://github.com/netease/tango/issues/157)) ([f854f75](https://github.com/netease/tango/commit/f854f75b8a8c25384d290bd76d6b8bb6fb69f22d))
# [1.1.0](https://github.com/netease/tango/compare/@music163/tango-core@1.0.2...@music163/tango-core@1.1.0) (2024-05-17)
### Bug Fixes
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@music163/tango-core",
"version": "1.1.0",
"version": "1.4.4",
"description": "tango core",
"author": "wwsun <ww.sun@outlook.com>",
"homepage": "",
@@ -28,7 +28,7 @@
"@babel/parser": "^7.23.5",
"@babel/traverse": "^7.23.5",
"@babel/types": "^7.23.5",
"@music163/tango-helpers": "^1.1.0",
"@music163/tango-helpers": "^1.2.4",
"@types/babel__generator": "^7.6.7",
"@types/babel__traverse": "^7.20.4",
"mobx": "6.12.3",
+14 -1
View File
@@ -1,4 +1,5 @@
import { Designer, Engine, SimulatorNameType } from './models';
import { MenuDataType } from '@music163/tango-helpers';
import { Designer, DesignerViewType, Engine, SimulatorNameType } from './models';
import { IWorkspace } from './models/interfaces';
interface ICreateEngineOptions {
@@ -6,6 +7,10 @@ interface ICreateEngineOptions {
* 自定义工作区
*/
workspace?: IWorkspace;
/**
* 菜单信息
*/
menuData?: MenuDataType;
/**
* 默认的模拟器模式
*/
@@ -14,6 +19,10 @@ interface ICreateEngineOptions {
* 默认激活的侧边栏
*/
defaultActiveSidebarPanel?: string;
/**
* 默认激活的视图
*/
defaultActiveView?: DesignerViewType;
}
/**
@@ -23,15 +32,19 @@ interface ICreateEngineOptions {
*/
export function createEngine({
workspace,
defaultActiveView = 'design',
defaultSimulatorMode = 'desktop',
defaultActiveSidebarPanel = '',
menuData,
}: ICreateEngineOptions) {
const engine = new Engine({
workspace,
designer: new Designer({
workspace,
simulator: defaultSimulatorMode,
activeView: defaultActiveView,
activeSidebarPanel: defaultActiveSidebarPanel,
menuData,
}),
});
+1 -1
View File
@@ -35,7 +35,7 @@ export function isTangoVariable(name: string) {
return /^tango\??\.(stores|services)\??\./.test(name) && name.split('.').length > 2;
}
const templatePattern = /^{(.+)}$/s;
const templatePattern = /^{(.+)}$/;
/**
* 判断给定字符串是否被表达式容器`{expCode}`包裹
+4 -16
View File
@@ -3,7 +3,7 @@
*/
import generator, { GeneratorOptions } from '@babel/generator';
import * as t from '@babel/types';
import { logger, wrapCode } from '@music163/tango-helpers';
import { Dict, logger, wrapCode } from '@music163/tango-helpers';
import { formatCode } from '../string';
const defaultGeneratorOptions: GeneratorOptions = {
@@ -25,19 +25,7 @@ export function ast2code(ast: t.Node, options: GeneratorOptions = defaultGenerat
return code;
}
const bracketPattern = /^\(.+\)$/s;
/**
* 是否被 () 包裹
*
* @example ({ foo: 'foo' }) -> true
* @example { foo: 'foo' } -> false
*
* @param str 目标字符串
*/
function isWrappingWithBrackets(str: string) {
return bracketPattern.test(str);
}
const bracketPattern = /^\(.+\)$/;
/**
* 将表达式生成为块级代码
@@ -54,7 +42,7 @@ export function expression2code(node: t.Expression) {
const isWrappingExpression = t.isObjectExpression(node) || t.isFunctionExpression(node);
if (isWrappingExpression && isWrappingWithBrackets(ret)) {
if (isWrappingExpression && bracketPattern.test(ret)) {
// 如果是对象,输出包含 ({}),则去掉首尾的括号
ret = ret.slice(1, -1);
}
@@ -195,7 +183,7 @@ export function node2value(node: t.Node, isWrapCode = true): any {
);
if (isSimpleObject) {
// simple object: { key1, key2, key3 }
ret = node.properties.reduce((prev, propertyNode) => {
ret = node.properties.reduce<Dict>((prev, propertyNode) => {
if (propertyNode.type === 'ObjectProperty') {
const key = keyNode2value(propertyNode.key);
const value = node2value(propertyNode.value, isWrapCode);
+14 -11
View File
@@ -68,11 +68,7 @@ export function isValidExpressionCode(code: string) {
* @returns
*/
export function code2ast(code: string): t.File {
try {
return parse(code, babelParserConfig);
} catch (err) {
logger.error('[code2ast failed!]', err);
}
return parse(code, babelParserConfig);
}
/**
@@ -97,8 +93,7 @@ export function code2expression(code: string) {
try {
expNode = t.cloneNode(parseExpression(code, babelParserConfig), false, true);
} catch (err) {
logger.error('invalid code', err);
// expNode = t.identifier('undefined');
logger.error('code2expression failed, invalid code:', code);
}
return expNode;
}
@@ -176,7 +171,7 @@ export function value2node(
* 将 js 普通对象解析为 t.Node
*/
export function object2node(
obj: object,
obj: Dict,
getValueNode: (value: any, key?: string) => t.Expression = value2node,
) {
if (!isPlainObject(obj)) {
@@ -194,7 +189,12 @@ export function code2jsxAttributeValueNode(code: string) {
return t.jsxExpressionContainer(code2expression(code));
}
// FIXME: 统一处理为 code2jsxAttributeValueNode
/**
* FIXME: 统一处理为 code2jsxAttributeValueNode
* 将 js value 转为 JSXAttributeValueNode
* @param value js value, or wrapped code
* @returns 返回 JSXAttributeValueNode,转换失败返回Node为 {undefined}
*/
export function value2jsxAttributeValueNode(value: any) {
let ret;
switch (typeof value) {
@@ -204,7 +204,8 @@ export function value2jsxAttributeValueNode(value: any) {
}
if (isWrappedCode(value)) {
const innerCode = getCodeOfWrappedCode(value);
ret = t.jsxExpressionContainer(code2expression(innerCode));
const node = code2expression(innerCode);
ret = t.jsxExpressionContainer(node || t.identifier('undefined'));
} else {
ret = t.stringLiteral(value);
}
@@ -221,10 +222,12 @@ export function value2jsxChildrenValueNode(value: any) {
let ret: t.JSXElement | t.JSXFragment | t.JSXExpressionContainer | t.JSXSpreadChild | t.JSXText;
switch (typeof value) {
case 'string':
if (isValidExpressionCode(value)) {
if (isWrappedCode(value)) {
// 代码模式
const innerString = getVariableContent(value);
ret = t.jsxExpressionContainer(code2expression(innerString));
} else {
// 普通的文本
ret = t.jsxText(value);
}
break;
+23 -2
View File
@@ -391,8 +391,10 @@ export function updateJSXElementAttribute(node: t.JSXElement, attrName: string,
isExist = true;
// @ts-ignore
if (t.isJSXAttribute(jsxAttributeNode)) {
// 更新 jsx 属性值 <Foo bar="1" /> 的模式
jsxAttributeNode.value = value2jsxAttributeValueNode(attrValue);
} else if (name === 'children') {
// 更新 jsx children 的情况 <Foo>children</Foo>
node.children = value2jsxChildrenValueNode(attrValue);
}
}
@@ -1007,7 +1009,7 @@ export function serviceConfig2Node(payload: object) {
});
}
export function updateServiceConfigToServiceFile(ast: t.File, config: Dict<object>) {
export function updateServiceConfigToServiceFile(ast: t.File, config: Dict<Dict>) {
traverse(ast, {
CallExpression(path) {
const calleeName = keyNode2value(path.node.callee) as string;
@@ -1015,7 +1017,7 @@ export function updateServiceConfigToServiceFile(ast: t.File, config: Dict<objec
const configNode = path.node.arguments[0];
if (t.isObjectExpression(configNode)) {
const newPropertiesNodeMap = Object.keys(config).reduce((properties, key) => {
const newPropertiesNodeMap = Object.keys(config).reduce<Dict>((properties, key) => {
const serviceConfig = config[key];
const property = t.objectProperty(t.identifier(key), serviceConfig2Node(serviceConfig));
properties[key] = property;
@@ -1425,3 +1427,22 @@ export function traverseFile(ast: t.File) {
imports,
};
}
/**
* app.js 入口文件解析
* @param ast
*/
export function traverseEntryFile(ast: t.File) {
let appConfig: any;
traverse(ast, {
CallExpression(path) {
const { node } = path;
const calleeName = keyNode2value(node.callee) as string;
if (calleeName === 'runApp') {
appConfig = node2value(node.arguments[0]);
path.stop();
}
},
});
return appConfig;
}
+1 -1
View File
@@ -11,7 +11,7 @@ export function namesToImportDeclarations(
names: string[],
nameMap: Dict<IImportSpecifierSourceData>,
) {
const map = {};
const map: Dict = {};
names.forEach((name) => {
const mod = nameMap[name];
if (mod) {
+10 -6
View File
@@ -20,6 +20,7 @@ export function prototype2importDeclarationData(
relativeFilepath?: string,
): { source: string; specifiers: IImportSpecifierData[] } {
let source = prototype.package;
const isSnippet = prototype.type === 'snippet';
if (relativeFilepath && isFilepath(source)) {
source = getRelativePath(relativeFilepath, source);
}
@@ -35,12 +36,15 @@ export function prototype2importDeclarationData(
type: 'ImportDefaultSpecifier',
});
} else {
[prototype.name, ...(prototype.relatedImports || [])].forEach((item) => {
specifiers.push({
localName: item,
type: 'ImportSpecifier',
});
});
// 忽略代码片段 name
[...(isSnippet ? [] : [prototype.name]), ...(prototype.relatedImports || [])].forEach(
(item) => {
specifiers.push({
localName: item,
type: 'ImportSpecifier',
});
},
);
}
return {
+2 -2
View File
@@ -1,9 +1,9 @@
import { parseDndId, uuid } from '@music163/tango-helpers';
import { Dict, parseDndId, uuid } from '@music163/tango-helpers';
// { id: 1, component, props: { id: 1 }, children: [ { id: 2, component } ] }
export function deepCloneNode(obj: any, component?: string): any {
function deepCloneObject() {
const target = {};
const target: Dict = {};
for (const key in obj) {
if (Object.hasOwn(obj, key)) {
target[key] = deepCloneNode(obj[key], component);
+1 -1
View File
@@ -13,7 +13,7 @@ export class TangoComponentsEntryModule extends TangoModule {
constructor(workspace: IWorkspace, props: IFileConfig) {
super(workspace, props, false);
this.update(props.code, false, false);
this.update(props.code, true, false);
makeObservable(this, {
_code: observable,
_cleanCode: observable,
+117 -3
View File
@@ -1,5 +1,6 @@
import { action, computed, makeObservable, observable, toJS } from 'mobx';
import { IWorkspace } from './interfaces';
import { MenuDataType } from '@music163/tango-helpers';
export type SimulatorNameType = 'desktop' | 'phone';
@@ -19,7 +20,15 @@ interface IViewportBounding {
interface IDesignerOptions {
workspace: IWorkspace;
simulator?: SimulatorNameType | ISimulatorType;
/**
* 菜单配置
*/
menuData: MenuDataType;
activeSidebarPanel?: string;
/**
* 默认激活的视图模式
*/
activeView?: DesignerViewType;
}
const ISimulatorTypes: Record<string, ISimulatorType> = {
@@ -64,6 +73,26 @@ export class Designer {
*/
_showSmartWizard = false;
/**
* 是否显示添加组件面板
*/
_showAddComponentPopover = false;
/**
* 添加组件面板的位置
*/
_addComponentPopoverPosition = { clientX: 0, clientY: 0 };
/**
* 是否显示右键菜单
*/
_showContextMenu = false;
/**
* 右键菜单在 iframe 上的位置
*/
_contextMenuPosition = { clientX: 0, clientY: 0 };
/**
* 是否显示右侧面板
*/
@@ -75,9 +104,9 @@ export class Designer {
_isPreview = false;
/**
* 默认展开的侧边栏
* 菜单列表
*/
defaultActiveSidebarPanel?: string;
_menuData?: MenuDataType = null;
private readonly workspace: IWorkspace;
@@ -109,10 +138,39 @@ export class Designer {
return this._showRightPanel;
}
get showAddComponentPopover() {
return this._showAddComponentPopover;
}
get addComponentPopoverPosition() {
return this._addComponentPopoverPosition;
}
get showContextMenu() {
return this._showContextMenu;
}
get contextMenuPosition() {
return this._contextMenuPosition;
}
get menuData() {
return this._menuData ?? ([] as MenuDataType);
}
constructor(options: IDesignerOptions) {
this.workspace = options.workspace;
const { simulator, activeSidebarPanel: defaultActiveSidebarPanel } = options;
const {
simulator,
menuData,
activeSidebarPanel: defaultActiveSidebarPanel,
activeView: defaultActiveView,
} = options;
if (menuData) {
this.setMenuData(menuData);
}
// 默认设计器模式
if (simulator) {
@@ -124,6 +182,11 @@ export class Designer {
this.setActiveSidebarPanel(defaultActiveSidebarPanel);
}
// 默认激活的视图
if (defaultActiveView) {
this.setActiveView(defaultActiveView);
}
makeObservable(this, {
_simulator: observable,
_viewport: observable,
@@ -131,6 +194,11 @@ export class Designer {
_activeSidebarPanel: observable,
_showSmartWizard: observable,
_showRightPanel: observable,
_showAddComponentPopover: observable,
_addComponentPopoverPosition: observable,
_showContextMenu: observable,
_contextMenuPosition: observable,
_menuData: observable,
_isPreview: observable,
simulator: computed,
viewport: computed,
@@ -139,6 +207,11 @@ export class Designer {
isPreview: computed,
showRightPanel: computed,
showSmartWizard: computed,
showAddComponentPopover: computed,
addComponentPopoverPosition: computed,
showContextMenu: computed,
contextMenuPosition: computed,
menuData: computed,
setSimulator: action,
setViewport: action,
setActiveView: action,
@@ -147,6 +220,8 @@ export class Designer {
toggleRightPanel: action,
toggleSmartWizard: action,
toggleIsPreview: action,
toggleAddComponentPopover: action,
toggleContextMenu: action,
});
}
@@ -164,6 +239,13 @@ export class Designer {
setActiveView(view: DesignerViewType) {
this._activeView = view;
if (view === 'dual') {
this.setActiveSidebarPanel('');
this.toggleRightPanel(false);
this.toggleIsPreview(true);
} else if (view === 'design') {
this.toggleIsPreview(false);
}
}
setActiveSidebarPanel(panel: string) {
@@ -173,6 +255,11 @@ export class Designer {
this._activeSidebarPanel = '';
}
}
setMenuData(menuData: MenuDataType) {
this._menuData = menuData;
}
closeSidebarPanel() {
this._activeSidebarPanel = '';
}
@@ -185,10 +272,37 @@ export class Designer {
this._showRightPanel = value ?? !this._showRightPanel;
}
/**
* 显示添加组件面板
* @param value 是否显示
* @param position 坐标
*/
toggleAddComponentPopover(
value: boolean,
position: {
clientX: number;
clientY: number;
} = this.addComponentPopoverPosition,
) {
this._showAddComponentPopover = value;
this._addComponentPopoverPosition = position;
}
toggleIsPreview(value: boolean) {
this._isPreview = value ?? !this._isPreview;
if (value) {
this.workspace.selectSource.clear();
}
}
toggleContextMenu(
value: boolean,
position: {
clientX: number;
clientY: number;
} = this.contextMenuPosition,
) {
this._showContextMenu = value;
this._contextMenuPosition = position;
}
}
+18
View File
@@ -0,0 +1,18 @@
import { traverseEntryFile } from '../helpers';
import { IFileConfig } from '../types';
import { IWorkspace } from './interfaces';
import { TangoModule } from './module';
export class AppEntryModule extends TangoModule {
routerType: string;
constructor(workspace: IWorkspace, props: IFileConfig) {
super(workspace, props, false);
this.update(props.code, true, false);
}
_analysisAst() {
const config = traverseEntryFile(this.ast);
this.routerType = config?.router?.type;
}
}
+11
View File
@@ -24,6 +24,16 @@ export class TangoFile {
*/
lastModified: number;
/**
* 文件解析是否出错
*/
isError: boolean;
/**
* 文件解析错误消息
*/
errorMessage: string;
_code: string;
_cleanCode: string;
@@ -40,6 +50,7 @@ export class TangoFile {
this.filename = props.filename;
this.type = props.type;
this.lastModified = Date.now();
this.isError = false;
// 这里主要是为了解决 umi ts 编译错误的问题,@see https://github.com/umijs/umi/issues/7594
if (isSyncCode) {
+1 -1
View File
@@ -58,7 +58,7 @@ export class TangoHistory {
}
get couldBack() {
return this._records.length > 0 && this._index > -1;
return this._records.length > 0 && this._index > 0;
}
get couldForward() {
+1
View File
@@ -7,6 +7,7 @@ export * from './drag-source';
export * from './history';
export * from './file';
export * from './module';
export * from './entry-module';
export * from './route-module';
export * from './service-module';
export * from './store-module';
+23 -2
View File
@@ -10,12 +10,14 @@ import {
IPageConfigData,
IImportSpecifierSourceData,
IImportSpecifierData,
IFileError,
} from '../types';
import { TangoFile, TangoJsonFile } from './file';
import { TangoRouteModule } from './route-module';
import { TangoStoreModule } from './store-module';
import { TangoServiceModule } from './service-module';
import { IdGenerator } from '../helpers';
import { AppEntryModule } from './entry-module';
export interface IViewFile {
readonly workspace: IWorkspace;
@@ -152,6 +154,10 @@ export interface IWorkspace {
* 解析后的 tango.config.json 文件,如果要获取项目配置,推荐使用 projectConfig 获取
*/
tangoConfigJson: TangoJsonFile;
/**
* app.js 入口文件解析后的模块
*/
appEntryModule: AppEntryModule;
/**
* 解析后的路由模块
*/
@@ -187,7 +193,18 @@ export interface IWorkspace {
renameFile: (oldFilename: string, newFilename: string) => void;
renameFolder: (oldFoldername: string, newFoldername: string) => void;
updateFile: (filename: string, code: string, shouldFormatCode?: boolean) => void;
/**
* 更新文件
* @param filename 文件名
* @param code 代码
* @param isSyncAst 是否同步 ast
*/
updateFile: (filename: string, code: string, isSyncAst?: boolean) => void;
/**
* 检查并同步文件的 ast
*/
syncFiles: () => void;
listFiles: () => Record<string, string>;
getFile: (filename: string) => TangoFile;
@@ -293,8 +310,12 @@ export interface IWorkspace {
get bizComps(): string[];
get baseComps(): string[];
get localComps(): string[];
get fileErrors(): IFileError[];
/**
* 是否是合法的项目
* 是否是有效的项目
* - 包含 tango.config.json
* - 包含视图模块
* - 没有文件错误
*/
get isValid(): boolean;
}
+60 -18
View File
@@ -21,6 +21,11 @@ import { IWorkspace } from './interfaces';
export class TangoModule extends TangoFile {
ast: t.File;
/**
* ast 是否与 code 保持同步
*/
isAstSynced: boolean;
/**
* 导入的依赖列表
*/
@@ -33,23 +38,53 @@ export class TangoModule extends TangoFile {
/**
* 基于最新的 ast 进行同步
* @param code 如果传入 code,则基于 code 进行同步
* @param isFormatCode 是否格式化代码
* @param refreshWorkspace 是否刷新 workspace
* @param isSyncAst 是否同步 ast
* @param isRefreshWorkspace 是否刷新 workspace
*/
update(code?: string, isFormatCode = true, refreshWorkspace = true) {
update(code?: string, isSyncAst = true, isRefreshWorkspace = true) {
this.lastModified = Date.now();
if (isNil(code)) {
this._syncByAst();
} else {
this._syncByCode(code, isFormatCode);
try {
if (isNil(code)) {
this._syncByAst();
} else {
this._syncByCode(code, isSyncAst);
}
if (isSyncAst) {
this._analysisAst();
}
this.isAstSynced = isSyncAst;
this.isError = false;
this.errorMessage = undefined;
this.workspace.onFilesChange([this.filename]);
if (isRefreshWorkspace) {
this.workspace.refresh([this.filename]);
}
} catch (err: any) {
this.isError = true;
this.errorMessage = err.message;
}
}
this._analysisAst();
this.workspace.onFilesChange([this.filename]);
if (refreshWorkspace) {
this.workspace.refresh([this.filename]);
/**
* 基于当前的代码重新生成 ast
*/
updateAst() {
if (!this.isAstSynced) {
try {
this.ast = code2ast(this._code);
this._analysisAst();
this.isAstSynced = true;
this.isError = false;
this.errorMessage = undefined;
} catch (err: any) {
this.isAstSynced = false;
this.isError = true;
this.errorMessage = err.message;
}
}
}
@@ -75,22 +110,26 @@ export class TangoModule extends TangoFile {
/**
* 基于输入的源码进行同步
* @param code 源码
* @param isFormatCode 是否格式化代码
* @param isSyncAst 是否同步 ast
* @returns
*/
_syncByCode(code: string, isFormatCode = true) {
_syncByCode(code: string, isSyncAst = true) {
if (code === this._code) {
return;
}
// 提前格式化代码
if (isFormatCode) {
try {
code = formatCode(code);
} catch (err) {
// err ignored, format code failed
}
this._code = code;
this._cleanCode = code;
this.ast = code2ast(code);
if (isSyncAst) {
this.ast = code2ast(code);
}
}
_analysisAst() {
@@ -105,14 +144,17 @@ export class TangoModule extends TangoFile {
export class TangoJsModule extends TangoModule {
constructor(workspace: IWorkspace, props: IFileConfig) {
super(workspace, props, false);
this.update(props.code, false, false);
this.update(props.code, true, false);
makeObservable(this, {
_code: observable,
_cleanCode: observable,
isError: observable,
errorMessage: observable,
code: computed,
cleanCode: computed,
update: action,
updateAst: action,
});
}
}
+5 -1
View File
@@ -1,4 +1,5 @@
import { action, computed, makeObservable, observable, toJS } from 'mobx';
import { logger } from '@music163/tango-helpers';
import {
traverseRouteFile,
addRouteToRouteFile,
@@ -27,10 +28,13 @@ export class TangoRouteModule extends TangoModule {
_routes: observable,
_code: observable,
_cleanCode: observable,
isError: observable,
errorMessage: observable,
routes: computed,
code: computed,
cleanCode: computed,
update: action,
updateAst: action,
});
}
@@ -74,7 +78,7 @@ export class TangoRouteModule extends TangoModule {
*/
removeRoute(route: string) {
if (route === '/') {
console.warn('index route should not be removed!');
logger.warn('index route should not be removed!');
return;
}
const record = this.getRouteByRoutePath(route);
+14
View File
@@ -109,6 +109,20 @@ export class SelectSource {
this._start = null;
}
/**
* 选中当前选中节点的父节点
*/
selectParent() {
const parents = this.first?.parents || [];
if (parents.length) {
const [parent, ...rest] = parents;
this.select({
...parent,
parents: rest,
});
}
}
setStart(data: StartDataType) {
this._start = data;
}
@@ -49,11 +49,14 @@ export class TangoServiceModule extends TangoModule {
_baseConfig: observable,
_code: observable,
_cleanCode: observable,
isError: observable,
errorMessage: observable,
serviceFunctions: computed,
baseConfig: computed,
cleanCode: computed,
code: computed,
update: action,
updateAst: action,
});
}
+3
View File
@@ -31,10 +31,13 @@ export class TangoStoreEntryModule extends TangoModule {
_stores: observable,
_code: observable,
_cleanCode: observable,
isError: observable,
errorMessage: observable,
stores: computed,
code: computed,
cleanCode: computed,
update: action,
updateAst: action,
});
}
+6 -2
View File
@@ -84,7 +84,7 @@ function nodeListToTreeData(list: ITangoViewNodeData[]) {
*/
export class TangoViewModule extends TangoModule implements IViewFile {
// 解析为树结构的 jsxNodes 数组
_nodesTree: ITangoViewNodeData[];
_nodesTree: ITangoViewNodeData[] = [];
/**
* 通过导入组件名查找组件来自的包
*/
@@ -138,10 +138,14 @@ export class TangoViewModule extends TangoModule implements IViewFile {
_code: observable,
_cleanCode: observable,
isError: observable,
errorMessage: observable,
code: computed,
cleanCode: computed,
update: action,
updateAst: action,
});
}
@@ -320,7 +324,7 @@ export class TangoViewModule extends TangoModule implements IViewFile {
updateNodeAttributes(nodeId: string, config: Record<string, any>, relatedImports?: string[]) {
if (relatedImports && relatedImports.length) {
// 导入依赖的组件
const newImportData = relatedImports.reduce((prev, name) => {
const newImportData = relatedImports.reduce<Dict<IImportSpecifierData[]>>((prev, name) => {
const proto = this.workspace.getPrototype(name);
const { source, specifiers } = prototype2importDeclarationData(proto, this.filename);
const existSpecifiers: IImportSpecifierData[] = prev[source];
+57 -24
View File
@@ -11,6 +11,7 @@ import {
parseServiceVariablePath,
parseStoreVariablePath,
uniq,
setValue,
} from '@music163/tango-helpers';
import {
prototype2jsxElement,
@@ -24,10 +25,10 @@ import {
import { DropMethod } from './drop-target';
import { HistoryMessage, TangoHistory } from './history';
import { TangoNode } from './node';
import { TangoJsModule } from './module';
import { TangoJsModule, TangoModule } from './module';
import { TangoFile, TangoJsonFile, TangoLessFile } from './file';
import { IWorkspace } from './interfaces';
import { IFileConfig, FileType, ITangoConfigPackages, IPageConfigData } from '../types';
import { IFileConfig, FileType, ITangoConfigPackages, IPageConfigData, IFileError } from '../types';
import { SelectSource } from './select-source';
import { DragSource } from './drag-source';
import { TangoRouteModule } from './route-module';
@@ -35,6 +36,7 @@ import { TangoStoreEntryModule, TangoStoreModule } from './store-module';
import { TangoServiceModule } from './service-module';
import { TangoViewModule } from './view-module';
import { TangoComponentsEntryModule } from './component-module';
import { AppEntryModule } from './entry-module';
export interface IWorkspaceOptions {
/**
@@ -97,6 +99,11 @@ export class Workspace extends EventTarget implements IWorkspace {
*/
activeViewFile: string;
/**
* 应用入口模块
*/
appEntryModule: AppEntryModule;
/**
* 路由配置模块
*/
@@ -144,11 +151,8 @@ export class Workspace extends EventTarget implements IWorkspace {
*/
private copyTempNodes: TangoNode[];
/**
* 是否是合法的项目
*/
get isValid() {
return !!this.tangoConfigJson && !!this.activeViewModule;
return !!this.tangoConfigJson && !!this.activeViewModule && this.fileErrors.length === 0;
}
/**
@@ -216,6 +220,19 @@ export class Workspace extends EventTarget implements IWorkspace {
return Object.keys(this.componentsEntryModule?.exportList || {});
}
get fileErrors() {
const errors: IFileError[] = [];
this.files.forEach((file) => {
if (file.isError) {
errors.push({
filename: file.filename,
message: file.errorMessage,
});
}
});
return errors;
}
constructor(options?: IWorkspaceOptions) {
super();
this.history = new TangoHistory(this);
@@ -249,6 +266,8 @@ export class Workspace extends EventTarget implements IWorkspace {
activeViewFile: observable,
pages: computed,
bizComps: computed,
fileErrors: computed,
isValid: computed,
setActiveRoute: action,
setActiveFile: action,
addFile: action,
@@ -329,6 +348,9 @@ export class Workspace extends EventTarget implements IWorkspace {
* @param fileType 模块类型
*/
addFile(filename: string, code: string, fileType?: FileType) {
if (!fileType && filename === this.entry) {
fileType = FileType.AppEntryModule;
}
const moduleType = fileType || inferFileType(filename);
const props = {
filename,
@@ -338,6 +360,10 @@ export class Workspace extends EventTarget implements IWorkspace {
let module;
switch (moduleType) {
case FileType.AppEntryModule:
module = new AppEntryModule(this, props);
this.appEntryModule = module;
break;
case FileType.StoreEntryModule:
module = new TangoStoreEntryModule(this, props);
this.storeEntryModule = module;
@@ -425,10 +451,16 @@ export class Workspace extends EventTarget implements IWorkspace {
);
}
updateFile(filename: string, code: string, shouldFormatCode = false) {
updateFile(filename: string, code: string, isSyncAst = true) {
const file = this.getFile(filename);
file.update(code);
if (shouldFormatCode && file instanceof TangoViewModule) {
if (file instanceof TangoModule) {
file.update(code, isSyncAst);
} else {
file.update(code);
}
const shouldFormat = this.projectConfig?.designerConfig?.autoFormatCode;
if (shouldFormat && file instanceof TangoViewModule) {
file.removeUnusedImportSpecifiers().update();
}
this.history.push({
@@ -439,12 +471,15 @@ export class Workspace extends EventTarget implements IWorkspace {
});
}
/**
* 删除工作区的文件
* @param filename
*/
syncFiles() {
this.files.forEach((file) => {
if (file instanceof TangoModule) {
file.updateAst();
}
});
}
removeFile(filename: string) {
// TODO: refactor visitFile to share this logic
if (this.files.get(filename)) {
// 如果是文件,直接删除
this.files.delete(filename);
@@ -500,7 +535,7 @@ export class Workspace extends EventTarget implements IWorkspace {
* @returns { [filename]: fileCode }
*/
listFiles() {
const ret = {};
const ret: Dict<string> = {};
this.files.forEach((file) => {
ret[file.filename] = file.cleanCode;
});
@@ -728,6 +763,7 @@ export class Workspace extends EventTarget implements IWorkspace {
* 更新依赖,没有就添加
* @param name
* @param version
* FIXME: 参数3的设置需要重新考虑下
*/
updateDependency(
name: string,
@@ -750,15 +786,12 @@ export class Workspace extends EventTarget implements IWorkspace {
if (!packages) {
return undefined;
}
if (options?.package || packages[name]) {
packages[name] = {
type: packages[name]?.type,
// 如果没有传入 package 信息,则沿用 tango.config.json 中已记录的数据
// 如果传入了,则全量使用传入的信息,适配可能在某个版本中如 resources 等字段被删除的情况
...(options?.package || packages[name]),
version,
};
}
setValue(packages, name, {
...packages[name], // 保留原有的配置
version, // 更新版本号
...options?.package, // 更新 package 配置
});
return packages;
})
+6
View File
@@ -8,6 +8,7 @@ export type SimulatorMode = 'desktop' | 'tablet' | 'phone';
export enum FileType {
// js 文件
Module = 'module',
AppEntryModule = 'appEntryModule',
StoreEntryModule = 'storeEntryModule',
RouteModule = 'routeModule',
ServiceModule = 'serviceModule',
@@ -56,6 +57,11 @@ export interface IFileConfig {
type?: FileType;
}
export interface IFileError {
filename: string;
message: string;
}
/**
* 视图节点数据类型
*/
+27 -3
View File
@@ -1,19 +1,28 @@
import { Identifier } from '@babel/types';
import {
object2node,
serviceConfig2Node,
isValidCode,
isValidExpressionCode,
code2expression,
value2jsxAttributeValueNode,
} from '../src/helpers';
describe('ast helpers', () => {
it('isValidCode', () => {
expect(isValidCode('')).toBeTruthy();
expect(isValidCode('1')).toBeTruthy();
expect(isValidCode('"hello"')).toBeTruthy();
expect(isValidCode('<div>hello</div>')).toBeTruthy();
expect(isValidCode('function fn() {}')).toBeTruthy();
// invalid function body
expect(isValidCode('() => { hello world }')).toBeFalsy();
// invalid function
expect(isValidCode('function() {}')).toBeFalsy();
});
it('isValidExpression', () => {
expect(isValidExpressionCode('() => { }')).toBeTruthy();
it('isValidExpressionCode', () => {
expect(isValidExpressionCode('1')).toBeTruthy();
expect(isValidExpressionCode('a = 1')).toBeTruthy();
expect(isValidExpressionCode('1 + 1')).toBeTruthy();
@@ -22,8 +31,11 @@ describe('ast helpers', () => {
expect(isValidExpressionCode('{ bizId: "vip", type: "category" }')).toBeTruthy();
expect(isValidExpressionCode('[1,2,3]')).toBeTruthy();
expect(isValidExpressionCode('<div>hello</div>')).toBeTruthy();
expect(isValidExpressionCode('<div>hello</div>')).toBeTruthy();
expect(isValidExpressionCode('tango.stores.app.title')).toBeTruthy();
expect(isValidExpressionCode('"hello" + window.location.path')).toBeTruthy();
expect(isValidExpressionCode('() => { }')).toBeTruthy();
expect(isValidExpressionCode('')).toBeFalsy();
expect(isValidExpressionCode('{1}')).toBeFalsy();
expect(isValidExpressionCode('{"1"}')).toBeFalsy();
expect(isValidExpressionCode('{ 1+1 }')).toBeFalsy();
@@ -68,4 +80,16 @@ describe('ast helpers', () => {
`;
expect(code2expression(arrayCode).type).toEqual('ArrayExpression');
});
it('value2jsxAttributeValueNode', () => {
expect(value2jsxAttributeValueNode('hello').type).toBe('StringLiteral');
expect(value2jsxAttributeValueNode(true).type).toBe('JSXExpressionContainer');
expect(value2jsxAttributeValueNode(1).type).toBe('JSXExpressionContainer');
expect(value2jsxAttributeValueNode('{{{ foo: "foo"}}}').type).toBe('JSXExpressionContainer');
// invalid code will return undefined
const node: any = value2jsxAttributeValueNode('{{tango.xx+}}');
expect(node.type).toBe('JSXExpressionContainer');
expect((node.expression as Identifier).name).toBe('undefined');
});
});
+112
View File
@@ -3,6 +3,118 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.4.6](https://github.com/netease/tango/compare/@music163/tango-designer@1.4.5...@music163/tango-designer@1.4.6) (2024-09-09)
### Bug Fixes
- add classNameSetter and classNameInput ([#207](https://github.com/netease/tango/issues/207)) ([55602fc](https://github.com/netease/tango/commit/55602fc961b5c20d923891ce13d7a51588bd047f))
- renderSetter with template ([#202](https://github.com/netease/tango/issues/202)) ([ea96872](https://github.com/netease/tango/commit/ea9687226123c839f7a9e001b4c01aa8315a135d))
- service support set description field ([#206](https://github.com/netease/tango/issues/206)) ([79f9a8c](https://github.com/netease/tango/commit/79f9a8c1791424f35f194ab2a9aa7c263ef39f40))
## [1.4.5](https://github.com/netease/tango/compare/@music163/tango-designer@1.4.4...@music163/tango-designer@1.4.5) (2024-09-02)
### Bug Fixes
- add prop value template & fix components popover ([#201](https://github.com/netease/tango/issues/201)) ([c4e1ed6](https://github.com/netease/tango/commit/c4e1ed67f55deb17dae740559602cd0adcfc8eb4))
## [1.4.4](https://github.com/netease/tango/compare/@music163/tango-designer@1.4.3...@music163/tango-designer@1.4.4) (2024-08-16)
### Bug Fixes
- CodeInput 支持 jsx css 代码补全 ([#198](https://github.com/netease/tango/issues/198)) ([6de5488](https://github.com/netease/tango/commit/6de54884b50d683c74d695a8c13184dc0ce8d3c4))
## [1.4.3](https://github.com/netease/tango/compare/@music163/tango-designer@1.4.2...@music163/tango-designer@1.4.3) (2024-08-09)
### Bug Fixes
- file errors overlay support click to error file & optimize ui ([#197](https://github.com/netease/tango/issues/197)) ([ca56edd](https://github.com/netease/tango/commit/ca56edd9ae201dbeb84b03ad390a09085433a257))
- route matching without query string & toggle button wrapping ([#195](https://github.com/netease/tango/issues/195)) ([9394666](https://github.com/netease/tango/commit/939466648d40331800f15e886256a0789b7e7623))
- update mobile simulator ui ([#196](https://github.com/netease/tango/issues/196)) ([65149f1](https://github.com/netease/tango/commit/65149f1326eaf78e8a27222993c3cacc674cd378))
## [1.4.2](https://github.com/netease/tango/compare/@music163/tango-designer@1.4.1...@music163/tango-designer@1.4.2) (2024-08-06)
**Note:** Version bump only for package @music163/tango-designer
## [1.4.1](https://github.com/netease/tango/compare/@music163/tango-designer@1.4.0...@music163/tango-designer@1.4.1) (2024-08-05)
### Bug Fixes
- parse template code & update maxRow of TextAreaSetter ([#192](https://github.com/netease/tango/issues/192)) ([a1eea02](https://github.com/netease/tango/commit/a1eea02f9409db73f042c74d7903ad84258f25c2))
- show right panel when design view select node & optimize editor css ([#193](https://github.com/netease/tango/issues/193)) ([b83d965](https://github.com/netease/tango/commit/b83d965955c8d33ed8d37063482c7abe079e62b1))
# [1.4.0](https://github.com/netease/tango/compare/@music163/tango-designer@1.3.3...@music163/tango-designer@1.4.0) (2024-08-01)
### Bug Fixes
- update types ([67d602a](https://github.com/netease/tango/commit/67d602a3ec6b7f74156bb78fda6f3b4bc2676e55))
### Features
- add isError and errorMessage to File & add isAstSynced to Module ([#190](https://github.com/netease/tango/issues/190)) ([8dd289c](https://github.com/netease/tango/commit/8dd289cd7daba628e54dc6b8929f22a1e2245160))
## [1.3.3](https://github.com/netease/tango/compare/@music163/tango-designer@1.3.2...@music163/tango-designer@1.3.3) (2024-07-12)
### Bug Fixes
- selection bug without prototype & update ToggleButton style ([#180](https://github.com/netease/tango/issues/180)) ([1d0fb4f](https://github.com/netease/tango/commit/1d0fb4f274a5b767962c54583ab5863329d5bcc5))
- update designer config ([#186](https://github.com/netease/tango/issues/186)) ([85c053b](https://github.com/netease/tango/commit/85c053b3db6d652b41c9873dba1366315174833f))
## [1.3.2](https://github.com/netease/tango/compare/@music163/tango-designer@1.3.1...@music163/tango-designer@1.3.2) (2024-06-20)
### Bug Fixes
- drag-panel add resizeable & height prop ([#175](https://github.com/netease/tango/issues/175)) ([b53a9f7](https://github.com/netease/tango/commit/b53a9f7eefc748ba8a7c94270c3a374b9d6ed211))
- fix global hotkey triggering on content editable elements ([#174](https://github.com/netease/tango/issues/174)) ([a2cc418](https://github.com/netease/tango/commit/a2cc418a73edfd9b7fe8aad456ae775a49df2166))
- update designer style ([#176](https://github.com/netease/tango/issues/176)) ([0f3f0af](https://github.com/netease/tango/commit/0f3f0afdfa8aee2532a97c5c2e92ef4230397d86))
## [1.3.1](https://github.com/netease/tango/compare/@music163/tango-designer@1.3.0...@music163/tango-designer@1.3.1) (2024-06-05)
### Bug Fixes
- fix context menu error on macOS ([#170](https://github.com/netease/tango/issues/170)) ([ca740c8](https://github.com/netease/tango/commit/ca740c83ae7f72a75c7db90d2e137a7e9a032326))
# [1.3.0](https://github.com/netease/tango/compare/@music163/tango-designer@1.2.3...@music163/tango-designer@1.3.0) (2024-06-03)
### Bug Fixes
- parse app entry file & pass correct routerType to sandbox ([#168](https://github.com/netease/tango/issues/168)) ([3f3981b](https://github.com/netease/tango/commit/3f3981bb9db874b738a67fd449c579c35c58d08b))
### Features
- add context menu ([#161](https://github.com/netease/tango/issues/161)) ([28040fc](https://github.com/netease/tango/commit/28040fc00604339a40ad3216b76baf7de93a13e0))
## [1.2.3](https://github.com/netease/tango/compare/@music163/tango-designer@1.2.2...@music163/tango-designer@1.2.3) (2024-05-30)
### Bug Fixes
- optimize variable panel scroll ui & onCancel bug ([#166](https://github.com/netease/tango/issues/166)) ([a0ed57f](https://github.com/netease/tango/commit/a0ed57ff4f332bd88749b8b1925bdb29319e4d13))
## [1.2.2](https://github.com/netease/tango/compare/@music163/tango-designer@1.2.1...@music163/tango-designer@1.2.2) (2024-05-27)
### Bug Fixes
- export usePreviewSandboxQuery & add builtin sandboxQuery ([#163](https://github.com/netease/tango/issues/163)) ([163eced](https://github.com/netease/tango/commit/163ecedff3ed7baee59e200a8cc60dcc63a24e48))
## [1.2.1](https://github.com/netease/tango/compare/@music163/tango-designer@1.2.0...@music163/tango-designer@1.2.1) (2024-05-22)
### Bug Fixes
- check local component prototypes ([#160](https://github.com/netease/tango/issues/160)) ([a0484e8](https://github.com/netease/tango/commit/a0484e8f64f20f67c30c25c3d5ce65de549b3e04))
# [1.2.0](https://github.com/netease/tango/compare/@music163/tango-designer@1.1.0...@music163/tango-designer@1.2.0) (2024-05-21)
### Bug Fixes
- enhance code value validate in SettingForm ([#152](https://github.com/netease/tango/issues/152)) ([791fbb1](https://github.com/netease/tango/commit/791fbb162a7147243924e01f54e9c0b586f14438))
- prototype2code & go back history error ([#156](https://github.com/netease/tango/issues/156)) ([8bf53a7](https://github.com/netease/tango/commit/8bf53a76f8a71eaf261ea68b9ee44e5bf19893aa))
- support add components with popover ([#155](https://github.com/netease/tango/issues/155)) ([f17ccbb](https://github.com/netease/tango/commit/f17ccbb7f645f8047ecd96d9f3f2185048a3b726))
### Features
- add history forward & back shortcut key ([#154](https://github.com/netease/tango/issues/154)) ([df3021f](https://github.com/netease/tango/commit/df3021f75e057e229756b429321c14d181223698))
- add select parent node of selected node ([#158](https://github.com/netease/tango/issues/158)) ([fe31246](https://github.com/netease/tango/commit/fe3124648325e72abfc58da8b2f8ff83301d40b8))
- event-setter & expression-setter use popover ([#159](https://github.com/netease/tango/issues/159)) ([9daf387](https://github.com/netease/tango/commit/9daf3872e743fcf706184877020bcbf1f75ffd25))
# [1.1.0](https://github.com/netease/tango/compare/@music163/tango-designer@1.0.3...@music163/tango-designer@1.1.0) (2024-05-17)
### Bug Fixes
+7 -7
View File
@@ -1,6 +1,6 @@
{
"name": "@music163/tango-designer",
"version": "1.1.0",
"version": "1.4.6",
"description": "lowcode designer",
"keywords": [
"react"
@@ -33,12 +33,12 @@
"dependencies": {
"@ant-design/icons": "^4.8.0",
"@music163/request": "^0.2.0",
"@music163/tango-context": "^1.1.0",
"@music163/tango-core": "^1.1.0",
"@music163/tango-helpers": "^1.1.0",
"@music163/tango-sandbox": "^1.0.3",
"@music163/tango-setting-form": "^1.2.0",
"@music163/tango-ui": "^1.1.0",
"@music163/tango-context": "^1.1.10",
"@music163/tango-core": "^1.4.4",
"@music163/tango-helpers": "^1.2.4",
"@music163/tango-sandbox": "^1.0.13",
"@music163/tango-setting-form": "^1.2.15",
"@music163/tango-ui": "^1.4.5",
"antd": "^4.24.2",
"cash-dom": "^8.1.2",
"classnames": "^2.5.1",
@@ -0,0 +1,139 @@
import React, { useCallback, useMemo, useState } from 'react';
import { Box } from 'coral-system';
import { observer, useDesigner, useWorkspace } from '@music163/tango-context';
import { IconFont, DragPanel } from '@music163/tango-ui';
import { ComponentsPanel, ComponentsPanelProps } from '../sidebar';
import { IComponentPrototype } from '@music163/tango-helpers';
interface ComponentsPopoverProps {
// 添加组件位置
type?: 'inner' | 'before' | 'after';
// 弹出方式 手动触发/DOM 触发
isControlled?: boolean;
title?: string;
prototype?: IComponentPrototype;
children?: React.ReactNode;
}
export const ComponentsPopover = observer(
({
type = 'inner',
title = '添加组件',
isControlled = false,
children,
...popoverProps
}: ComponentsPopoverProps) => {
const [layout, setLayout] = useState<ComponentsPanelProps['layout']>('grid');
const workspace = useWorkspace();
const designer = useDesigner();
const { addComponentPopoverPosition, showAddComponentPopover } = designer;
const selectedNode = workspace.selectSource.selected?.[0];
const selectedNodeId = selectedNode?.codeId ?? '未选中';
const prototype =
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
workspace.componentPrototypes.get(selectedNode?.name) ?? ({} as IComponentPrototype);
const recommendedList = useMemo(() => {
if (type === 'inner') {
return prototype?.childrenName
? Array.isArray(prototype?.childrenName)
? prototype.childrenName
: [prototype.childrenName]
: [];
}
// 默认推荐使用相同类型的组件作为兄弟节点
return prototype.siblingNames || [prototype.name];
}, [prototype.childrenName, prototype.siblingNames, prototype.name, type]);
const tipsTextMap = useMemo(
() => ({
before: `点击,在 ${selectedNodeId} 的前方添加节点`,
after: `点击,在 ${selectedNodeId} 的后方添加节点`,
inner: `点击,在 ${selectedNodeId} 内部添加节点`,
}),
[selectedNodeId],
);
const handleSelect = useCallback(
(name: string) => {
switch (type) {
case 'before':
workspace.insertBeforeSelectedNode(name);
break;
case 'after':
workspace.insertAfterSelectedNode(name);
break;
case 'inner':
workspace.insertToSelectedNode(name);
break;
default:
break;
}
},
[type, workspace],
);
const changeLayout = useCallback(() => {
setLayout(layout === 'grid' ? 'line' : 'grid');
}, [layout]);
const menuData = useMemo(() => {
const menuList = JSON.parse(JSON.stringify(designer.menuData));
const commonList = menuList['common'] ?? [];
if (commonList?.length && recommendedList.length) {
commonList.unshift({
title: '推荐使用',
items: recommendedList,
});
}
return menuList;
}, [recommendedList, designer.menuData]);
const innerTypeProps =
// 手动触发 适用于 点击添加组件
type === 'inner' && isControlled
? {
open: showAddComponentPopover,
onOpenChange: (open: boolean) => designer.toggleAddComponentPopover(open),
left: addComponentPopoverPosition.clientX,
top: addComponentPopoverPosition.clientY,
}
: {};
return (
<DragPanel
{...innerTypeProps}
title={title}
extra={
<Box fontSize="12px">
{layout === 'grid' ? (
<IconFont type="icon-liebiaoitem" onClick={changeLayout} />
) : (
<IconFont type="icon-grid1" onClick={changeLayout} />
)}
</Box>
}
footer={tipsTextMap[type]}
width="330px"
height="450px"
resizeable
maskClosable
body={
<ComponentsPanel
isScope
showBizComps={false}
menuData={menuData}
layout={layout}
onItemSelect={handleSelect}
/>
}
{...popoverProps}
>
{children}
</DragPanel>
);
},
);
@@ -0,0 +1,130 @@
import React from 'react';
import { getWidget } from '../widgets';
import { Menu, MenuProps } from 'antd';
import { observer, useWorkspace } from '@music163/tango-context';
import { ISelectedItemData, isString } from '@music163/tango-helpers';
import { Box, css } from 'coral-system';
import { IconFont } from '@music163/tango-ui';
const contextMenuStyle = css`
.ant-dropdown-menu {
width: 240px;
}
.ant-dropdown-menu-title-content {
padding-left: 22px;
}
.ant-dropdown-menu-item-icon {
font-size: 14px;
width: 14px;
}
.ant-dropdown-menu-item-icon + .ant-dropdown-menu-title-content {
padding-left: 0;
}
.ant-dropdown-menu-submenu-popup {
padding: 0;
margin-top: -4px;
}
`;
const ParentNodesMenuItem = ({
record,
onClick,
key,
}: {
record: ISelectedItemData;
onClick: () => any;
key?: string;
}) => {
const workspace = useWorkspace();
const componentPrototype = workspace.componentPrototypes.get(record.name);
const icon = componentPrototype?.icon || 'icon-placeholder';
const iconRender = icon.startsWith('icon-') ? (
<IconFont className="material-icon" type={icon} />
) : (
<img className="material-icon" src={icon} alt={componentPrototype.name} />
);
return (
<Menu.Item key={key || record.id} icon={iconRender} onClick={onClick}>
{record.name}
{!!record.codeId && ` (${record.codeId})`}
</Menu.Item>
);
};
const ParentNodesMenu = observer(() => {
const workspace = useWorkspace();
const selectSource = workspace.selectSource;
const parents = selectSource.first?.parents;
if (!parents?.length) {
return null;
}
return (
<Menu.SubMenu key="parentNodes" title="选取父节点">
{parents.map((item, index) => (
<ParentNodesMenuItem
key={item.id}
record={item}
onClick={() => {
selectSource.select({
...item,
parents: parents.slice(index + 1),
});
}}
/>
))}
</Menu.SubMenu>
);
});
export interface ContextMenuProps extends MenuProps {
/**
* 动作列表,默认列出全部
*/
actions?: Array<string | React.ReactElement>;
/**
* 是否显示父节点选项
*/
showParents?: boolean;
className?: string;
style?: React.CSSProperties;
menuStyle?: React.CSSProperties;
}
export const ContextMenu = observer(
({
showParents,
actions: actionsProp,
className,
style,
menuStyle,
...rest
}: ContextMenuProps) => {
const actions = actionsProp || Object.keys(getWidget('contextMenu'));
const menus = actions.map((item) => {
if (isString(item)) {
const widget = getWidget(['contextMenu', item].join('.'));
return widget ? React.createElement(widget) : null;
}
return item;
});
if (showParents) {
menus.unshift(<ParentNodesMenu />);
}
return (
<Box display="inline-block" css={contextMenuStyle} className={className} style={style}>
<Menu activeKey={null} {...rest} style={menuStyle}>
{menus}
</Menu>
</Box>
);
},
);
@@ -0,0 +1,133 @@
import React, { useState } from 'react';
import { Box, css, Text } from 'coral-system';
import { observer, useDesigner, useWorkspace } from '@music163/tango-context';
import { CloseOutlined } from '@ant-design/icons';
const errorMessageStyle = css`
padding: 35px;
position: relative;
white-space: pre-wrap;
color: #f45755;
font-weight: bold;
height: 100%;
background-color: #171717;
border-radius: 8px;
.top-bar {
border-radius: 8px 8px 0 0;
position: absolute;
top: 0;
left: 0;
right: 0;
height: 10px;
background-color: #f45755;
}
.WorkspaceErrorOverlayItem {
font-size: 18px;
padding-top: 20px;
padding-bottom: 20px;
.WorkspaceErrorOverlayItemFilename {
color: #48cacb;
text-decoration: underline;
letter-spacing: 1px;
&:hover {
color: #51b1ff;
}
}
}
`;
/**
* 文件错误提示浮层
*/
export const FileErrorsOverlay = observer(() => {
const [isVisible, setIsVisible] = useState<boolean>(true);
const workspace = useWorkspace();
const designer = useDesigner();
const handleClose = () => {
setIsVisible(false);
};
const handleOpenErrorFile = (fileName: string) => {
workspace.setActiveFile(fileName);
designer.setActiveView('code');
};
if (workspace.fileErrors.length === 0) {
return null;
}
if (!isVisible) {
return null;
}
return (
<Box
className="WorkspaceErrorOverlay"
position="absolute"
top="0"
left="0"
right="0"
height="100%"
bg="rgb(84, 84, 84)"
padding="30px"
color="red"
overflow="auto"
zIndex={1999}
>
<Box position="relative" p="4" boxShadow="0 0 10px rgba(0, 0, 0, 0.5)">
<CloseOutlined
style={{
position: 'absolute',
top: 24,
right: 12,
color: '#fff',
zIndex: 2,
}}
onClick={handleClose}
/>
<Box css={errorMessageStyle}>
<Box className="top-bar" />
<Box fontSize="18px" mb="l">
<Text letterSpacing=".5px" color="#c29ef5">
[plugin: @babel/parser]
</Text>
<Text marginLeft={'8px'} color="#f45755">
SyntaxError in {workspace.fileErrors.length} filesClick file to modify the error
code
</Text>
</Box>
<Box>
{workspace.fileErrors.map((fileError, index) => (
<Box
className="WorkspaceErrorOverlayItem"
key={fileError.filename}
borderBottom={index === workspace.fileErrors.length - 1 ? 'none' : 'dashed'}
borderBottomColor="line2"
py="l"
>
<Box
className="WorkspaceErrorOverlayItemFilename"
fontWeight="bold"
style={{ cursor: 'pointer' }}
onClick={() => handleOpenErrorFile(fileError.filename)}
>
{fileError.filename}
</Box>
<Box
as="code"
display="block"
color="#daa15e"
fontSize="16px"
fontWeight={'normal'}
>
{fileError.message}
</Box>
</Box>
))}
</Box>
</Box>
</Box>
</Box>
);
});
@@ -1,4 +1,7 @@
export * from './context-menu';
export * from './drag-box';
export * from './input-kv';
export * from './variable-tree';
export * from './variable-tree-modal';
export * from './components-popover';
export * from './file-errors-overlay';
@@ -1,11 +1,11 @@
import { isValidFunctionCode, url2serviceName } from '@music163/tango-helpers';
import { Dict, isValidFunctionCode, url2serviceName } from '@music163/tango-helpers';
import { InputCode } from '@music163/tango-ui';
import { Button, Dropdown, Form, FormProps, Input, Select, Space } from 'antd';
import { Box } from 'coral-system';
import React, { useState } from 'react';
interface AddServiceFormProps extends FormProps {
initialValues?: object;
initialValues?: Dict;
onSubmit: (values: object) => void;
onCancel: () => void;
serviceModules: object[];
@@ -88,6 +88,10 @@ export function AddServiceForm({
>
<Input placeholder="请输入数据服务调用名称" disabled={disabled || isModifyMode} />
</Form.Item>
{/* 备注 */}
<Form.Item label="备注" name="description">
<Input placeholder="请输入备注信息" />
</Form.Item>
<Form.Item label="路径" name="url" rules={[{ required: true, type: 'url' }]}>
<Input placeholder="请输入数据服务调用名称" disabled={disabled || isModifyMode} />
</Form.Item>
@@ -166,7 +166,7 @@ export function VariableTree(props: VariableTreeProps) {
return (
<Box display="flex" columnGap="l" className="VariableTree" css={varTreeStyle} {...rest}>
<Box className="VariableList" width="40%">
<Box className="VariableList" width="40%" overflow="auto">
{renderHeaderExtra?.(props, state)}
<Box mb="m" position="sticky" top="0" bg="white" zIndex={2}>
<Search placeholder="请输入变量名" onChange={(val) => setKeyword(val?.trim())} />
@@ -203,7 +203,11 @@ export function VariableTree(props: VariableTreeProps) {
<Box flex="0 0 72px" textAlign="right">
{node.showRemoveButton && (
<Popconfirm
zIndex={99999}
title={`确认删除吗 ${node.title}?该操作会导致引用此模型的代码报错,请谨慎操作!`}
onCancel={(e) => {
e.stopPropagation();
}}
onConfirm={(e) => {
e.stopPropagation();
if (isStoreVariablePath(node.key)) {
@@ -333,7 +337,14 @@ export function VariableTree(props: VariableTreeProps) {
}}
/>
) : (
<ValueDefine data={activeNode} onSave={onUpdateStoreVariable} />
<ValueDefine
data={activeNode}
onSave={(variableKey, code) => {
onUpdateStoreVariable(variableKey, code);
// 更新当前节点 code
setActiveNode((pre) => ({ ...pre, raw: code }));
}}
/>
)
}
</ValueDetail>
@@ -84,6 +84,8 @@ export function ValueDefine({ data, onSave = noop }: ValueDefineProps) {
onClick={() => {
off();
setError('');
// 重置到原始值
setValue(data.raw);
}}
>
@@ -0,0 +1,19 @@
import React from 'react';
import { useWorkspace, observer } from '@music163/tango-context';
import { ContextAction } from '@music163/tango-ui';
import { CopyOutlined } from '@ant-design/icons';
export const CopyNodeContextAction = observer(() => {
const workspace = useWorkspace();
return (
<ContextAction
icon={<CopyOutlined />}
hotkey="Command+C"
onClick={() => {
workspace.copySelectedNode();
}}
>
</ContextAction>
);
});
@@ -0,0 +1,19 @@
import React from 'react';
import { useWorkspace, observer } from '@music163/tango-context';
import { ContextAction } from '@music163/tango-ui';
import { DeleteOutlined } from '@ant-design/icons';
export const DeleteNodeContextAction = observer(() => {
const workspace = useWorkspace();
return (
<ContextAction
icon={<DeleteOutlined />}
hotkey="Backspace"
onClick={() => {
workspace.removeSelectedNode();
}}
>
</ContextAction>
);
});
@@ -0,0 +1,4 @@
export * from './copy-node';
export * from './delete-node';
export * from './paste-node';
export * from './view-source';
@@ -0,0 +1,19 @@
import React from 'react';
import { useWorkspace, observer } from '@music163/tango-context';
import { ContextAction } from '@music163/tango-ui';
import { SnippetsOutlined } from '@ant-design/icons';
export const PasteNodeContextAction = observer(() => {
const workspace = useWorkspace();
return (
<ContextAction
icon={<SnippetsOutlined />}
hotkey="Command+V"
onClick={() => {
workspace.pasteSelectedNode();
}}
>
</ContextAction>
);
});
@@ -0,0 +1,18 @@
import React from 'react';
import { useDesigner, observer } from '@music163/tango-context';
import { ContextAction } from '@music163/tango-ui';
import { CodeOutlined } from '@ant-design/icons';
export const ViewSourceContextAction = observer(() => {
const designer = useDesigner();
return (
<ContextAction
icon={<CodeOutlined />}
onClick={() => {
designer.setActiveView('code');
}}
>
</ContextAction>
);
});
+11 -3
View File
@@ -6,10 +6,14 @@ export interface IDesignerContext<S = any> {
* 沙箱查询实例
*/
sandboxQuery: DndQuery;
/**
* 预览沙箱查询实例
*/
previewSandboxQuery: DndQuery;
/**
* 远程服务
*/
remoteServices?: Record<string, S>;
remoteServices: Record<string, S>;
}
const [DesignerProvider, useDesigner] = createContext<IDesignerContext>({
@@ -19,9 +23,13 @@ const [DesignerProvider, useDesigner] = createContext<IDesignerContext>({
export { DesignerProvider };
export const useSandboxQuery = () => {
return useDesigner()?.sandboxQuery;
return useDesigner().sandboxQuery;
};
export const usePreviewSandboxQuery = () => {
return useDesigner().previewSandboxQuery;
};
export const useRemoteServices = () => {
return useDesigner()?.remoteServices;
return useDesigner().remoteServices;
};
+23 -3
View File
@@ -5,8 +5,18 @@ import { TangoEngineProvider, ITangoEngineContext } from '@music163/tango-contex
import zhCN from 'antd/lib/locale/zh_CN';
import { DesignerProvider, IDesignerContext } from './context';
import defaultTheme from './themes/default';
import { DndQuery } from './dnd';
import { DESIGN_SANDBOX_ID, PREVIEW_SANDBOX_ID } from './helpers';
export interface DesignerProps extends IDesignerContext, ITangoEngineContext {
const builtinSandboxQuery = new DndQuery({
context: `#${DESIGN_SANDBOX_ID}`,
});
const builtinPreviewSandboxQuery = new DndQuery({
context: `#${PREVIEW_SANDBOX_ID}`,
});
export interface DesignerProps extends Partial<IDesignerContext>, ITangoEngineContext {
/**
* 主题包
*/
@@ -20,13 +30,23 @@ export interface DesignerProps extends IDesignerContext, ITangoEngineContext {
* @returns
*/
export function Designer(props: DesignerProps) {
const { engine, config, theme: themeProp, sandboxQuery, remoteServices = {}, children } = props;
const {
engine,
config,
theme: themeProp,
sandboxQuery = builtinSandboxQuery,
previewSandboxQuery = builtinPreviewSandboxQuery,
remoteServices = {},
children,
} = props;
const theme = useMemo(() => extendTheme(themeProp, defaultTheme), [themeProp]);
return (
<SystemProvider theme={theme} prefix="--tango">
<ConfigProvider locale={zhCN}>
<TangoEngineProvider value={{ engine, config }}>
<DesignerProvider value={{ sandboxQuery, remoteServices }}>{children}</DesignerProvider>
<DesignerProvider value={{ sandboxQuery, previewSandboxQuery, remoteServices }}>
{children}
</DesignerProvider>
</TangoEngineProvider>
</ConfigProvider>
</SystemProvider>
+6 -1
View File
@@ -12,7 +12,6 @@ export const DRAGGABLE_SELECTOR = `[${SLOT.dnd}]`;
interface DndQueryOptions {
/**
* DOM 查询上下文选择器
* TODO: 是不是可以合并成一个 API
*/
context?: string;
/**
@@ -63,6 +62,9 @@ export class DndQuery {
return false;
}
/**
* 沙箱内的 window 对象
*/
get window() {
if (this.context && 'defaultView' in this.context) {
return (this.context as unknown as Document).defaultView;
@@ -71,6 +73,9 @@ export class DndQuery {
return window;
}
/**
* 沙箱内的全局滚动偏移
*/
get scrollTop() {
if (this.context && 'documentElement' in this.context) {
return (this.context as unknown as Document).documentElement.scrollTop;
+3 -1
View File
@@ -1,8 +1,10 @@
import { Dict } from '@music163/tango-helpers';
/**
* 快捷键
*/
export class Hotkey {
private readonly hotkeyMap = {};
private readonly hotkeyMap: Dict = {};
constructor(hotkeys: Record<string, Function>) {
Object.keys(hotkeys).forEach((hotkey) => {
+81 -5
View File
@@ -58,6 +58,15 @@ export function useDnd({
'command+v,ctrl+v': () => {
workspace.pasteSelectedNode();
},
'command+arrowup,ctrl+arrowup': () => {
workspace.selectSource.selectParent();
},
'command+z,ctrl+z': () => {
workspace.history.back();
},
'command+shift+z,ctrl+shift+z': () => {
workspace.history.forward();
},
});
}, [workspace]);
@@ -68,6 +77,9 @@ export function useDnd({
if (designer.isPreview) {
return;
}
if (designer.showContextMenu) {
designer.toggleContextMenu(false);
}
const point = sandboxQuery.getRelativePoint({ x: e.clientX, y: e.clientY });
selectSource.setStart({
@@ -84,10 +96,10 @@ export function useDnd({
const onMouseMove = (e: React.MouseEvent) => {
const point = sandboxQuery.getRelativePoint({ x: e.clientX, y: e.clientY });
setElementStyle('.SelectionMask', {
width: Math.abs(selectSource.start?.point.x - point.x) + 'px',
height: Math.abs(selectSource.start?.point.y - point.y) + 'px',
left: Math.min(selectSource.start?.point.x, point.x) + 'px',
top: Math.min(selectSource.start?.point.y, point.y) + 'px',
width: `${Math.abs(selectSource.start?.point.x - point.x)}px`,
height: `${Math.abs(selectSource.start?.point.y - point.y)}px`,
left: `${Math.min(selectSource.start?.point.x, point.x)}px`,
top: `${Math.min(selectSource.start?.point.y, point.y)}px`,
});
};
@@ -119,9 +131,14 @@ export function useDnd({
};
const onClick = (e: React.MouseEvent) => {
if (designer.showContextMenu) {
designer.toggleContextMenu(false);
}
const data = sandboxQuery.getDraggableParentsData(e.target as HTMLElement, true);
if (data && data.id) {
selectSource.select(data);
// 画布选中节点时,自动唤起 right-panel
designer.toggleRightPanel(true);
}
};
@@ -371,7 +388,8 @@ export function useDnd({
};
const onKeyDown = (e: React.KeyboardEvent) => {
const isInputElement = isInputElements((e.target as HTMLElement).nodeName);
const target = e.target as HTMLElement;
const isInputElement = target.isContentEditable || isInputElements(target.nodeName);
// 禁用输入事件的触发的快捷键逻辑
if (!isInputElement) {
const key = getHotkey(e);
@@ -379,6 +397,56 @@ export function useDnd({
}
};
const onContextMenu = (event: React.MouseEvent) => {
if (designer.showContextMenu) {
designer.toggleContextMenu(false);
}
// 按下其他按键时,视为用户有特殊操作,此时不展示右键菜单
if (event.ctrlKey || event.altKey || event.metaKey || event.shiftKey) {
return;
}
const { clientX, clientY } = event;
let target;
if (workspace.selectSource.isSelected) {
for (const item of workspace.selectSource.selected) {
if (
// 如果选中的节点是页面根节点(无 parents),则忽略
item.parents?.length &&
item.bounding &&
clientX >= item.bounding.left &&
clientX <= item.bounding.left + item.bounding.width &&
clientY >= item.bounding.top &&
clientY <= item.bounding.top + item.bounding.height
) {
// 右键坐标已经在当前选中组件的选区内,直接展示右键菜单
target = item;
break;
}
}
}
// 否则,根据右键的元素选中最接近的组件
if (!target) {
target = sandboxQuery.getDraggableParentsData(event.target as HTMLElement, true);
}
if (target && target.id) {
if (!target.parents?.length) {
// 页面根节点不展示右键菜单操作
return;
}
// 右键时高亮选中当前元素
// 以防之前选区有多个元素,即便已经是选中的元素也再选中一遍
event.preventDefault();
selectSource.select(target);
// 在下一周期再展示右键菜单,以让先前的菜单先被销毁
requestAnimationFrame(() => {
designer.toggleContextMenu(true, {
clientX,
clientY,
});
});
}
};
const onTango = (e: CustomEvent) => {
const detail = e.detail || {};
@@ -406,6 +474,13 @@ export function useDnd({
// 打开智能向导弹窗
designer.toggleSmartWizard(true);
break;
case 'addComponent':
// 打开添加组件面板
designer.toggleAddComponentPopover(true, {
clientX: (e.detail.meta as any).clientX + 40,
clientY: (e.detail.meta as any).clientY + 110,
});
break;
default:
break;
}
@@ -421,6 +496,7 @@ export function useDnd({
onDragEnd,
onScroll,
onKeyDown,
onContextMenu,
onTango,
...selectHandler,
};
+81 -102
View File
@@ -1,9 +1,7 @@
import React, { useRef, useEffect, useCallback } from 'react';
import { Box } from 'coral-system';
import { MultiEditor, MultiEditorProps } from '@music163/tango-ui';
import { observer, useWorkspace } from '@music163/tango-context';
import { isValidCode } from '@music163/tango-core';
import { Modal } from 'antd';
import { observer, useDesigner, useWorkspace } from '@music163/tango-context';
const ideConfig = {
// disableFileOps: {
@@ -21,108 +19,89 @@ const ideConfig = {
// disableSetting: true,
};
export interface CodeEditorProps extends Partial<MultiEditorProps> {
/**
* 是否自动清楚未使用的导入
*/
autoRemoveUnusedImports?: boolean;
}
export type CodeEditorProps = Partial<MultiEditorProps>;
export const CodeEditor = observer(
({ autoRemoveUnusedImports = true, ...rest }: CodeEditorProps) => {
const editorRef = useRef(null);
const workspace = useWorkspace();
const files = workspace.listFiles();
const activeFile = workspace.activeFile;
export const CodeEditor = observer((props: CodeEditorProps) => {
const editorRef = useRef(null);
const workspace = useWorkspace();
const designer = useDesigner();
const files = workspace.listFiles();
const activeFile = workspace.activeFile;
let loc: any; // 记录视图代码的选中位置
const selectNode = workspace.selectSource.firstNode;
if (selectNode && activeFile === workspace.activeViewFile) {
loc = selectNode.loc;
}
let loc: any; // 记录视图代码的选中位置
const selectNode = workspace.selectSource.firstNode;
if (selectNode && activeFile === workspace.activeViewFile) {
loc = selectNode.loc;
}
useEffect(() => {
editorRef.current?.refresh(files, activeFile, loc);
}, [files, activeFile, loc]);
useEffect(() => {
editorRef.current?.refresh(files, activeFile, loc);
}, [files, activeFile, loc]);
const fileSave = useCallback(
(path: string, value: string) => {
if (!isJsFile(path)) {
// 非 js 文件直接保存
workspace.updateFile(path, value, autoRemoveUnusedImports);
return;
const fileSave = useCallback(
(path: string, value: string) => {
workspace.updateFile(path, value, false);
},
[workspace],
);
const handleFileChange = useCallback(
(type: string, info: any) => {
switch (type) {
case 'addFile':
workspace.addFile(info.path, info.value);
break;
case 'deleteFile':
case 'deleteFolder':
workspace.removeFile(info.path);
break;
case 'renameFile':
workspace.renameFile(info.path, info.newpath);
workspace.setActiveFile(info.newpath);
break;
case 'renameFolder':
workspace.renameFolder(info.path, info.newpath);
break;
case 'addFolder':
default:
break;
}
},
[workspace],
);
const handlePathChange = useCallback(
(path: string) => {
workspace.setActiveFile(path);
},
[workspace],
);
const borderStyle =
designer.activeView === 'dual'
? {
borderLeft: 'solid 1px var(--tango-colors-line2)',
borderRight: 'solid 1px var(--tango-colors-line2)',
}
: {};
// js 文件需要先检查语法,只有语法正确才会保存
if (isValidCode(value)) {
workspace.updateFile(path, value, autoRemoveUnusedImports);
} else {
Modal.confirm({
title: '检测到代码中存在语法错误,暂时无法将代码同步给设计器,是否回退到安全代码?',
onOk: () => {
editorRef.current?.refresh(files, activeFile);
},
onCancel: () => {},
});
}
},
[workspace, autoRemoveUnusedImports, activeFile, files],
);
const handleFileChange = useCallback(
(type: string, info: any) => {
switch (type) {
case 'addFile':
workspace.addFile(info.path, info.value);
break;
case 'deleteFile':
case 'deleteFolder':
workspace.removeFile(info.path);
break;
case 'renameFile':
workspace.renameFile(info.path, info.newpath);
workspace.setActiveFile(info.newpath);
break;
case 'renameFolder':
workspace.renameFolder(info.path, info.newpath);
break;
case 'addFolder':
default:
break;
}
},
[workspace],
);
const handlePathChange = useCallback(
(path: string) => {
workspace.setActiveFile(path);
},
[workspace],
);
return (
<Box display="flex" flexDirection="row" height="100%" bg="white">
<MultiEditor
ref={editorRef}
options={{
fontSize: 14,
automaticLayout: true,
}}
ideConfig={ideConfig}
onFileSave={fileSave}
onPathChange={handlePathChange}
onFileChange={handleFileChange}
defaultPath={activeFile}
defaultTheme="GithubLightDefault"
defaultFiles={files}
{...rest}
/>
</Box>
);
},
);
function isJsFile(path: string) {
return /.jsx?$/.test(path);
}
return (
<Box display="flex" flexDirection="row" height="100%" bg="white" {...borderStyle}>
<MultiEditor
ref={editorRef}
options={{
fontSize: 14,
automaticLayout: true,
}}
ideConfig={ideConfig}
onFileSave={fileSave}
onPathChange={handlePathChange}
onFileChange={handleFileChange}
defaultPath={activeFile}
defaultTheme="GithubLightDefault"
defaultFiles={files}
{...props}
/>
</Box>
);
});
+14 -2
View File
@@ -7,6 +7,20 @@ import {
parseDndId,
} from '@music163/tango-helpers';
// -----------
// CONSTANTS
// -----------
export const DRAG_GHOST_ID = 'dragGhost';
export const DESIGN_SANDBOX_ID = 'sandbox-container';
export const PREVIEW_SANDBOX_ID = 'preview-sandbox-container';
// -----------
// DOM Helpers
// -----------
export function buildQueryBySlotId(id: string) {
return `[${SLOT.dnd}="${id}"]`;
}
@@ -15,8 +29,6 @@ export function getElement(selector: Selector) {
return $(selector).get(0);
}
export const DRAG_GHOST_ID = 'dragGhost';
export const getDragGhostElement = () => getElement(`#${DRAG_GHOST_ID}`);
export function setElementStyle(selector: Selector, style: any) {
+15 -6
View File
@@ -1,13 +1,14 @@
import React, { useImperativeHandle, ForwardedRef, useRef, useState, useEffect } from 'react';
import { Box } from 'coral-system';
import { CodeSandbox, CodeSandboxProps } from '@music163/tango-sandbox';
import { getValue, isFunction, logger, pick, setValue } from '@music163/tango-helpers';
import { Dict, getValue, isFunction, logger, pick, setValue } from '@music163/tango-helpers';
import { observer, useWorkspace, useDesigner } from '@music163/tango-context';
import { Simulator, Viewport } from '../simulator';
import { useSandboxQuery } from '../context';
import { DndQuery, useDnd } from '../dnd';
import { Navigator } from './navigator';
import { SelectionToolsProps } from '../simulator/selection';
import { DESIGN_SANDBOX_ID, PREVIEW_SANDBOX_ID } from '../helpers';
interface ISandboxEventHandlerConfig {
sandboxQuery?: DndQuery;
@@ -48,6 +49,10 @@ export interface CombinedSandboxRef {
const LANDING_PAGE_PATH = '/__background_landing_page__';
function fixRouterMode(routerType: string): CodeSandboxProps['routerMode'] {
return routerType === 'hash' ? 'hash' : undefined;
}
function useSandbox({
isPreview: isPreviewProp,
configFormatter,
@@ -62,6 +67,7 @@ function useSandbox({
const workspace = useWorkspace();
const designer = useDesigner();
const sandboxQuery = useSandboxQuery();
const isPreview = isPreviewProp ?? designer.isPreview;
// 组件不一定会立即刷新,因此 isActive 需要实时获取
@@ -82,7 +88,7 @@ function useSandbox({
onViewChange: (data) => onViewChange && onViewChange(data, getSandboxConfig()),
});
let files = Array.from(workspace.files.keys()).reduce((prev, filename) => {
let files = Array.from(workspace.files.keys()).reduce<Dict>((prev, filename) => {
let code = workspace.getFile(filename).code;
if (filename === '/tango.config.json') {
code = mergeTangoConfigJson(code, { isPreview, injectScript, formatter: configFormatter });
@@ -103,23 +109,26 @@ function useSandbox({
// 根据当前 workspace 状态与组件传入的状态是否一致,控制是否需要切换到空白路由
const display = isActive ? 'block' : 'none';
const routePath = isActive ? startRoute || workspace.activeRoute : LANDING_PAGE_PATH;
const routerMode = fixRouterMode(workspace.appEntryModule?.routerType);
const sandboxProps = isPreview
? {
files,
eventHandlers: pick(dndHandlers, ['onTango']),
onMessage,
onLoad,
display,
startRoute: routePath,
onLoad,
routerMode,
}
: {
files,
eventHandlers: dndHandlers as any,
onMessage,
onLoad,
display,
startRoute: routePath,
onLoad,
routerMode,
};
return sandboxProps;
@@ -140,7 +149,7 @@ const PreviewSandbox = observer(
return (
<Box display={display} width="100%" height="100%">
<CodeSandbox ref={ref} iframeId="preview-sandbox-container" {...sandboxProps} {...rest} />
<CodeSandbox ref={ref} iframeId={PREVIEW_SANDBOX_ID} {...sandboxProps} {...rest} />
</Box>
);
},
@@ -188,7 +197,7 @@ const DesignSandbox = observer(
return (
<Box display={display} width="100%" height="100%">
<CodeSandbox ref={ref} {...sandboxProps} {...rest} />
<CodeSandbox ref={ref} iframeId={DESIGN_SANDBOX_ID} {...sandboxProps} {...rest} />
</Box>
);
},
@@ -1,3 +1,5 @@
export * from './copy-node';
export * from './delete-node';
export * from './more-actions';
export * from './select-parent-node';
export * from './view-source';
@@ -0,0 +1,16 @@
import React from 'react';
import { observer } from '@music163/tango-context';
import { SelectAction } from '@music163/tango-ui';
import { MoreOutlined } from '@ant-design/icons';
import { Dropdown } from 'antd';
import { ContextMenu } from '../components';
export const MoreActionsAction = observer(() => {
return (
<Dropdown placement="bottomRight" overlay={<ContextMenu showParents />}>
<SelectAction tooltip="更多">
<MoreOutlined />
</SelectAction>
</Dropdown>
);
});
@@ -0,0 +1,18 @@
import React from 'react';
import { useWorkspace, observer } from '@music163/tango-context';
import { IconFont, SelectAction } from '@music163/tango-ui';
export const SelectParentNodeAction = observer(() => {
const workspace = useWorkspace();
return (
<SelectAction
tooltip="选中父节点"
onClick={() => {
workspace.selectSource.selectParent();
}}
>
<IconFont type="icon-huiche1" rotate={90} />
</SelectAction>
);
});
@@ -1,11 +1,11 @@
import React, { useCallback } from 'react';
import { Radio, RadioProps, Tooltip } from 'antd';
import type { OptionType } from '@music163/tango-helpers';
import type { IOptionItem } from '@music163/tango-helpers';
import { FormItemComponentProps } from '@music163/tango-setting-form';
import { IconFont } from '@music163/tango-ui';
interface ChoiceSetterProps {
options?: OptionType[];
options?: IOptionItem[];
}
export function ChoiceSetter({
@@ -0,0 +1,7 @@
import { FormItemComponentProps } from '@music163/tango-setting-form';
import { ClassNameInput } from '@music163/tango-ui';
import React from 'react';
export function ClassNameSetter({ value, onChange }: FormItemComponentProps<string>) {
return <ClassNameInput value={value} onChange={onChange} />;
}
@@ -0,0 +1,396 @@
import React, { useState, useEffect, useCallback } from 'react';
import { Box, Text, css } from 'coral-system';
import { Dropdown, Button } from 'antd';
import { isValidExpressionCode } from '@music163/tango-core';
import { getValue, interpolate, IVariableTreeNode, noop } from '@music163/tango-helpers';
import { CloseCircleFilled, MenuOutlined } from '@ant-design/icons';
import {
Panel,
InputCode,
Action,
DragPanel,
PopOutOutlined,
InputCodeProps,
InputStyleCode,
} from '@music163/tango-ui';
import { FormItemComponentProps } from '@music163/tango-setting-form';
import { useWorkspace, useWorkspaceData } from '@music163/tango-context';
import { VariableTree } from '../components';
import { useSandboxQuery } from '../context';
import { CODE_TEMPLATES } from '../helpers';
import { shapeServiceValues } from '../sidebar/datasource-panel/interface-config';
export const expressionValueValidate = (value: string) => {
if (!isValidExpressionCode(value)) {
return '表达式存在语法错误!';
}
};
export const jsonValueValidate = (value: string) => {
try {
JSON.parse(value);
} catch (e) {
return '不是合法的 JSON 语法!';
}
};
/**
* 拼装回调函数
* @param value 回调函数体
* @param template 回调函数模板
* @returns
*/
export function getCallbackValue(value: string, template?: string) {
if (!value) {
return;
}
return template ? interpolate(template, { content: value }) : `() => {\n ${value}\n}`;
}
const suffixStyle = css`
display: flex;
align-items: center;
.anticon-close-circle {
color: rgba(0, 0, 0, 0.25);
&:hover {
color: rgba(0, 0, 0, 0.45);
}
}
`;
export interface CodeSetterProps extends FormItemComponentProps<string> {
modalTitle?: string;
modalTip?: string;
autoCompleteOptions?: string[];
allowClear?: boolean;
showOptionsDropDown?: boolean;
/**
* 表达式类型指定为 css object
*/
expressionType?: 'cssObject';
}
export function CodeSetter(props: CodeSetterProps) {
const {
onChange,
modalTitle,
modalTip,
autoCompleteOptions,
template,
placeholder = '在这里输入代码',
value: valueProp,
status,
allowClear = true,
newStoreTemplate,
showOptionsDropDown = true,
expressionType,
} = props;
// const codeValue = getCodeOfWrappedCode(valueProp);
const [inputValue, setInputValue] = useState(valueProp);
// when receive new value, sync state
useEffect(() => {
setInputValue(valueProp);
}, [valueProp]);
const change = useCallback(
(code: string) => {
if (code === valueProp) {
return;
}
onChange(code);
},
[valueProp, onChange],
);
const sandbox = useSandboxQuery();
const evaluateContext = sandbox.window;
const InputCodeComponent = expressionType === 'cssObject' ? InputStyleCode : InputCode;
return (
<Box className="ExpressionSetter">
{/* 同时支持下拉框展示 */}
<InputCodeComponent
placeholder={placeholder}
suffix={
<Box css={suffixStyle}>
{allowClear && (
<CloseCircleFilled
title="清空"
onClick={() => {
change(undefined);
}}
/>
)}
{showOptionsDropDown && autoCompleteOptions?.length && (
<Dropdown
menu={{
items: autoCompleteOptions.map((option) => ({
key: option,
label: (
<Text
onClick={() => {
change(option);
}}
>
{option}
</Text>
),
})),
}}
>
<Action tooltip="使用预设代码片段" icon={<MenuOutlined />} size="small" />
</Dropdown>
)}
<ExpressionPopover
title={modalTitle}
subTitle={modalTip}
placeholder={placeholder}
autoCompleteOptions={autoCompleteOptions}
template={template}
newStoreTemplate={newStoreTemplate}
value={inputValue}
expressionType={expressionType}
onOk={(value) => {
change(value);
}}
/>
</Box>
}
value={inputValue}
onChange={setInputValue}
onBlur={() => {
change(inputValue);
}}
autoCompleteContext={evaluateContext}
autoCompleteOptions={autoCompleteOptions}
status={status}
maxHeight="200px"
/>
</Box>
);
}
export interface ExpressionPopoverProps extends InputCodeProps {
title?: string;
subTitle?: string;
placeholder?: string;
defaultValue?: string;
value?: string;
onOk?: (value: string) => void;
dataSource?: IVariableTreeNode[];
autoCompleteOptions?: string[];
/**
* 值的模板,一般用于定义函数模板
*/
template?: string;
/**
* 新建 store 的模板代码
*/
newStoreTemplate?: string;
/**
* 表达式类型指定为 css object
*/
expressionType?: 'cssObject';
children?: React.ReactNode;
}
export function ExpressionPopover({
title,
subTitle,
placeholder,
onOk = noop,
defaultValue,
value,
dataSource,
autoCompleteOptions,
template,
newStoreTemplate = CODE_TEMPLATES.newStoreTemplate,
children,
expressionType,
}: ExpressionPopoverProps) {
const [exp, setExp] = useState(value ?? defaultValue);
const [error, setError] = useState('');
const workspace = useWorkspace();
const InputCodeComponent = expressionType === 'cssObject' ? InputStyleCode : InputCode;
const selectNodePath = workspace.selectSource.selected[0]?.codeId;
const { expressionVariables } = useWorkspaceData();
const serviceModules = Object.keys(workspace.serviceModules).map((key) => ({
label: key === 'index' ? '默认模块' : key,
value: key,
}));
const sandbox = useSandboxQuery();
const evaluateContext: any = sandbox.window;
const handleExpInputChange = (val: string) => {
setExp(val?.trim());
};
useEffect(() => {
setExp(value);
}, [value]);
return (
<DragPanel
width={700}
height={615}
resizeable
title={`使用代码设置 ${selectNodePath} 组件的${title}`}
onOpenChange={(open) => {
if (!open) {
setExp(undefined);
setError('');
}
}}
body={
<Box display="flex" flexDirection="column">
<Box p="m">
<InputCodeComponent
shape="inset"
minHeight="56px"
maxHeight="160px"
value={exp}
placeholder={placeholder}
onChange={handleExpInputChange}
onBlur={() => {
if (exp) {
setError(expressionValueValidate(exp));
}
}}
autoCompleteContext={evaluateContext}
autoCompleteOptions={autoCompleteOptions}
/>
{error ? (
<Text color="red" fontSize="12px" as="div">
</Text>
) : null}
<Box fontSize="12px" color="text2">
<Text display="block"></Text>
{subTitle && <Text display="block">{subTitle}</Text>}
<Text display="block">
javascript 使 jsx
</Text>
</Box>
</Box>
<Panel
title="从变量列表中选中"
shape="solid"
borderLeft="0"
borderRight="0"
flex={1}
bodyProps={{
style: {
overflow: 'hidden',
},
}}
>
<VariableTree
height="100%"
showViewButton
dataSource={dataSource || expressionVariables}
appContext={evaluateContext['tango']}
getStoreNames={() => Object.keys(workspace.storeModules)}
serviceModules={serviceModules}
getServiceData={(serviceKey) => {
const data = workspace.getServiceFunction(serviceKey);
return {
name: data.name,
moduleName: data.moduleName,
method: 'get',
...data.config,
};
}}
onSelect={(node) => {
if (!node.key) {
return;
}
if (node.key.split('.').length < 2) {
return;
}
let str;
if (/^(stores|services)\./.test(node.key)) {
// 从匹配到的第二个点开始替换为 ?.,因为第一个点是 stores 或 services
str = `tango.${node.key.replace(/(?<=\..*?)\./g, '?.')}`;
if (node.type === 'function') {
str = getCallbackValue(`${str}();`, template);
}
} else {
str = `${node.key}`;
}
setExp(str);
}}
onAddStoreVariable={(storeName, data) => {
workspace.addStoreState(storeName, data.name, data.initialValue);
}}
onUpdateStoreVariable={(variableKey, code) => {
workspace.updateStoreVariable(variableKey, code);
}}
onAddStore={(storeName) => {
workspace.addStoreFile(storeName, newStoreTemplate);
}}
onRemoveStoreVariable={(variableKey) => {
workspace.removeStoreVariable(variableKey);
}}
onRemoveService={(serviceKey) => {
workspace.removeServiceFunction(serviceKey);
}}
onAddService={(data) => {
const { name, moduleName, ...payload } = shapeServiceValues(data);
workspace.addServiceFunction(name, payload, moduleName);
}}
onUpdateService={(data) => {
const { name, moduleName, ...payload } = shapeServiceValues(data);
workspace.updateServiceFunction(name, payload, moduleName);
}}
getPreviewValue={(node) => {
if (!node || !node.key) {
return;
}
if (node.type === 'function') {
return;
}
return getValue(evaluateContext['tango'], node.key);
}}
/>
</Panel>
</Box>
}
footer={(close) => (
<Box display="flex" width="100%" justifyContent="flex-end" gap="5px">
<Button
type="primary"
size="small"
onClick={() => {
if (!error) {
onOk(exp);
close();
}
}}
>
</Button>
<Button size="small" onClick={close}>
</Button>
</Box>
)}
>
{children || (
<Action
tooltip="弹出代码编辑和变量选择面板"
tooltipProps={{ placement: 'topLeft' }}
icon={<PopOutOutlined />}
size="small"
/>
)}
</DragPanel>
);
}
+55 -58
View File
@@ -1,11 +1,11 @@
import React, { useCallback, useState } from 'react';
import { css, Box } from 'coral-system';
import { AutoComplete } from 'antd';
import React, { useCallback, useMemo, useState } from 'react';
import { css, Box, Text } from 'coral-system';
import { AutoComplete, Input } from 'antd';
import { ActionSelect } from '@music163/tango-ui';
import { FormItemComponentProps } from '@music163/tango-setting-form';
import { useWorkspace, useWorkspaceData } from '@music163/tango-context';
import { wrapCode } from '@music163/tango-helpers';
import { ExpressionModal } from './expression-setter';
import { Dict, wrapCode } from '@music163/tango-helpers';
import { ExpressionPopover, getCallbackValue } from './code-setter';
import { value2code } from '@music163/tango-core';
enum EventAction {
@@ -25,25 +25,15 @@ const wrapperStyle = css`
}
`;
const options = [
{ label: '无动作', value: EventAction.NoAction },
{ label: '打印事件', value: EventAction.ConsoleLog },
{ label: '绑定 JS 表达式', value: EventAction.BindExpression },
{ label: '打开页面', value: EventAction.NavigateTo },
{ label: '打开弹窗', value: EventAction.OpenModal },
{ label: '关闭弹窗', value: EventAction.CloseModal },
];
export type EventSetterProps = FormItemComponentProps<string>;
/**
* 事件监听函数绑定器
*/
export function EventSetter(props: EventSetterProps) {
const { value, onChange, modalTitle } = props;
const { value, onChange, modalTitle, modalTip, template } = props;
const [type, setType] = useState<EventAction>(); // 事件类型
const [temp, setTemp] = useState(''); // 二级暂存值
const [expModalVisible, setExpModalVisible] = useState(false); // 弹窗是否显示
const { actionVariables, routeOptions } = useWorkspaceData();
const workspace = useWorkspace();
const modalOptions = workspace.activeViewModule.listModals() || [];
@@ -61,42 +51,59 @@ export function EventSetter(props: EventSetterProps) {
},
[onChange, code],
);
const options = useMemo(
() => [
{ label: '无动作', value: EventAction.NoAction },
{ label: '打印事件', value: EventAction.ConsoleLog },
{
label: (
<ExpressionPopover
title={modalTitle}
subTitle={modalTip}
value={value}
template={template}
onOk={(nextValue) => {
handleChange(nextValue);
}}
dataSource={actionVariables}
>
<Text> JS </Text>
</ExpressionPopover>
),
value: EventAction.BindExpression,
},
{ label: '打开页面', value: EventAction.NavigateTo },
{ label: '打开弹窗', value: EventAction.OpenModal },
{ label: '关闭弹窗', value: EventAction.CloseModal },
],
[modalTitle, value, actionVariables, template, handleChange],
);
const onAction = (key: string) => {
setType(key as EventAction); // 记录事件类型
setTemp(''); // 重置二级选项值
switch (key) {
case EventAction.BindExpression:
setExpModalVisible(true);
break;
case EventAction.ConsoleLog:
handleChange('(...args) => console.log(...args)');
break;
case EventAction.NoAction:
handleChange(undefined);
break;
default:
break;
if (key === EventAction.NoAction) {
handleChange(undefined);
return;
}
};
const actionText = getActionText(type, temp, code);
return (
<Box css={wrapperStyle}>
<ActionSelect options={options} onSelect={onAction} text={actionText} />
<ExpressionModal
title={modalTitle}
value={code}
visible={expModalVisible}
onCancel={() => setExpModalVisible(false)}
onOk={(nextValue) => {
setExpModalVisible(false);
handleChange(nextValue);
}}
dataSource={actionVariables}
/>
<ActionSelect options={options} onSelect={onAction} defaultText="请选择动作类型" />
{type === EventAction.ConsoleLog && (
<Input
placeholder="输入 Console.log 日志内容"
value={temp}
onChange={(e) => setTemp(e.target.value)}
onBlur={() => {
if (temp) {
handleChange(getExpressionValue(type, temp));
}
}}
/>
)}
{type === EventAction.NavigateTo && (
<AutoComplete
placeholder="选择或输入页面路由"
@@ -140,26 +147,16 @@ export function EventSetter(props: EventSetterProps) {
);
}
const handlerMap = {
[EventAction.OpenModal]: 'openModal',
[EventAction.CloseModal]: 'closeModal',
[EventAction.NavigateTo]: 'navigateTo',
const handlerMap: Dict = {
[EventAction.ConsoleLog]: 'console.log',
[EventAction.OpenModal]: 'tango.openModal',
[EventAction.CloseModal]: 'tango.closeModal',
[EventAction.NavigateTo]: 'tango.navigateTo',
};
function getActionText(type: EventAction, temp: string, fallbackCode: string) {
let text;
if (handlerMap[type]) {
text = getExpressionValue(type, temp);
} else if (fallbackCode) {
text = fallbackCode;
}
text = text || '请选择';
return text;
}
function getExpressionValue(type: EventAction, value = '') {
const handler = handlerMap[type];
if (handler) {
return `() => tango.${handler}("${value}")`;
return getCallbackValue(`${handler}("${value}");`);
}
}
@@ -1,320 +0,0 @@
import React, { useState, useEffect, useCallback } from 'react';
import { Box, Text, css } from 'coral-system';
import { Dropdown, Modal } from 'antd';
import { isValidExpressionCode } from '@music163/tango-core';
import { noop, useBoolean, getValue, IVariableTreeNode } from '@music163/tango-helpers';
import { CloseCircleFilled, ExpandAltOutlined, MenuOutlined } from '@ant-design/icons';
import { Panel, InputCode, Action } from '@music163/tango-ui';
import { FormItemComponentProps } from '@music163/tango-setting-form';
import { useWorkspace, useWorkspaceData } from '@music163/tango-context';
import { VariableTree } from '../components';
import { useSandboxQuery } from '../context';
import { CODE_TEMPLATES } from '../helpers';
import { shapeServiceValues } from '../sidebar/datasource-panel/interface-config';
export const expressionValueValidate = (value: string) => {
if (!isValidExpressionCode(value)) {
return '表达式存在语法错误!';
}
};
export const jsonValueValidate = (value: string) => {
try {
JSON.parse(value);
} catch (e) {
return '不是合法的 JSON 语法!';
}
};
const suffixStyle = css`
display: flex;
align-items: center;
.anticon-close-circle {
color: rgba(0, 0, 0, 0.25);
&:hover {
color: rgba(0, 0, 0, 0.45);
}
}
`;
export interface ExpressionSetterProps extends FormItemComponentProps<string> {
modalTitle?: string;
modalTip?: string;
autoCompleteOptions?: string[];
allowClear?: boolean;
showOptionsDropDown?: boolean;
}
export function ExpressionSetter(props: ExpressionSetterProps) {
const {
onChange,
modalTitle,
modalTip,
autoCompleteOptions,
placeholder = '在这里输入JS代码',
value: valueProp,
status,
allowClear = true,
newStoreTemplate,
showOptionsDropDown = true,
} = props;
// const codeValue = getCodeOfWrappedCode(valueProp);
const [inputValue, setInputValue] = useState(valueProp);
const [visible, { on, off }] = useBoolean();
// when receive new value, sync state
useEffect(() => {
setInputValue(valueProp);
}, [valueProp]);
const change = useCallback(
(code: string) => {
if (code === valueProp) {
return;
}
onChange(code);
},
[valueProp, onChange],
);
const sandbox = useSandboxQuery();
const evaluateContext = sandbox.window;
return (
<Box className="ExpressionSetter">
{/* 同时支持下拉框展示 */}
<InputCode
placeholder={placeholder}
suffix={
<Box css={suffixStyle}>
{allowClear && (
<CloseCircleFilled
title="清空"
onClick={() => {
change('');
}}
/>
)}
{showOptionsDropDown && autoCompleteOptions?.length && (
<Dropdown
menu={{
items: autoCompleteOptions.map((option) => ({
key: option,
label: (
<Text
onClick={() => {
change(option);
}}
>
{option}
</Text>
),
})),
}}
>
<Action tooltip="使用预设代码片段" icon={<MenuOutlined />} size="small" />
</Dropdown>
)}
<Action
tooltip="打开表达式变量选择面板"
icon={<ExpandAltOutlined />}
onClick={on}
size="small"
/>
</Box>
}
value={inputValue}
onChange={setInputValue}
onBlur={() => {
change(inputValue);
}}
autoCompleteContext={evaluateContext}
autoCompleteOptions={autoCompleteOptions}
status={status}
maxHeight="200px"
/>
<ExpressionModal
title={modalTitle}
subTitle={modalTip}
placeholder={placeholder}
autoCompleteOptions={autoCompleteOptions}
newStoreTemplate={newStoreTemplate}
visible={visible}
value={inputValue}
onCancel={() => off()}
onOk={(value) => {
change(value);
off();
}}
/>
</Box>
);
}
export interface ExpressionModalProps {
title?: string;
subTitle?: string;
placeholder?: string;
visible?: boolean;
defaultValue?: string;
value?: string;
onCancel?: () => void;
onOk?: (value: string) => void;
dataSource?: IVariableTreeNode[];
autoCompleteOptions?: string[];
/**
* 新建 store 的模板代码
*/
newStoreTemplate?: string;
}
export function ExpressionModal({
title,
subTitle,
placeholder,
visible,
onCancel = noop,
onOk = noop,
defaultValue,
value,
dataSource,
autoCompleteOptions,
newStoreTemplate = CODE_TEMPLATES.newStoreTemplate,
}: ExpressionModalProps) {
const [exp, setExp] = useState(value ?? defaultValue);
const [error, setError] = useState('');
const workspace = useWorkspace();
const { expressionVariables } = useWorkspaceData();
const serviceModules = Object.keys(workspace.serviceModules).map((key) => ({
label: key === 'index' ? '默认模块' : key,
value: key,
}));
const sandbox = useSandboxQuery();
const evaluateContext = sandbox.window;
const handleExpInputChange = (val: string) => {
setExp(val?.trim());
};
useEffect(() => {
setExp(value);
}, [value]);
return (
<Modal
closable={false}
destroyOnClose
width="60%"
open={visible}
onCancel={onCancel}
onOk={() => {
onOk(exp);
}}
bodyStyle={{
padding: 0,
}}
>
<Panel title={`${title} 设置为引用变量或自定义表达式`} subTitle={subTitle} shape="solid">
<InputCode
shape="inset"
minHeight="56px"
maxHeight="200px"
value={exp}
placeholder={placeholder}
onChange={handleExpInputChange}
onBlur={() => {
setError(expressionValueValidate(exp));
}}
autoCompleteContext={evaluateContext}
autoCompleteOptions={autoCompleteOptions}
/>
{error ? (
<Text color="red" fontSize="12px">
</Text>
) : (
<Text fontSize="12px" color="text3">
javascript 使 jsx
</Text>
)}
</Panel>
<Panel
title="从变量列表中选中"
shape="solid"
borderTop="0"
overflow="hidden"
bodyProps={{ overflow: 'hidden' }}
>
<VariableTree
height={380}
showViewButton
dataSource={dataSource || expressionVariables}
appContext={sandbox?.window['tango']}
getStoreNames={() => Object.keys(workspace.storeModules)}
serviceModules={serviceModules}
getServiceData={(serviceKey) => {
const data = workspace.getServiceFunction(serviceKey);
return {
name: data.name,
moduleName: data.moduleName,
method: 'get',
...data.config,
};
}}
onSelect={(node) => {
if (!node.key) {
return;
}
if (node.key.split('.').length < 2) {
return;
}
let str;
if (/^(stores|services)\./.test(node.key)) {
str = `tango.${node.key.replaceAll('.', '?.')}`;
} else {
str = `${node.key}`;
}
setExp(str);
}}
onAddStoreVariable={(storeName, data) => {
workspace.addStoreState(storeName, data.name, data.initialValue);
}}
onUpdateStoreVariable={(variableKey, code) => {
workspace.updateStoreVariable(variableKey, code);
}}
onAddStore={(storeName) => {
workspace.addStoreFile(storeName, newStoreTemplate);
}}
onRemoveStoreVariable={(variableKey) => {
workspace.removeStoreVariable(variableKey);
}}
onRemoveService={(serviceKey) => {
workspace.removeServiceFunction(serviceKey);
}}
onAddService={(data) => {
const { name, moduleName, ...payload } = shapeServiceValues(data);
workspace.addServiceFunction(name, payload, moduleName);
}}
onUpdateService={(data) => {
const { name, moduleName, ...payload } = shapeServiceValues(data);
workspace.updateServiceFunction(name, payload, moduleName);
}}
getPreviewValue={(node) => {
if (!node || !node.key) {
return;
}
if (node.type === 'function') {
return;
}
return getValue(evaluateContext['tango'], node.key);
}}
/>
</Panel>
</Modal>
);
}
+32 -14
View File
@@ -5,14 +5,14 @@ import { CssSetter } from './css-setter';
import { DateRangeSetter, DateSetter, TimeRangeSetter } from './date-setter';
import { EnumSetter } from './enum-setter';
import { EventSetter } from './event-setter';
import { ExpressionSetter } from './expression-setter';
import { CodeSetter } from './code-setter';
import { JSONSetter } from './json-setter';
import { JsxSetter } from './jsx-setter';
import { ListSetter } from './list-setter';
import { ModelSetter } from './model-setter';
import { OptionSetter } from './option-setter';
import { PickerSetter } from './picker-setter';
import { RenderSetter, TableCellSetter, TableExpandableSetter } from './render-setter';
import { RenderSetter } from './render-setter';
import { RouterSetter } from './router-setter';
import {
SpacingSetter,
@@ -26,13 +26,37 @@ import {
FlexDirectionSetter,
} from './style-setter';
import { ChoiceSetter } from './choice-setter';
import { ClassNameSetter } from './classname-setter';
import { isValidExpressionCode } from '@music163/tango-core';
const codeValidate: IFormItemCreateOptions['validate'] = (value, field) => {
if (!value) return;
const rawCode = field.detail.rawCode;
if (!rawCode) return;
return isValidExpressionCode(rawCode) ? '' : '请输入合法的 Javascript 代码片段';
};
const jsonValidate: IFormItemCreateOptions['validate'] = (value, field) => {
if (!value) return;
try {
JSON.parse(field.detail.rawCode);
return;
} catch (e) {
return '请输入合法的 JSON 字符串';
}
};
export const BUILT_IN_SETTERS: IFormItemCreateOptions[] = [
{
name: 'codeSetter',
alias: ['expSetter', 'expressionSetter'],
component: ExpressionSetter,
component: CodeSetter,
type: 'code',
validate: codeValidate,
},
{
name: 'classNameSetter',
component: ClassNameSetter,
},
{
name: 'radioGroupSetter',
@@ -81,11 +105,13 @@ export const BUILT_IN_SETTERS: IFormItemCreateOptions[] = [
name: 'jsonSetter',
component: JSONSetter,
type: 'code',
validate: jsonValidate,
},
{
name: 'jsxSetter',
component: JsxSetter,
type: 'code',
validate: codeValidate,
},
{
name: 'listSetter',
@@ -105,19 +131,11 @@ export const BUILT_IN_SETTERS: IFormItemCreateOptions[] = [
component: PickerSetter,
},
{
name: 'renderPropsSetter',
name: 'renderSetter',
alias: ['renderPropsSetter'],
component: RenderSetter,
type: 'code',
},
{
name: 'tableCellSetter',
component: TableCellSetter,
type: 'code',
},
{
name: 'tableExpandableSetter',
component: TableExpandableSetter,
type: 'code',
validate: codeValidate,
},
{
name: 'routerSetter',
@@ -3,10 +3,11 @@ import { css, Box } from 'coral-system';
import { Form, Input, Button, Popover } from 'antd';
import { DeleteOutlined, EditOutlined, HolderOutlined } from '@ant-design/icons';
import { FormItemComponentProps } from '@music163/tango-setting-form';
import { Dict } from '@music163/tango-helpers';
import { DragBox } from '../components';
function copyWithoutUndefined(source: Record<string, any>) {
const ret = {};
function copyWithoutUndefined(source: Dict) {
const ret: Dict = {};
for (const key in source) {
if (source[key] !== undefined) {
ret[key] = source[key];
@@ -60,7 +60,7 @@ export function ModelSetter({
}: FormItemComponentProps) {
const [inputValue, setInputValue] = useState(value);
const { modelVariables } = useWorkspaceData();
const evaluateContext = useSandboxQuery().window || {};
const evaluateContext: any = useSandboxQuery().window || {};
const workspace = useWorkspace();
const definedVariables = useMemo(() => {
const list: string[] = [];
+11 -80
View File
@@ -2,21 +2,16 @@ import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { ActionSelect, InputCode } from '@music163/tango-ui';
import { FormItemComponentProps } from '@music163/tango-setting-form';
import { Box } from 'coral-system';
interface IRenderOption {
label: string;
value: string;
render?: string;
relatedImports?: string[];
}
import { Dict, IOptionItem } from '@music163/tango-helpers';
import { getCallbackValue } from './code-setter';
export interface RenderSetterProps {
text?: string;
options?: IRenderOption[];
fallbackOption?: IRenderOption;
options?: IOptionItem[];
fallbackOption?: IOptionItem;
}
const defaultOptions: IRenderOption[] = [
const defaultOptions: IOptionItem[] = [
{ label: '取消自定义', value: '' },
{ label: '自定义渲染', value: 'Box', render: '() => <Box></Box>' },
];
@@ -29,6 +24,7 @@ export function RenderSetter({
onChange,
text = '自定义渲染为',
options = defaultOptions,
template = `() => {{content}}`,
fallbackOption,
}: FormItemComponentProps & RenderSetterProps) {
const [inputValue, setInputValue] = useState(value || '');
@@ -37,7 +33,7 @@ export function RenderSetter({
}, [value]);
const optionsMap = useMemo(() => {
return options.reduce((prev, cur) => {
return options.reduce<Dict>((prev, cur) => {
prev[cur.value] = cur;
return prev;
}, {});
@@ -46,13 +42,14 @@ export function RenderSetter({
const onSelect = useCallback(
(key: string) => {
const option = optionsMap[key] || fallbackOption;
if (option?.render) {
onChange(option.render, { relatedImports: option.relatedImports });
const next = option?.render || getCallbackValue(option.renderBody, template);
if (next) {
onChange(next, { relatedImports: option.relatedImports });
} else {
onChange(undefined);
}
},
[optionsMap, fallbackOption, onChange],
[optionsMap, fallbackOption, onChange, template],
);
return (
<Box>
@@ -67,69 +64,3 @@ export function RenderSetter({
</Box>
);
}
const getRender = (content: string, type?: 'tableCell' | 'tableExpandable') => {
let code;
switch (type) {
case 'tableCell':
code = `(value, record, index) => ${content}`;
break;
case 'tableExpandable':
code = `{
expandedRowRender: (record) => ${content},
rowExpandable: (record) => true
}`;
break;
default:
code = `() => ${content}`;
break;
}
return code;
};
const tableCellOptions: RenderSetterProps['options'] = [
{ label: '取消自定义', value: '' },
{
label: '自定义区域',
value: 'Box',
render: getRender('<Box></Box>', 'tableCell'),
relatedImports: ['Box'],
},
{
label: '标签',
value: 'Tag',
render: getRender('<Tag>tag</Tag>', 'tableCell'),
relatedImports: ['Tag'],
},
{
label: '按钮',
value: 'Button',
render: getRender('<Button>button</Button>', 'tableCell'),
relatedImports: ['Button'],
},
{
label: '图片',
value: 'Image',
render: getRender('<Image width={150} src="https://picsum.photos/100" />', 'tableCell'),
relatedImports: ['Image'],
},
];
const tableExpandableOptions: RenderSetterProps['options'] = [
{
label: '设置可展开行',
value: 'Box',
render: getRender('<Box></Box>', 'tableExpandable'),
relatedImports: ['Box'],
},
{ label: '取消可展开行', value: '' },
];
export function TableCellSetter(props: FormItemComponentProps) {
return <RenderSetter options={tableCellOptions} {...props} />;
}
// FIXME: 应该直接用 props 嵌套的模式
export function TableExpandableSetter(props: FormItemComponentProps) {
return <RenderSetter options={tableExpandableOptions} text="配置表格可展开行" {...props} />;
}
@@ -1,11 +1,17 @@
import React, { useEffect, useState } from 'react';
import { Box } from 'coral-system';
import { Input, Radio } from 'antd';
import { isValidUrl } from '@music163/tango-helpers';
import { Dict, isValidUrl } from '@music163/tango-helpers';
import { FormItemComponentProps } from '@music163/tango-setting-form';
import { useWorkspaceData } from '@music163/tango-context';
import { PickerSetter } from './picker-setter';
const routerModeMap: Dict = {
link: '链接',
router: '路由',
both: '',
};
export function RouterSetter(props: FormItemComponentProps) {
const [type, setType] = useState<'input' | 'select'>(() => {
return isValidUrl(props.value) ? 'input' : 'select';
@@ -37,7 +43,7 @@ export function RouterSetter(props: FormItemComponentProps) {
)}
{type === 'input' && (
<Input
placeholder={`请输入任意${{ link: '链接', router: '路由', both: '' }[displayType]}地址`}
placeholder={`请输入任意${routerModeMap[displayType]}地址`}
{...props}
value={input}
onChange={(e) => setInput(e.target.value)}
+7 -3
View File
@@ -2,11 +2,15 @@ import React from 'react';
import { Box } from 'coral-system';
import { SettingForm, FormModel, SettingFormProps } from '@music163/tango-setting-form';
import { Panel } from '@music163/tango-ui';
import { clone, parseDndId } from '@music163/tango-helpers';
import { clone, Dict, parseDndId } from '@music163/tango-helpers';
import { observer, useDesigner, useWorkspace } from '@music163/tango-context';
import { registerBuiltinSetters } from './setters';
registerBuiltinSetters();
let registered = false;
if (!registered) {
registerBuiltinSetters();
registered = true;
}
export interface SettingPanelProps extends SettingFormProps {
title?: React.ReactNode;
@@ -30,7 +34,7 @@ export const SettingPanel = observer((props: SettingPanelProps) => {
}
const getSettingValue = (attributes: Record<string, string>) => {
const ret = {};
const ret: Dict = {};
const keys = Object.keys(attributes);
for (const key of keys) {
if (/^data-/.test(key)) {
@@ -1,21 +1,30 @@
import React, { useMemo, useState } from 'react';
import { Box, Grid, Text } from 'coral-system';
import styled from 'styled-components';
import styled, { css } from 'styled-components';
import {
Dict,
IComponentPrototype,
MenuDataType,
MenuValueType,
createContext,
logger,
PartialRecord,
upperCamelCase,
} from '@music163/tango-helpers';
import { CollapsePanel, IconFont, Search, Tabs } from '@music163/tango-ui';
import { observer, useWorkspace } from '@music163/tango-context';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { Button, Empty, Spin, Popover } from 'antd';
import { Button, Empty, Spin, Popover, TabsProps } from 'antd';
import { getDragGhostElement } from '../helpers';
type MenuKeyType = 'common' | 'atom' | 'snippet' | 'bizComp' | 'localComp';
type MenuValueType = Array<{ title: string; items: string[] }>;
export type MenuDataType = PartialRecord<MenuKeyType, MenuValueType>;
type IComponentsPanelContext = {
isScope: boolean;
onItemSelect: (name: string) => void;
layout: 'grid' | 'line';
};
const [ComponentsPanelProvider, usePanelContext] = createContext<IComponentsPanelContext>({
name: 'ComponentsPanelContext',
});
export interface ComponentsPanelProps {
/**
@@ -36,9 +45,29 @@ export interface ComponentsPanelProps {
* @returns
*/
getBizCompName?: (name: string) => string;
/**
* 是否局部模式 (快捷添加组件面板中使用)
*/
isScope?: boolean;
/**
* 组件选中回调
*/
onItemSelect?: (name: string) => void;
/**
* 自定义样式
*/
style?: React.CSSProperties;
/**
* tabProps
*/
tabProps?: TabsProps;
/**
* 布局模式,默认网格布局
*/
layout?: 'grid' | 'line';
}
const localeMap = {
const localeMap: Dict = {
common: '基础组件',
atom: '原子组件',
snippet: '组合',
@@ -72,10 +101,15 @@ export function useFlatMenuData<T>(menuData: T) {
export const ComponentsPanel = observer(
({
isScope = false,
menuData = emptyMenuData,
showBizComps = true,
getBizCompName = upperCamelCase,
loading = false,
style,
tabProps,
onItemSelect,
layout = 'grid',
}: ComponentsPanelProps) => {
const [keyword, setKeyword] = useState<string>('');
const allList = useFlatMenuData<MenuDataType>(menuData);
@@ -91,7 +125,7 @@ export const ComponentsPanel = observer(
const tabs = Object.keys(menuData).map((key) => ({
key,
label: localeMap[key],
children: <MaterialList data={menuData[key]} />,
children: <MaterialList data={(menuData as any)[key]} />,
}));
if (showBizComps) {
@@ -109,22 +143,44 @@ export const ComponentsPanel = observer(
children: <MaterialList data={localCompData} />,
});
}
const contentNode =
tabs.length === 1 ? (
tabs[0].children
) : (
<Tabs centered isTabBarSticky tabBarStickyOffset={48} items={tabs} />
<Tabs
size={isScope ? 'small' : 'middle'}
centered
isTabBarSticky
tabBarStickyOffset={48}
items={tabs}
{...tabProps}
/>
);
return (
<Box className="ComponentsView" overflowY="auto">
<Box px="l" py="m" position="sticky" top="0" zIndex={1} bg="white">
<Search placeholder="搜索物料" onChange={setKeyword} />
<ComponentsPanelProvider
value={{
isScope,
onItemSelect,
layout,
}}
>
<Box className="ComponentsView" overflowY="auto" style={style}>
<Box px="l" py="m" position="sticky" top="0" zIndex={3} bg="white">
<Search
style={{
borderRadius: '4px',
}}
placeholder="搜索物料"
onChange={setKeyword}
/>
</Box>
<Spin spinning={loading} tip="正在加载物料列表...">
{!keyword ? contentNode : <MaterialList data={allList} filterKeyword={keyword} />}
</Spin>
</Box>
<Spin spinning={loading} tip="正在加载物料列表...">
{!keyword ? contentNode : <MaterialList data={allList} filterKeyword={keyword} />}
</Spin>
</Box>
</ComponentsPanelProvider>
);
},
);
@@ -146,6 +202,9 @@ interface MaterialListProps {
function MaterialList({ data, filterKeyword, type = 'common' }: MaterialListProps) {
const workspace = useWorkspace();
const { layout } = usePanelContext();
const isGrid = layout === 'grid';
return (
<Box className="ComponentsViewList">
{data.map((cate) => {
@@ -166,15 +225,21 @@ function MaterialList({ data, filterKeyword, type = 'common' }: MaterialListProp
title={cate.title}
borderBottom="solid"
borderColor="line.normal"
showBottomBorder={false}
bodyProps={{
padding: isGrid ? '4px 12px 12px' : '0',
}}
>
{!items.length && (
<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="没有匹配到任何组件" />
)}
<Grid
columns={type === 'localComp' ? 1 : 2}
templateColumns={isGrid ? 'repeat(auto-fit,minmax(55px,1fr))' : '1fr'}
spacing="1px"
bg="background.normal"
padding="0"
gap={isGrid ? '12px 8px' : '0'}
backgroundColor="white"
>
{items.map((item) => {
const prototype = workspace.componentPrototypes.get(item);
@@ -202,9 +267,8 @@ const StyledCommonGridItem = styled.div`
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 8px;
cursor: move;
justify-content: start;
cursor: ${(props) => (props.draggable ? 'grab' : 'pointer')};
text-align: center;
color: var(--tango-colors-text-body);
background-color: #fff;
@@ -213,7 +277,23 @@ const StyledCommonGridItem = styled.div`
white-space: nowrap;
.material-icon {
font-size: 40px;
display: flex;
align-items: center;
justify-content: center;
font-size: 36px;
background: #f9f9f9;
border-radius: 4px;
border: 1px solid #ebebeb;
width: 100%;
height: 52px;
position: relative;
transition: 0.15s ease-in-out;
transition-property: transform;
will-change: transform;
img {
width: unset;
height: 85%;
}
}
.info {
@@ -225,19 +305,13 @@ const StyledCommonGridItem = styled.div`
.anticon-question-circle {
display: none;
font-size: 13px;
position: absolute;
top: 8px;
right: 8px;
}
img {
height: 40px;
width: 40px;
top: 4px;
right: 4px;
}
&:hover {
box-shadow: 0 0 10px rgb(0 0 0 / 10%);
> span {
color: var(--tango-colors-brand);
}
@@ -245,11 +319,26 @@ const StyledCommonGridItem = styled.div`
.anticon-question-circle {
display: inline-block;
}
.material-icon {
border-color: #c7c7c7;
}
}
`;
const GridLineItemStyle = css`
cursor: pointer;
user-select: none;
&:hover {
background-color: var(--tango-colors-fill2);
}
`;
function MaterialGrid({ data }: MaterialProps) {
const workspace = useWorkspace();
const { isScope, onItemSelect, layout } = usePanelContext();
const isLine = layout === 'line';
const handleDragStart = (e: React.DragEvent) => {
e.dataTransfer.effectAllowed = 'move';
@@ -266,28 +355,92 @@ function MaterialGrid({ data }: MaterialProps) {
workspace.dragSource.clear();
};
const handleSelect = () => {
onItemSelect?.(data.name);
};
const icon = data.icon || 'icon-placeholder';
const iconNode = icon.startsWith('icon-') ? (
<IconFont className="material-icon" type={data.icon || 'icon-placeholder'} />
) : (
<Box className="material-icon">
<img src={icon} alt={data.name} height="32" />
</Box>
);
if (isLine) {
return (
<Box
key={data.name}
display="flex"
columnGap="m"
px="l"
py="m"
fontSize="12px"
css={GridLineItemStyle}
onClick={handleSelect}
>
<Box
p="m"
fontSize="32px"
width="46px"
height="46px"
background="fill1"
border="1px solid"
borderRadius="4px"
borderColor="line2"
display="flex"
alignItems="center"
justifyContent="center"
>
{iconNode}
</Box>
<Box flex={1}>
<Box fontWeight="500" display="flex" justifyContent="space-between">
<Text flex={1}>{data.title}</Text>
{data.docs ? (
<Popover
zIndex={9999}
placement="right"
title={data.title}
content={<CommonMaterialInfoBox docs={data.docs} />}
>
<QuestionCircleOutlined />
</Popover>
) : null}
</Box>
<Box color="text2" fontStyle="italic">
{data.help ?? data.title}
</Box>
</Box>
</Box>
);
}
return (
<StyledCommonGridItem
draggable
key={data.name}
draggable={!isScope}
data-name={data.name}
onDragStart={handleDragStart}
onDragEnd={handleDragEnd}
onClick={handleSelect}
>
{icon.startsWith('icon-') ? (
<IconFont className="material-icon" type={data.icon || 'icon-placeholder'} />
) : (
<img src={icon} alt={data.name} />
)}
<Text fontSize="12px" lineHeight="1.5">
{data.title}
{iconNode}
<Text fontSize="12px" marginTop="4px">
{data.title ?? data.name}
</Text>
<Text fontSize="12px" color="gray.50">
<Text fontSize="10px" color="gray.50">
{data.name}
</Text>
{data.docs || data.help ? (
<Popover placement="right" title={data.title} content={<CommonMaterialInfoBox {...data} />}>
<Popover
zIndex={9999}
placement="right"
title={data.title}
content={<CommonMaterialInfoBox {...data} />}
>
<QuestionCircleOutlined />
</Popover>
) : null}
@@ -295,7 +448,7 @@ function MaterialGrid({ data }: MaterialProps) {
);
}
function CommonMaterialInfoBox({ help, docs }: IComponentPrototype) {
function CommonMaterialInfoBox({ help, docs }: Pick<IComponentPrototype, 'help' | 'docs'>) {
return (
<Box maxWidth={300}>
{!!help && <Box mb="m">{help}</Box>}
@@ -24,7 +24,7 @@ const DataSourceView = observer(() => {
<Box className="ServiceFunctionList" p="m">
<VariableTree
dataSource={serviceVariables}
appContext={sandbox?.window['tango']}
appContext={(sandbox?.window as any)['tango']}
serviceModules={serviceModules}
onRemoveService={(variableKey) => {
workspace.removeServiceFunction(variableKey);
@@ -4,6 +4,7 @@ import { ConfigGroup, ConfigItem } from '@music163/tango-ui';
import { Box, css } from 'coral-system';
import { Input, Switch, Form, Button, message, FormProps } from 'antd';
import { CloseCircleOutlined, CloseOutlined } from '@ant-design/icons';
import { Dict } from '@music163/tango-helpers';
export default observer(() => {
const workspace = useWorkspace();
@@ -63,7 +64,7 @@ function ProxyManage({
initialValues: initialValuesProp = {},
onSave,
}: {
initialValues?: object;
initialValues?: Dict;
onSave?: (values: any) => void;
}) {
const initialValues = useMemo(() => {
@@ -84,7 +85,7 @@ function ProxyManage({
{...proxyManageFormStyle}
initialValues={initialValues}
onFinish={(values) => {
const proxy = values.proxy.reduce((prev: object, { path, ...rest }: any) => {
const proxy = values.proxy.reduce((prev: any, { path, ...rest }: any) => {
prev[path] = rest;
return prev;
}, {});
@@ -68,17 +68,6 @@ export const DependencyPanel = observer(
[dependencies, baseDependencies, bizDependencies, packages, packageNames],
);
// 业务组件依赖
const bizDeps = useMemo(
() =>
bizDependencies?.map((name: string) => ({
name,
version: dependencies[name] ?? packages?.[name]?.version,
package: packages?.[name],
})) || [],
[bizDependencies, dependencies, packages],
);
// 基础包
const baseDeps = useMemo(
() =>
@@ -8,6 +8,7 @@ import { DropMethod, ITangoViewNodeData } from '@music163/tango-core';
import { noop, parseDndId } from '@music163/tango-helpers';
import { useSandboxQuery } from '../../context';
import { buildQueryBySlotId } from '../../helpers';
import { ContextMenu } from '../../components';
export interface ComponentsTreeProps {
/**
@@ -143,6 +144,18 @@ export const ComponentsTree: React.FC<ComponentsTreeProps> = observer(
const file = workspace.activeViewModule;
const nodesTree = (file?.nodesTree ?? []) as ITangoViewNodeData[];
const [expandedKeys, setExpandedKeys] = useState(getNodeKeys(nodesTree));
const [contextMenuOpen, setContextMenuOpen] = useState(false);
const handleSelect = (keys: React.Key[]) => {
const slotKey = keys?.[0] as string;
const data = sandboxQuery.getDraggableParentsData(buildQueryBySlotId(slotKey), true);
if (data && data.id) {
workspace.selectSource.select(data);
}
// export selected
onSelect(slotKey);
setSelectedKeys(keys);
};
useEffect(() => {
setSelectedKeys(workspace.selectSource.selected.map((item) => item.id));
@@ -164,64 +177,83 @@ export const ComponentsTree: React.FC<ComponentsTreeProps> = observer(
return (
<Box css={outlineStyle}>
<Tree
selectedKeys={selectedKeys as string[]}
fieldNames={filedNames}
treeData={nodesTree as any[]}
onSelect={(keys) => {
const slotKey = keys?.[0] as string;
const data = sandboxQuery.getDraggableParentsData(buildQueryBySlotId(slotKey), true);
if (data && data.id) {
workspace.selectSource.select(data);
<Dropdown
placement="bottomLeft"
trigger={['contextMenu']}
open={contextMenuOpen}
onOpenChange={(val) => {
if (!val) {
setContextMenuOpen(val);
}
// export selected
onSelect(slotKey);
setSelectedKeys(keys);
}}
blockNode
expandedKeys={expandedKeys}
onExpand={(keys) => setExpandedKeys(keys as string[])}
draggable
onDragStart={(data) => {
const prototype = workspace.componentPrototypes.get(data.node.component);
if (!prototype) {
return;
}
const { canDrag } = prototype.rules || {};
if (canDrag && !canDrag()) {
return;
}
workspace.dragSource.set({
id: data.node.id,
name: data.node.component,
});
}}
onDrop={(data) => {
const dropKey = data.node.key as string;
let method;
if (data.dropToGap) {
// 插入节点的后面
method = DropMethod.InsertAfter;
} else {
// 作为第一个子节点
method = DropMethod.InsertFirstChild;
}
workspace.dragSource.dropTarget.set(
{
id: dropKey,
},
method,
);
workspace.dropNode();
}}
titleRender={(node) => (
<OutlineTreeNode
actionItems={actionItems}
showToggleVisibleIcon={showToggleVisibleIcon}
node={node}
/>
)}
/>
overlay={<ContextMenu onClick={() => setContextMenuOpen(false)} showParents={false} />}
>
<Tree
selectedKeys={selectedKeys as string[]}
fieldNames={filedNames}
treeData={nodesTree as any[]}
onSelect={handleSelect}
blockNode
expandedKeys={expandedKeys}
onExpand={(keys) => setExpandedKeys(keys as string[])}
draggable
onDragStart={(data) => {
const prototype = workspace.componentPrototypes.get(data.node.component);
if (!prototype) {
return;
}
const { canDrag } = prototype.rules || {};
if (canDrag && !canDrag()) {
return;
}
workspace.dragSource.set({
id: data.node.id,
name: data.node.component,
});
}}
onDrop={(data) => {
const dropKey = data.node.key as string;
let method;
if (data.dropToGap) {
// 插入节点的后面
method = DropMethod.InsertAfter;
} else {
// 作为第一个子节点
method = DropMethod.InsertFirstChild;
}
workspace.dragSource.dropTarget.set(
{
id: dropKey,
},
method,
);
workspace.dropNode();
}}
onRightClick={({ event, node }) => {
// 按下其他按键时,视为用户有特殊操作,此时不展示右键菜单
if (event.ctrlKey || event.altKey || event.metaKey || event.shiftKey) {
setContextMenuOpen(false);
return;
}
// 顶层的 Page 组件不展示右键菜单
if (node.component === 'Page') {
setContextMenuOpen(false);
return;
}
event.preventDefault();
// 由于部分操作是基于 selectSource 实现的,因此右键时默认选中当前项
handleSelect([node.key]);
setContextMenuOpen(true);
}}
titleRender={(node) => (
<OutlineTreeNode
actionItems={actionItems}
showToggleVisibleIcon={showToggleVisibleIcon}
node={node}
/>
)}
/>
</Dropdown>
</Box>
);
},
@@ -1,12 +1,12 @@
import React, { useEffect, useReducer } from 'react';
import { observer } from '@music163/tango-context';
import { isFunction, isObject, pick } from '@music163/tango-helpers';
import { Dict, isFunction, isObject, pick } from '@music163/tango-helpers';
import { CollapsePanel, IconButton, JsonView } from '@music163/tango-ui';
import { ReloadOutlined } from '@ant-design/icons';
import { useSandboxQuery } from '../../context';
function processTango(obj: any = {}, index = 0) {
const ret = {};
function processTango(obj: Dict = {}, index = 0) {
const ret: Dict = {};
Object.keys(obj).forEach((key) => {
const val = obj[key];
if (index > 2) {
@@ -25,11 +25,12 @@ function processTango(obj: any = {}, index = 0) {
export const StateTree = observer(() => {
const sandboxQuery = useSandboxQuery();
const [, forceUpdate] = useReducer((x) => x + 1, 0);
const tangoContext = pick(sandboxQuery.window['tango'] || {}, [
const tangoContext = pick((sandboxQuery.window as any)['tango'] || {}, [
'stores',
'pageStore',
'services',
'config',
'routeData',
]);
const callback = () => {
forceUpdate();
@@ -19,7 +19,7 @@ const resizeHandleStyle = (axis: ResizableBoxProps['axis'], barStyle: HTMLCoralP
cursor: ${axis === 'x' ? 'col-resize' : 'row-resize'};
${barStyle &&
Object.keys(barStyle)
.map((key) => `${key}: ${barStyle[key]};`)
.map((key) => `${key}: ${(barStyle as any)[key]};`)
.join('')}
&:hover,
&:active {
+29 -19
View File
@@ -3,7 +3,7 @@ import cx from 'classnames';
import { Box, Text, css, HTMLCoralProps } from 'coral-system';
import { Badge } from 'antd';
import { ReactComponentProps } from '@music163/tango-helpers';
import { observer, useDesigner } from '@music163/tango-context';
import { observer, useDesigner, useWorkspace } from '@music163/tango-context';
import { ResizableBox } from './resizable-box';
import { getWidget } from '../widgets';
@@ -19,15 +19,22 @@ const sidebarStyle = css`
list-style: none;
user-select: none;
transition: all 0.3s ease;
&.disabled {
pointer-events: none;
}
}
.SidebarPanelBarListItem {
color: var(--tango-colors-text2);
&.active {
background-color: var(--tango-colors-custom-sidebarItemActiveBg);
color: var(--tango-colors-brand);
background-color: var(--tango-colors-custom-sidebarItemActiveBg, --tango-colors-fill2);
}
&:hover {
background-color: var(--tango-colors-custom-sidebarItemHoverBg);
background-color: var(--tango-colors-custom-sidebarItemHoverBg, --tango-colors-fill2);
}
}
`;
@@ -74,8 +81,9 @@ export interface SidebarPanelItemProps
widgetProps?: object;
}
function BaseSidebarPanel({ panelWidth: defaultPanelWidth = 280, footer, children }: SidebarProps) {
function BaseSidebarPanel({ panelWidth: defaultPanelWidth = 266, footer, children }: SidebarProps) {
const designer = useDesigner();
const workspace = useWorkspace();
const items = useMemo(() => {
const ret: Record<string, SidebarPanelItemProps> = {};
@@ -92,10 +100,23 @@ function BaseSidebarPanel({ panelWidth: defaultPanelWidth = 280, footer, childre
return ret;
}, [children]);
if (designer.activeView !== 'design') {
return null;
}
return (
<Box display="flex" flexShrink={0} css={sidebarStyle} className="SidebarPanel">
<Box className="SidebarPanelBar" display="flex" flexDirection="column" position="relative">
<Box as="ul" flex="0" p="0" m="0" textAlign="center" className="SidebarPanelBarList">
<Box
as="ul"
flex="0"
p="0"
m="0"
textAlign="center"
className={cx('SidebarPanelBarList', {
disabled: workspace.fileErrors.length > 0,
})}
>
{Object.keys(items).map((key) => {
const item = items[key];
const isActive = key === designer.activeSidebarPanel;
@@ -112,7 +133,6 @@ function BaseSidebarPanel({ panelWidth: defaultPanelWidth = 280, footer, childre
icon={item.icon}
label={item.label}
showBadge={item.showBadge}
isActive={isActive}
/>
</li>
);
@@ -183,10 +203,6 @@ BaseSidebarPanel.Item = function ({
export const Sidebar = observer(BaseSidebarPanel);
interface SidebarPanelBarItemProps {
/**
* 是否选中
*/
isActive?: boolean;
/**
* 侧边栏图标
*/
@@ -212,15 +228,9 @@ interface SidebarPanelBarItemProps {
};
}
function SidebarPanelBarItem({
isActive,
icon: iconProp,
label,
showBadge,
}: SidebarPanelBarItemProps) {
const color = isActive ? 'brand' : 'text.body';
function SidebarPanelBarItem({ icon: iconProp, label, showBadge }: SidebarPanelBarItemProps) {
let icon = (
<Text fontSize="24px" lineHeight={1} color={color}>
<Text fontSize="24px" lineHeight={1}>
{iconProp}
</Text>
);
@@ -241,7 +251,7 @@ function SidebarPanelBarItem({
py="12px"
>
{icon}
<Text fontSize="12px" mt="s" color={color}>
<Text fontSize="12px" mt="s">
{label}
</Text>
</Box>
@@ -29,7 +29,7 @@ export const VariablePanel = observer(
</Button>
}
bodyProps={{ p: 'm' }}
bodyProps={{ p: 'm', height: '100%' }}
>
{isAdd ? (
<AddStoreForm
@@ -42,6 +42,7 @@ export const VariablePanel = observer(
/>
) : (
<VariableTree
height="100%"
defaultValueDetailMode="define"
dataSource={storeVariables}
onAddStoreVariable={(storeName, data) => {
+22 -169
View File
@@ -1,13 +1,13 @@
import React from 'react';
import styled, { css, keyframes } from 'styled-components';
import { Box, Button, Group, HTMLCoralProps } from 'coral-system';
import { Dropdown, DropdownProps, Tooltip } from 'antd';
import { Tooltip } from 'antd';
import { HolderOutlined, InfoCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { ISelectedItemData, isString, noop } from '@music163/tango-helpers';
import { observer, useDesigner, useWorkspace } from '@music163/tango-context';
import { IconFont } from '@music163/tango-ui';
import { getDragGhostElement } from '../helpers';
import { getWidget } from '../widgets';
import { ComponentsPopover } from '../components';
/**
* 选择辅助工具的对齐方式
@@ -24,7 +24,15 @@ export interface SelectionToolsProps {
}
export const SelectionTools = observer(
({ actions: actionsProp = ['viewSource', 'copyNode', 'deleteNode'] }: SelectionToolsProps) => {
({
actions: actionsProp = [
'selectParentNode',
'viewSource',
'copyNode',
'deleteNode',
'moreActions',
],
}: SelectionToolsProps) => {
const workspace = useWorkspace();
const selectSource = workspace.selectSource;
const actions = actionsProp.map((item) => {
@@ -79,13 +87,6 @@ const bottomAddSiblingBtnStyle = css`
pointer-events: auto;
`;
interface IInsertedData {
name: string;
label: string;
icon: string;
description: string;
}
export interface SelectionBoxProps {
/**
* 是否显示操作按钮
@@ -117,36 +118,6 @@ function SelectionBox({ showActions, actions, data }: SelectionBoxProps) {
const prototype = workspace.componentPrototypes.get(data.name);
const isPage = prototype?.type === 'page';
// 如果声明了 childrenName,提供快捷子元素创建入口
let insertedList: IInsertedData[] = [];
if (prototype?.childrenName) {
const names = Array.isArray(prototype?.childrenName)
? prototype.childrenName
: [prototype.childrenName];
insertedList = names.map((child) => {
const proto = workspace.componentPrototypes.get(child);
return {
name: child,
label: proto?.title || child,
icon: proto?.icon,
description: proto?.help,
};
});
}
let siblingList: IInsertedData[] = [];
if (prototype?.siblingNames) {
siblingList = prototype.siblingNames?.map((item) => {
const proto = workspace.componentPrototypes.get(item);
return {
name: item,
label: proto?.title || item,
icon: proto?.icon,
description: proto?.help,
};
});
}
let selectionHelpersAlign: SelectionHelperAlignType = 'top-right';
if (data.bounding) {
if (data.bounding.left + data.bounding.width + boundingOffset < designer.viewport.width) {
@@ -159,6 +130,7 @@ function SelectionBox({ showActions, actions, data }: SelectionBoxProps) {
}
const isFromCurrentFile = data.filename === workspace.activeViewFile;
const selectedNodeName = workspace.selectSource?.selected?.[0]?.codeId ?? '未选中';
let style: React.CSSProperties;
if (data.bounding) {
@@ -183,30 +155,18 @@ function SelectionBox({ showActions, actions, data }: SelectionBoxProps) {
css={selectionBoxStyle}
style={style}
>
{siblingList.length > 0 ? (
{!isPage ? (
<>
<InsertedDropdown
title="在当前节点的前方添加兄弟节点"
options={siblingList}
onSelect={(name) => {
workspace.insertBeforeSelectedNode(name);
}}
>
<Tooltip title="在当前节点的前方添加兄弟节点">
<ComponentsPopover type="before">
<Tooltip title={`${selectedNodeName} 的前方添加兄弟节点`}>
<SelectionHelper icon={<PlusOutlined />} css={topAddSiblingBtnStyle} />
</Tooltip>
</InsertedDropdown>
<InsertedDropdown
title="在当前节点的后方添加兄弟节点"
options={siblingList}
onSelect={(name) => {
workspace.insertAfterSelectedNode(name);
}}
>
<Tooltip title="在当前节点的后方添加兄弟节点">
</ComponentsPopover>
<ComponentsPopover type="after">
<Tooltip title={`${selectedNodeName} 的后方添加兄弟节点`}>
<SelectionHelper icon={<PlusOutlined />} css={bottomAddSiblingBtnStyle} />
</Tooltip>
</InsertedDropdown>
</ComponentsPopover>
</>
) : null}
{showActions && (
@@ -246,17 +206,12 @@ function SelectionBox({ showActions, actions, data }: SelectionBoxProps) {
}
/>
<SelectionToolSet>{!isPage && actions}</SelectionToolSet>
{insertedList.length > 0 && (
<InsertedDropdown
options={insertedList}
onSelect={(name) => {
workspace.insertToSelectedNode(name);
}}
>
{isFromCurrentFile && prototype?.hasChildren && (
<ComponentsPopover>
<Tooltip title="快捷添加子元素">
<SelectionHelper icon={<PlusOutlined />} />
</Tooltip>
</InsertedDropdown>
</ComponentsPopover>
)}
</SelectionHelpers>
)}
@@ -429,105 +384,3 @@ const NameSelector = ({ label, parents = [], onSelect = noop }: NameSelectorProp
</NameSelectorWrapper>
);
};
interface InsertedDropdownProps extends DropdownProps {
title?: string;
options?: IInsertedData[];
onSelect?: (name: string) => void;
}
function InsertedDropdown({
title = '为当前节点添加子元素',
options = [],
onSelect,
...props
}: InsertedDropdownProps) {
return (
<Dropdown
trigger={['click']}
dropdownRender={() => {
return (
<Box
bg="#FFF"
borderRadius="m"
boxShadow="lowDown"
border="solid"
borderColor="line2"
overflow="hidden"
width="320px"
>
<Box px="l" py="m" color="text2">
{title}
</Box>
<Box maxHeight={360} overflowY="auto">
{options.map((item) => (
<InsertedItem
key={item.name}
label={item.label}
icon={item.icon}
description={item.description || '暂无组件描述'}
onClick={() => onSelect?.(item.name)}
/>
))}
</Box>
</Box>
);
}}
{...props}
/>
);
}
const insertedItemStyle = css`
cursor: pointer;
user-select: none;
&:hover {
background-color: var(--tango-colors-fill2);
}
`;
function InsertedItem({
label,
icon,
description,
...rest
}: HTMLCoralProps<'div'> & Omit<IInsertedData, 'name'>) {
let iconNode;
if (!icon) {
iconNode = <IconFont className="material-icon" type="icon-placeholder" />;
} else if (icon.startsWith('icon-')) {
iconNode = <IconFont className="material-icon" type={icon} />;
} else {
iconNode = <img src={icon} alt={label} />;
}
return (
<Box
display="flex"
columnGap="m"
px="l"
py="m"
fontSize="12px"
css={insertedItemStyle}
{...rest}
>
<Box
size="35px"
fontSize="32px"
background="fill1"
border="1px solid"
borderColor="line2"
display="flex"
alignItems="center"
justifyContent="center"
>
{iconNode}
</Box>
<Box>
<Box fontWeight="500">{label}</Box>
<Box color="text2">{description}</Box>
</Box>
</Box>
);
}
+35 -12
View File
@@ -25,22 +25,45 @@ function DesktopSimulator({ children }: HTMLCoralProps<'div'>) {
}
const mobileStyle = css`
--device-viewport-width: 375px;
--device-viewport-height: 812px;
--device-frame-width: 13px;
background-image: url(https://p5.music.126.net/obj/wonDlsKUwrLClGjCm8Kx/21897838692/b1c5/2665/56db/10558c1bb2030d55ceabbcc74431de99.png);
background-repeat: no-repeat;
background-size: 100% 100%;
box-shadow: 0 2px 8px rgb(2 8 20 / 10%), 0 8px 16px rgb(2 8 20 / 8%);
border-radius: 62px;
overflow: hidden;
--device-viewport-width: 360px;
--device-viewport-height: 640px;
position: relative;
margin: auto;
border: 16px black solid;
border-top-width: 60px;
border-bottom-width: 60px;
border-radius: 36px;
&::before {
content: '';
display: block;
width: 60px;
height: 5px;
position: absolute;
top: -30px;
left: 50%;
transform: translate(-50%, -50%);
background: #333;
border-radius: 10px;
}
&::after {
content: '';
display: block;
width: 35px;
height: 35px;
position: absolute;
left: 50%;
bottom: -65px;
transform: translate(-50%, -50%);
background: #333;
border-radius: 50%;
}
.MobileSimulatorDeviceFrame {
border-radius: 50px;
width: var(--device-viewport-width);
height: var(--device-viewport-height);
margin: var(--device-frame-width);
overflow: hidden;
background: white;
}
`;
+42 -1
View File
@@ -1,20 +1,61 @@
import React, { useEffect, useRef } from 'react';
import cx from 'classnames';
import { Box, HTMLCoralProps } from 'coral-system';
import { useDesigner, useWorkspace } from '@music163/tango-context';
import { observer, useDesigner, useWorkspace } from '@music163/tango-context';
import { Ghost } from './ghost';
import { useSandboxQuery } from '../context';
import { SelectionTools, SelectionToolsProps } from './selection';
import { InsertionPrompt } from './insertion';
import { DraggingMask } from './mask';
import { Dropdown, DropdownProps } from 'antd';
import { ContextMenu } from '../components';
export interface ViewportProps extends HTMLCoralProps<'div'> {
selectionTools?: SelectionToolsProps['actions'];
}
const ViewportContextMenu = observer((props: DropdownProps) => {
const designer = useDesigner();
// FIXME: 考虑优化定位实现?
// 由于 iframe 内的 contextmenu 事件无法被外层感知到,所以无法自动展示与定位
// 而手动指定 align 会干扰 contextmenu 溢出时的位置处理,会定位到完全相反的位置
// 因此,给 dropdown 单独提供一个定位容器,将其定位至 iframe 内触发点击的位置
// 并在每次 contextmenu 隐藏时销毁 dropdown,让 dropdown 能重新获取新的位置
return (
designer.showContextMenu && (
<Dropdown
autoAdjustOverflow
trigger={['contextMenu']}
placement="bottomLeft"
open
onOpenChange={(val) => {
if (!val) {
designer.toggleContextMenu(val);
}
}}
overlay={<ContextMenu onClick={() => designer.toggleContextMenu(false)} showParents />}
{...props}
>
<Box
width={0}
height={0}
position="absolute"
style={{
left: designer.contextMenuPosition.clientX,
top: designer.contextMenuPosition.clientY,
pointerEvents: 'none',
}}
/>
</Dropdown>
)
);
});
export function Viewport({ selectionTools, children, className, ...rest }: ViewportProps) {
return (
<Box position="relative" height="100%" className={cx('Viewport', className)} {...rest}>
<ViewportContextMenu />
<ViewportBody>{children}</ViewportBody>
<div className="AuxTools">
<SelectionTools actions={selectionTools} />
+3 -2
View File
@@ -5,11 +5,12 @@ import { observer, useWorkspace } from '@music163/tango-context';
export const HistoryTool = observer(() => {
const workspace = useWorkspace();
const disabled = !workspace.isValid;
return (
<Box display="flex" columnGap="m">
<ToggleButton
shape="ghost"
disabled={!workspace.history.couldBack || workspace.history.index === 0}
disabled={disabled || !workspace.history.couldBack || workspace.history.index === 0}
tooltip="撤销"
onClick={() => {
workspace.history.back();
@@ -20,7 +21,7 @@ export const HistoryTool = observer(() => {
</ToggleButton>
<ToggleButton
shape="ghost"
disabled={!workspace.history.couldForward}
disabled={disabled || !workspace.history.couldForward}
tooltip="重做"
onClick={() => {
workspace.history.forward();
+3 -16
View File
@@ -1,6 +1,5 @@
import React, { useCallback } from 'react';
import React from 'react';
import { Group } from 'coral-system';
import { Modal } from 'antd';
import { ToggleButton, CodeOutlined, DualOutlined } from '@music163/tango-ui';
import { observer, useDesigner, useWorkspace } from '@music163/tango-context';
import { BorderOutlined } from '@ant-design/icons';
@@ -9,23 +8,13 @@ export const ModeSwitchTool = observer(() => {
const workspace = useWorkspace();
const designer = useDesigner();
const activeFileCheck = useCallback(() => {
if (workspace.activeFile !== workspace.activeViewFile) {
Modal.confirm({
title: '当前打开的文件与视图不匹配,是否切换到当前视图对应的文件?',
onOk: () => {
workspace.setActiveFile(workspace.activeViewFile);
},
});
}
}, [workspace]);
return (
<Group attached>
<Group attached whiteSpace="nowrap">
<ToggleButton
shape="ghost"
selected={designer.activeView === 'design'}
onClick={() => {
workspace.syncFiles(); // 保证 ast 与 code 是同步的
designer.setActiveView('design');
}}
tooltip="设计视图"
@@ -38,7 +27,6 @@ export const ModeSwitchTool = observer(() => {
onClick={() => {
designer.setActiveView('code'); // 切换到源码视图
designer.setActiveSidebarPanel(''); // 关闭左侧面板
activeFileCheck();
}}
tooltip="源码视图"
>
@@ -50,7 +38,6 @@ export const ModeSwitchTool = observer(() => {
onClick={() => {
designer.setActiveView('dual'); // 切换到双屏视图
designer.setActiveSidebarPanel(''); // 关闭左侧面板
activeFileCheck();
}}
tooltip="双屏视图"
>
+4 -2
View File
@@ -1,13 +1,15 @@
import React from 'react';
import { ToggleButton } from '@music163/tango-ui';
import { EyeOutlined } from '@ant-design/icons';
import { observer, useDesigner } from '@music163/tango-context';
import { observer, useDesigner, useWorkspace } from '@music163/tango-context';
export const PreviewTool = observer(() => {
const designer = useDesigner();
const workspace = useWorkspace();
return (
<ToggleButton
disabled={!workspace.isValid}
shape="ghost"
selected={designer.isPreview}
onClick={() => {
@@ -17,7 +19,7 @@ export const PreviewTool = observer(() => {
designer.setActiveView('design');
}
}}
tooltip="预览"
tooltip={designer.isPreview ? '切换到设计模式' : '切换到预览模式'}
>
<EyeOutlined />
</ToggleButton>
@@ -47,11 +47,14 @@ function PageSelect({ value, onSelect, onRemove, onUpdate, onCopy, options }: Pa
setVisible(false);
};
const current = optionMap[value];
const pathname = value?.split?.('?')[0];
const current = optionMap[pathname];
return (
<ToggleButton
shape="ghost"
minWidth={100}
maxWidth={200}
textAlign="left"
dropdownProps={{
open: visible,
onOpenChange: setVisible,
+47 -17
View File
@@ -1,6 +1,8 @@
import React, { useMemo } from 'react';
import { Box, Group } from 'coral-system';
import { ReactComponentProps } from '@music163/tango-helpers';
import { DesignerViewType } from '@music163/tango-core';
import { observer, useDesigner } from '@music163/tango-context';
import { getWidget } from '../widgets';
export interface ToolbarProps {
@@ -15,25 +17,23 @@ export function Toolbar({ children }: ToolbarProps) {
let prevPlacement: string;
React.Children.forEach(children, (child: React.ReactElement, index) => {
let fallbackNode;
const childProps = child.props;
let fallbackChildren;
if (child.key) {
const Widget = getWidget(['toolbar', child.key].join('.'));
if (Widget) {
fallbackNode = React.createElement(Widget, child.props.widgetProps);
fallbackChildren = <Widget {...childProps.widgetProps} />;
}
}
let node = child.props.children ?? fallbackNode ?? null;
if (!node) {
node = child; // separator
}
const key = child.key || index;
node = (
<div key={key} className="ToolbarPanelItem" data-key={key}>
{node}
</div>
);
const placement = child.props.placement || prevPlacement || 'center';
const node = React.cloneElement(child, {
key,
'data-key': key,
children: childProps.children || fallbackChildren,
});
const placement = childProps.placement || prevPlacement || 'center';
switch (placement) {
case 'left':
left.push(node);
@@ -60,7 +60,7 @@ export function Toolbar({ children }: ToolbarProps) {
<Group display="flex" alignItems="center" gap="m">
{centerTools}
</Group>
<Group display="flex" alignItems="center" gap="m">
<Group display="flex" alignItems="center" justifyContent="flex-end" gap="m">
{rightTools}
</Group>
</Box>
@@ -68,17 +68,47 @@ export function Toolbar({ children }: ToolbarProps) {
}
export interface ToolbarItemProps extends ReactComponentProps {
/**
* 类型
*/
type?: 'divider';
placement?: 'left' | 'center' | 'right';
children?: React.ReactElement;
/**
* 如果 key 匹配到内置组件的话,传递给子节点的属性
*/
widgetProps?: object;
/**
* 工具箱展示的视图
*/
activeViews?: DesignerViewType[];
}
function ToolbarItem({ placement, widgetProps, children }: ToolbarItemProps) {
return <div>{children}</div>;
}
const ToolbarItem = observer(
({
activeViews = ['code', 'design', 'dual'],
type,
placement,
widgetProps,
children,
...rest
}: ToolbarItemProps) => {
const designer = useDesigner();
if (!activeViews.includes(designer.activeView)) {
return null;
}
if (type === 'divider') {
return <Separator />;
}
return (
<div className="ToolbarPanelItem" {...rest}>
{children}
</div>
);
},
);
function Separator() {
return <Box className="Separator" width={1} height={16} bg="colors.custom.toolbarDividerColor" />;

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