Compare commits

..

29 Commits

Author SHA1 Message Date
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
113 changed files with 1902 additions and 619 deletions
+1
View File
@@ -9,3 +9,4 @@ coverage/
.umi-production/ .umi-production/
.log .log
.eslintcache .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 - 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 - Developed using TypeScript, providing complete type definition files
## 🎯 Milestone ## 💡 Examples
```mermaid You can use tango to build lowcode builders, for example:
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".)
section Builder Release | Preview | Description |
1.0 Alpha : m1, 2023-10-01, 2024-01-31 | ---------------------------------------------------------------------------------------------- | ----------------------- |
1.0 RC : m2, 2024-02-01, 2024-04-30 | ![image](https://github.com/NetEase/tango/assets/6984035/56a71741-4536-4336-803a-d81d51128a76) | Internal App Builder |
1.0 Stable : m3, 2024-04-30, 2024-12-31 | ![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 |
> [!NOTE] | ![mail app](public/mail-builder.png) | Email Builder |
> 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.
## 🌐 Compatibility ## 🌐 Compatibility
@@ -76,6 +70,23 @@ yarn
yarn start 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 ## 💬 Community
Join NetEase Tango Community to share your ideas, suggestions, or questions and connect with other users and contributors. 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 和协议 - 提供基于源码 AST 驱动的低代码引擎,无私有 DSL 和协议
- 提供实时出码能力,支持源码进,源码出 - 提供实时出码能力,支持源码进,源码出,适配多种源码开发场景
- 开箱即用的前端低代码设计器,提供灵活易用的设计器 React 组件 - 提供开箱即用的前端低代码设计器,提供灵活易用的设计器 React 组件
- 使用 TypeScript 开发,提供完整的类型定义文件 - 使用 TypeScript 开发,提供完整的类型定义文件和完善的文档支持
## 🎯 里程碑 ## 💡 例子
```mermaid 你可以使用 Tango 快速构建多种类型的基于源码的低代码搭建工具,例如:
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".)
section Builder Release | 预览图 | 说明 |
1.0 Alpha : m1, 2023-10-01, 2024-01-31 | ---------------------------------------------------------------------------------------------- | -------------------- |
1.0 RC : m2, 2024-02-01, 2024-04-30 | ![image](https://github.com/NetEase/tango/assets/6984035/56a71741-4536-4336-803a-d81d51128a76) | 中后台系统搭建 |
1.0 Stable : m3, 2024-04-30, 2024-12-31 | ![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 应用搭建 |
> [!NOTE] | ![mail app](public/mail-builder.png) | 营销类邮件搭建 |
> Alpha 版本会持续对一些实现协议进行优化,并持续融合网易内网版本中的新增特性;RC 版本将会提供基本稳定的解析协议和实现;1.0 正式版本计划在 2024 年Q2发布。1.0 正式版发布后我们将会持续进行版本迭代,并逐步融入内网版本中的流程设计、组件库、AIGC 等核心基础能力。
## 🌐 兼容环境 ## 🌐 兼容环境
@@ -76,6 +70,23 @@ yarn
yarn start yarn start
``` ```
### 本地 https 证书
如果需要在本地开发环境中使用 https,可以使用以下命令生成证书:
```bash
brew install mkcert
# 将 mkcert 添加到本地根 CA,仅在本地生效
mkcert -install
# 进入 playground 应用目录
cd apps/playground
# 为网站生成一个由 mkcert 签名的证书
mkcert local.netease.com
```
## 💬 社区讨论 ## 💬 社区讨论
参与 NetEase Tango 的社区,以分享您的想法、建议或问题,并与其他用户和贡献者建立联系。 参与 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-----
+12 -2
View File
@@ -5,6 +5,7 @@ import { BranchesOutlined, MenuOutlined, QuestionCircleOutlined } from '@ant-des
import { registerSetter } from '@music163/tango-designer'; import { registerSetter } from '@music163/tango-designer';
import type { IVariableTreeNode } from '@music163/tango-helpers'; import type { IVariableTreeNode } from '@music163/tango-helpers';
import { FooSetter } from '../components'; import { FooSetter } from '../components';
import { ToggleButton } from '@music163/tango-ui';
export * from './mock-files'; export * from './mock-files';
@@ -46,8 +47,17 @@ registerSetter({
// 平台 Logo // 平台 Logo
export function Logo() { export function Logo() {
return ( return (
<Box width="50px" display="flex" alignItems="center" justifyContent="center" fontSize="20px"> <Box width="50px" display="flex" alignItems="center" justifyContent="center" fontSize="14px">
<MenuOutlined /> <ToggleButton
shape="text"
items={[
{ label: '回到首页', key: 'home' },
{ label: '文档', key: 'doc' },
{ label: '设置', key: 'setting' },
]}
>
<MenuOutlined />
</ToggleButton>
</Box> </Box>
); );
} }
+2 -3
View File
@@ -2,7 +2,7 @@ const packageJson = {
name: 'demo', name: 'demo',
private: true, private: true,
dependencies: { dependencies: {
'@music163/tango-mail': '0.1.1', '@music163/tango-mail': '0.2.4',
'@music163/tango-boot': '0.2.5', '@music163/tango-boot': '0.2.5',
react: '17.0.2', react: '17.0.2',
'react-dom': '17.0.2', 'react-dom': '17.0.2',
@@ -44,7 +44,7 @@ const tangoConfigJson = {
}, },
'@music163/tango-mail': { '@music163/tango-mail': {
description: 'TangoMail 基础物料', description: 'TangoMail 基础物料',
version: '0.1.1', version: '0.2.4',
library: 'TangoMail', library: 'TangoMail',
type: 'baseDependency', type: 'baseDependency',
resources: ['https://unpkg.com/@music163/tango-mail@{{version}}/dist/index.js'], resources: ['https://unpkg.com/@music163/tango-mail@{{version}}/dist/index.js'],
@@ -116,7 +116,6 @@ const WelcomeEmail = () => (
</Section> </Section>
<Text style={paragraph}> <Text style={paragraph}>
Best, Best,
<br />
The Koala team The Koala team
</Text> </Text>
<Hr style={hr} /> <Hr style={hr} />
+16 -3
View File
@@ -3,7 +3,7 @@ const packageJson = {
private: true, private: true,
dependencies: { dependencies: {
'@music163/antd': '0.2.5', '@music163/antd': '0.2.5',
'@music163/tango-boot': '0.2.5', '@music163/tango-boot': '0.3.5',
react: '17.0.2', react: '17.0.2',
'react-dom': '17.0.2', 'react-dom': '17.0.2',
'prop-types': '15.7.2', 'prop-types': '15.7.2',
@@ -48,7 +48,7 @@ const tangoConfigJson = {
}, },
'@music163/tango-boot': { '@music163/tango-boot': {
description: '云音乐低代码运行时框架', description: '云音乐低代码运行时框架',
version: '0.2.5', version: '0.3.5',
library: 'TangoBoot', library: 'TangoBoot',
type: 'baseDependency', type: 'baseDependency',
resources: ['https://unpkg.com/@music163/tango-boot@{{version}}/dist/boot.js'], resources: ['https://unpkg.com/@music163/tango-boot@{{version}}/dist/boot.js'],
@@ -56,7 +56,7 @@ const tangoConfigJson = {
}, },
'@music163/antd': { '@music163/antd': {
description: '云音乐低代码中后台应用基础物料', description: '云音乐低代码中后台应用基础物料',
version: '0.2.5', version: '0.2.6',
library: 'TangoAntd', library: 'TangoAntd',
type: 'baseDependency', type: 'baseDependency',
resources: [ resources: [
@@ -161,6 +161,8 @@ import {
} from "@music163/antd"; } from "@music163/antd";
import { Space } from "@music163/antd"; import { Space } from "@music163/antd";
import { LocalButton } from "../components"; import { LocalButton } from "../components";
import { OutButton } from "../components";
class App extends React.Component { class App extends React.Component {
render() { render() {
return ( return (
@@ -181,6 +183,7 @@ class App extends React.Component {
<Section tid="section2"> <Section tid="section2">
<Space tid="space1"> <Space tid="space1">
<LocalButton /> <LocalButton />
<OutButton />
<Button tid="button1">button</Button> <Button tid="button1">button</Button>
</Space> </Space>
</Section> </Section>
@@ -290,6 +293,14 @@ registerComponentPrototype({
}); });
`; `;
const outButtonCode = `
import React from 'react';
export default function OutButton(props) {
return <button {...props}>Out button (from other file)</button>
}
`;
const componentsInputCode = ` const componentsInputCode = `
import React from 'react'; import React from 'react';
import { registerComponentPrototype } from '../utils'; import { registerComponentPrototype } from '../utils';
@@ -312,6 +323,7 @@ registerComponentPrototype({
const componentsEntryCode = ` const componentsEntryCode = `
export { default as LocalButton } from './button'; export { default as LocalButton } from './button';
export { default as LocalInput } from './input'; export { default as LocalInput } from './input';
export { default as OutButton } from './out-button';
`; `;
const storeApp = ` const storeApp = `
@@ -412,6 +424,7 @@ export const sampleFiles = [
{ filename: '/src/pages/list.js', code: viewHomeCode }, { filename: '/src/pages/list.js', code: viewHomeCode },
{ filename: '/src/pages/detail.js', code: emptyPageCode }, { filename: '/src/pages/detail.js', code: emptyPageCode },
{ filename: '/src/components/button.js', code: componentsButtonCode }, { 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/input.js', code: componentsInputCode },
{ filename: '/src/components/index.js', code: componentsEntryCode }, { filename: '/src/components/index.js', code: componentsEntryCode },
{ filename: '/src/routes.js', code: routesCode }, { filename: '/src/routes.js', code: routesCode },
+10 -11
View File
@@ -20,12 +20,11 @@ import {
ApiOutlined, ApiOutlined,
AppstoreAddOutlined, AppstoreAddOutlined,
BuildOutlined, BuildOutlined,
ClusterOutlined,
FunctionOutlined, FunctionOutlined,
PlusOutlined, PlusOutlined,
createFromIconfontCN, createFromIconfontCN,
} from '@ant-design/icons'; } from '@ant-design/icons';
import { Action } from '@music163/tango-ui'; import { Action, PackageOutlined } from '@music163/tango-ui';
import { useState } from 'react'; import { useState } from 'react';
const menuData = { const menuData = {
@@ -114,8 +113,8 @@ export default function App() {
actions={ actions={
<Box px="l"> <Box px="l">
<Toolbar> <Toolbar>
<Toolbar.Item key="routeSwitch" placement="left" /> <Toolbar.Item key="routeSwitch" placement="left" activeViews={['design']} />
<Toolbar.Item key="addPage" placement="left"> <Toolbar.Item key="addPage" placement="left" activeViews={['design']}>
<Action <Action
tooltip="添加页面" tooltip="添加页面"
shape="outline" shape="outline"
@@ -123,10 +122,10 @@ export default function App() {
onClick={() => setShowNewPageModal(true)} onClick={() => setShowNewPageModal(true)}
/> />
</Toolbar.Item> </Toolbar.Item>
<Toolbar.Item key="history" placement="left" /> <Toolbar.Item key="history" placement="left" activeViews={['design']} />
<Toolbar.Item key="preview" placement="left" /> <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="modeSwitch" placement="right" />
<Toolbar.Item key="togglePanel" placement="right" />
<Toolbar.Separator /> <Toolbar.Separator />
<Toolbar.Item placement="right"> <Toolbar.Item placement="right">
<Space> <Space>
@@ -182,12 +181,15 @@ export default function App() {
<Sidebar.Item <Sidebar.Item
key="dependency" key="dependency"
label="依赖" label="依赖"
icon={<ClusterOutlined />} icon={<PackageOutlined />}
isFloat isFloat
width={800} width={800}
/> />
</Sidebar> </Sidebar>
<WorkspacePanel> <WorkspacePanel>
<WorkspaceView mode="code">
<CodeEditor />
</WorkspaceView>
<WorkspaceView mode="design"> <WorkspaceView mode="design">
<Sandbox <Sandbox
onMessage={(e) => { onMessage={(e) => {
@@ -209,9 +211,6 @@ export default function App() {
navigatorExtra={<Button size="small">hello world</Button>} navigatorExtra={<Button size="small">hello world</Button>}
/> />
</WorkspaceView> </WorkspaceView>
<WorkspaceView mode="code">
<CodeEditor />
</WorkspaceView>
</WorkspacePanel> </WorkspacePanel>
<SettingPanel /> <SettingPanel />
</DesignerPanel> </DesignerPanel>
@@ -79,6 +79,11 @@ const prototypeHasBasicProps: IComponentPrototype = {
title: 'textAreaSetter', title: 'textAreaSetter',
setter: 'textAreaSetter', setter: 'textAreaSetter',
}, },
{
name: 'src',
title: 'imageSetter',
setter: 'imageSetter',
},
{ {
name: 'number', name: 'number',
title: 'numberSetter', title: 'numberSetter',
@@ -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>
);
}
+20
View File
@@ -3,6 +3,26 @@
All notable changes to this project will be documented in this file. All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [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) ## [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 **Note:** Version bump only for package @music163/tango-context
+3 -3
View File
@@ -1,6 +1,6 @@
{ {
"name": "@music163/tango-context", "name": "@music163/tango-context",
"version": "1.1.1", "version": "1.1.6",
"description": "react context for tango-apps", "description": "react context for tango-apps",
"keywords": [ "keywords": [
"react", "react",
@@ -31,8 +31,8 @@
"react": ">= 16.8" "react": ">= 16.8"
}, },
"dependencies": { "dependencies": {
"@music163/tango-core": "^1.2.0", "@music163/tango-core": "^1.4.0",
"@music163/tango-helpers": "^1.1.1", "@music163/tango-helpers": "^1.2.1",
"mobx-react-lite": "4.0.7" "mobx-react-lite": "4.0.7"
}, },
"publishConfig": { "publishConfig": {
+38
View File
@@ -3,6 +3,44 @@
All notable changes to this project will be documented in this file. All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
# [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) # [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 ### Bug Fixes
+2 -2
View File
@@ -1,6 +1,6 @@
{ {
"name": "@music163/tango-core", "name": "@music163/tango-core",
"version": "1.2.0", "version": "1.4.0",
"description": "tango core", "description": "tango core",
"author": "wwsun <ww.sun@outlook.com>", "author": "wwsun <ww.sun@outlook.com>",
"homepage": "", "homepage": "",
@@ -28,7 +28,7 @@
"@babel/parser": "^7.23.5", "@babel/parser": "^7.23.5",
"@babel/traverse": "^7.23.5", "@babel/traverse": "^7.23.5",
"@babel/types": "^7.23.5", "@babel/types": "^7.23.5",
"@music163/tango-helpers": "^1.1.1", "@music163/tango-helpers": "^1.2.1",
"@types/babel__generator": "^7.6.7", "@types/babel__generator": "^7.6.7",
"@types/babel__traverse": "^7.20.4", "@types/babel__traverse": "^7.20.4",
"mobx": "6.12.3", "mobx": "6.12.3",
+1 -1
View File
@@ -35,7 +35,7 @@ export function isTangoVariable(name: string) {
return /^tango\??\.(stores|services)\??\./.test(name) && name.split('.').length > 2; return /^tango\??\.(stores|services)\??\./.test(name) && name.split('.').length > 2;
} }
const templatePattern = /^{(.+)}$/s; const templatePattern = /^{(.+)}$/;
/** /**
* 判断给定字符串是否被表达式容器`{expCode}`包裹 * 判断给定字符串是否被表达式容器`{expCode}`包裹
+4 -16
View File
@@ -3,7 +3,7 @@
*/ */
import generator, { GeneratorOptions } from '@babel/generator'; import generator, { GeneratorOptions } from '@babel/generator';
import * as t from '@babel/types'; 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'; import { formatCode } from '../string';
const defaultGeneratorOptions: GeneratorOptions = { const defaultGeneratorOptions: GeneratorOptions = {
@@ -25,19 +25,7 @@ export function ast2code(ast: t.Node, options: GeneratorOptions = defaultGenerat
return code; return code;
} }
const bracketPattern = /^\(.+\)$/s; const bracketPattern = /^\(.+\)$/;
/**
* 是否被 () 包裹
*
* @example ({ foo: 'foo' }) -> true
* @example { foo: 'foo' } -> false
*
* @param str 目标字符串
*/
function isWrappingWithBrackets(str: string) {
return bracketPattern.test(str);
}
/** /**
* 将表达式生成为块级代码 * 将表达式生成为块级代码
@@ -54,7 +42,7 @@ export function expression2code(node: t.Expression) {
const isWrappingExpression = t.isObjectExpression(node) || t.isFunctionExpression(node); const isWrappingExpression = t.isObjectExpression(node) || t.isFunctionExpression(node);
if (isWrappingExpression && isWrappingWithBrackets(ret)) { if (isWrappingExpression && bracketPattern.test(ret)) {
// 如果是对象,输出包含 ({}),则去掉首尾的括号 // 如果是对象,输出包含 ({}),则去掉首尾的括号
ret = ret.slice(1, -1); ret = ret.slice(1, -1);
} }
@@ -195,7 +183,7 @@ export function node2value(node: t.Node, isWrapCode = true): any {
); );
if (isSimpleObject) { if (isSimpleObject) {
// simple object: { key1, key2, key3 } // simple object: { key1, key2, key3 }
ret = node.properties.reduce((prev, propertyNode) => { ret = node.properties.reduce<Dict>((prev, propertyNode) => {
if (propertyNode.type === 'ObjectProperty') { if (propertyNode.type === 'ObjectProperty') {
const key = keyNode2value(propertyNode.key); const key = keyNode2value(propertyNode.key);
const value = node2value(propertyNode.value, isWrapCode); const value = node2value(propertyNode.value, isWrapCode);
+5 -8
View File
@@ -68,11 +68,7 @@ export function isValidExpressionCode(code: string) {
* @returns * @returns
*/ */
export function code2ast(code: string): t.File { export function code2ast(code: string): t.File {
try { return parse(code, babelParserConfig);
return parse(code, babelParserConfig);
} catch (err) {
logger.error('[code2ast failed!]', err);
}
} }
/** /**
@@ -175,7 +171,7 @@ export function value2node(
* 将 js 普通对象解析为 t.Node * 将 js 普通对象解析为 t.Node
*/ */
export function object2node( export function object2node(
obj: object, obj: Dict,
getValueNode: (value: any, key?: string) => t.Expression = value2node, getValueNode: (value: any, key?: string) => t.Expression = value2node,
) { ) {
if (!isPlainObject(obj)) { if (!isPlainObject(obj)) {
@@ -222,15 +218,16 @@ export function value2jsxAttributeValueNode(value: any) {
return ret; return ret;
} }
// TODO: 待校验
export function value2jsxChildrenValueNode(value: any) { export function value2jsxChildrenValueNode(value: any) {
let ret: t.JSXElement | t.JSXFragment | t.JSXExpressionContainer | t.JSXSpreadChild | t.JSXText; let ret: t.JSXElement | t.JSXFragment | t.JSXExpressionContainer | t.JSXSpreadChild | t.JSXText;
switch (typeof value) { switch (typeof value) {
case 'string': case 'string':
if (isValidExpressionCode(value)) { if (isWrappedCode(value)) {
// 代码模式
const innerString = getVariableContent(value); const innerString = getVariableContent(value);
ret = t.jsxExpressionContainer(code2expression(innerString)); ret = t.jsxExpressionContainer(code2expression(innerString));
} else { } else {
// 普通的文本
ret = t.jsxText(value); ret = t.jsxText(value);
} }
break; break;
+23 -2
View File
@@ -391,8 +391,10 @@ export function updateJSXElementAttribute(node: t.JSXElement, attrName: string,
isExist = true; isExist = true;
// @ts-ignore // @ts-ignore
if (t.isJSXAttribute(jsxAttributeNode)) { if (t.isJSXAttribute(jsxAttributeNode)) {
// 更新 jsx 属性值 <Foo bar="1" /> 的模式
jsxAttributeNode.value = value2jsxAttributeValueNode(attrValue); jsxAttributeNode.value = value2jsxAttributeValueNode(attrValue);
} else if (name === 'children') { } else if (name === 'children') {
// 更新 jsx children 的情况 <Foo>children</Foo>
node.children = value2jsxChildrenValueNode(attrValue); 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, { traverse(ast, {
CallExpression(path) { CallExpression(path) {
const calleeName = keyNode2value(path.node.callee) as string; 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]; const configNode = path.node.arguments[0];
if (t.isObjectExpression(configNode)) { 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 serviceConfig = config[key];
const property = t.objectProperty(t.identifier(key), serviceConfig2Node(serviceConfig)); const property = t.objectProperty(t.identifier(key), serviceConfig2Node(serviceConfig));
properties[key] = property; properties[key] = property;
@@ -1425,3 +1427,22 @@ export function traverseFile(ast: t.File) {
imports, 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[], names: string[],
nameMap: Dict<IImportSpecifierSourceData>, nameMap: Dict<IImportSpecifierSourceData>,
) { ) {
const map = {}; const map: Dict = {};
names.forEach((name) => { names.forEach((name) => {
const mod = nameMap[name]; const mod = nameMap[name];
if (mod) { if (mod) {
+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 } ] } // { id: 1, component, props: { id: 1 }, children: [ { id: 2, component } ] }
export function deepCloneNode(obj: any, component?: string): any { export function deepCloneNode(obj: any, component?: string): any {
function deepCloneObject() { function deepCloneObject() {
const target = {}; const target: Dict = {};
for (const key in obj) { for (const key in obj) {
if (Object.hasOwn(obj, key)) { if (Object.hasOwn(obj, key)) {
target[key] = deepCloneNode(obj[key], component); target[key] = deepCloneNode(obj[key], component);
+1 -1
View File
@@ -13,7 +13,7 @@ export class TangoComponentsEntryModule extends TangoModule {
constructor(workspace: IWorkspace, props: IFileConfig) { constructor(workspace: IWorkspace, props: IFileConfig) {
super(workspace, props, false); super(workspace, props, false);
this.update(props.code, false, false); this.update(props.code, true, false);
makeObservable(this, { makeObservable(this, {
_code: observable, _code: observable,
_cleanCode: observable, _cleanCode: observable,
+41
View File
@@ -83,6 +83,16 @@ export class Designer {
*/ */
_addComponentPopoverPosition = { clientX: 0, clientY: 0 }; _addComponentPopoverPosition = { clientX: 0, clientY: 0 };
/**
* 是否显示右键菜单
*/
_showContextMenu = false;
/**
* 右键菜单在 iframe 上的位置
*/
_contextMenuPosition = { clientX: 0, clientY: 0 };
/** /**
* 是否显示右侧面板 * 是否显示右侧面板
*/ */
@@ -136,6 +146,14 @@ export class Designer {
return this._addComponentPopoverPosition; return this._addComponentPopoverPosition;
} }
get showContextMenu() {
return this._showContextMenu;
}
get contextMenuPosition() {
return this._contextMenuPosition;
}
get menuData() { get menuData() {
return this._menuData ?? ([] as MenuDataType); return this._menuData ?? ([] as MenuDataType);
} }
@@ -178,6 +196,8 @@ export class Designer {
_showRightPanel: observable, _showRightPanel: observable,
_showAddComponentPopover: observable, _showAddComponentPopover: observable,
_addComponentPopoverPosition: observable, _addComponentPopoverPosition: observable,
_showContextMenu: observable,
_contextMenuPosition: observable,
_menuData: observable, _menuData: observable,
_isPreview: observable, _isPreview: observable,
simulator: computed, simulator: computed,
@@ -189,6 +209,8 @@ export class Designer {
showSmartWizard: computed, showSmartWizard: computed,
showAddComponentPopover: computed, showAddComponentPopover: computed,
addComponentPopoverPosition: computed, addComponentPopoverPosition: computed,
showContextMenu: computed,
contextMenuPosition: computed,
menuData: computed, menuData: computed,
setSimulator: action, setSimulator: action,
setViewport: action, setViewport: action,
@@ -199,6 +221,7 @@ export class Designer {
toggleSmartWizard: action, toggleSmartWizard: action,
toggleIsPreview: action, toggleIsPreview: action,
toggleAddComponentPopover: action, toggleAddComponentPopover: action,
toggleContextMenu: action,
}); });
} }
@@ -216,6 +239,13 @@ export class Designer {
setActiveView(view: DesignerViewType) { setActiveView(view: DesignerViewType) {
this._activeView = view; this._activeView = view;
if (view === 'dual') {
this.setActiveSidebarPanel('');
this.toggleRightPanel(false);
this.toggleIsPreview(true);
} else if (view === 'design') {
this.toggleIsPreview(false);
}
} }
setActiveSidebarPanel(panel: string) { setActiveSidebarPanel(panel: string) {
@@ -264,4 +294,15 @@ export class Designer {
this.workspace.selectSource.clear(); 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; lastModified: number;
/**
* 文件解析是否出错
*/
isError: boolean;
/**
* 文件解析错误消息
*/
errorMessage: string;
_code: string; _code: string;
_cleanCode: string; _cleanCode: string;
@@ -40,6 +50,7 @@ export class TangoFile {
this.filename = props.filename; this.filename = props.filename;
this.type = props.type; this.type = props.type;
this.lastModified = Date.now(); this.lastModified = Date.now();
this.isError = false;
// 这里主要是为了解决 umi ts 编译错误的问题,@see https://github.com/umijs/umi/issues/7594 // 这里主要是为了解决 umi ts 编译错误的问题,@see https://github.com/umijs/umi/issues/7594
if (isSyncCode) { if (isSyncCode) {
+1
View File
@@ -7,6 +7,7 @@ export * from './drag-source';
export * from './history'; export * from './history';
export * from './file'; export * from './file';
export * from './module'; export * from './module';
export * from './entry-module';
export * from './route-module'; export * from './route-module';
export * from './service-module'; export * from './service-module';
export * from './store-module'; export * from './store-module';
+23 -2
View File
@@ -10,12 +10,14 @@ import {
IPageConfigData, IPageConfigData,
IImportSpecifierSourceData, IImportSpecifierSourceData,
IImportSpecifierData, IImportSpecifierData,
IFileError,
} from '../types'; } from '../types';
import { TangoFile, TangoJsonFile } from './file'; import { TangoFile, TangoJsonFile } from './file';
import { TangoRouteModule } from './route-module'; import { TangoRouteModule } from './route-module';
import { TangoStoreModule } from './store-module'; import { TangoStoreModule } from './store-module';
import { TangoServiceModule } from './service-module'; import { TangoServiceModule } from './service-module';
import { IdGenerator } from '../helpers'; import { IdGenerator } from '../helpers';
import { AppEntryModule } from './entry-module';
export interface IViewFile { export interface IViewFile {
readonly workspace: IWorkspace; readonly workspace: IWorkspace;
@@ -152,6 +154,10 @@ export interface IWorkspace {
* 解析后的 tango.config.json 文件,如果要获取项目配置,推荐使用 projectConfig 获取 * 解析后的 tango.config.json 文件,如果要获取项目配置,推荐使用 projectConfig 获取
*/ */
tangoConfigJson: TangoJsonFile; tangoConfigJson: TangoJsonFile;
/**
* app.js 入口文件解析后的模块
*/
appEntryModule: AppEntryModule;
/** /**
* 解析后的路由模块 * 解析后的路由模块
*/ */
@@ -187,7 +193,18 @@ export interface IWorkspace {
renameFile: (oldFilename: string, newFilename: string) => void; renameFile: (oldFilename: string, newFilename: string) => void;
renameFolder: (oldFoldername: string, newFoldername: 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>; listFiles: () => Record<string, string>;
getFile: (filename: string) => TangoFile; getFile: (filename: string) => TangoFile;
@@ -293,8 +310,12 @@ export interface IWorkspace {
get bizComps(): string[]; get bizComps(): string[];
get baseComps(): string[]; get baseComps(): string[];
get localComps(): string[]; get localComps(): string[];
get fileErrors(): IFileError[];
/** /**
* 是否是合法的项目 * 是否是有效的项目
* - 包含 tango.config.json
* - 包含视图模块
* - 没有文件错误
*/ */
get isValid(): boolean; get isValid(): boolean;
} }
+60 -18
View File
@@ -21,6 +21,11 @@ import { IWorkspace } from './interfaces';
export class TangoModule extends TangoFile { export class TangoModule extends TangoFile {
ast: t.File; ast: t.File;
/**
* ast 是否与 code 保持同步
*/
isAstSynced: boolean;
/** /**
* 导入的依赖列表 * 导入的依赖列表
*/ */
@@ -33,23 +38,53 @@ export class TangoModule extends TangoFile {
/** /**
* 基于最新的 ast 进行同步 * 基于最新的 ast 进行同步
* @param code 如果传入 code,则基于 code 进行同步 * @param code 如果传入 code,则基于 code 进行同步
* @param isFormatCode 是否格式化代码 * @param isSyncAst 是否同步 ast
* @param refreshWorkspace 是否刷新 workspace * @param isRefreshWorkspace 是否刷新 workspace
*/ */
update(code?: string, isFormatCode = true, refreshWorkspace = true) { update(code?: string, isSyncAst = true, isRefreshWorkspace = true) {
this.lastModified = Date.now(); this.lastModified = Date.now();
if (isNil(code)) {
this._syncByAst(); try {
} else { if (isNil(code)) {
this._syncByCode(code, isFormatCode); 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(); /**
* 基于当前的代码重新生成 ast
this.workspace.onFilesChange([this.filename]); */
updateAst() {
if (refreshWorkspace) { if (!this.isAstSynced) {
this.workspace.refresh([this.filename]); 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 code 源码
* @param isFormatCode 是否格式化代码 * @param isSyncAst 是否同步 ast
* @returns * @returns
*/ */
_syncByCode(code: string, isFormatCode = true) { _syncByCode(code: string, isSyncAst = true) {
if (code === this._code) { if (code === this._code) {
return; return;
} }
// 提前格式化代码 // 提前格式化代码
if (isFormatCode) { try {
code = formatCode(code); code = formatCode(code);
} catch (err) {
// err ignored, format code failed
} }
this._code = code; this._code = code;
this._cleanCode = code; this._cleanCode = code;
this.ast = code2ast(code); if (isSyncAst) {
this.ast = code2ast(code);
}
} }
_analysisAst() { _analysisAst() {
@@ -105,14 +144,17 @@ export class TangoModule extends TangoFile {
export class TangoJsModule extends TangoModule { export class TangoJsModule extends TangoModule {
constructor(workspace: IWorkspace, props: IFileConfig) { constructor(workspace: IWorkspace, props: IFileConfig) {
super(workspace, props, false); super(workspace, props, false);
this.update(props.code, false, false); this.update(props.code, true, false);
makeObservable(this, { makeObservable(this, {
_code: observable, _code: observable,
_cleanCode: observable, _cleanCode: observable,
isError: observable,
errorMessage: observable,
code: computed, code: computed,
cleanCode: computed, cleanCode: computed,
update: action, update: action,
updateAst: action,
}); });
} }
} }
+5 -1
View File
@@ -1,4 +1,5 @@
import { action, computed, makeObservable, observable, toJS } from 'mobx'; import { action, computed, makeObservable, observable, toJS } from 'mobx';
import { logger } from '@music163/tango-helpers';
import { import {
traverseRouteFile, traverseRouteFile,
addRouteToRouteFile, addRouteToRouteFile,
@@ -27,10 +28,13 @@ export class TangoRouteModule extends TangoModule {
_routes: observable, _routes: observable,
_code: observable, _code: observable,
_cleanCode: observable, _cleanCode: observable,
isError: observable,
errorMessage: observable,
routes: computed, routes: computed,
code: computed, code: computed,
cleanCode: computed, cleanCode: computed,
update: action, update: action,
updateAst: action,
}); });
} }
@@ -74,7 +78,7 @@ export class TangoRouteModule extends TangoModule {
*/ */
removeRoute(route: string) { removeRoute(route: string) {
if (route === '/') { if (route === '/') {
console.warn('index route should not be removed!'); logger.warn('index route should not be removed!');
return; return;
} }
const record = this.getRouteByRoutePath(route); const record = this.getRouteByRoutePath(route);
@@ -49,11 +49,14 @@ export class TangoServiceModule extends TangoModule {
_baseConfig: observable, _baseConfig: observable,
_code: observable, _code: observable,
_cleanCode: observable, _cleanCode: observable,
isError: observable,
errorMessage: observable,
serviceFunctions: computed, serviceFunctions: computed,
baseConfig: computed, baseConfig: computed,
cleanCode: computed, cleanCode: computed,
code: computed, code: computed,
update: action, update: action,
updateAst: action,
}); });
} }
+3
View File
@@ -31,10 +31,13 @@ export class TangoStoreEntryModule extends TangoModule {
_stores: observable, _stores: observable,
_code: observable, _code: observable,
_cleanCode: observable, _cleanCode: observable,
isError: observable,
errorMessage: observable,
stores: computed, stores: computed,
code: computed, code: computed,
cleanCode: computed, cleanCode: computed,
update: action, update: action,
updateAst: action,
}); });
} }
+5 -1
View File
@@ -138,10 +138,14 @@ export class TangoViewModule extends TangoModule implements IViewFile {
_code: observable, _code: observable,
_cleanCode: observable, _cleanCode: observable,
isError: observable,
errorMessage: observable,
code: computed, code: computed,
cleanCode: computed, cleanCode: computed,
update: action, update: action,
updateAst: action,
}); });
} }
@@ -320,7 +324,7 @@ export class TangoViewModule extends TangoModule implements IViewFile {
updateNodeAttributes(nodeId: string, config: Record<string, any>, relatedImports?: string[]) { updateNodeAttributes(nodeId: string, config: Record<string, any>, relatedImports?: string[]) {
if (relatedImports && relatedImports.length) { 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 proto = this.workspace.getPrototype(name);
const { source, specifiers } = prototype2importDeclarationData(proto, this.filename); const { source, specifiers } = prototype2importDeclarationData(proto, this.filename);
const existSpecifiers: IImportSpecifierData[] = prev[source]; const existSpecifiers: IImportSpecifierData[] = prev[source];
+57 -24
View File
@@ -11,6 +11,7 @@ import {
parseServiceVariablePath, parseServiceVariablePath,
parseStoreVariablePath, parseStoreVariablePath,
uniq, uniq,
setValue,
} from '@music163/tango-helpers'; } from '@music163/tango-helpers';
import { import {
prototype2jsxElement, prototype2jsxElement,
@@ -24,10 +25,10 @@ import {
import { DropMethod } from './drop-target'; import { DropMethod } from './drop-target';
import { HistoryMessage, TangoHistory } from './history'; import { HistoryMessage, TangoHistory } from './history';
import { TangoNode } from './node'; import { TangoNode } from './node';
import { TangoJsModule } from './module'; import { TangoJsModule, TangoModule } from './module';
import { TangoFile, TangoJsonFile, TangoLessFile } from './file'; import { TangoFile, TangoJsonFile, TangoLessFile } from './file';
import { IWorkspace } from './interfaces'; 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 { SelectSource } from './select-source';
import { DragSource } from './drag-source'; import { DragSource } from './drag-source';
import { TangoRouteModule } from './route-module'; import { TangoRouteModule } from './route-module';
@@ -35,6 +36,7 @@ import { TangoStoreEntryModule, TangoStoreModule } from './store-module';
import { TangoServiceModule } from './service-module'; import { TangoServiceModule } from './service-module';
import { TangoViewModule } from './view-module'; import { TangoViewModule } from './view-module';
import { TangoComponentsEntryModule } from './component-module'; import { TangoComponentsEntryModule } from './component-module';
import { AppEntryModule } from './entry-module';
export interface IWorkspaceOptions { export interface IWorkspaceOptions {
/** /**
@@ -97,6 +99,11 @@ export class Workspace extends EventTarget implements IWorkspace {
*/ */
activeViewFile: string; activeViewFile: string;
/**
* 应用入口模块
*/
appEntryModule: AppEntryModule;
/** /**
* 路由配置模块 * 路由配置模块
*/ */
@@ -144,11 +151,8 @@ export class Workspace extends EventTarget implements IWorkspace {
*/ */
private copyTempNodes: TangoNode[]; private copyTempNodes: TangoNode[];
/**
* 是否是合法的项目
*/
get isValid() { 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 || {}); 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) { constructor(options?: IWorkspaceOptions) {
super(); super();
this.history = new TangoHistory(this); this.history = new TangoHistory(this);
@@ -249,6 +266,8 @@ export class Workspace extends EventTarget implements IWorkspace {
activeViewFile: observable, activeViewFile: observable,
pages: computed, pages: computed,
bizComps: computed, bizComps: computed,
fileErrors: computed,
isValid: computed,
setActiveRoute: action, setActiveRoute: action,
setActiveFile: action, setActiveFile: action,
addFile: action, addFile: action,
@@ -329,6 +348,9 @@ export class Workspace extends EventTarget implements IWorkspace {
* @param fileType 模块类型 * @param fileType 模块类型
*/ */
addFile(filename: string, code: string, fileType?: FileType) { addFile(filename: string, code: string, fileType?: FileType) {
if (!fileType && filename === this.entry) {
fileType = FileType.AppEntryModule;
}
const moduleType = fileType || inferFileType(filename); const moduleType = fileType || inferFileType(filename);
const props = { const props = {
filename, filename,
@@ -338,6 +360,10 @@ export class Workspace extends EventTarget implements IWorkspace {
let module; let module;
switch (moduleType) { switch (moduleType) {
case FileType.AppEntryModule:
module = new AppEntryModule(this, props);
this.appEntryModule = module;
break;
case FileType.StoreEntryModule: case FileType.StoreEntryModule:
module = new TangoStoreEntryModule(this, props); module = new TangoStoreEntryModule(this, props);
this.storeEntryModule = module; 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); const file = this.getFile(filename);
file.update(code); if (file instanceof TangoModule) {
if (shouldFormatCode && file instanceof TangoViewModule) { file.update(code, isSyncAst);
} else {
file.update(code);
}
const shouldFormat = this.projectConfig?.designerConfig?.autoFormatCode;
if (shouldFormat && file instanceof TangoViewModule) {
file.removeUnusedImportSpecifiers().update(); file.removeUnusedImportSpecifiers().update();
} }
this.history.push({ this.history.push({
@@ -439,12 +471,15 @@ export class Workspace extends EventTarget implements IWorkspace {
}); });
} }
/** syncFiles() {
* 删除工作区的文件 this.files.forEach((file) => {
* @param filename if (file instanceof TangoModule) {
*/ file.updateAst();
}
});
}
removeFile(filename: string) { removeFile(filename: string) {
// TODO: refactor visitFile to share this logic
if (this.files.get(filename)) { if (this.files.get(filename)) {
// 如果是文件,直接删除 // 如果是文件,直接删除
this.files.delete(filename); this.files.delete(filename);
@@ -500,7 +535,7 @@ export class Workspace extends EventTarget implements IWorkspace {
* @returns { [filename]: fileCode } * @returns { [filename]: fileCode }
*/ */
listFiles() { listFiles() {
const ret = {}; const ret: Dict<string> = {};
this.files.forEach((file) => { this.files.forEach((file) => {
ret[file.filename] = file.cleanCode; ret[file.filename] = file.cleanCode;
}); });
@@ -728,6 +763,7 @@ export class Workspace extends EventTarget implements IWorkspace {
* 更新依赖,没有就添加 * 更新依赖,没有就添加
* @param name * @param name
* @param version * @param version
* FIXME: 参数3的设置需要重新考虑下
*/ */
updateDependency( updateDependency(
name: string, name: string,
@@ -750,15 +786,12 @@ export class Workspace extends EventTarget implements IWorkspace {
if (!packages) { if (!packages) {
return undefined; return undefined;
} }
if (options?.package || packages[name]) {
packages[name] = { setValue(packages, name, {
type: packages[name]?.type, ...packages[name], // 保留原有的配置
// 如果没有传入 package 信息,则沿用 tango.config.json 中已记录的数据 version, // 更新版本号
// 如果传入了,则全量使用传入的信息,适配可能在某个版本中如 resources 等字段被删除的情况 ...options?.package, // 更新 package 配置
...(options?.package || packages[name]), });
version,
};
}
return packages; return packages;
}) })
+6
View File
@@ -8,6 +8,7 @@ export type SimulatorMode = 'desktop' | 'tablet' | 'phone';
export enum FileType { export enum FileType {
// js 文件 // js 文件
Module = 'module', Module = 'module',
AppEntryModule = 'appEntryModule',
StoreEntryModule = 'storeEntryModule', StoreEntryModule = 'storeEntryModule',
RouteModule = 'routeModule', RouteModule = 'routeModule',
ServiceModule = 'serviceModule', ServiceModule = 'serviceModule',
@@ -56,6 +57,11 @@ export interface IFileConfig {
type?: FileType; type?: FileType;
} }
export interface IFileError {
filename: string;
message: string;
}
/** /**
* 视图节点数据类型 * 视图节点数据类型
*/ */
+59
View File
@@ -3,6 +3,65 @@
All notable changes to this project will be documented in this file. All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
# [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) # [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 ### Bug Fixes
+7 -7
View File
@@ -1,6 +1,6 @@
{ {
"name": "@music163/tango-designer", "name": "@music163/tango-designer",
"version": "1.2.0", "version": "1.4.0",
"description": "lowcode designer", "description": "lowcode designer",
"keywords": [ "keywords": [
"react" "react"
@@ -33,12 +33,12 @@
"dependencies": { "dependencies": {
"@ant-design/icons": "^4.8.0", "@ant-design/icons": "^4.8.0",
"@music163/request": "^0.2.0", "@music163/request": "^0.2.0",
"@music163/tango-context": "^1.1.1", "@music163/tango-context": "^1.1.6",
"@music163/tango-core": "^1.2.0", "@music163/tango-core": "^1.4.0",
"@music163/tango-helpers": "^1.1.1", "@music163/tango-helpers": "^1.2.1",
"@music163/tango-sandbox": "^1.0.4", "@music163/tango-sandbox": "^1.0.9",
"@music163/tango-setting-form": "^1.2.1", "@music163/tango-setting-form": "^1.2.9",
"@music163/tango-ui": "^1.2.0", "@music163/tango-ui": "^1.4.0",
"antd": "^4.24.2", "antd": "^4.24.2",
"cash-dom": "^8.1.2", "cash-dom": "^8.1.2",
"classnames": "^2.5.1", "classnames": "^2.5.1",
@@ -125,6 +125,8 @@ export const ComponentsPopover = observer(
} }
footer={tipsTextMap[type]} footer={tipsTextMap[type]}
width="330px" width="330px"
height="450px"
resizeable
maskClosable maskClosable
body={ body={
<ComponentsPanel <ComponentsPanel
@@ -133,10 +135,6 @@ export const ComponentsPopover = observer(
menuData={menuData} menuData={menuData}
layout={layout} layout={layout}
onItemSelect={handleSelect} onItemSelect={handleSelect}
style={{
maxHeight: '400px',
overflow: 'auto',
}}
/> />
} }
{...popoverProps} {...popoverProps}
@@ -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,68 @@
import React, { useState } from 'react';
import { Box, css } from 'coral-system';
import { observer, useWorkspace } from '@music163/tango-context';
import { CloseOutlined } from '@ant-design/icons';
const errorMessageStyle = css`
padding: 24px;
white-space: pre-wrap;
`;
/**
* 文件错误提示浮层
*/
export const FileErrorsOverlay = observer(() => {
const [isVisible, setIsVisible] = useState<boolean>(true);
const workspace = useWorkspace();
const handleClose = () => {
setIsVisible(false);
};
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="rgba(244, 244, 244, 0.9)"
color="red"
zIndex={1999}
>
<Box position="relative" p="4">
<CloseOutlined
style={{
position: 'absolute',
top: 12,
right: 12,
color: '#000',
}}
onClick={handleClose}
/>
<Box css={errorMessageStyle}>
<Box fontSize="20px" mb="l">
</Box>
{workspace.fileErrors.map((fileError) => (
<Box key={fileError.filename} borderBottom="solid" borderBottomColor="line2" py="l">
<Box fontWeight="bold">{fileError.filename}</Box>
<Box as="code" display="block">
{fileError.message}
</Box>
</Box>
))}
</Box>
</Box>
</Box>
);
});
@@ -1,5 +1,7 @@
export * from './context-menu';
export * from './drag-box'; export * from './drag-box';
export * from './input-kv'; export * from './input-kv';
export * from './variable-tree'; export * from './variable-tree';
export * from './variable-tree-modal'; export * from './variable-tree-modal';
export * from './components-popover'; 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 { InputCode } from '@music163/tango-ui';
import { Button, Dropdown, Form, FormProps, Input, Select, Space } from 'antd'; import { Button, Dropdown, Form, FormProps, Input, Select, Space } from 'antd';
import { Box } from 'coral-system'; import { Box } from 'coral-system';
import React, { useState } from 'react'; import React, { useState } from 'react';
interface AddServiceFormProps extends FormProps { interface AddServiceFormProps extends FormProps {
initialValues?: object; initialValues?: Dict;
onSubmit: (values: object) => void; onSubmit: (values: object) => void;
onCancel: () => void; onCancel: () => void;
serviceModules: object[]; serviceModules: object[];
@@ -166,7 +166,7 @@ export function VariableTree(props: VariableTreeProps) {
return ( return (
<Box display="flex" columnGap="l" className="VariableTree" css={varTreeStyle} {...rest}> <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)} {renderHeaderExtra?.(props, state)}
<Box mb="m" position="sticky" top="0" bg="white" zIndex={2}> <Box mb="m" position="sticky" top="0" bg="white" zIndex={2}>
<Search placeholder="请输入变量名" onChange={(val) => setKeyword(val?.trim())} /> <Search placeholder="请输入变量名" onChange={(val) => setKeyword(val?.trim())} />
@@ -203,7 +203,11 @@ export function VariableTree(props: VariableTreeProps) {
<Box flex="0 0 72px" textAlign="right"> <Box flex="0 0 72px" textAlign="right">
{node.showRemoveButton && ( {node.showRemoveButton && (
<Popconfirm <Popconfirm
zIndex={99999}
title={`确认删除吗 ${node.title}?该操作会导致引用此模型的代码报错,请谨慎操作!`} title={`确认删除吗 ${node.title}?该操作会导致引用此模型的代码报错,请谨慎操作!`}
onCancel={(e) => {
e.stopPropagation();
}}
onConfirm={(e) => { onConfirm={(e) => {
e.stopPropagation(); e.stopPropagation();
if (isStoreVariablePath(node.key)) { 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> </ValueDetail>
@@ -84,6 +84,8 @@ export function ValueDefine({ data, onSave = noop }: ValueDefineProps) {
onClick={() => { onClick={() => {
off(); off();
setError(''); 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; sandboxQuery: DndQuery;
/**
* 预览沙箱查询实例
*/
previewSandboxQuery: DndQuery;
/** /**
* 远程服务 * 远程服务
*/ */
remoteServices?: Record<string, S>; remoteServices: Record<string, S>;
} }
const [DesignerProvider, useDesigner] = createContext<IDesignerContext>({ const [DesignerProvider, useDesigner] = createContext<IDesignerContext>({
@@ -19,9 +23,13 @@ const [DesignerProvider, useDesigner] = createContext<IDesignerContext>({
export { DesignerProvider }; export { DesignerProvider };
export const useSandboxQuery = () => { export const useSandboxQuery = () => {
return useDesigner()?.sandboxQuery; return useDesigner().sandboxQuery;
};
export const usePreviewSandboxQuery = () => {
return useDesigner().previewSandboxQuery;
}; };
export const useRemoteServices = () => { 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 zhCN from 'antd/lib/locale/zh_CN';
import { DesignerProvider, IDesignerContext } from './context'; import { DesignerProvider, IDesignerContext } from './context';
import defaultTheme from './themes/default'; 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 * @returns
*/ */
export function Designer(props: DesignerProps) { 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]); const theme = useMemo(() => extendTheme(themeProp, defaultTheme), [themeProp]);
return ( return (
<SystemProvider theme={theme} prefix="--tango"> <SystemProvider theme={theme} prefix="--tango">
<ConfigProvider locale={zhCN}> <ConfigProvider locale={zhCN}>
<TangoEngineProvider value={{ engine, config }}> <TangoEngineProvider value={{ engine, config }}>
<DesignerProvider value={{ sandboxQuery, remoteServices }}>{children}</DesignerProvider> <DesignerProvider value={{ sandboxQuery, previewSandboxQuery, remoteServices }}>
{children}
</DesignerProvider>
</TangoEngineProvider> </TangoEngineProvider>
</ConfigProvider> </ConfigProvider>
</SystemProvider> </SystemProvider>
+6 -1
View File
@@ -12,7 +12,6 @@ export const DRAGGABLE_SELECTOR = `[${SLOT.dnd}]`;
interface DndQueryOptions { interface DndQueryOptions {
/** /**
* DOM 查询上下文选择器 * DOM 查询上下文选择器
* TODO: 是不是可以合并成一个 API
*/ */
context?: string; context?: string;
/** /**
@@ -63,6 +62,9 @@ export class DndQuery {
return false; return false;
} }
/**
* 沙箱内的 window 对象
*/
get window() { get window() {
if (this.context && 'defaultView' in this.context) { if (this.context && 'defaultView' in this.context) {
return (this.context as unknown as Document).defaultView; return (this.context as unknown as Document).defaultView;
@@ -71,6 +73,9 @@ export class DndQuery {
return window; return window;
} }
/**
* 沙箱内的全局滚动偏移
*/
get scrollTop() { get scrollTop() {
if (this.context && 'documentElement' in this.context) { if (this.context && 'documentElement' in this.context) {
return (this.context as unknown as Document).documentElement.scrollTop; 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 { export class Hotkey {
private readonly hotkeyMap = {}; private readonly hotkeyMap: Dict = {};
constructor(hotkeys: Record<string, Function>) { constructor(hotkeys: Record<string, Function>) {
Object.keys(hotkeys).forEach((hotkey) => { Object.keys(hotkeys).forEach((hotkey) => {
+59 -1
View File
@@ -77,6 +77,9 @@ export function useDnd({
if (designer.isPreview) { if (designer.isPreview) {
return; return;
} }
if (designer.showContextMenu) {
designer.toggleContextMenu(false);
}
const point = sandboxQuery.getRelativePoint({ x: e.clientX, y: e.clientY }); const point = sandboxQuery.getRelativePoint({ x: e.clientX, y: e.clientY });
selectSource.setStart({ selectSource.setStart({
@@ -128,6 +131,9 @@ export function useDnd({
}; };
const onClick = (e: React.MouseEvent) => { const onClick = (e: React.MouseEvent) => {
if (designer.showContextMenu) {
designer.toggleContextMenu(false);
}
const data = sandboxQuery.getDraggableParentsData(e.target as HTMLElement, true); const data = sandboxQuery.getDraggableParentsData(e.target as HTMLElement, true);
if (data && data.id) { if (data && data.id) {
selectSource.select(data); selectSource.select(data);
@@ -380,7 +386,8 @@ export function useDnd({
}; };
const onKeyDown = (e: React.KeyboardEvent) => { 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) { if (!isInputElement) {
const key = getHotkey(e); const key = getHotkey(e);
@@ -388,6 +395,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 onTango = (e: CustomEvent) => {
const detail = e.detail || {}; const detail = e.detail || {};
@@ -437,6 +494,7 @@ export function useDnd({
onDragEnd, onDragEnd,
onScroll, onScroll,
onKeyDown, onKeyDown,
onContextMenu,
onTango, onTango,
...selectHandler, ...selectHandler,
}; };
+79 -109
View File
@@ -2,8 +2,6 @@ import React, { useRef, useEffect, useCallback } from 'react';
import { Box } from 'coral-system'; import { Box } from 'coral-system';
import { MultiEditor, MultiEditorProps } from '@music163/tango-ui'; import { MultiEditor, MultiEditorProps } from '@music163/tango-ui';
import { observer, useDesigner, useWorkspace } from '@music163/tango-context'; import { observer, useDesigner, useWorkspace } from '@music163/tango-context';
import { isValidCode } from '@music163/tango-core';
import { Modal } from 'antd';
const ideConfig = { const ideConfig = {
// disableFileOps: { // disableFileOps: {
@@ -21,116 +19,88 @@ const ideConfig = {
// disableSetting: true, // disableSetting: true,
}; };
export interface CodeEditorProps extends Partial<MultiEditorProps> { export type CodeEditorProps = Partial<MultiEditorProps>;
/**
* 是否自动清楚未使用的导入
*/
autoRemoveUnusedImports?: boolean;
}
export const CodeEditor = observer( export const CodeEditor = observer((props: CodeEditorProps) => {
({ autoRemoveUnusedImports = true, ...rest }: CodeEditorProps) => { const editorRef = useRef(null);
const editorRef = useRef(null); const workspace = useWorkspace();
const workspace = useWorkspace(); const designer = useDesigner();
const designer = useDesigner(); const files = workspace.listFiles();
const files = workspace.listFiles(); const activeFile = workspace.activeFile;
const activeFile = workspace.activeFile;
let loc: any; // 记录视图代码的选中位置 let loc: any; // 记录视图代码的选中位置
const selectNode = workspace.selectSource.firstNode; const selectNode = workspace.selectSource.firstNode;
if (selectNode && activeFile === workspace.activeViewFile) { if (selectNode && activeFile === workspace.activeViewFile) {
loc = selectNode.loc; loc = selectNode.loc;
} }
useEffect(() => { useEffect(() => {
editorRef.current?.refresh(files, activeFile, loc); editorRef.current?.refresh(files, activeFile, loc);
}, [files, activeFile, loc]); }, [files, activeFile, loc]);
const fileSave = useCallback( const fileSave = useCallback(
(path: string, value: string) => { (path: string, value: string) => {
if (!isJsFile(path)) { workspace.updateFile(path, value, false);
// 非 js 文件直接保存 },
workspace.updateFile(path, value, autoRemoveUnusedImports); [workspace],
return; );
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)',
} }
: {};
// js 文件需要先检查语法,只有语法正确才会保存 return (
if (isValidCode(value)) { <Box display="flex" flexDirection="row" height="100%" bg="white" {...borderStyle}>
workspace.updateFile(path, value, autoRemoveUnusedImports); <MultiEditor
} else { ref={editorRef}
Modal.confirm({ options={{
title: '检测到代码中存在语法错误,暂时无法将代码同步给设计器,是否回退到安全代码?', fontSize: 14,
onOk: () => { automaticLayout: true,
editorRef.current?.refresh(files, activeFile); }}
}, ideConfig={ideConfig}
onCancel: () => {}, onFileSave={fileSave}
}); onPathChange={handlePathChange}
} onFileChange={handleFileChange}
}, defaultPath={activeFile}
[workspace, autoRemoveUnusedImports, activeFile, files], defaultTheme="GithubLightDefault"
); defaultFiles={files}
{...props}
const handleFileChange = useCallback( />
(type: string, info: any) => { </Box>
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)',
}
: {};
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}
{...rest}
/>
</Box>
);
},
);
function isJsFile(path: string) {
return /.jsx?$/.test(path);
}
+14 -2
View File
@@ -7,6 +7,20 @@ import {
parseDndId, parseDndId,
} from '@music163/tango-helpers'; } 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) { export function buildQueryBySlotId(id: string) {
return `[${SLOT.dnd}="${id}"]`; return `[${SLOT.dnd}="${id}"]`;
} }
@@ -15,8 +29,6 @@ export function getElement(selector: Selector) {
return $(selector).get(0); return $(selector).get(0);
} }
export const DRAG_GHOST_ID = 'dragGhost';
export const getDragGhostElement = () => getElement(`#${DRAG_GHOST_ID}`); export const getDragGhostElement = () => getElement(`#${DRAG_GHOST_ID}`);
export function setElementStyle(selector: Selector, style: any) { 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 React, { useImperativeHandle, ForwardedRef, useRef, useState, useEffect } from 'react';
import { Box } from 'coral-system'; import { Box } from 'coral-system';
import { CodeSandbox, CodeSandboxProps } from '@music163/tango-sandbox'; 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 { observer, useWorkspace, useDesigner } from '@music163/tango-context';
import { Simulator, Viewport } from '../simulator'; import { Simulator, Viewport } from '../simulator';
import { useSandboxQuery } from '../context'; import { useSandboxQuery } from '../context';
import { DndQuery, useDnd } from '../dnd'; import { DndQuery, useDnd } from '../dnd';
import { Navigator } from './navigator'; import { Navigator } from './navigator';
import { SelectionToolsProps } from '../simulator/selection'; import { SelectionToolsProps } from '../simulator/selection';
import { DESIGN_SANDBOX_ID, PREVIEW_SANDBOX_ID } from '../helpers';
interface ISandboxEventHandlerConfig { interface ISandboxEventHandlerConfig {
sandboxQuery?: DndQuery; sandboxQuery?: DndQuery;
@@ -48,6 +49,10 @@ export interface CombinedSandboxRef {
const LANDING_PAGE_PATH = '/__background_landing_page__'; const LANDING_PAGE_PATH = '/__background_landing_page__';
function fixRouterMode(routerType: string): CodeSandboxProps['routerMode'] {
return routerType === 'hash' ? 'hash' : undefined;
}
function useSandbox({ function useSandbox({
isPreview: isPreviewProp, isPreview: isPreviewProp,
configFormatter, configFormatter,
@@ -62,6 +67,7 @@ function useSandbox({
const workspace = useWorkspace(); const workspace = useWorkspace();
const designer = useDesigner(); const designer = useDesigner();
const sandboxQuery = useSandboxQuery(); const sandboxQuery = useSandboxQuery();
const isPreview = isPreviewProp ?? designer.isPreview; const isPreview = isPreviewProp ?? designer.isPreview;
// 组件不一定会立即刷新,因此 isActive 需要实时获取 // 组件不一定会立即刷新,因此 isActive 需要实时获取
@@ -82,7 +88,7 @@ function useSandbox({
onViewChange: (data) => onViewChange && onViewChange(data, getSandboxConfig()), 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; let code = workspace.getFile(filename).code;
if (filename === '/tango.config.json') { if (filename === '/tango.config.json') {
code = mergeTangoConfigJson(code, { isPreview, injectScript, formatter: configFormatter }); code = mergeTangoConfigJson(code, { isPreview, injectScript, formatter: configFormatter });
@@ -103,23 +109,26 @@ function useSandbox({
// 根据当前 workspace 状态与组件传入的状态是否一致,控制是否需要切换到空白路由 // 根据当前 workspace 状态与组件传入的状态是否一致,控制是否需要切换到空白路由
const display = isActive ? 'block' : 'none'; const display = isActive ? 'block' : 'none';
const routePath = isActive ? startRoute || workspace.activeRoute : LANDING_PAGE_PATH; const routePath = isActive ? startRoute || workspace.activeRoute : LANDING_PAGE_PATH;
const routerMode = fixRouterMode(workspace.appEntryModule?.routerType);
const sandboxProps = isPreview const sandboxProps = isPreview
? { ? {
files, files,
eventHandlers: pick(dndHandlers, ['onTango']), eventHandlers: pick(dndHandlers, ['onTango']),
onMessage, onMessage,
onLoad,
display, display,
startRoute: routePath, startRoute: routePath,
onLoad, routerMode,
} }
: { : {
files, files,
eventHandlers: dndHandlers as any, eventHandlers: dndHandlers as any,
onMessage, onMessage,
onLoad,
display, display,
startRoute: routePath, startRoute: routePath,
onLoad, routerMode,
}; };
return sandboxProps; return sandboxProps;
@@ -140,7 +149,7 @@ const PreviewSandbox = observer(
return ( return (
<Box display={display} width="100%" height="100%"> <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> </Box>
); );
}, },
@@ -188,7 +197,7 @@ const DesignSandbox = observer(
return ( return (
<Box display={display} width="100%" height="100%"> <Box display={display} width="100%" height="100%">
<CodeSandbox ref={ref} {...sandboxProps} {...rest} /> <CodeSandbox ref={ref} iframeId={DESIGN_SANDBOX_ID} {...sandboxProps} {...rest} />
</Box> </Box>
); );
}, },
@@ -1,4 +1,5 @@
export * from './copy-node'; export * from './copy-node';
export * from './delete-node'; export * from './delete-node';
export * from './more-actions';
export * from './select-parent-node'; export * from './select-parent-node';
export * from './view-source'; 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>
);
});
@@ -4,7 +4,7 @@ import { AutoComplete } from 'antd';
import { ActionSelect } from '@music163/tango-ui'; import { ActionSelect } from '@music163/tango-ui';
import { FormItemComponentProps } from '@music163/tango-setting-form'; import { FormItemComponentProps } from '@music163/tango-setting-form';
import { useWorkspace, useWorkspaceData } from '@music163/tango-context'; import { useWorkspace, useWorkspaceData } from '@music163/tango-context';
import { wrapCode } from '@music163/tango-helpers'; import { Dict, wrapCode } from '@music163/tango-helpers';
import { ExpressionPopover } from './expression-setter'; import { ExpressionPopover } from './expression-setter';
import { value2code } from '@music163/tango-core'; import { value2code } from '@music163/tango-core';
@@ -141,7 +141,7 @@ export function EventSetter(props: EventSetterProps) {
); );
} }
const handlerMap = { const handlerMap: Dict = {
[EventAction.OpenModal]: 'openModal', [EventAction.OpenModal]: 'openModal',
[EventAction.CloseModal]: 'closeModal', [EventAction.CloseModal]: 'closeModal',
[EventAction.NavigateTo]: 'navigateTo', [EventAction.NavigateTo]: 'navigateTo',
@@ -3,8 +3,8 @@ import { Box, Text, css } from 'coral-system';
import { Dropdown, Button } from 'antd'; import { Dropdown, Button } from 'antd';
import { isValidExpressionCode } from '@music163/tango-core'; import { isValidExpressionCode } from '@music163/tango-core';
import { getValue, IVariableTreeNode, noop } from '@music163/tango-helpers'; import { getValue, IVariableTreeNode, noop } from '@music163/tango-helpers';
import { CloseCircleFilled, ExpandAltOutlined, MenuOutlined } from '@ant-design/icons'; import { CloseCircleFilled, MenuOutlined } from '@ant-design/icons';
import { Panel, InputCode, Action, DragPanel } from '@music163/tango-ui'; import { Panel, InputCode, Action, DragPanel, PopOutOutlined } from '@music163/tango-ui';
import { FormItemComponentProps } from '@music163/tango-setting-form'; import { FormItemComponentProps } from '@music163/tango-setting-form';
import { useWorkspace, useWorkspaceData } from '@music163/tango-context'; import { useWorkspace, useWorkspaceData } from '@music163/tango-context';
import { VariableTree } from '../components'; import { VariableTree } from '../components';
@@ -182,7 +182,7 @@ export function ExpressionPopover({
})); }));
const sandbox = useSandboxQuery(); const sandbox = useSandboxQuery();
const evaluateContext = sandbox.window; const evaluateContext: any = sandbox.window;
const handleExpInputChange = (val: string) => { const handleExpInputChange = (val: string) => {
setExp(val?.trim()); setExp(val?.trim());
@@ -195,56 +195,65 @@ export function ExpressionPopover({
return ( return (
<DragPanel <DragPanel
width={700} width={700}
title={`${selectNodePath}/${title} 设置为引用变量或自定义表达式`} height={615}
extra={subTitle} resizeable
title={`使用代码设置 ${selectNodePath} 组件的${title}`}
onOpenChange={(open) => { onOpenChange={(open) => {
if (!open) { if (!open) {
setExp(undefined); setExp(undefined);
setError(''); setError('');
} }
}} }}
popoverStyle={{
height: '615px',
}}
body={ body={
<> <Box display="flex" flexDirection="column">
<Panel shape="solid"> <Box p="m">
<InputCode <InputCode
shape="inset" shape="inset"
minHeight="56px" minHeight="56px"
maxHeight="200px" maxHeight="160px"
value={exp} value={exp}
placeholder={placeholder} placeholder={placeholder}
onChange={handleExpInputChange} onChange={handleExpInputChange}
onBlur={() => { onBlur={() => {
setError(expressionValueValidate(exp)); if (exp) {
setError(expressionValueValidate(exp));
}
}} }}
autoCompleteContext={evaluateContext} autoCompleteContext={evaluateContext}
autoCompleteOptions={autoCompleteOptions} autoCompleteOptions={autoCompleteOptions}
/> />
{error ? ( {error ? (
<Text color="red" fontSize="12px"> <Text color="red" fontSize="12px" as="p">
</Text> </Text>
) : ( ) : null}
<Text fontSize="12px" color="text3"> {subTitle && (
javascript 使 jsx <Text fontSize="12px" color="text3" as="p">
{subTitle}
</Text> </Text>
)} )}
</Panel> <Text fontSize="12px" color="text3" as="p">
javascript 使 jsx
</Text>
</Box>
<Panel <Panel
title="从变量列表中选中" title="从变量列表中选中"
shape="solid" shape="solid"
borderTop="0" borderLeft="0"
overflow="hidden" borderRight="0"
bodyProps={{ overflow: 'hidden' }} flex={1}
bodyProps={{
style: {
overflow: 'hidden',
},
}}
> >
<VariableTree <VariableTree
height={380} height="100%"
showViewButton showViewButton
dataSource={dataSource || expressionVariables} dataSource={dataSource || expressionVariables}
appContext={sandbox?.window['tango']} appContext={evaluateContext['tango']}
getStoreNames={() => Object.keys(workspace.storeModules)} getStoreNames={() => Object.keys(workspace.storeModules)}
serviceModules={serviceModules} serviceModules={serviceModules}
getServiceData={(serviceKey) => { getServiceData={(serviceKey) => {
@@ -307,10 +316,10 @@ export function ExpressionPopover({
}} }}
/> />
</Panel> </Panel>
</> </Box>
} }
footer={(close) => ( footer={(close) => (
<Box display="flex" justifyContent="flex-end" gap="5px"> <Box display="flex" width="100%" justifyContent="flex-end" gap="5px">
<Button <Button
type="primary" type="primary"
size="small" size="small"
@@ -330,7 +339,12 @@ export function ExpressionPopover({
)} )}
> >
{children || ( {children || (
<Action tooltip="打开表达式变量选择面板" icon={<ExpandAltOutlined />} size="small" /> <Action
tooltip="弹出代码编辑和变量选择面板"
tooltipProps={{ placement: 'topLeft' }}
icon={<PopOutOutlined />}
size="small"
/>
)} )}
</DragPanel> </DragPanel>
); );
@@ -3,10 +3,11 @@ import { css, Box } from 'coral-system';
import { Form, Input, Button, Popover } from 'antd'; import { Form, Input, Button, Popover } from 'antd';
import { DeleteOutlined, EditOutlined, HolderOutlined } from '@ant-design/icons'; import { DeleteOutlined, EditOutlined, HolderOutlined } from '@ant-design/icons';
import { FormItemComponentProps } from '@music163/tango-setting-form'; import { FormItemComponentProps } from '@music163/tango-setting-form';
import { Dict } from '@music163/tango-helpers';
import { DragBox } from '../components'; import { DragBox } from '../components';
function copyWithoutUndefined(source: Record<string, any>) { function copyWithoutUndefined(source: Dict) {
const ret = {}; const ret: Dict = {};
for (const key in source) { for (const key in source) {
if (source[key] !== undefined) { if (source[key] !== undefined) {
ret[key] = source[key]; ret[key] = source[key];
@@ -60,7 +60,7 @@ export function ModelSetter({
}: FormItemComponentProps) { }: FormItemComponentProps) {
const [inputValue, setInputValue] = useState(value); const [inputValue, setInputValue] = useState(value);
const { modelVariables } = useWorkspaceData(); const { modelVariables } = useWorkspaceData();
const evaluateContext = useSandboxQuery().window || {}; const evaluateContext: any = useSandboxQuery().window || {};
const workspace = useWorkspace(); const workspace = useWorkspace();
const definedVariables = useMemo(() => { const definedVariables = useMemo(() => {
const list: string[] = []; const list: string[] = [];
@@ -2,6 +2,7 @@ import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { ActionSelect, InputCode } from '@music163/tango-ui'; import { ActionSelect, InputCode } from '@music163/tango-ui';
import { FormItemComponentProps } from '@music163/tango-setting-form'; import { FormItemComponentProps } from '@music163/tango-setting-form';
import { Box } from 'coral-system'; import { Box } from 'coral-system';
import { Dict } from '@music163/tango-helpers';
interface IRenderOption { interface IRenderOption {
label: string; label: string;
@@ -37,7 +38,7 @@ export function RenderSetter({
}, [value]); }, [value]);
const optionsMap = useMemo(() => { const optionsMap = useMemo(() => {
return options.reduce((prev, cur) => { return options.reduce<Dict>((prev, cur) => {
prev[cur.value] = cur; prev[cur.value] = cur;
return prev; return prev;
}, {}); }, {});
@@ -1,11 +1,17 @@
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } from 'react';
import { Box } from 'coral-system'; import { Box } from 'coral-system';
import { Input, Radio } from 'antd'; 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 { FormItemComponentProps } from '@music163/tango-setting-form';
import { useWorkspaceData } from '@music163/tango-context'; import { useWorkspaceData } from '@music163/tango-context';
import { PickerSetter } from './picker-setter'; import { PickerSetter } from './picker-setter';
const routerModeMap: Dict = {
link: '链接',
router: '路由',
both: '',
};
export function RouterSetter(props: FormItemComponentProps) { export function RouterSetter(props: FormItemComponentProps) {
const [type, setType] = useState<'input' | 'select'>(() => { const [type, setType] = useState<'input' | 'select'>(() => {
return isValidUrl(props.value) ? 'input' : 'select'; return isValidUrl(props.value) ? 'input' : 'select';
@@ -37,7 +43,7 @@ export function RouterSetter(props: FormItemComponentProps) {
)} )}
{type === 'input' && ( {type === 'input' && (
<Input <Input
placeholder={`请输入任意${{ link: '链接', router: '路由', both: '' }[displayType]}地址`} placeholder={`请输入任意${routerModeMap[displayType]}地址`}
{...props} {...props}
value={input} value={input}
onChange={(e) => setInput(e.target.value)} onChange={(e) => setInput(e.target.value)}
+2 -2
View File
@@ -2,7 +2,7 @@ import React from 'react';
import { Box } from 'coral-system'; import { Box } from 'coral-system';
import { SettingForm, FormModel, SettingFormProps } from '@music163/tango-setting-form'; import { SettingForm, FormModel, SettingFormProps } from '@music163/tango-setting-form';
import { Panel } from '@music163/tango-ui'; 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 { observer, useDesigner, useWorkspace } from '@music163/tango-context';
import { registerBuiltinSetters } from './setters'; import { registerBuiltinSetters } from './setters';
@@ -34,7 +34,7 @@ export const SettingPanel = observer((props: SettingPanelProps) => {
} }
const getSettingValue = (attributes: Record<string, string>) => { const getSettingValue = (attributes: Record<string, string>) => {
const ret = {}; const ret: Dict = {};
const keys = Object.keys(attributes); const keys = Object.keys(attributes);
for (const key of keys) { for (const key of keys) {
if (/^data-/.test(key)) { if (/^data-/.test(key)) {
@@ -2,6 +2,7 @@ import React, { useMemo, useState } from 'react';
import { Box, Grid, Text } from 'coral-system'; import { Box, Grid, Text } from 'coral-system';
import styled, { css } from 'styled-components'; import styled, { css } from 'styled-components';
import { import {
Dict,
IComponentPrototype, IComponentPrototype,
MenuDataType, MenuDataType,
MenuValueType, MenuValueType,
@@ -66,7 +67,7 @@ export interface ComponentsPanelProps {
layout?: 'grid' | 'line'; layout?: 'grid' | 'line';
} }
const localeMap = { const localeMap: Dict = {
common: '基础组件', common: '基础组件',
atom: '原子组件', atom: '原子组件',
snippet: '组合', snippet: '组合',
@@ -124,7 +125,7 @@ export const ComponentsPanel = observer(
const tabs = Object.keys(menuData).map((key) => ({ const tabs = Object.keys(menuData).map((key) => ({
key, key,
label: localeMap[key], label: localeMap[key],
children: <MaterialList data={menuData[key]} />, children: <MaterialList data={(menuData as any)[key]} />,
})); }));
if (showBizComps) { if (showBizComps) {
@@ -289,6 +290,10 @@ const StyledCommonGridItem = styled.div`
transition: 0.15s ease-in-out; transition: 0.15s ease-in-out;
transition-property: transform; transition-property: transform;
will-change: transform; will-change: transform;
img {
width: unset;
height: 85%;
}
} }
.info { .info {
@@ -355,6 +360,15 @@ function MaterialGrid({ data }: MaterialProps) {
}; };
const icon = data.icon || 'icon-placeholder'; 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} />
</Box>
);
if (isLine) { if (isLine) {
return ( return (
<Box <Box
@@ -380,11 +394,7 @@ function MaterialGrid({ data }: MaterialProps) {
alignItems="center" alignItems="center"
justifyContent="center" justifyContent="center"
> >
{icon.startsWith('icon-') ? ( {iconNode}
<IconFont className="material-icon" type={data.icon || 'icon-placeholder'} />
) : (
<img className="material-icon" src={icon} alt={data.name} />
)}
</Box> </Box>
<Box flex={1}> <Box flex={1}>
<Box fontWeight="500" display="flex" justifyContent="space-between"> <Box fontWeight="500" display="flex" justifyContent="space-between">
@@ -417,11 +427,7 @@ function MaterialGrid({ data }: MaterialProps) {
onDragEnd={handleDragEnd} onDragEnd={handleDragEnd}
onClick={handleSelect} onClick={handleSelect}
> >
{icon.startsWith('icon-') ? ( {iconNode}
<IconFont className="material-icon" type={data.icon || 'icon-placeholder'} />
) : (
<img className="material-icon" src={icon} alt={data.name} />
)}
<Text fontSize="12px" marginTop="4px"> <Text fontSize="12px" marginTop="4px">
{data.title ?? data.name} {data.title ?? data.name}
</Text> </Text>
@@ -24,7 +24,7 @@ const DataSourceView = observer(() => {
<Box className="ServiceFunctionList" p="m"> <Box className="ServiceFunctionList" p="m">
<VariableTree <VariableTree
dataSource={serviceVariables} dataSource={serviceVariables}
appContext={sandbox?.window['tango']} appContext={(sandbox?.window as any)['tango']}
serviceModules={serviceModules} serviceModules={serviceModules}
onRemoveService={(variableKey) => { onRemoveService={(variableKey) => {
workspace.removeServiceFunction(variableKey); workspace.removeServiceFunction(variableKey);
@@ -4,6 +4,7 @@ import { ConfigGroup, ConfigItem } from '@music163/tango-ui';
import { Box, css } from 'coral-system'; import { Box, css } from 'coral-system';
import { Input, Switch, Form, Button, message, FormProps } from 'antd'; import { Input, Switch, Form, Button, message, FormProps } from 'antd';
import { CloseCircleOutlined, CloseOutlined } from '@ant-design/icons'; import { CloseCircleOutlined, CloseOutlined } from '@ant-design/icons';
import { Dict } from '@music163/tango-helpers';
export default observer(() => { export default observer(() => {
const workspace = useWorkspace(); const workspace = useWorkspace();
@@ -63,7 +64,7 @@ function ProxyManage({
initialValues: initialValuesProp = {}, initialValues: initialValuesProp = {},
onSave, onSave,
}: { }: {
initialValues?: object; initialValues?: Dict;
onSave?: (values: any) => void; onSave?: (values: any) => void;
}) { }) {
const initialValues = useMemo(() => { const initialValues = useMemo(() => {
@@ -84,7 +85,7 @@ function ProxyManage({
{...proxyManageFormStyle} {...proxyManageFormStyle}
initialValues={initialValues} initialValues={initialValues}
onFinish={(values) => { 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; prev[path] = rest;
return prev; return prev;
}, {}); }, {});
@@ -68,17 +68,6 @@ export const DependencyPanel = observer(
[dependencies, baseDependencies, bizDependencies, packages, packageNames], [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( const baseDeps = useMemo(
() => () =>
@@ -8,6 +8,7 @@ import { DropMethod, ITangoViewNodeData } from '@music163/tango-core';
import { noop, parseDndId } from '@music163/tango-helpers'; import { noop, parseDndId } from '@music163/tango-helpers';
import { useSandboxQuery } from '../../context'; import { useSandboxQuery } from '../../context';
import { buildQueryBySlotId } from '../../helpers'; import { buildQueryBySlotId } from '../../helpers';
import { ContextMenu } from '../../components';
export interface ComponentsTreeProps { export interface ComponentsTreeProps {
/** /**
@@ -143,6 +144,18 @@ export const ComponentsTree: React.FC<ComponentsTreeProps> = observer(
const file = workspace.activeViewModule; const file = workspace.activeViewModule;
const nodesTree = (file?.nodesTree ?? []) as ITangoViewNodeData[]; const nodesTree = (file?.nodesTree ?? []) as ITangoViewNodeData[];
const [expandedKeys, setExpandedKeys] = useState(getNodeKeys(nodesTree)); 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(() => { useEffect(() => {
setSelectedKeys(workspace.selectSource.selected.map((item) => item.id)); setSelectedKeys(workspace.selectSource.selected.map((item) => item.id));
@@ -164,64 +177,83 @@ export const ComponentsTree: React.FC<ComponentsTreeProps> = observer(
return ( return (
<Box css={outlineStyle}> <Box css={outlineStyle}>
<Tree <Dropdown
selectedKeys={selectedKeys as string[]} placement="bottomLeft"
fieldNames={filedNames} trigger={['contextMenu']}
treeData={nodesTree as any[]} open={contextMenuOpen}
onSelect={(keys) => { onOpenChange={(val) => {
const slotKey = keys?.[0] as string; if (!val) {
const data = sandboxQuery.getDraggableParentsData(buildQueryBySlotId(slotKey), true); setContextMenuOpen(val);
if (data && data.id) {
workspace.selectSource.select(data);
} }
// export selected
onSelect(slotKey);
setSelectedKeys(keys);
}} }}
blockNode overlay={<ContextMenu onClick={() => setContextMenuOpen(false)} showParents={false} />}
expandedKeys={expandedKeys} >
onExpand={(keys) => setExpandedKeys(keys as string[])} <Tree
draggable selectedKeys={selectedKeys as string[]}
onDragStart={(data) => { fieldNames={filedNames}
const prototype = workspace.componentPrototypes.get(data.node.component); treeData={nodesTree as any[]}
if (!prototype) { onSelect={handleSelect}
return; blockNode
} expandedKeys={expandedKeys}
const { canDrag } = prototype.rules || {}; onExpand={(keys) => setExpandedKeys(keys as string[])}
if (canDrag && !canDrag()) { draggable
return; onDragStart={(data) => {
} const prototype = workspace.componentPrototypes.get(data.node.component);
workspace.dragSource.set({ if (!prototype) {
id: data.node.id, return;
name: data.node.component, }
}); const { canDrag } = prototype.rules || {};
}} if (canDrag && !canDrag()) {
onDrop={(data) => { return;
const dropKey = data.node.key as string; }
let method; workspace.dragSource.set({
if (data.dropToGap) { id: data.node.id,
// 插入节点的后面 name: data.node.component,
method = DropMethod.InsertAfter; });
} else { }}
// 作为第一个子节点 onDrop={(data) => {
method = DropMethod.InsertFirstChild; const dropKey = data.node.key as string;
} let method;
workspace.dragSource.dropTarget.set( if (data.dropToGap) {
{ // 插入节点的后面
id: dropKey, method = DropMethod.InsertAfter;
}, } else {
method, // 作为第一个子节点
); method = DropMethod.InsertFirstChild;
workspace.dropNode(); }
}} workspace.dragSource.dropTarget.set(
titleRender={(node) => ( {
<OutlineTreeNode id: dropKey,
actionItems={actionItems} },
showToggleVisibleIcon={showToggleVisibleIcon} method,
node={node} );
/> 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> </Box>
); );
}, },
@@ -1,12 +1,12 @@
import React, { useEffect, useReducer } from 'react'; import React, { useEffect, useReducer } from 'react';
import { observer } from '@music163/tango-context'; 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 { CollapsePanel, IconButton, JsonView } from '@music163/tango-ui';
import { ReloadOutlined } from '@ant-design/icons'; import { ReloadOutlined } from '@ant-design/icons';
import { useSandboxQuery } from '../../context'; import { useSandboxQuery } from '../../context';
function processTango(obj: any = {}, index = 0) { function processTango(obj: Dict = {}, index = 0) {
const ret = {}; const ret: Dict = {};
Object.keys(obj).forEach((key) => { Object.keys(obj).forEach((key) => {
const val = obj[key]; const val = obj[key];
if (index > 2) { if (index > 2) {
@@ -25,11 +25,12 @@ function processTango(obj: any = {}, index = 0) {
export const StateTree = observer(() => { export const StateTree = observer(() => {
const sandboxQuery = useSandboxQuery(); const sandboxQuery = useSandboxQuery();
const [, forceUpdate] = useReducer((x) => x + 1, 0); const [, forceUpdate] = useReducer((x) => x + 1, 0);
const tangoContext = pick(sandboxQuery.window['tango'] || {}, [ const tangoContext = pick((sandboxQuery.window as any)['tango'] || {}, [
'stores', 'stores',
'pageStore', 'pageStore',
'services', 'services',
'config', 'config',
'routeData',
]); ]);
const callback = () => { const callback = () => {
forceUpdate(); forceUpdate();
@@ -19,7 +19,7 @@ const resizeHandleStyle = (axis: ResizableBoxProps['axis'], barStyle: HTMLCoralP
cursor: ${axis === 'x' ? 'col-resize' : 'row-resize'}; cursor: ${axis === 'x' ? 'col-resize' : 'row-resize'};
${barStyle && ${barStyle &&
Object.keys(barStyle) Object.keys(barStyle)
.map((key) => `${key}: ${barStyle[key]};`) .map((key) => `${key}: ${(barStyle as any)[key]};`)
.join('')} .join('')}
&:hover, &:hover,
&:active { &:active {
+28 -18
View File
@@ -3,7 +3,7 @@ import cx from 'classnames';
import { Box, Text, css, HTMLCoralProps } from 'coral-system'; import { Box, Text, css, HTMLCoralProps } from 'coral-system';
import { Badge } from 'antd'; import { Badge } from 'antd';
import { ReactComponentProps } from '@music163/tango-helpers'; 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 { ResizableBox } from './resizable-box';
import { getWidget } from '../widgets'; import { getWidget } from '../widgets';
@@ -19,15 +19,22 @@ const sidebarStyle = css`
list-style: none; list-style: none;
user-select: none; user-select: none;
transition: all 0.3s ease; transition: all 0.3s ease;
&.disabled {
pointer-events: none;
}
} }
.SidebarPanelBarListItem { .SidebarPanelBarListItem {
color: var(--tango-colors-text2);
&.active { &.active {
background-color: var(--tango-colors-custom-sidebarItemActiveBg); color: var(--tango-colors-brand);
background-color: var(--tango-colors-custom-sidebarItemActiveBg, --tango-colors-fill2);
} }
&:hover { &:hover {
background-color: var(--tango-colors-custom-sidebarItemHoverBg); background-color: var(--tango-colors-custom-sidebarItemHoverBg, --tango-colors-fill2);
} }
} }
`; `;
@@ -76,6 +83,7 @@ export interface SidebarPanelItemProps
function BaseSidebarPanel({ panelWidth: defaultPanelWidth = 266, footer, children }: SidebarProps) { function BaseSidebarPanel({ panelWidth: defaultPanelWidth = 266, footer, children }: SidebarProps) {
const designer = useDesigner(); const designer = useDesigner();
const workspace = useWorkspace();
const items = useMemo(() => { const items = useMemo(() => {
const ret: Record<string, SidebarPanelItemProps> = {}; const ret: Record<string, SidebarPanelItemProps> = {};
@@ -92,10 +100,23 @@ function BaseSidebarPanel({ panelWidth: defaultPanelWidth = 266, footer, childre
return ret; return ret;
}, [children]); }, [children]);
if (designer.activeView !== 'design') {
return null;
}
return ( return (
<Box display="flex" flexShrink={0} css={sidebarStyle} className="SidebarPanel"> <Box display="flex" flexShrink={0} css={sidebarStyle} className="SidebarPanel">
<Box className="SidebarPanelBar" display="flex" flexDirection="column" position="relative"> <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) => { {Object.keys(items).map((key) => {
const item = items[key]; const item = items[key];
const isActive = key === designer.activeSidebarPanel; const isActive = key === designer.activeSidebarPanel;
@@ -112,7 +133,6 @@ function BaseSidebarPanel({ panelWidth: defaultPanelWidth = 266, footer, childre
icon={item.icon} icon={item.icon}
label={item.label} label={item.label}
showBadge={item.showBadge} showBadge={item.showBadge}
isActive={isActive}
/> />
</li> </li>
); );
@@ -183,10 +203,6 @@ BaseSidebarPanel.Item = function ({
export const Sidebar = observer(BaseSidebarPanel); export const Sidebar = observer(BaseSidebarPanel);
interface SidebarPanelBarItemProps { interface SidebarPanelBarItemProps {
/**
* 是否选中
*/
isActive?: boolean;
/** /**
* 侧边栏图标 * 侧边栏图标
*/ */
@@ -212,15 +228,9 @@ interface SidebarPanelBarItemProps {
}; };
} }
function SidebarPanelBarItem({ function SidebarPanelBarItem({ icon: iconProp, label, showBadge }: SidebarPanelBarItemProps) {
isActive,
icon: iconProp,
label,
showBadge,
}: SidebarPanelBarItemProps) {
const color = isActive ? 'brand' : 'text.body';
let icon = ( let icon = (
<Text fontSize="24px" lineHeight={1} color={color}> <Text fontSize="24px" lineHeight={1}>
{iconProp} {iconProp}
</Text> </Text>
); );
@@ -241,7 +251,7 @@ function SidebarPanelBarItem({
py="12px" py="12px"
> >
{icon} {icon}
<Text fontSize="12px" mt="s" color={color}> <Text fontSize="12px" mt="s">
{label} {label}
</Text> </Text>
</Box> </Box>
@@ -29,7 +29,7 @@ export const VariablePanel = observer(
</Button> </Button>
} }
bodyProps={{ p: 'm' }} bodyProps={{ p: 'm', height: '100%' }}
> >
{isAdd ? ( {isAdd ? (
<AddStoreForm <AddStoreForm
@@ -42,6 +42,7 @@ export const VariablePanel = observer(
/> />
) : ( ) : (
<VariableTree <VariableTree
height="100%"
defaultValueDetailMode="define" defaultValueDetailMode="define"
dataSource={storeVariables} dataSource={storeVariables}
onAddStoreVariable={(storeName, data) => { onAddStoreVariable={(storeName, data) => {
+22 -14
View File
@@ -25,7 +25,13 @@ export interface SelectionToolsProps {
export const SelectionTools = observer( export const SelectionTools = observer(
({ ({
actions: actionsProp = ['selectParentNode', 'viewSource', 'copyNode', 'deleteNode'], actions: actionsProp = [
'selectParentNode',
'viewSource',
'copyNode',
'deleteNode',
'moreActions',
],
}: SelectionToolsProps) => { }: SelectionToolsProps) => {
const workspace = useWorkspace(); const workspace = useWorkspace();
const selectSource = workspace.selectSource; const selectSource = workspace.selectSource;
@@ -149,18 +155,20 @@ function SelectionBox({ showActions, actions, data }: SelectionBoxProps) {
css={selectionBoxStyle} css={selectionBoxStyle}
style={style} style={style}
> >
<> {!isPage ? (
<ComponentsPopover type="before"> <>
<Tooltip title={`${selectedNodeName} 的前方添加兄弟节点`}> <ComponentsPopover type="before">
<SelectionHelper icon={<PlusOutlined />} css={topAddSiblingBtnStyle} /> <Tooltip title={`${selectedNodeName} 的前方添加兄弟节点`}>
</Tooltip> <SelectionHelper icon={<PlusOutlined />} css={topAddSiblingBtnStyle} />
</ComponentsPopover> </Tooltip>
<ComponentsPopover type="after"> </ComponentsPopover>
<Tooltip title={`${selectedNodeName} 的后方添加兄弟节点`}> <ComponentsPopover type="after">
<SelectionHelper icon={<PlusOutlined />} css={bottomAddSiblingBtnStyle} /> <Tooltip title={`${selectedNodeName} 的后方添加兄弟节点`}>
</Tooltip> <SelectionHelper icon={<PlusOutlined />} css={bottomAddSiblingBtnStyle} />
</ComponentsPopover> </Tooltip>
</> </ComponentsPopover>
</>
) : null}
{showActions && ( {showActions && (
<SelectionHelpers align={selectionHelpersAlign}> <SelectionHelpers align={selectionHelpersAlign}>
<SelectionHelper <SelectionHelper
@@ -198,7 +206,7 @@ function SelectionBox({ showActions, actions, data }: SelectionBoxProps) {
} }
/> />
<SelectionToolSet>{!isPage && actions}</SelectionToolSet> <SelectionToolSet>{!isPage && actions}</SelectionToolSet>
{prototype.hasChildren !== false && ( {isFromCurrentFile && prototype?.hasChildren && (
<ComponentsPopover> <ComponentsPopover>
<Tooltip title="快捷添加子元素"> <Tooltip title="快捷添加子元素">
<SelectionHelper icon={<PlusOutlined />} /> <SelectionHelper icon={<PlusOutlined />} />
+42 -1
View File
@@ -1,20 +1,61 @@
import React, { useEffect, useRef } from 'react'; import React, { useEffect, useRef } from 'react';
import cx from 'classnames'; import cx from 'classnames';
import { Box, HTMLCoralProps } from 'coral-system'; 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 { Ghost } from './ghost';
import { useSandboxQuery } from '../context'; import { useSandboxQuery } from '../context';
import { SelectionTools, SelectionToolsProps } from './selection'; import { SelectionTools, SelectionToolsProps } from './selection';
import { InsertionPrompt } from './insertion'; import { InsertionPrompt } from './insertion';
import { DraggingMask } from './mask'; import { DraggingMask } from './mask';
import { Dropdown, DropdownProps } from 'antd';
import { ContextMenu } from '../components';
export interface ViewportProps extends HTMLCoralProps<'div'> { export interface ViewportProps extends HTMLCoralProps<'div'> {
selectionTools?: SelectionToolsProps['actions']; 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) { export function Viewport({ selectionTools, children, className, ...rest }: ViewportProps) {
return ( return (
<Box position="relative" height="100%" className={cx('Viewport', className)} {...rest}> <Box position="relative" height="100%" className={cx('Viewport', className)} {...rest}>
<ViewportContextMenu />
<ViewportBody>{children}</ViewportBody> <ViewportBody>{children}</ViewportBody>
<div className="AuxTools"> <div className="AuxTools">
<SelectionTools actions={selectionTools} /> <SelectionTools actions={selectionTools} />
+3 -2
View File
@@ -5,11 +5,12 @@ import { observer, useWorkspace } from '@music163/tango-context';
export const HistoryTool = observer(() => { export const HistoryTool = observer(() => {
const workspace = useWorkspace(); const workspace = useWorkspace();
const disabled = !workspace.isValid;
return ( return (
<Box display="flex" columnGap="m"> <Box display="flex" columnGap="m">
<ToggleButton <ToggleButton
shape="ghost" shape="ghost"
disabled={!workspace.history.couldBack || workspace.history.index === 0} disabled={disabled || !workspace.history.couldBack || workspace.history.index === 0}
tooltip="撤销" tooltip="撤销"
onClick={() => { onClick={() => {
workspace.history.back(); workspace.history.back();
@@ -20,7 +21,7 @@ export const HistoryTool = observer(() => {
</ToggleButton> </ToggleButton>
<ToggleButton <ToggleButton
shape="ghost" shape="ghost"
disabled={!workspace.history.couldForward} disabled={disabled || !workspace.history.couldForward}
tooltip="重做" tooltip="重做"
onClick={() => { onClick={() => {
workspace.history.forward(); workspace.history.forward();
+2 -15
View File
@@ -1,6 +1,5 @@
import React, { useCallback } from 'react'; import React from 'react';
import { Group } from 'coral-system'; import { Group } from 'coral-system';
import { Modal } from 'antd';
import { ToggleButton, CodeOutlined, DualOutlined } from '@music163/tango-ui'; import { ToggleButton, CodeOutlined, DualOutlined } from '@music163/tango-ui';
import { observer, useDesigner, useWorkspace } from '@music163/tango-context'; import { observer, useDesigner, useWorkspace } from '@music163/tango-context';
import { BorderOutlined } from '@ant-design/icons'; import { BorderOutlined } from '@ant-design/icons';
@@ -9,23 +8,13 @@ export const ModeSwitchTool = observer(() => {
const workspace = useWorkspace(); const workspace = useWorkspace();
const designer = useDesigner(); const designer = useDesigner();
const activeFileCheck = useCallback(() => {
if (workspace.activeFile !== workspace.activeViewFile) {
Modal.confirm({
title: '当前打开的文件与视图不匹配,是否切换到当前视图对应的文件?',
onOk: () => {
workspace.setActiveFile(workspace.activeViewFile);
},
});
}
}, [workspace]);
return ( return (
<Group attached> <Group attached>
<ToggleButton <ToggleButton
shape="ghost" shape="ghost"
selected={designer.activeView === 'design'} selected={designer.activeView === 'design'}
onClick={() => { onClick={() => {
workspace.syncFiles(); // 保证 ast 与 code 是同步的
designer.setActiveView('design'); designer.setActiveView('design');
}} }}
tooltip="设计视图" tooltip="设计视图"
@@ -38,7 +27,6 @@ export const ModeSwitchTool = observer(() => {
onClick={() => { onClick={() => {
designer.setActiveView('code'); // 切换到源码视图 designer.setActiveView('code'); // 切换到源码视图
designer.setActiveSidebarPanel(''); // 关闭左侧面板 designer.setActiveSidebarPanel(''); // 关闭左侧面板
activeFileCheck();
}} }}
tooltip="源码视图" tooltip="源码视图"
> >
@@ -50,7 +38,6 @@ export const ModeSwitchTool = observer(() => {
onClick={() => { onClick={() => {
designer.setActiveView('dual'); // 切换到双屏视图 designer.setActiveView('dual'); // 切换到双屏视图
designer.setActiveSidebarPanel(''); // 关闭左侧面板 designer.setActiveSidebarPanel(''); // 关闭左侧面板
activeFileCheck();
}} }}
tooltip="双屏视图" tooltip="双屏视图"
> >
+4 -2
View File
@@ -1,13 +1,15 @@
import React from 'react'; import React from 'react';
import { ToggleButton } from '@music163/tango-ui'; import { ToggleButton } from '@music163/tango-ui';
import { EyeOutlined } from '@ant-design/icons'; 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(() => { export const PreviewTool = observer(() => {
const designer = useDesigner(); const designer = useDesigner();
const workspace = useWorkspace();
return ( return (
<ToggleButton <ToggleButton
disabled={!workspace.isValid}
shape="ghost" shape="ghost"
selected={designer.isPreview} selected={designer.isPreview}
onClick={() => { onClick={() => {
@@ -17,7 +19,7 @@ export const PreviewTool = observer(() => {
designer.setActiveView('design'); designer.setActiveView('design');
} }
}} }}
tooltip="预览" tooltip={designer.isPreview ? '切换到设计模式' : '切换到预览模式'}
> >
<EyeOutlined /> <EyeOutlined />
</ToggleButton> </ToggleButton>
+47 -17
View File
@@ -1,6 +1,8 @@
import React, { useMemo } from 'react'; import React, { useMemo } from 'react';
import { Box, Group } from 'coral-system'; import { Box, Group } from 'coral-system';
import { ReactComponentProps } from '@music163/tango-helpers'; import { ReactComponentProps } from '@music163/tango-helpers';
import { DesignerViewType } from '@music163/tango-core';
import { observer, useDesigner } from '@music163/tango-context';
import { getWidget } from '../widgets'; import { getWidget } from '../widgets';
export interface ToolbarProps { export interface ToolbarProps {
@@ -15,25 +17,23 @@ export function Toolbar({ children }: ToolbarProps) {
let prevPlacement: string; let prevPlacement: string;
React.Children.forEach(children, (child: React.ReactElement, index) => { React.Children.forEach(children, (child: React.ReactElement, index) => {
let fallbackNode; const childProps = child.props;
let fallbackChildren;
if (child.key) { if (child.key) {
const Widget = getWidget(['toolbar', child.key].join('.')); const Widget = getWidget(['toolbar', child.key].join('.'));
if (Widget) { 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; const key = child.key || index;
node = ( const node = React.cloneElement(child, {
<div key={key} className="ToolbarPanelItem" data-key={key}> key,
{node} 'data-key': key,
</div> children: childProps.children || fallbackChildren,
); });
const placement = child.props.placement || prevPlacement || 'center';
const placement = childProps.placement || prevPlacement || 'center';
switch (placement) { switch (placement) {
case 'left': case 'left':
left.push(node); left.push(node);
@@ -60,7 +60,7 @@ export function Toolbar({ children }: ToolbarProps) {
<Group display="flex" alignItems="center" gap="m"> <Group display="flex" alignItems="center" gap="m">
{centerTools} {centerTools}
</Group> </Group>
<Group display="flex" alignItems="center" gap="m"> <Group display="flex" alignItems="center" justifyContent="flex-end" gap="m">
{rightTools} {rightTools}
</Group> </Group>
</Box> </Box>
@@ -68,17 +68,47 @@ export function Toolbar({ children }: ToolbarProps) {
} }
export interface ToolbarItemProps extends ReactComponentProps { export interface ToolbarItemProps extends ReactComponentProps {
/**
* 类型
*/
type?: 'divider';
placement?: 'left' | 'center' | 'right'; placement?: 'left' | 'center' | 'right';
children?: React.ReactElement; children?: React.ReactElement;
/** /**
* 如果 key 匹配到内置组件的话,传递给子节点的属性 * 如果 key 匹配到内置组件的话,传递给子节点的属性
*/ */
widgetProps?: object; widgetProps?: object;
/**
* 工具箱展示的视图
*/
activeViews?: DesignerViewType[];
} }
function ToolbarItem({ placement, widgetProps, children }: ToolbarItemProps) { const ToolbarItem = observer(
return <div>{children}</div>; ({
} 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() { function Separator() {
return <Box className="Separator" width={1} height={16} bg="colors.custom.toolbarDividerColor" />; return <Box className="Separator" width={1} height={16} bg="colors.custom.toolbarDividerColor" />;
+15 -2
View File
@@ -18,14 +18,21 @@ import {
DeleteNodeAction, DeleteNodeAction,
ViewSourceAction, ViewSourceAction,
SelectParentNodeAction, SelectParentNodeAction,
MoreActionsAction,
} from './selection-menu'; } from './selection-menu';
import {
CopyNodeContextAction,
DeleteNodeContextAction,
PasteNodeContextAction,
ViewSourceContextAction,
} from './context-menu';
const widgets = {}; const widgets = {};
export function registerWidget(key: string, component: React.ComponentType<any>) { export function registerWidget(key: string, component: React.ComponentType<any>) {
if (!/^(toolbar|sidebar|selectionMenu)\.[a-zA-z]+$/.test(key)) { if (!/^(toolbar|sidebar|selectionMenu|contextMenu)\.[a-zA-Z]+$/.test(key)) {
throw new Error( throw new Error(
`Invalid widget key(${key}), should start with toolbar, sidebar, or selection-menu`, `Invalid widget key(${key}), should start with toolbar, sidebar, contextMenu or selectionMenu`,
); );
} }
setValue(widgets, key, component); setValue(widgets, key, component);
@@ -55,3 +62,9 @@ registerWidget('selectionMenu.copyNode', CopyNodeAction);
registerWidget('selectionMenu.deleteNode', DeleteNodeAction); registerWidget('selectionMenu.deleteNode', DeleteNodeAction);
registerWidget('selectionMenu.selectParentNode', SelectParentNodeAction); registerWidget('selectionMenu.selectParentNode', SelectParentNodeAction);
registerWidget('selectionMenu.viewSource', ViewSourceAction); registerWidget('selectionMenu.viewSource', ViewSourceAction);
registerWidget('selectionMenu.moreActions', MoreActionsAction);
registerWidget('contextMenu.viewSource', ViewSourceContextAction);
registerWidget('contextMenu.copyNode', CopyNodeContextAction);
registerWidget('contextMenu.pasteNode', PasteNodeContextAction);
registerWidget('contextMenu.deleteNode', DeleteNodeContextAction);
+9 -7
View File
@@ -1,35 +1,37 @@
import React from 'react'; import React from 'react';
import { Box } from 'coral-system'; import { Box, HTMLCoralProps } from 'coral-system';
import { observer, useDesigner } from '@music163/tango-context'; import { observer, useDesigner } from '@music163/tango-context';
import { DesignerViewType } from '@music163/tango-core'; import { DesignerViewType } from '@music163/tango-core';
import { ComponentsPopover } from './components'; import cx from 'classnames';
import { ComponentsPopover, FileErrorsOverlay } from './components';
export interface WorkspaceViewProps { export interface WorkspaceViewProps extends HTMLCoralProps<'div'> {
/** /**
* 视图面板模式,对应 Workspace 的模式 * 视图面板模式,对应 Workspace 的模式
*/ */
mode?: DesignerViewType; mode?: DesignerViewType;
children: React.ReactNode;
} }
export const WorkspaceView = observer((props: WorkspaceViewProps) => { export const WorkspaceView = observer((props: WorkspaceViewProps) => {
const { mode = 'design', children } = props; const { mode = 'design', children, className, ...rest } = props;
const designer = useDesigner(); const designer = useDesigner();
const display = mode !== designer.activeView ? 'none' : 'block'; const display = mode !== designer.activeView ? 'none' : 'block';
// 云音乐移动端模式小屏幕适配,可能会溢出屏幕 // 移动端模式小屏幕适配,可能会溢出屏幕
const overflow = const overflow =
designer.simulator.name === 'phone' ? 'auto' : designer.isPreview ? 'auto' : 'hidden'; designer.simulator.name === 'phone' ? 'auto' : designer.isPreview ? 'auto' : 'hidden';
return ( return (
<Box <Box
className={`ViewPanel ${mode}`} className={cx('ViewPanel', mode, className)}
display={designer.activeView === 'dual' ? 'block' : display} display={designer.activeView === 'dual' ? 'block' : display}
flex="1" flex="1"
overflow={overflow} overflow={overflow}
position="relative" position="relative"
{...rest}
> >
{children} {children}
{/* 添加组件弹层 */} {/* 添加组件弹层 */}
{display === 'block' && <ComponentsPopover type="inner" isControlled />} {display === 'block' && <ComponentsPopover type="inner" isControlled />}
{mode === 'design' && <FileErrorsOverlay />}
</Box> </Box>
); );
}); });
+12
View File
@@ -3,6 +3,18 @@
All notable changes to this project will be documented in this file. All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.2.1](https://github.com/netease/tango/compare/@music163/tango-helpers@1.2.0...@music163/tango-helpers@1.2.1) (2024-08-01)
### Bug Fixes
- update types ([67d602a](https://github.com/netease/tango/commit/67d602a3ec6b7f74156bb78fda6f3b4bc2676e55))
# [1.2.0](https://github.com/netease/tango/compare/@music163/tango-helpers@1.1.1...@music163/tango-helpers@1.2.0) (2024-06-03)
### Features
- add context menu ([#161](https://github.com/netease/tango/issues/161)) ([28040fc](https://github.com/netease/tango/commit/28040fc00604339a40ad3216b76baf7de93a13e0))
## [1.1.1](https://github.com/netease/tango/compare/@music163/tango-helpers@1.1.0...@music163/tango-helpers@1.1.1) (2024-05-21) ## [1.1.1](https://github.com/netease/tango/compare/@music163/tango-helpers@1.1.0...@music163/tango-helpers@1.1.1) (2024-05-21)
### Bug Fixes ### Bug Fixes
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@music163/tango-helpers", "name": "@music163/tango-helpers",
"version": "1.1.1", "version": "1.2.1",
"description": "Shared types, helpers, and hooks of tango-apps", "description": "Shared types, helpers, and hooks of tango-apps",
"keywords": [ "keywords": [
"shared", "shared",
+2 -2
View File
@@ -43,7 +43,7 @@ export function filterTreeData<T = unknown>(
childrenProp = 'children', childrenProp = 'children',
onlyLeaf = false, onlyLeaf = false,
) { ) {
const reducer = (result: T[], current: T) => { const reducer = (result: T[], current: any) => {
if (current[childrenProp]) { if (current[childrenProp]) {
const newChildren = current[childrenProp].reduce(reducer, []); const newChildren = current[childrenProp].reduce(reducer, []);
if (newChildren.length) { if (newChildren.length) {
@@ -70,7 +70,7 @@ export function mapTreeData<T = unknown>(
mapper: (node: T) => any, mapper: (node: T) => any,
childrenProp = 'children', childrenProp = 'children',
) { ) {
return treeData.map((node) => { return treeData.map((node: any) => {
const newNode = mapper(node); const newNode = mapper(node);
if (node[childrenProp]) { if (node[childrenProp]) {
newNode[childrenProp] = mapTreeData(node[childrenProp], mapper, childrenProp); newNode[childrenProp] = mapTreeData(node[childrenProp], mapper, childrenProp);
+7
View File
@@ -68,3 +68,10 @@ export function isServiceVariablePath(key: string) {
export function isInTangoDesignMode() { export function isInTangoDesignMode() {
return !!(window as any).__TANGO_DESIGNER__; return !!(window as any).__TANGO_DESIGNER__;
} }
/**
* 是否是 macOS 或 iOS like 设备
*/
export function isApplePlatform() {
return /Mac|iPhone|iPad|iPod/i.test(navigator.platform);
}
+1 -1
View File
@@ -32,7 +32,7 @@ export function isValidFunctionCode(str: string) {
} }
} }
const templatePattern = /^{{(.+)}}$/s; const templatePattern = /^{{(.+)}}$/;
/** /**
* 判断给定代码是否被双花括号包裹 * 判断给定代码是否被双花括号包裹
+3 -2
View File
@@ -1,5 +1,6 @@
import get from 'lodash.get'; import get from 'lodash.get';
import set from 'lodash.set'; import set from 'lodash.set';
import { Dict } from '../types';
/** /**
* 合并 target 和 source 对象,source 对象的优先级更高,如存在重名,覆盖 target 中的 key * 合并 target 和 source 对象,source 对象的优先级更高,如存在重名,覆盖 target 中的 key
@@ -45,7 +46,7 @@ export function clone(obj: any, withUndefined = true) {
return obj; return obj;
} }
const target = {}; const target: Dict = {};
for (const key in obj) { for (const key in obj) {
if (withUndefined) { if (withUndefined) {
target[key] = obj[key]; target[key] = obj[key];
@@ -65,7 +66,7 @@ export function omit(obj: any, keys: string[]) {
} }
export function pick(obj: any, keys: string[]) { export function pick(obj: any, keys: string[]) {
const target = {}; const target: Dict = {};
for (const key of keys) { for (const key of keys) {
target[key] = obj[key]; target[key] = obj[key];
} }
+1 -1
View File
@@ -57,7 +57,7 @@ export function withDnd(options: IWithDndOptions<any>) {
const override = options.overrideProps || {}; const override = options.overrideProps || {};
const renderFooter = options.renderFooter || renderEmpty; const renderFooter = options.renderFooter || renderEmpty;
const Component = forwardRef<unknown, P & DraggableComponentProps>((props, refProp) => { const Component = forwardRef<unknown, P & DraggableComponentProps>((props: any, refProp) => {
const dndProps = { const dndProps = {
[SLOT.id]: props.tid, // id 作为唯一标记 [SLOT.id]: props.tid, // id 作为唯一标记
[SLOT.dnd]: props[SLOT.dnd], // dnd 作为追踪标记 [SLOT.dnd]: props[SLOT.dnd], // dnd 作为追踪标记
+3 -2
View File
@@ -1,13 +1,14 @@
import { warning } from '../helpers'; import { warning } from '../helpers';
import { Dict } from '../types';
type ListStoreOptionsType<T = object> = { type ListStoreOptionsType<T extends Dict = Dict> = {
data: T[]; data: T[];
keyProp?: string; keyProp?: string;
labelProp?: string; labelProp?: string;
childrenProp?: string; childrenProp?: string;
}; };
export class ListStore<T = object> { export class ListStore<T extends Dict = Dict> {
private nodeMap: Map<string, T>; private nodeMap: Map<string, T>;
private keyProp: string; private keyProp: string;
private childrenProp: string; private childrenProp: string;
+22
View File
@@ -3,6 +3,28 @@
All notable changes to this project will be documented in this file. All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.0.9](https://github.com/netease/tango/compare/@music163/tango-sandbox@1.0.8...@music163/tango-sandbox@1.0.9) (2024-08-01)
**Note:** Version bump only for package @music163/tango-sandbox
## [1.0.8](https://github.com/netease/tango/compare/@music163/tango-sandbox@1.0.7...@music163/tango-sandbox@1.0.8) (2024-07-12)
**Note:** Version bump only for package @music163/tango-sandbox
## [1.0.7](https://github.com/netease/tango/compare/@music163/tango-sandbox@1.0.6...@music163/tango-sandbox@1.0.7) (2024-06-20)
**Note:** Version bump only for package @music163/tango-sandbox
## [1.0.6](https://github.com/netease/tango/compare/@music163/tango-sandbox@1.0.5...@music163/tango-sandbox@1.0.6) (2024-06-05)
**Note:** Version bump only for package @music163/tango-sandbox
## [1.0.5](https://github.com/netease/tango/compare/@music163/tango-sandbox@1.0.4...@music163/tango-sandbox@1.0.5) (2024-06-03)
### Bug Fixes
- use addEventListener to bind iframe event handlers ([#169](https://github.com/netease/tango/issues/169)) ([c1306e2](https://github.com/netease/tango/commit/c1306e24e0c747d0f4bd845dc1714488ddd8cdac))
## [1.0.4](https://github.com/netease/tango/compare/@music163/tango-sandbox@1.0.3...@music163/tango-sandbox@1.0.4) (2024-05-21) ## [1.0.4](https://github.com/netease/tango/compare/@music163/tango-sandbox@1.0.3...@music163/tango-sandbox@1.0.4) (2024-05-21)
**Note:** Version bump only for package @music163/tango-sandbox **Note:** Version bump only for package @music163/tango-sandbox
+3 -3
View File
@@ -1,6 +1,6 @@
{ {
"name": "@music163/tango-sandbox", "name": "@music163/tango-sandbox",
"version": "1.0.4", "version": "1.0.9",
"description": "sandbox of tango apps", "description": "sandbox of tango apps",
"author": "wwsun <ww.sun@outlook.com>", "author": "wwsun <ww.sun@outlook.com>",
"homepage": "", "homepage": "",
@@ -29,8 +29,8 @@
}, },
"dependencies": { "dependencies": {
"@ant-design/icons": "^4.8.0", "@ant-design/icons": "^4.8.0",
"@music163/tango-core": "^1.2.0", "@music163/tango-core": "^1.4.0",
"@music163/tango-helpers": "^1.1.1", "@music163/tango-helpers": "^1.2.1",
"crypto-js": "^4.1.1", "crypto-js": "^4.1.1",
"lodash.isequal": "4.5.0", "lodash.isequal": "4.5.0",
"react-frame-component": "^5.2.4" "react-frame-component": "^5.2.4"
+39 -17
View File
@@ -3,7 +3,13 @@ import { TangoEventName } from '@music163/tango-helpers';
import Loading from './loading'; import Loading from './loading';
import Manager from './manager'; import Manager from './manager';
import { createMissingPackageJSON, changeRoute } from './helper'; import { createMissingPackageJSON, changeRoute } from './helper';
import { IFiles, CodeSandboxState, CodeSandboxProps, UnsubscribeFunction } from '../types'; import {
IFiles,
CodeSandboxState,
CodeSandboxProps,
UnsubscribeFunction,
EventHandlers,
} from '../types';
// CodeSandbox 使用示例 // CodeSandbox 使用示例
// <CodeSandbox files={files} entry={entry} template={template} bundlerURL={`${window.location.protocol}//codesandbox.fn.netease.com/`} /> // <CodeSandbox files={files} entry={entry} template={template} bundlerURL={`${window.location.protocol}//codesandbox.fn.netease.com/`} />
@@ -32,6 +38,8 @@ export class CodeSandbox extends React.Component<CodeSandboxProps, CodeSandboxSt
iframe: HTMLIFrameElement; iframe: HTMLIFrameElement;
private eventHandlers: EventHandlers;
constructor(props: CodeSandboxProps) { constructor(props: CodeSandboxProps) {
super(props); super(props);
@@ -75,11 +83,8 @@ export class CodeSandbox extends React.Component<CodeSandboxProps, CodeSandboxSt
this.manager.cleanup(); this.manager.cleanup();
// clear tango event // clear tango event
if (this.iframe && this.props?.eventHandlers?.onTango) { if (this.iframe && this.eventHandlers) {
this.iframe.contentDocument?.removeEventListener( this.unbindEvents(this.eventHandlers);
TangoEventName.DesignerAction,
this.props.eventHandlers.onTango,
);
} }
} }
@@ -116,6 +121,29 @@ export class CodeSandbox extends React.Component<CodeSandboxProps, CodeSandboxSt
externalResources: this.props.externalResources, externalResources: this.props.externalResources,
}); });
normalizeEventType = (eventType: string) =>
eventType === 'onTango'
? TangoEventName.DesignerAction
: eventType.replace(/^on/, '').toLowerCase();
bindEvents = (eventHandlers: EventHandlers) => {
Object.keys(eventHandlers).forEach((eventType) => {
this.iframe?.contentDocument?.addEventListener(
this.normalizeEventType(eventType),
eventHandlers[eventType],
);
});
};
unbindEvents = (eventHandlers: EventHandlers) => {
Object.keys(eventHandlers).forEach((eventType) => {
this.iframe?.contentDocument?.removeEventListener(
this.normalizeEventType(eventType),
eventHandlers[eventType],
);
});
};
// Manager 实例化,即开始构建页面 // Manager 实例化,即开始构建页面
// 将 el 传给 Manager 作为实例化参数,当构建完成后,会将构建的页面 dom 设置给 el // 将 el 传给 Manager 作为实例化参数,当构建完成后,会将构建的页面 dom 设置给 el
// 注:Manager是一个管理者的角色,从大局上把控整个转译和执行的流程 // 注:Manager是一个管理者的角色,从大局上把控整个转译和执行的流程
@@ -155,17 +183,11 @@ export class CodeSandbox extends React.Component<CodeSandboxProps, CodeSandboxSt
// 注册监听函数 // 注册监听函数
const { eventHandlers } = this.props; const { eventHandlers } = this.props;
Object.keys(eventHandlers).forEach((eventType) => { if (eventHandlers) {
if (el.contentDocument) { this.bindEvents(eventHandlers);
el.contentDocument[eventType.toLowerCase()] = eventHandlers[eventType]; // 保存一份当前的 eventHandlers,避免 props 变更导致无法取消现在已注册的事件绑定
} this.eventHandlers = eventHandlers;
if (eventType === 'onTango') { }
el.contentDocument?.addEventListener(
TangoEventName.DesignerAction,
eventHandlers[eventType],
);
}
});
}; };
} }
}; };
+36
View File
@@ -3,6 +3,42 @@
All notable changes to this project will be documented in this file. All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.2.9](https://github.com/netease/tango/compare/@music163/tango-setting-form@1.2.8...@music163/tango-setting-form@1.2.9) (2024-08-01)
### Bug Fixes
- update types ([67d602a](https://github.com/netease/tango/commit/67d602a3ec6b7f74156bb78fda6f3b4bc2676e55))
## [1.2.8](https://github.com/netease/tango/compare/@music163/tango-setting-form@1.2.7...@music163/tango-setting-form@1.2.8) (2024-07-12)
**Note:** Version bump only for package @music163/tango-setting-form
## [1.2.7](https://github.com/netease/tango/compare/@music163/tango-setting-form@1.2.6...@music163/tango-setting-form@1.2.7) (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.2.6](https://github.com/netease/tango/compare/@music163/tango-setting-form@1.2.5...@music163/tango-setting-form@1.2.6) (2024-06-05)
**Note:** Version bump only for package @music163/tango-setting-form
## [1.2.5](https://github.com/netease/tango/compare/@music163/tango-setting-form@1.2.4...@music163/tango-setting-form@1.2.5) (2024-06-03)
**Note:** Version bump only for package @music163/tango-setting-form
## [1.2.4](https://github.com/netease/tango/compare/@music163/tango-setting-form@1.2.3...@music163/tango-setting-form@1.2.4) (2024-05-30)
**Note:** Version bump only for package @music163/tango-setting-form
## [1.2.3](https://github.com/netease/tango/compare/@music163/tango-setting-form@1.2.2...@music163/tango-setting-form@1.2.3) (2024-05-27)
**Note:** Version bump only for package @music163/tango-setting-form
## [1.2.2](https://github.com/netease/tango/compare/@music163/tango-setting-form@1.2.1...@music163/tango-setting-form@1.2.2) (2024-05-22)
**Note:** Version bump only for package @music163/tango-setting-form
## [1.2.1](https://github.com/netease/tango/compare/@music163/tango-setting-form@1.2.0...@music163/tango-setting-form@1.2.1) (2024-05-21) ## [1.2.1](https://github.com/netease/tango/compare/@music163/tango-setting-form@1.2.0...@music163/tango-setting-form@1.2.1) (2024-05-21)
### Bug Fixes ### Bug Fixes
+4 -4
View File
@@ -1,6 +1,6 @@
{ {
"name": "@music163/tango-setting-form", "name": "@music163/tango-setting-form",
"version": "1.2.1", "version": "1.2.9",
"description": "setting form of tango-apps", "description": "setting form of tango-apps",
"author": "wwsun <ww.sun@outlook.com>", "author": "wwsun <ww.sun@outlook.com>",
"homepage": "", "homepage": "",
@@ -28,9 +28,9 @@
}, },
"dependencies": { "dependencies": {
"@ant-design/icons": "^4.8.0", "@ant-design/icons": "^4.8.0",
"@music163/tango-core": "^1.2.0", "@music163/tango-core": "^1.4.0",
"@music163/tango-helpers": "^1.1.1", "@music163/tango-helpers": "^1.2.1",
"@music163/tango-ui": "^1.2.0", "@music163/tango-ui": "^1.4.0",
"antd": "^4.24.2", "antd": "^4.24.2",
"coral-system": "^1.0.5", "coral-system": "^1.0.5",
"mobx": "6.12.3", "mobx": "6.12.3",
+2 -1
View File
@@ -7,6 +7,7 @@ import {
noop, noop,
filterTreeData, filterTreeData,
mapTreeData, mapTreeData,
Dict,
} from '@music163/tango-helpers'; } from '@music163/tango-helpers';
import { Action, Search, Tabs } from '@music163/tango-ui'; import { Action, Search, Tabs } from '@music163/tango-ui';
import { SettingFormItem, register } from './form-item'; import { SettingFormItem, register } from './form-item';
@@ -24,7 +25,7 @@ function normalizeComponentProps(
props: IComponentPrototype['props'], props: IComponentPrototype['props'],
groupOptions: IFormTabsGroupOption[], groupOptions: IFormTabsGroupOption[],
) { ) {
const groups: Record<string, IComponentProp[]> = groupOptions.reduce((prev, cur) => { const groups: Record<string, IComponentProp[]> = groupOptions.reduce<Dict>((prev, cur) => {
prev[cur.value] = []; prev[cur.value] = [];
return prev; return prev;
}, {}); }, {});
@@ -1,3 +1,4 @@
import React from 'react';
import { CodeSetter } from './code-setter'; import { CodeSetter } from './code-setter';
import { BoolSetter } from './bool-setter'; import { BoolSetter } from './bool-setter';
import { IdSetter } from './id-setter'; import { IdSetter } from './id-setter';
@@ -36,6 +37,10 @@ const BASIC_SETTERS: IFormItemCreateOptions[] = [
name: 'idSetter', name: 'idSetter',
component: IdSetter, component: IdSetter,
}, },
{
name: 'imageSetter',
render: (props) => <TextSetter placeholder="请提供图片地址" {...props} />,
},
]; ];
let registered = false; let registered = false;
+51
View File
@@ -3,6 +3,57 @@
All notable changes to this project will be documented in this file. All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
# [1.4.0](https://github.com/netease/tango/compare/@music163/tango-ui@1.3.3...@music163/tango-ui@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-ui@1.3.2...@music163/tango-ui@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))
## [1.3.2](https://github.com/netease/tango/compare/@music163/tango-ui@1.3.1...@music163/tango-ui@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))
- 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-ui@1.3.0...@music163/tango-ui@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-ui@1.2.3...@music163/tango-ui@1.3.0) (2024-06-03)
### 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-ui@1.2.2...@music163/tango-ui@1.2.3) (2024-05-30)
### Bug Fixes
- popover re-click position bug & drag panel drag bug ([#165](https://github.com/netease/tango/issues/165)) ([f83c6bc](https://github.com/netease/tango/commit/f83c6bc0f69820582720512eefedc9ddf5db2975))
## [1.2.2](https://github.com/netease/tango/compare/@music163/tango-ui@1.2.1...@music163/tango-ui@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-ui@1.2.0...@music163/tango-ui@1.2.1) (2024-05-22)
**Note:** Version bump only for package @music163/tango-ui
# [1.2.0](https://github.com/netease/tango/compare/@music163/tango-ui@1.1.0...@music163/tango-ui@1.2.0) (2024-05-21) # [1.2.0](https://github.com/netease/tango/compare/@music163/tango-ui@1.1.0...@music163/tango-ui@1.2.0) (2024-05-21)
### Bug Fixes ### Bug Fixes
+2 -2
View File
@@ -1,6 +1,6 @@
{ {
"name": "@music163/tango-ui", "name": "@music163/tango-ui",
"version": "1.2.0", "version": "1.4.0",
"description": "ui widgets of tango", "description": "ui widgets of tango",
"keywords": [ "keywords": [
"react", "react",
@@ -38,7 +38,7 @@
"@codemirror/lang-javascript": "^6.2.2", "@codemirror/lang-javascript": "^6.2.2",
"@codemirror/lint": "^6.7.1", "@codemirror/lint": "^6.7.1",
"@codemirror/search": "^6.5.6", "@codemirror/search": "^6.5.6",
"@music163/tango-helpers": "^1.1.1", "@music163/tango-helpers": "^1.2.1",
"@uiw/react-codemirror": "^4.22.0", "@uiw/react-codemirror": "^4.22.0",
"antd": "^4.24.2", "antd": "^4.24.2",
"classnames": "^2.5.1", "classnames": "^2.5.1",
+12 -2
View File
@@ -1,4 +1,4 @@
import { Tooltip } from 'antd'; import { Tooltip, TooltipProps } from 'antd';
import React from 'react'; import React from 'react';
import { css, Button, Link, HTMLCoralProps } from 'coral-system'; import { css, Button, Link, HTMLCoralProps } from 'coral-system';
import cx from 'classnames'; import cx from 'classnames';
@@ -14,6 +14,7 @@ const actionStyle = css`
border-radius: var(--tango-radii-s); border-radius: var(--tango-radii-s);
color: var(--tango-colors-text2); color: var(--tango-colors-text2);
background-color: transparent; background-color: transparent;
white-space: nowrap;
&:hover { &:hover {
background-color: var(--tango-colors-fill2); background-color: var(--tango-colors-fill2);
@@ -47,6 +48,10 @@ export interface ActionProps extends HTMLCoralProps<any> {
* 提示文本 * 提示文本
*/ */
tooltip?: string; tooltip?: string;
/**
* Tooltip属性透传
*/
tooltipProps?: TooltipProps;
/** /**
* 超链接 * 超链接
*/ */
@@ -74,6 +79,7 @@ export interface ActionProps extends HTMLCoralProps<any> {
export function Action({ export function Action({
icon, icon,
tooltip, tooltip,
tooltipProps,
href, href,
size, size,
shape, shape,
@@ -109,7 +115,11 @@ export function Action({
} }
if (tooltip) { if (tooltip) {
return <Tooltip title={tooltip}>{ret}</Tooltip>; return (
<Tooltip title={tooltip} {...tooltipProps}>
{ret}
</Tooltip>
);
} }
return ret; return ret;
} }

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