this.onPortMouseDown(e, node, port.name, true, def)}
+ onMouseUp={e => this.onPortMouseUp(e, node, port.name, true)}
+ />
+ )}
+
{port.label || port.name}
+ {!isInput && (
+
this.onPortMouseDown(e, node, port.name, false, def)}
+ onMouseUp={e => this.onPortMouseUp(e, node, port.name, false)}
+ />
+ )}
+
+ );
+ }
+
+ render () {
+ const {graph, selectedNodeId} = this.props;
+ const {pan, zoom, linkFrom, mouseWorld} = this.state;
+ const nodes = graph.nodes.map(n => {
+ const def = getType(n.type);
+ const width = def && (def.isExtensionBlock || def.isFunction) ? 230 : 200;
+ return {...n, width, __def: def};
+ });
+
+ const edgePaths = graph.edges.map((edge, i) => {
+ const fromNode = nodes.find(n => n.id === edge.from.node);
+ const toNode = nodes.find(n => n.id === edge.to.node);
+ if (!fromNode || !toNode) return null;
+ const fromDef = fromNode.__def;
+ const toDef = toNode.__def;
+ if (!fromDef || !toDef) return null;
+ const fromPortDef = (fromDef.outputs || []).find(p => p.name === edge.from.port);
+ const toPortDef = (toDef.inputs || []).find(p => p.name === edge.to.port);
+ if (!fromPortDef || !toPortDef) return null;
+ const a = this.portPos(fromNode, edge.from.port, false, fromDef);
+ const b = this.portPos(toNode, edge.to.port, true, toDef);
+ if (!a || !b) return null;
+ const isExec = fromPortDef.kind === 'exec';
+ const type = portTypeOf(fromDef, edge.from.port, false);
+ const color = isExec ? '#cfd9e8' : (PORT_TYPE_COLORS[type] || '#56c8f0');
+ let path;
+ if (isExec) {
+ // UE exec:直角折线
+ const midX = a.x + Math.max(24, Math.abs(b.x - a.x) / 2);
+ path = `M ${a.x} ${a.y} L ${midX} ${a.y} L ${midX} ${b.y} L ${b.x} ${b.y}`;
+ } else {
+ const dx = Math.max(30, Math.abs(b.x - a.x) / 2);
+ path = `M ${a.x} ${a.y} C ${a.x + dx} ${a.y}, ${b.x - dx} ${b.y}, ${b.x} ${b.y}`;
+ }
+ return (
+
this.onEdgeClick(e, edge)}
+ />
+ );
+ });
+
+ let ghost = null;
+ if (linkFrom && mouseWorld) {
+ const a = linkFrom.isInput ? mouseWorld : {x: linkFrom.x, y: linkFrom.y};
+ const b = linkFrom.isInput ? {x: linkFrom.x, y: linkFrom.y} : mouseWorld;
+ const dx = Math.max(30, Math.abs(b.x - a.x) / 2);
+ ghost = (`M ${a.x} ${a.y} C ${a.x + dx} ${a.y}, ${b.x - dx} ${b.y}, ${b.x} ${b.y}`);
+ }
+
+ return (
+
+
+
+ {nodes.length === 0 && (
+
+ 从左侧面板点击/拖入节点开始搭建…
+
+ )}
+ {nodes.map(node => {
+ const def = node.__def;
+ if (!def) return null;
+ const titleColor = CATEGORY_COLORS[def.category] || '#3c4a6b';
+ return (
+
this.onNodeMouseDown(e, node)}
+ onDoubleClick={e => this.onNodeDoubleClick(e, node)}
+ onContextMenu={e => {
+ e.preventDefault();
+ e.stopPropagation();
+ this.props.onRemoveNode(node.id);
+ }}
+ >
+
this.onNodeTitleMouseDown(e, node)}
+ >
+ {def.title}
+ {node.id}
+
+
+ {(def.inputs || []).map(p => this.renderPortDot(node, def, p, true))}
+ {(def.outputs || []).map(p => this.renderPortDot(node, def, p, false))}
+ {(def.params || []).some(p => p.type === 'graph') && (
+
双击节点进入子图
+ )}
+
+
+ );
+ })}
+
+
+ 拖空白平移 · Ctrl+滚轮缩放 · 拖端口连线 · 点连线删除 · 右键节点删除 · 双击进子图
+
+
+ );
+ }
+}
+
+NodeCanvas.propTypes = {
+ graph: PropTypes.object.isRequired,
+ selectedNodeId: PropTypes.string,
+ onMoveNode: PropTypes.func,
+ onSelectNode: PropTypes.func,
+ onConnect: PropTypes.func,
+ onRemoveEdge: PropTypes.func,
+ onRemoveNode: PropTypes.func,
+ onOpenSubGraph: PropTypes.func
+};
+
+export default NodeCanvas;
diff --git a/src/components/visual-editor/node-inspector.jsx b/src/components/visual-editor/node-inspector.jsx
new file mode 100644
index 00000000000..a4ba68f3076
--- /dev/null
+++ b/src/components/visual-editor/node-inspector.jsx
@@ -0,0 +1,187 @@
+/**
+ * 可视化节点编辑器 · 属性面板(右侧)
+ * 选中节点的参数编辑(text/number/bool/select/code/graph)。
+ */
+import React from 'react';
+import PropTypes from 'prop-types';
+import bindAll from 'lodash.bindall';
+import {getType} from '../../lib/visual-node-engine/node-types.js';
+import styles from './visual-editor-modal.css';
+
+class NodeInspector extends React.Component {
+ constructor (props) {
+ super(props);
+ bindAll(this, ['handleChange', 'renderParam', 'renderMeta']);
+ }
+
+ handleChange (name, value) {
+ this.props.onParamChange(this.props.node.id, name, value);
+ }
+
+ renderMeta () {
+ const {mode, meta, onMetaChange} = this.props;
+ const metaFields = mode === 'addon' ? [
+ ['name', '插件名称'],
+ ['description', '插件描述']
+ ] : [
+ ['name', '扩展名称'],
+ ['id', '扩展 ID'],
+ ['description', '扩展描述']
+ ];
+ return (
+
+
信息
+ {metaFields.map(([k, label]) => (
+
+
+ onMetaChange(k, e.target.value)}
+ />
+
+ ))}
+
+
+ );
+ }
+
+ renderParam (p, node) {
+ const value = node.params ? node.params[p.name] : null;
+ switch (p.type) {
+ case 'bool':
+ return (
+
+
+
+ this.handleChange(p.name, e.target.checked)}
+ />
+ {value ? '开' : '关'}
+
+
+ );
+ case 'number':
+ return (
+
+
+ this.handleChange(p.name, Number(e.target.value))}
+ />
+
+ );
+ case 'select':
+ return (
+
+
+
+
+ );
+ case 'code':
+ return (
+
+
+
+ );
+ case 'graph':
+ return (
+
+
+
+
+ );
+ default:
+ return (
+
+
+ this.handleChange(p.name, e.target.value)}
+ />
+
+ );
+ }
+ }
+
+ render () {
+ const {node, mode, meta} = this.props;
+ return (
+
+ {this.renderMeta()}
+ {!node ? (
+
+ ) : (
+ (() => {
+ const def = getType(node.type);
+ if (!def) {
+ return (
+
+
未知节点
+
类型 {node.type} 不存在
+
+ );
+ }
+ return (
+
+
{def.title}
+
+ {def.category} · 节点 id {node.id}
+
+ {(def.params || []).map(p => this.renderParam(p, node))}
+
+
+ );
+ })()
+ )}
+
+ );
+ }
+}
+
+NodeInspector.propTypes = {
+ node: PropTypes.object,
+ mode: PropTypes.oneOf(['extension', 'addon']),
+ meta: PropTypes.object,
+ onMetaChange: PropTypes.func,
+ onParamChange: PropTypes.func,
+ onRemoveNode: PropTypes.func,
+ onOpenSubGraph: PropTypes.func
+};
+
+export default NodeInspector;
diff --git a/src/components/visual-editor/node-palette.jsx b/src/components/visual-editor/node-palette.jsx
new file mode 100644
index 00000000000..d9f3c7b7f48
--- /dev/null
+++ b/src/components/visual-editor/node-palette.jsx
@@ -0,0 +1,99 @@
+/**
+ * 可视化节点编辑器 · 节点面板(左侧)
+ * 分类分组 + 搜索;点击添加到画布。子图内额外显示「积木参数值」节点。
+ */
+import React from 'react';
+import PropTypes from 'prop-types';
+import bindAll from 'lodash.bindall';
+import {NODE_TYPES, CATEGORIES} from '../../lib/visual-node-engine/node-types.js';
+import styles from './visual-editor-modal.css';
+
+// 分类色条(与画布标题栏一致)
+const CATEGORY_COLORS = {
+ '事件': '#2e5f9e',
+ '流程控制': '#2e7d54',
+ '变量': '#6d54a0',
+ '运算': '#a2701f',
+ '函数': '#4a5cc0',
+ 'Scratch 交互': '#d99e2b',
+ 'DOM/UI': '#b85c4e',
+ '网络/存储': '#3a8e68',
+ '扩展积木': '#8e44ad',
+ '插件 API': '#16867a'
+};
+
+class NodePalette extends React.Component {
+ constructor (props) {
+ super(props);
+ bindAll(this, ['handleSearch', 'addItem']);
+ this.state = {search: ''};
+ }
+
+ handleSearch (e) {
+ this.setState({search: e.target.value});
+ }
+
+ addItem (typeId) {
+ this.props.onAddNode(typeId);
+ }
+
+ render () {
+ const {search} = this.state;
+ const {mode, inSubGraph} = this.props;
+ const q2 = search.trim().toLowerCase();
+ const visible = NODE_TYPES.filter(t => {
+ if (t.addonOnly && mode !== 'addon') return false;
+ if (t.onlyInBlockBody && !inSubGraph) return false;
+ if (t.isExtensionBlock && mode !== 'extension') return false;
+ if (q2) {
+ return t.title.toLowerCase().includes(q2) ||
+ t.id.toLowerCase().includes(q2) ||
+ t.category.toLowerCase().includes(q2);
+ }
+ return true;
+ });
+
+ return (
+
+
+
+
+
+ {CATEGORIES.map(cat => {
+ const items = visible.filter(t => t.category === cat);
+ if (!items.length) return null;
+ return (
+
+
{cat}
+ {items.map(t => (
+
+ ))}
+
+ );
+ })}
+
+
+ );
+ }
+}
+
+NodePalette.propTypes = {
+ mode: PropTypes.oneOf(['extension', 'addon']),
+ inSubGraph: PropTypes.bool,
+ onAddNode: PropTypes.func
+};
+
+export default NodePalette;
diff --git a/src/components/visual-editor/visual-editor-modal.css b/src/components/visual-editor/visual-editor-modal.css
new file mode 100644
index 00000000000..afe0c9f9240
--- /dev/null
+++ b/src/components/visual-editor/visual-editor-modal.css
@@ -0,0 +1,480 @@
+/* 可视化节点编辑器 · UE 蓝图风格样式(CSS Modules,组件内经 styles.xxx 引用) */
+
+.veModal {
+ position: fixed;
+ inset: 0;
+ z-index: 500;
+ background: #0f1420;
+ color: #dce4f2;
+ display: flex;
+ flex-direction: column;
+ font-family: inherit;
+ direction: ltr;
+ box-shadow: inset 0 0 120px rgba(0, 0, 0, .45);
+}
+
+.veTopbar {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 7px 14px;
+ background: linear-gradient(180deg, #1a2233, #141a28);
+ border-bottom: 1px solid #2c3852;
+ flex-shrink: 0;
+}
+
+.veTitle {
+ font-weight: bold;
+ font-size: 15px;
+ white-space: nowrap;
+ color: #eaf1ff;
+ text-shadow: 0 1px 2px rgba(0, 0, 0, .6);
+}
+
+.veModeBadge {
+ font-size: 11px;
+ padding: 2px 10px;
+ border-radius: 10px;
+ background: linear-gradient(180deg, #2d5b8e, #23466f);
+ border: 1px solid #3f6ea5;
+ white-space: nowrap;
+ color: #cfe3ff;
+}
+
+.veBreadcrumb {
+ font-size: 12px;
+ color: #8fa4c8;
+ display: flex;
+ gap: 4px;
+ align-items: center;
+ overflow: hidden;
+ white-space: nowrap;
+ margin-left: 4px;
+}
+
+.veCrumb {
+ cursor: pointer;
+ padding: 3px 8px;
+ border-radius: 5px;
+ border: 1px solid transparent;
+}
+
+.veCrumb:hover {
+ background: #25304a;
+ border-color: #35415f;
+ color: #fff;
+}
+
+.veCrumbCurrent {
+ color: #ffd479;
+ font-weight: bold;
+ cursor: default;
+}
+
+.veToolbar {
+ margin-left: auto;
+ display: flex;
+ gap: 7px;
+ align-items: center;
+}
+
+.veBtn {
+ background: linear-gradient(180deg, #33639c, #27507e);
+ color: #fff;
+ border: 1px solid #487ab0;
+ border-radius: 5px;
+ padding: 5px 11px;
+ cursor: pointer;
+ font-size: 12.5px;
+ white-space: nowrap;
+ text-shadow: 0 1px 1px rgba(0, 0, 0, .4);
+}
+.veBtn:hover { background: linear-gradient(180deg, #3e77b8, #2f5f92); }
+.veBtn:active { transform: translateY(1px); }
+.veBtn:disabled { opacity: .4; cursor: default; }
+.veBtnSecondary { background: linear-gradient(180deg, #38445e, #2c3649); border-color: #4a5878; }
+.veBtnSecondary:hover { background: linear-gradient(180deg, #445273, #364260); }
+.veBtnDanger { background: linear-gradient(180deg, #963535, #7a2b2b); border-color: #b04a4a; }
+.veBtnDanger:hover { background: linear-gradient(180deg, #ad4242, #8c3535); }
+.veBtnSuccess { background: linear-gradient(180deg, #2f8e5b, #257049); border-color: #48a873; }
+.veBtnSuccess:hover { background: linear-gradient(180deg, #3aa86c, #2c8757); }
+
+.veBody {
+ flex: 1;
+ display: flex;
+ min-height: 0;
+}
+
+/* ---------- 左侧节点面板 ---------- */
+.vePalette {
+ width: 235px;
+ flex-shrink: 0;
+ background: #121826;
+ border-right: 1px solid #2c3852;
+ display: flex;
+ flex-direction: column;
+}
+
+.vePaletteSearch {
+ padding: 8px;
+ border-bottom: 1px solid #2c3852;
+}
+
+.vePaletteSearchInput {
+ width: 100%;
+ box-sizing: border-box;
+ background: #0c111c;
+ color: #dce4f2;
+ border: 1px solid #2c3852;
+ border-radius: 6px;
+ padding: 6px 9px;
+ font-size: 12.5px;
+ outline: none;
+}
+.vePaletteSearchInput:focus { border-color: #487ab0; }
+
+.vePaletteList {
+ flex: 1;
+ overflow-y: auto;
+ padding: 4px 6px 10px;
+}
+.vePaletteList::-webkit-scrollbar { width: 8px; }
+.vePaletteList::-webkit-scrollbar-thumb { background: #2c3852; border-radius: 4px; }
+
+.vePaletteCat {
+ font-size: 10.5px;
+ font-weight: bold;
+ color: #6f84ad;
+ margin: 10px 4px 4px;
+ text-transform: uppercase;
+ letter-spacing: 1px;
+ border-bottom: 1px solid #232c42;
+ padding-bottom: 3px;
+}
+
+.vePaletteItem {
+ display: block;
+ width: 100%;
+ text-align: left;
+ background: #1a2233;
+ color: #c3d1e8;
+ border: 1px solid #26314a;
+ border-left: 3px solid #3d5a8c;
+ border-radius: 5px;
+ padding: 5px 9px;
+ margin: 3px 0;
+ font-size: 12px;
+ cursor: grab;
+ overflow: hidden;
+ white-space: nowrap;
+ text-overflow: ellipsis;
+ transition: background .08s;
+}
+.vePaletteItem:hover { background: #25314d; color: #fff; border-left-color: #7aa8ff; }
+
+/* ---------- 画布 ---------- */
+.veCanvasWrap {
+ flex: 1;
+ position: relative;
+ overflow: hidden;
+ background-color: #0d1119;
+ background-image:
+ linear-gradient(rgba(56, 72, 108, .22) 1px, transparent 1px),
+ linear-gradient(90deg, rgba(56, 72, 108, .22) 1px, transparent 1px),
+ linear-gradient(rgba(56, 72, 108, .38) 1px, transparent 1px),
+ linear-gradient(90deg, rgba(56, 72, 108, .38) 1px, transparent 1px);
+ background-size: 16px 16px, 16px 16px, 80px 80px, 80px 80px;
+ cursor: default;
+}
+
+.veCanvasWrapPanning { cursor: grabbing !important; }
+
+.veViewport {
+ position: absolute;
+ top: 0;
+ left: 0;
+ transform-origin: 0 0;
+}
+
+/* ---------- 节点 ---------- */
+.veNode {
+ position: absolute;
+ background: rgba(26, 32, 48, .96);
+ border: 1px solid #3c4a6b;
+ border-radius: 7px;
+ min-width: 190px;
+ box-shadow: 0 4px 14px rgba(0, 0, 0, .5), inset 0 1px 0 rgba(255, 255, 255, .05);
+ user-select: none;
+}
+.veNodeSelected {
+ border-color: #7aa8ff;
+ box-shadow: 0 0 0 2px rgba(122, 168, 255, .4), 0 4px 18px rgba(0, 0, 0, .55);
+}
+
+.veNodeTitle {
+ padding: 5px 10px 5px 12px;
+ font-size: 12px;
+ font-weight: bold;
+ color: #fff;
+ border-radius: 6px 6px 0 0;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ cursor: grab;
+ text-shadow: 0 1px 2px rgba(0, 0, 0, .55);
+ border-bottom: 1px solid rgba(0, 0, 0, .35);
+ white-space: nowrap;
+ overflow: hidden;
+}
+.veNodeId {
+ font-size: 9px;
+ opacity: .75;
+ font-weight: normal;
+ margin-left: 6px;
+}
+
+.veNodeBody {
+ padding: 5px 0 6px;
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+}
+
+.vePortRow {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ font-size: 11px;
+ color: #b9c8e2;
+ padding: 0 10px;
+ position: relative;
+ height: 18px;
+}
+.vePortRowOutput { justify-content: flex-end; }
+
+.vePortLabel {
+ flex: 1;
+ text-align: left;
+ overflow: hidden;
+ white-space: nowrap;
+ text-overflow: ellipsis;
+}
+.vePortRowOutput .vePortLabel { text-align: right; }
+
+/* 端口圆点/箭头:UE 风格 */
+.vePortDot {
+ width: 12px;
+ height: 12px;
+ border-radius: 50%;
+ border: 2px solid;
+ background: #0d1119;
+ cursor: crosshair;
+ flex-shrink: 0;
+ position: relative;
+ z-index: 2;
+ box-sizing: border-box;
+ transition: transform .06s;
+}
+.vePortDot:hover { transform: scale(1.35); background: #fff; }
+
+.vePortDotExec {
+ border-radius: 3px;
+ border: none;
+ width: 11px;
+ height: 13px;
+ background: #dfe6f0;
+ clip-path: polygon(0 0, 100% 50%, 0 100%);
+}
+.vePortDotExec:hover { background: #fff; }
+
+.vePortDotNumber { border-color: #7ce87c; }
+.vePortDotString { border-color: #ff7ce8; }
+.vePortDotBool { border-color: #ff6b6b; }
+.vePortDotAny { border-color: #56c8f0; }
+
+.veSubGraphHint {
+ font-size: 10px;
+ color: #8fa4c8;
+ padding: 2px 10px;
+ opacity: .8;
+}
+
+/* ---------- 连线 ---------- */
+.veEdgeSvg {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ overflow: visible;
+ pointer-events: none;
+}
+
+.veEdgePath {
+ stroke: #58c8f0;
+ stroke-width: 2.5;
+ fill: none;
+ pointer-events: stroke;
+ cursor: pointer;
+ filter: drop-shadow(0 1px 3px rgba(0, 0, 0, .5));
+}
+.veEdgePathExec { stroke: #cfd9e8; }
+.veEdgePathHover { stroke: #ff8866 !important; stroke-width: 3.5; }
+
+.veEdgeGhost {
+ stroke: #7aa8ff;
+ stroke-dasharray: 7 5;
+ stroke-width: 2;
+ fill: none;
+ opacity: .85;
+}
+
+/* ---------- 右侧属性面板 ---------- */
+.veInspector {
+ width: 275px;
+ flex-shrink: 0;
+ background: #121826;
+ border-left: 1px solid #2c3852;
+ overflow-y: auto;
+ padding: 10px 12px;
+ font-size: 13px;
+}
+.veInspector::-webkit-scrollbar { width: 8px; }
+.veInspector::-webkit-scrollbar-thumb { background: #2c3852; border-radius: 4px; }
+
+.veInspectorTitle {
+ margin: 0 0 2px;
+ font-size: 14px;
+ color: #eaf1ff;
+}
+
+.veInspHint {
+ font-size: 11px;
+ color: #6f84ad;
+ margin: 2px 0 10px;
+ border-bottom: 1px solid #232c42;
+ padding-bottom: 8px;
+}
+
+.veParam { margin-bottom: 10px; }
+
+.veParamLabel {
+ display: block;
+ font-size: 11px;
+ color: #8fa4c8;
+ margin-bottom: 3px;
+}
+
+.veParamInput,
+.veParamSelect,
+.veParamTextarea {
+ width: 100%;
+ box-sizing: border-box;
+ background: #0c111c;
+ color: #dce4f2;
+ border: 1px solid #2c3852;
+ border-radius: 5px;
+ padding: 5px 8px;
+ font-size: 12px;
+ outline: none;
+ font-family: inherit;
+}
+.veParamInput:focus,
+.veParamSelect:focus,
+.veParamTextarea:focus { border-color: #487ab0; }
+
+.veParamTextarea {
+ font-family: 'Consolas', 'Menlo', monospace;
+ min-height: 58px;
+ resize: vertical;
+ white-space: pre;
+ line-height: 1.45;
+}
+
+.veBoolRow {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ font-size: 12px;
+ color: #b9c8e2;
+}
+
+.veDeleteBtn {
+ width: 100%;
+ margin-top: 10px;
+}
+
+/* ---------- 底部代码区 ---------- */
+.veCodePane {
+ flex-shrink: 0;
+ height: 250px;
+ border-top: 1px solid #2c3852;
+ background: #10151f;
+ display: flex;
+ flex-direction: column;
+}
+
+.veCodeBar {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 5px 12px;
+ border-bottom: 1px solid #2c3852;
+ font-size: 12px;
+ flex-shrink: 0;
+ color: #b9c8e2;
+}
+
+.veCodeNote {
+ color: #6f84ad;
+ font-size: 11px;
+ overflow: hidden;
+ white-space: nowrap;
+ text-overflow: ellipsis;
+}
+
+.veCodeStatus {
+ color: #ffd479;
+ margin-left: auto;
+ font-size: 11.5px;
+ white-space: nowrap;
+}
+
+.veCodeInput {
+ flex: 1;
+ background: #0c111c;
+ color: #c8e0ff;
+ border: none;
+ outline: none;
+ resize: none;
+ padding: 9px 14px;
+ font-family: 'Consolas', 'Menlo', monospace;
+ font-size: 12px;
+ line-height: 1.5;
+ white-space: pre;
+ overflow: auto;
+ direction: ltr;
+}
+
+/* ---------- 画布提示 ---------- */
+.veCanvasHint {
+ position: absolute;
+ bottom: 8px;
+ left: 12px;
+ font-size: 10.5px;
+ color: #4f6187;
+ pointer-events: none;
+ background: rgba(13, 17, 25, .7);
+ padding: 3px 8px;
+ border-radius: 4px;
+ z-index: 5;
+}
+
+.veEmptyNote {
+ position: absolute;
+ top: 60px;
+ left: 60px;
+ color: #55688f;
+ font-size: 14px;
+ pointer-events: none;
+}
diff --git a/src/components/visual-editor/visual-editor-modal.jsx b/src/components/visual-editor/visual-editor-modal.jsx
new file mode 100644
index 00000000000..2e4cac755d3
--- /dev/null
+++ b/src/components/visual-editor/visual-editor-modal.jsx
@@ -0,0 +1,433 @@
+/**
+ * 可视化编辑器主组件(扩展 / 插件)
+ * - 左:节点面板;中:节点画布;右:属性面板;底:JS 代码面板(双向转换)
+ * - 子图栈:双击函数/积木/定时器节点进入其 bodyGraph;面包屑返回
+ * - 导出:下载 js / 导入作品(扩展=dataURL+loadExtensionURL;插件=customPlugins.add)
+ */
+import React from 'react';
+import PropTypes from 'prop-types';
+import bindAll from 'lodash.bindall';
+import styles from './visual-editor-modal.css';
+import NodeCanvas from './node-canvas.jsx';
+import NodePalette from './node-palette.jsx';
+import NodeInspector from './node-inspector.jsx';
+import {
+ createNode, addNode, removeNode, moveNode, connect, disconnect, getNode
+} from '../../lib/visual-node-engine/graph-model.js';
+import {getType} from '../../lib/visual-node-engine/node-types.js';
+import {compile} from '../../lib/visual-node-engine/compile.js';
+import {parse} from '../../lib/visual-node-engine/parse.js';
+import {
+ extensionStarterGraph, addonStarterGraph, defaultMeta, extensionDemoGraph
+} from '../../lib/visual-node-engine/templates.js';
+
+const subGraphParams = ['bodyGraph'];
+
+class VisualEditorModal extends React.Component {
+ constructor (props) {
+ super(props);
+ bindAll(this, [
+ 'handleAddNode',
+ 'handleMoveNode',
+ 'handleSelectNode',
+ 'handleConnect',
+ 'handleRemoveEdge',
+ 'handleRemoveNode',
+ 'handleParamChange',
+ 'handleOpenSubGraph',
+ 'handleBreadcrumb',
+ 'handleMetaChange',
+ 'handleGenerateCode',
+ 'handleApplyCode',
+ 'handleImportCode',
+ 'handleDownload',
+ 'handleImportToProject',
+ 'handleLoadDemo',
+ 'handleClear',
+ 'handleUndo',
+ 'handleClose',
+ 'snapshot'
+ ]);
+ const mode = props.mode || 'extension';
+ this.state = {
+ mode,
+ meta: defaultMeta(mode),
+ graphStack: [{
+ graph: mode === 'addon' ? addonStarterGraph() : extensionStarterGraph(mode),
+ title: '主图',
+ ownerNodeId: null
+ }],
+ selectedNodeId: null,
+ code: '',
+ codeStatus: '',
+ undoStack: []
+ };
+ }
+
+ get currentFrame () {
+ return this.state.graphStack[this.state.graphStack.length - 1];
+ }
+
+ get currentGraph () {
+ return this.currentFrame.graph;
+ }
+
+ get selectedNode () {
+ return getNode(this.currentGraph, this.state.selectedNodeId) || null;
+ }
+
+ // ---- 快照(undo) ----
+ snapshot () {
+ this.setState(s => ({
+ undoStack: [...s.undoStack.slice(-29), JSON.stringify({
+ graphStack: s.graphStack, meta: s.meta
+ })]
+ }));
+ }
+
+ mutateGraph (fn) {
+ this.snapshot();
+ this.setState(s => {
+ const frames = s.graphStack.slice();
+ const last = frames[frames.length - 1];
+ frames[frames.length - 1] = {title: last.title, ownerNodeId: last.ownerNodeId, graph: fn(last.graph)};
+ return {graphStack: frames};
+ });
+ }
+
+ handleUndo () {
+ if (!this.state.undoStack.length) return;
+ const snap = JSON.parse(this.state.undoStack[this.state.undoStack.length - 1]);
+ this.setState(s => ({
+ graphStack: snap.graphStack,
+ meta: snap.meta,
+ undoStack: s.undoStack.slice(0, -1)
+ }));
+ }
+
+ // ---- 节点操作 ----
+ handleAddNode (typeId) {
+ const g = this.currentGraph;
+ let x = 360;
+ let y = 120;
+ for (let i = 0; i < 40; i++) {
+ if (!g.nodes.some(n => Math.abs(n.x - x) < 30 && Math.abs(n.y - y) < 30)) break;
+ y += 60;
+ if (y > 800) { y = 120; x += 60; }
+ }
+ const def = getType(typeId);
+ const node = createNode(typeId, x, y, def && def.params ?
+ Object.fromEntries(def.params
+ .filter(p => p.type !== 'graph')
+ .map(p => [p.name, p.default])) : {});
+ this.mutateGraph(graph => {
+ addNode(graph, {...node});
+ return graph;
+ });
+ this.setState({selectedNodeId: node.id});
+ }
+
+ handleMoveNode (id, x, y) {
+ this.mutateGraph(graph => {
+ moveNode(graph, id, x, y);
+ return graph;
+ });
+ }
+
+ handleSelectNode (id) {
+ this.setState({selectedNodeId: id});
+ }
+
+ handleConnect (fromNode, fromPort, toNode, toPort) {
+ this.mutateGraph(graph => {
+ connect(graph, fromNode, fromPort, toNode, toPort);
+ return graph;
+ });
+ }
+
+ handleRemoveEdge (edge) {
+ this.mutateGraph(graph => {
+ disconnect(graph, edge);
+ return graph;
+ });
+ }
+
+ handleRemoveNode (id) {
+ this.mutateGraph(graph => {
+ removeNode(graph, id);
+ return graph;
+ });
+ if (this.state.selectedNodeId === id) this.setState({selectedNodeId: null});
+ }
+
+ handleParamChange (id, name, value) {
+ this.mutateGraph(graph => {
+ const node = getNode(graph, id);
+ if (node) {
+ node.params = {...(node.params || {}), [name]: value};
+ }
+ return graph;
+ });
+ }
+
+ // ---- 子图栈 ----
+ handleOpenSubGraph (nodeId) {
+ const node = getNode(this.currentGraph, nodeId);
+ if (!node) return;
+ const def = getType(node.type);
+ const hasBody = (def.params || []).some(p => subGraphParams.includes(p.name));
+ if (!hasBody) return;
+ const body = node.params && node.params.bodyGraph;
+ this.setState(s => ({
+ graphStack: [...s.graphStack, {
+ graph: (body && body.nodes) ? body : {nodes: [], edges: []},
+ title: `子图 · ${def.title}`,
+ ownerNodeId: nodeId
+ }],
+ selectedNodeId: null
+ }));
+ }
+
+ handleBreadcrumb (index) {
+ if (index === this.state.graphStack.length - 1) return;
+ // 中途跳转时把当前帧写回 owner 节点
+ this.setState(s => {
+ const frames = s.graphStack.slice(0, index + 1);
+ const closed = s.graphStack.slice(index + 1);
+ // 把最内层写回
+ let carry = null;
+ for (const frame of closed) {
+ if (frame.ownerNodeId && carry === null) {
+ carry = frame.graph;
+ } else if (frame.ownerNodeId && carry !== null) {
+ carry = frame.graph; // 多层时逐层收拢(简化:直接取该层)
+ }
+ }
+ if (carry !== null) {
+ const target = frames[frames.length - 1];
+ const node = target.graph.nodes.find(n => n.id === closed[0].ownerNodeId);
+ if (node) {
+ node.params = {...(node.params || {}), bodyGraph: carry};
+ }
+ }
+ return {graphStack: frames, selectedNodeId: null};
+ });
+ }
+
+ // ---- meta ----
+ handleMetaChange (name, value) {
+ this.setState(s => ({meta: {...s.meta, [name]: value}}));
+ }
+
+ // ---- 代码 ⇄ 节点 ----
+ handleGenerateCode () {
+ const code = compile(this.currentGraph, this.state.mode, this.state.meta);
+ this.setState({code, codeStatus: '已从节点图生成(含往返标记)'});
+ }
+
+ handleApplyCode () {
+ const res = parse(this.state.code);
+ if (!res.graph) {
+ this.setState({codeStatus: '解析失败:无可用图'});
+ return;
+ }
+ this.snapshot();
+ this.setState({
+ graphStack: [{graph: res.graph, title: '主图', ownerNodeId: null}],
+ meta: {...this.state.meta, ...res.meta},
+ selectedNodeId: null,
+ codeStatus: res.partial ?
+ '外部代码已导入为「任意 JS 语句」节点链(尽力解析)' :
+ '已还原完整节点图(往返无损)'
+ });
+ }
+
+ handleImportCode () {
+ // textarea 上粘贴外部代码后调用
+ this.handleApplyCode();
+ }
+
+ // ---- 下载 / 导入作品 ----
+ handleDownload () {
+ const code = this.state.code || compile(this.currentGraph, this.state.mode, this.state.meta);
+ const name = (this.state.meta.name || 'visual').replace(/[\\/:*?"<>|]/g, '_');
+ const blob = new Blob([code], {type: 'application/javascript'});
+ const a = document.createElement('a');
+ a.href = URL.createObjectURL(blob);
+ a.download = `${name}.js`;
+ a.click();
+ URL.revokeObjectURL(a.href);
+ this.setState({code, codeStatus: `已下载 ${name}.js`});
+ }
+
+ async handleImportToProject () {
+ const code = this.state.code || compile(this.currentGraph, this.state.mode, this.state.meta);
+ try {
+ if (this.state.mode === 'extension') {
+ const url = `data:application/javascript,${encodeURIComponent(code)}`;
+ const sm = await import('../../containers/tw-security-manager.jsx');
+ if (sm.markExtensionAsCustom) sm.markExtensionAsCustom(url);
+ if (sm.manuallyTrustExtension) sm.manuallyTrustExtension(url);
+ await this.props.vm.extensionManager.loadExtensionURL(url);
+ this.setState({code, codeStatus: '✔ 已作为自定义扩展导入作品'});
+ } else {
+ const cp = (await import('../../addons/custom-plugins.js')).default;
+ const meta = {
+ name: this.state.meta.name || '我的插件',
+ description: this.state.meta.description || '可视化插件编辑器生成',
+ settings: this.state.meta.settings || []
+ };
+ await cp.add(meta, code, true);
+ this.setState({code, codeStatus: '✔ 已导入自定义插件(设置→插件 可管理,刷新后生效)'});
+ }
+ } catch (err) {
+ this.setState({codeStatus: `导入失败:${String(err && err.message || err)}`});
+ }
+ }
+
+ handleLoadDemo () {
+ if (this.state.mode === 'extension') {
+ this.snapshot();
+ this.setState({
+ graphStack: [{graph: extensionDemoGraph(), title: '主图', ownerNodeId: null}],
+ meta: {name: '示例扩展', id: 'demoExtension', description: '带积木定义的示例'},
+ selectedNodeId: null
+ });
+ } else {
+ this.snapshot();
+ this.setState({
+ graphStack: [{graph: addonStarterGraph(), title: '主图', ownerNodeId: null}],
+ meta: {name: '示例插件', description: '基础示例', enabledByDefault: false, settings: [], css: ''},
+ selectedNodeId: null
+ });
+ }
+ }
+
+ handleClear () {
+ this.snapshot();
+ this.setState({
+ graphStack: [{
+ graph: {nodes: [], edges: []},
+ title: '主图',
+ ownerNodeId: null
+ }],
+ selectedNodeId: null
+ });
+ }
+
+ handleClose () {
+ this.props.onClose();
+ }
+
+ render () {
+ const {mode, meta, code, codeStatus} = this.state;
+ const graph = this.currentGraph;
+ const selected = this.selectedNode;
+
+ return (
+
+
+
+ {mode === 'addon' ? '可视化插件编辑器' : '可视化扩展编辑器'}
+
+
+ {mode === 'addon' ? '插件 (addon)' : '扩展 (extension)'}
+
+
+ {this.state.graphStack.map((frame, i) => (
+ this.handleBreadcrumb(i)}
+ >
+ {i > 0 ? '› ' : ''}{frame.title}
+
+ ))}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ 1}
+ onAddNode={this.handleAddNode}
+ />
+
+ selected && this.handleOpenSubGraph(selected.id)}
+ />
+
+
+
+
+ JS 代码
+
+ (双向转换:编译产物头部含节点图存档,粘贴回读无损还原)
+
+ {codeStatus}
+
+
+
+ );
+ }
+}
+
+VisualEditorModal.propTypes = {
+ mode: PropTypes.oneOf(['extension', 'addon']),
+ vm: PropTypes.shape({
+ extensionManager: PropTypes.shape({
+ loadExtensionURL: PropTypes.func
+ })
+ }),
+ onClose: PropTypes.func
+};
+
+export default VisualEditorModal;
diff --git a/src/containers/visual-addon-editor-modal.jsx b/src/containers/visual-addon-editor-modal.jsx
new file mode 100644
index 00000000000..b9fd978539a
--- /dev/null
+++ b/src/containers/visual-addon-editor-modal.jsx
@@ -0,0 +1,41 @@
+/**
+ * 可视化插件编辑器容器:接 redux modal 开关 + vm 注入。
+ */
+import PropTypes from 'prop-types';
+import React from 'react';
+import {connect} from 'react-redux';
+import {closeVisualAddonEditor} from '../reducers/modals';
+
+const VisualEditorModal = React.lazy(() => import('../components/visual-editor/visual-editor-modal.jsx'));
+
+const mapStateToProps = state => ({
+ visible: state.scratchGui.modals.visualAddonEditor,
+ vm: state.scratchGui.vm
+});
+
+const mapDispatchToProps = dispatch => ({
+ onClose: () => dispatch(closeVisualAddonEditor())
+});
+
+const VisualAddonEditorContainer = props => (
+ props.visible ? (
+
+
+
+ ) : null
+);
+
+VisualAddonEditorContainer.propTypes = {
+ visible: PropTypes.bool,
+ vm: PropTypes.shape({}),
+ onClose: PropTypes.func
+};
+
+export default connect(
+ mapStateToProps,
+ mapDispatchToProps
+)(VisualAddonEditorContainer);
diff --git a/src/containers/visual-extension-editor-modal.jsx b/src/containers/visual-extension-editor-modal.jsx
new file mode 100644
index 00000000000..8b40225a96a
--- /dev/null
+++ b/src/containers/visual-extension-editor-modal.jsx
@@ -0,0 +1,41 @@
+/**
+ * 可视化扩展编辑器容器:接 redux modal 开关 + vm 注入。
+ */
+import PropTypes from 'prop-types';
+import React from 'react';
+import {connect} from 'react-redux';
+import {closeVisualExtensionEditor} from '../reducers/modals';
+
+const VisualEditorModal = React.lazy(() => import('../components/visual-editor/visual-editor-modal.jsx'));
+
+const mapStateToProps = state => ({
+ visible: state.scratchGui.modals.visualExtensionEditor,
+ vm: state.scratchGui.vm
+});
+
+const mapDispatchToProps = dispatch => ({
+ onClose: () => dispatch(closeVisualExtensionEditor())
+});
+
+const VisualExtensionEditorContainer = props => (
+ props.visible ? (
+
+
+
+ ) : null
+);
+
+VisualExtensionEditorContainer.propTypes = {
+ visible: PropTypes.bool,
+ vm: PropTypes.shape({}),
+ onClose: PropTypes.func
+};
+
+export default connect(
+ mapStateToProps,
+ mapDispatchToProps
+)(VisualExtensionEditorContainer);
diff --git a/src/lib/tw-translations/local-messages.js b/src/lib/tw-translations/local-messages.js
index 5a8db60da6f..2c9eb2a474b 100644
--- a/src/lib/tw-translations/local-messages.js
+++ b/src/lib/tw-translations/local-messages.js
@@ -458,6 +458,10 @@ const localMessages = {
'gui.menuBar.normalMode': '普通模式',
'gui.menuBar.caturdayMode': '猫猫模式',
+ // 可视化扩展/插件编辑器(工具菜单)
+ 'mw.menuBar.visualExtensionEditor': '可视化扩展编辑器',
+ 'mw.menuBar.visualAddonEditor': '可视化插件编辑器',
+
// WebGL 不支持提示
'tw.browserModal.webglDesktop': '你也可以试试在桌面端设置里打开「硬件加速」选项:',
'tw.browserModal.webglBrowser': '请使用较新版本的 Chrome、Firefox 或 Safari,并确保显卡驱动已更新。你也可以试试在浏览器设置里打开「图形加速」或「硬件加速」选项。',
diff --git a/src/lib/visual-node-engine/compile.js b/src/lib/visual-node-engine/compile.js
new file mode 100644
index 00000000000..910462d6ec5
--- /dev/null
+++ b/src/lib/visual-node-engine/compile.js
@@ -0,0 +1,312 @@
+/**
+ * 可视化节点编辑器 · 编译器(graph → JS)
+ *
+ * 输出结构:
+ * - 头部注释 /* VE-GRAPH ... * / 内嵌完整图 JSON(往返转换的锚点)
+ * - 每个语句节点输出行尾标记 // ⟦id⟧(调试/对位用)
+ * - extension 模式:Scratch.extensions.register 类模板
+ * - addon 模式:manifest + default async function 模板
+ */
+import {getType, lit, q} from './node-types.js';
+
+const MARK = id => ` /*⟦${id}⟧*/`;
+
+const makeCtx = (graph, opts) => {
+ const {mode, level = 0, funcNames, blockBodyArgs, scopeGraph} = opts;
+ const indent = n => ' '.repeat(level + n);
+ const getNode = id => graph.nodes.find(n => n.id === id);
+
+ const ctx = {
+ graph,
+ mode,
+ level,
+ indent,
+
+ // ---- 参数读取 ----
+ param: (node, name) => node.params ? node.params[name] : null,
+ paramStr: (node, name) => q(String(node.params ? node.params[name] : '')),
+ ident: (node, name) => {
+ const raw = String(node.params && node.params[name] || '');
+ const m = raw.match(/^[A-Za-z_$][A-Za-z0-9_$]*$/);
+ return m ? m[0] : null;
+ },
+
+ // ---- 表达式求值(递归内联) ----
+ expr: (node, portName) => {
+ const type = getType(node.type);
+ if (!type) return 'null';
+ // 有连线:找源节点
+ const edge = graph.edges.find(
+ e => e.to.node === node.id && e.to.port === portName
+ );
+ if (edge) {
+ const src = getNode(edge.from.node);
+ if (src) {
+ const srcType = getType(src.type);
+ if (srcType && srcType.isExpression) {
+ return srcType.compileExpr(ctx, src);
+ }
+ return 'null';
+ }
+ }
+ // 无连线:params 字面量 / 代码片段
+ const raw = node.params ? node.params[portName] : null;
+ const def = (type.params || []).find(p => p.name === portName);
+ if (def && def.type === 'number') return `(${raw === '' || raw == null ? def.default : Number(raw) || 0})`;
+ if (def && def.type === 'bool') return String(!!raw);
+ if (def && (def.type === 'code' || def.type === 'json')) return `(${raw === '' || raw == null ? def.default : String(raw)})`;
+ return lit(raw === undefined ? def.default : raw);
+ },
+
+ // ---- 语句链生成 ----
+ chainStatements: (node, outPort = 'exec') => {
+ const outgoing = graph.edges
+ .filter(e => e.from.node === node.id && e.from.port === outPort)
+ .sort((a, b) => (a.order || 0) - (b.order || 0));
+ const lines = [];
+ for (const edge of outgoing) {
+ const target = getNode(edge.to.node);
+ if (!target) continue;
+ const targetType = getType(target.type);
+ if (!targetType || targetType.isExpression || targetType.isFunction || targetType.isExtensionBlock) continue;
+ lines.push(...ctx.statements(target));
+ }
+ return lines;
+ },
+
+ // 生成单个语句节点的语句(含行尾标记)
+ statements: node => {
+ const type = getType(node.type);
+ if (!type || !type.compile) return [];
+ const out = type.compile(ctx, node);
+ const flat = Array.isArray(out) ? out : String(out).split('\n');
+ return flat.map(line => line.trim() === '' ? line : `${line}${MARK(node.id)}`);
+ },
+
+ // 控制流节点用:生成嵌套体(已缩进字符串块)
+ chain: (node, outPort = 'exec', depth = 1) => {
+ const lines = ctx.chainStatements(node, outPort);
+ return lines.map(l => indent(depth) + l).join('\n');
+ },
+
+ // 子图编译(函数体/积木回调/定时器回调)
+ subGraph: (node, paramName, depth) => {
+ const body = node.params && node.params[paramName];
+ if (!body || !body.nodes || body.nodes.length === 0) {
+ return indent(depth) + '// (空)';
+ }
+ const sub = makeCtx(body, {
+ mode,
+ level: level + depth,
+ funcNames,
+ blockBodyArgs
+ });
+ return sub.compileTop().map(l => ' '.repeat(depth) + l).join('\n');
+ },
+
+ // ---- 函数相关(func-call 用) ----
+ funcName: node => {
+ const refId = node.params && node.params.funcNodeId;
+ const target = refId && getNode(refId);
+ if (target && target.params && target.params.name) {
+ return `fn_${String(target.params.name).replace(/[^A-Za-z0-9_]/g, '_')}`;
+ }
+ return 'fn_unknown';
+ },
+ argsList: (node, portName = 'args') => {
+ // 收集连入本节点指定输入端口的多根线 + 无连线时的文本参数
+ const incoming = graph.edges
+ .filter(e => e.to.node === node.id && e.to.port === portName)
+ .sort((a, b) => (a.order || 0) - (b.order || 0));
+ const parts = [];
+ for (const edge of incoming) {
+ const srcNode = getNode(edge.from.node);
+ const srcT = srcNode && getType(srcNode.type);
+ if (srcNode && srcT && srcT.isExpression) {
+ parts.push(srcT.compileExpr(ctx, srcNode));
+ }
+ }
+ const text = node.params && (node.params.argsText !== undefined ? node.params.argsText : node.params[portName]);
+ if (text) String(text).split(',').map(s => s.trim()).filter(Boolean).forEach(s => parts.push(s));
+ return parts.join(', ');
+ },
+
+ // ---- 箭头函数(func-arrow) ----
+ argsOfArrow: node => String(node.params && node.params.args || '').trim(),
+ bodyOfArrow: node => {
+ const body = node.params && node.params.bodyGraph;
+ if (!body || !body.nodes || body.nodes.length === 0) return 'null';
+ const sub = makeCtx(body, {mode, level: 0, funcNames, blockBodyArgs});
+ const lines = sub.compileTop();
+ if (lines.length === 1 && !lines[0].includes('\n') && /;$/.test(lines[0])) {
+ return `(${lines[0].slice(0, -1)})`;
+ }
+ return `{\n${lines.map(l => ' ' + l).join('\n')}\n}`;
+ },
+
+ // 顶层:事件节点 + 语句孤儿 → 代码
+ compileTop: () => {
+ const lines = [];
+ const covered = new Set();
+ // 1) 事件节点(含函数/积木定义在顶层展开处理)
+ for (const node of graph.nodes) {
+ const type = getType(node.type);
+ if (!type) continue;
+ if (type.isEvent) {
+ covered.add(node.id);
+ const out = type.compile ? type.compile(ctx, node) : [];
+ (Array.isArray(out) ? out : String(out).split('\n'))
+ .forEach(l => lines.push(l));
+ } else if (type.isFunction) {
+ covered.add(node.id);
+ lines.push(...compileFunctionDef(ctx, node, graph, mode, level));
+ } else if (type.isExtensionBlock) {
+ covered.add(node.id);
+ // 积木定义收集到块清单(由模板层聚合)
+ (opts.blocks = opts.blocks || []).push(node);
+ }
+ }
+ // 2) 顶层散落语句(有 exec 输入且不是事件,且无入边)
+ for (const node of graph.nodes) {
+ if (covered.has(node.id)) continue;
+ const type = getType(node.type);
+ if (!type || type.isExpression || type.isEvent || type.isFunction || type.isExtensionBlock) continue;
+ const hasIn = type.inputs && type.inputs.some(i => i.kind === 'exec') &&
+ graph.edges.some(e => e.to.node === node.id && e.to.port === 'exec');
+ if (!hasIn) {
+ covered.add(node.id);
+ lines.push(...ctx.statements(node));
+ // 该节点后续链已由 statements 内 chain 生成
+ }
+ }
+ return lines;
+ }
+ };
+ void scopeGraph;
+ void funcNames;
+ void blockBodyArgs;
+ return ctx;
+};
+
+/** 函数定义:在顶层展开为 async/normal 函数声明 */
+const compileFunctionDef = (ctx, node, graph, mode, level) => {
+ const name = `fn_${String(node.params.name || 'myFunction').replace(/[^A-Za-z0-9_]/g, '_')}`;
+ const args = String(node.params.args || '').split(',').map(s => s.trim()).filter(Boolean);
+ const isAsync = !!node.params.isAsync;
+ const body = node.params.bodyGraph;
+ const lines = [`${isAsync ? 'async ' : ''}function ${name}(${args.join(', ')}) {`];
+ if (body && body.nodes && body.nodes.length) {
+ const sub = makeCtx(body, {mode, level: level + 1, blocks: ctx.__opts && ctx.__opts.blocks});
+ sub.compileTop().forEach(l => lines.push(' ' + l));
+ } else {
+ lines.push(' // (空函数体)');
+ }
+ lines.push(`}${MARK(node.id)}`);
+ return lines;
+};
+
+/** 事件节点包 async:PROJECT_START 等回调里允许 await */
+const wrapAsync = fnHeader => `${fnHeader}`;
+
+/**
+ * 主入口:graph → 完整 JS 文件内容
+ * @param {object} graph {nodes, edges}
+ * @param {string} mode 'extension' | 'addon'
+ * @param {object} meta {name, description, blockCount...}(插件 manifest / 扩展信息)
+ */
+const compile = (graph, mode, meta) => {
+ const opts = {mode, blocks: []};
+ const ctx = makeCtx(graph, opts);
+ ctx.__opts = opts;
+ const bodyLines = ctx.compileTop();
+ const graphJson = JSON.stringify({mode, meta, graph});
+ const header = `/* VE-GRAPH v1 ${encodeURIComponent(graphJson)} */`;
+
+ if (mode === 'extension') {
+ return buildExtension(header, bodyLines, opts.blocks, meta);
+ }
+ return buildAddon(header, bodyLines, meta);
+};
+
+// ---- 扩展模板 ----
+const buildExtension = (header, bodyLines, blockNodes, meta) => {
+ const name = (meta && meta.name) || 'MyExtension';
+ const id = (meta && meta.id) || 'myExtension';
+ const blockDefs = (blockNodes || []).map(node => {
+ const p = node.params || {};
+ const args = p.args || '[]';
+ const blockType = p.blockType || 'command';
+ return ` {
+ opcode: ${q(p.opcode || 'myBlock')},
+ blockType: Scratch.BlockType.${blockType.toUpperCase()},
+ text: ${q(p.text || '我的积木')},
+ arguments: ${args}
+ }`;
+ }).join(',\n');
+
+ const blocksCode = blockDefs ? `\n getInfo () {\n return {\n id: ${q(id)},\n name: ${q(name)},\n blocks: [\n${blockDefs}\n ]\n };\n }` : '';
+
+ const blockBodies = (blockNodes || []).map(node => {
+ const p = node.params || {};
+ const body = p.bodyGraph;
+ let inner = ' // (空)';
+ if (body && body.nodes && body.nodes.length) {
+ const sub = makeCtx(body, {mode: 'extension', level: 2});
+ inner = sub.compileTop().map(l => ' ' + l).join('\n');
+ }
+ return ` async ${p.opcode || 'myBlock'} (args, util) {\n${inner}\n }${MARK(node.id)}`;
+ }).join('\n');
+
+ return `${header}
+// 可视化扩展编辑器生成 —— ${name}
+// 由节点图编译;顶部 VE-GRAPH 注释保存完整节点图(导入即可回到可视化编辑)
+class ${id.replace(/[^A-Za-z0-9_]/g, '_')} {
+ constructor () {
+ this.vm = typeof vm !== 'undefined' ? vm : (typeof window !== 'undefined' && window.vm);
+ }${blocksCode}
+${blockBodies}
+}
+
+(function register () {
+ const instance = new ${id.replace(/[^A-Za-z0-9_]/g, '_')}();
+ if (typeof Scratch !== 'undefined' && Scratch.extensions) {
+ Scratch.extensions.register(instance);
+ } else if (typeof window !== 'undefined' && window.__mwExtensionRegistrar) {
+ window.__mwExtensionRegistrar(instance);
+ }
+})();
+
+// ---- 顶层事件/逻辑 ----
+(async function main () {
+${bodyLines.map(l => ' ' + l).join('\n')}
+})();
+`;
+};
+
+// ---- 插件模板 ----
+const buildAddon = (header, bodyLines, meta) => {
+ const m = meta || {};
+ const settingsJson = JSON.stringify(m.settings || [], null, 8)
+ .replace(/^/gm, ' '.repeat(0)).replace(/\n/g, '\n ');
+ const manifest = `export const manifest = {
+ name: ${q(m.name || '我的插件')},
+ description: ${q(m.description || '由可视化插件编辑器生成')},
+ tags: ['custom'],
+ enabledByDefault: ${!!m.enabledByDefault},${m.css ? `\n css: ${q(m.css)},` : ''}
+ settings: ${settingsJson}
+};`;
+
+ return `${header}
+// 可视化插件编辑器生成 —— ${m.name || '我的插件'}
+// 由节点图编译;顶部 VE-GRAPH 注释保存完整节点图(导入即可回到可视化编辑)
+
+${manifest}
+
+export default async function ({addon, console, msg}) {
+${bodyLines.map(l => ' ' + l).join('\n')}
+ return Promise.resolve();
+};
+`;
+};
+
+export {compile, MARK};
diff --git a/src/lib/visual-node-engine/graph-model.js b/src/lib/visual-node-engine/graph-model.js
new file mode 100644
index 00000000000..ce12b4ebf80
--- /dev/null
+++ b/src/lib/visual-node-engine/graph-model.js
@@ -0,0 +1,99 @@
+/**
+ * 可视化节点编辑器 · 数据模型(graph model)
+ * 节点图:nodes + edges;端口分 exec(控制流)/ data(数据流)。
+ * 连线规则:exec→exec(一进多出按序号)、data→data;data 端口无连线时取 params 字面量。
+ */
+
+let nextId = 1;
+const genId = () => `n${(nextId++).toString(36)}${Date.now().toString(36).slice(-4)}`;
+
+const createGraph = () => ({
+ nodes: [],
+ edges: []
+});
+
+const createNode = (typeId, x, y, params) => ({
+ id: genId(),
+ type: typeId,
+ x: Math.round(x),
+ y: Math.round(y),
+ params: params || null
+});
+
+const addNode = (graph, node) => {
+ graph.nodes.push(node);
+ return node;
+};
+
+const removeNode = (graph, nodeId) => {
+ graph.nodes = graph.nodes.filter(n => n.id !== nodeId);
+ graph.edges = graph.edges.filter(e => e.from.node !== nodeId && e.to.node !== nodeId);
+};
+
+const moveNode = (graph, nodeId, x, y) => {
+ const node = graph.nodes.find(n => n.id === nodeId);
+ if (node) {
+ node.x = Math.round(x);
+ node.y = Math.round(y);
+ }
+};
+
+/** 端口占用查询:一个 data 输入端口只能接一根线 */
+const findEdgeTo = (graph, nodeId, portName) =>
+ graph.edges.find(e => e.to.node === nodeId && e.to.port === portName);
+
+const findEdgesFrom = (graph, nodeId, portName) =>
+ graph.edges.filter(e => e.from.node === nodeId && e.from.port === portName)
+ .sort((a, b) => (a.order || 0) - (b.order || 0));
+
+const connect = (graph, fromNode, fromPort, toNode, toPort) => {
+ // 禁止自连
+ if (fromNode === toNode) return null;
+ // data 输入端口独占:先移除旧线
+ if (toPort !== 'exec') {
+ graph.edges = graph.edges.filter(e => !(e.to.node === toNode && e.to.port === toPort));
+ } else {
+ // 同一 exec 输出口到同一目标去重
+ graph.edges = graph.edges.filter(
+ e => !(e.from.node === fromNode && e.from.port === fromPort && e.to.node === toNode)
+ );
+ }
+ graph.edges.push({
+ from: {node: fromNode, port: fromPort},
+ to: {node: toNode, port: toPort},
+ order: findEdgesFrom(graph, fromNode, fromPort).length
+ });
+ return graph.edges[graph.edges.length - 1];
+};
+
+const disconnect = (graph, edge) => {
+ const idx = graph.edges.indexOf(edge);
+ if (idx !== -1) graph.edges.splice(idx, 1);
+};
+
+/** 返回 data 输入端口的取值来源:连线则回节点 id,否则 params 字面量 */
+const inputOf = (graph, node, portName) => {
+ const edge = findEdgeTo(graph, node.id, portName);
+ if (edge) return {connected: true, node: edge.from.node};
+ const fallback = (node.params && node.params[portName]) !== undefined ?
+ node.params[portName] :
+ null;
+ return {connected: false, value: fallback};
+};
+
+const getNode = (graph, id) => graph.nodes.find(n => n.id === id);
+
+export {
+ createGraph,
+ createNode,
+ addNode,
+ removeNode,
+ moveNode,
+ getNode,
+ findEdgeTo,
+ findEdgesFrom,
+ connect,
+ disconnect,
+ inputOf,
+ genId
+};
diff --git a/src/lib/visual-node-engine/node-types.js b/src/lib/visual-node-engine/node-types.js
new file mode 100644
index 00000000000..8f3db7540a7
--- /dev/null
+++ b/src/lib/visual-node-engine/node-types.js
@@ -0,0 +1,1193 @@
+/**
+ * 可视化节点编辑器 · 节点类型目录(node catalog)
+ *
+ * 约定:
+ * - 语句节点:有 exec 输入/输出,compile(ctx, node) 返回代码字符串数组;
+ * ctx.chain(node, outPort) 沿 exec 链继续生成。
+ * - 表达式节点:无 exec 端口,compileExpr(ctx, node) 返回表达式字符串;
+ * ctx.expr(node, portName) 递归内联。
+ * - 子图:函数体/积木回调的图 JSON 存于 params.bodyGraph,
+ * 双击节点进入子图编辑(UI 面包屑导航)。
+ * - 万能逃生舱:misc-expression / misc-statement —— 任意 JS 表达式/语句,
+ * 保证「JS 能写的节点都能做」。
+ */
+
+// ---- 表达式工具:字面量 → JS ----
+const lit = v => {
+ if (v === null || v === undefined) return String(v);
+ if (typeof v === 'object') return JSON.stringify(v);
+ return JSON.stringify(v);
+};
+
+const q = s => JSON.stringify(String(s));
+
+/**
+ * 节点目录。category 用于面板分组。
+ * inputs/outputs: {name, label, kind: 'exec'|'data'}
+ * params: {name, label, type: 'text'|'number'|'bool'|'select'|'code'|'json'|'graph',
+ * default, options?, placeholder?}
+ */
+const NODE_TYPES = [
+ // ============================== 事件 ==============================
+ {
+ id: 'event-start',
+ category: '事件',
+ title: '程序启动',
+ outputs: [{name: 'exec', label: '', kind: 'exec'}],
+ params: [],
+ isEvent: true,
+ compile: (ctx, node) => ctx.chain(node)
+ },
+ {
+ id: 'event-green-flag',
+ category: '事件',
+ title: '当绿旗被点击',
+ outputs: [{name: 'exec', label: '', kind: 'exec'}],
+ params: [],
+ isEvent: true,
+ compile: (ctx, node) => `vm.runtime.on('PROJECT_START', () => {\n${ctx.chain(node, 'exec', 1)}\n});`
+ },
+ {
+ id: 'event-stop',
+ category: '事件',
+ title: '当停止按钮被点击',
+ outputs: [{name: 'exec', label: '', kind: 'exec'}],
+ params: [],
+ isEvent: true,
+ compile: (ctx, node) => `vm.runtime.on('PROJECT_STOP_ALL', () => {\n${ctx.chain(node, 'exec', 1)}\n});`
+ },
+ {
+ id: 'event-broadcast',
+ category: '事件',
+ title: '当接收到广播',
+ outputs: [{name: 'exec', label: '', kind: 'exec'}],
+ params: [
+ {name: 'name', label: '广播名称', type: 'text', default: '消息1'}
+ ],
+ isEvent: true,
+ compile: (ctx, node) => `vm.runtime.on('BROADCAST_MESSAGE_RECEIVED_${ctx.param(node, 'name') || ''}', () => {\n${ctx.chain(node, 'exec', 1)}\n});`
+ },
+ {
+ id: 'event-key',
+ category: '事件',
+ title: '当按下键盘按键',
+ outputs: [{name: 'exec', label: '', kind: 'exec'}],
+ params: [
+ {name: 'key', label: '按键', type: 'text', default: 'a', placeholder: 'a / space / left …'}
+ ],
+ isEvent: true,
+ compile: (ctx, node) => `vm.runtime.on('KEY_PRESSED', k => {\n if (k === ${ctx.paramStr(node, 'key')}) {\n${ctx.chain(node, 'exec', 2)}\n }\n});`
+ },
+ {
+ id: 'event-sprite-click',
+ category: '事件',
+ title: '当角色被点击',
+ outputs: [{name: 'exec', label: '', kind: 'exec'}],
+ params: [],
+ isEvent: true,
+ compile: (ctx, node) => `vm.runtime.on('TARGET_CLICKED', () => {\n${ctx.chain(node, 'exec', 1)}\n});`
+ },
+ {
+ id: 'event-tick',
+ category: '事件',
+ title: '每帧循环',
+ outputs: [{name: 'exec', label: '', kind: 'exec'}],
+ params: [],
+ isEvent: true,
+ compile: (ctx, node) => `vm.runtime.on('BEFORE_STEP', () => {\n${ctx.chain(node, 'exec', 1)}\n});`
+ },
+ {
+ id: 'event-dom',
+ category: '事件',
+ title: '当 DOM 元素触发事件',
+ outputs: [{name: 'exec', label: '', kind: 'exec'}],
+ params: [
+ {name: 'selector', label: 'CSS 选择器', type: 'text', default: 'button'},
+ {name: 'event', label: '事件类型', type: 'select', default: 'click',
+ options: ['click', 'input', 'change', 'keydown', 'keyup', 'mousedown', 'dblclick']}
+ ],
+ isEvent: true,
+ compile: (ctx, node) => `document.querySelectorAll(${ctx.paramStr(node, 'selector')}).forEach(el => {\n el.addEventListener(${ctx.paramStr(node, 'event')}, () => {\n${ctx.chain(node, 'exec', 2)}\n });\n});`
+ },
+ {
+ id: 'event-addon-setting',
+ category: '事件',
+ title: '当插件设置项改变(插件)',
+ outputs: [{name: 'exec', label: '', kind: 'exec'}],
+ params: [{name: 'settingId', label: '设置 ID', type: 'text', default: 'mySetting'}],
+ isEvent: true,
+ addonOnly: true,
+ compile: (ctx, node) => `addon.settings.addEventListener('change', e => {\n if (e.detail && e.detail.id === ${ctx.paramStr(node, 'settingId')}) {\n${ctx.chain(node, 'exec', 2)}\n }\n});`
+ },
+ {
+ id: 'event-project-changed',
+ category: '事件',
+ title: '当作品内容改变',
+ outputs: [{name: 'exec', label: '', kind: 'exec'}],
+ params: [],
+ isEvent: true,
+ compile: (ctx, node) => `vm.runtime.on('PROJECT_CHANGED', () => {\n${ctx.chain(node, 'exec', 1)}\n});`
+ },
+
+ // ============================== 流程控制 ==============================
+ {
+ id: 'control-if',
+ category: '流程控制',
+ title: '如果…就…',
+ inputs: [
+ {name: 'exec', label: '', kind: 'exec'},
+ {name: 'condition', label: '条件', kind: 'data'}
+ ],
+ outputs: [{name: 'exec', label: '', kind: 'exec'}],
+ params: [{name: 'condition', label: '条件(无连线时)', type: 'code', default: 'true'}],
+ compile: (ctx, node) => [
+ `if (${ctx.expr(node, 'condition')}) {`,
+ ctx.chain(node, 'exec', 1),
+ `}`
+ ]
+ },
+ {
+ id: 'control-if-else',
+ category: '流程控制',
+ title: '如果…否则…',
+ inputs: [
+ {name: 'exec', label: '', kind: 'exec'},
+ {name: 'condition', label: '条件', kind: 'data'}
+ ],
+ outputs: [
+ {name: 'exec', label: '真', kind: 'exec'},
+ {name: 'execFalse', label: '假', kind: 'exec'}
+ ],
+ params: [{name: 'condition', label: '条件(无连线时)', type: 'code', default: 'true'}],
+ compile: (ctx, node) => [
+ `if (${ctx.expr(node, 'condition')}) {`,
+ ctx.chain(node, 'exec', 1),
+ `} else {`,
+ ctx.chain(node, 'execFalse', 1),
+ `}`
+ ]
+ },
+ {
+ id: 'control-for',
+ category: '流程控制',
+ title: '循环…次',
+ inputs: [
+ {name: 'exec', label: '', kind: 'exec'},
+ {name: 'from', label: '起始', kind: 'data'},
+ {name: 'to', label: '结束', kind: 'data'},
+ {name: 'by', label: '步长', kind: 'data'}
+ ],
+ outputs: [{name: 'exec', label: '', kind: 'exec'}],
+ params: [
+ {name: 'from', label: '起始', type: 'number', default: 1},
+ {name: 'to', label: '结束', type: 'number', default: 10},
+ {name: 'by', label: '步长', type: 'number', default: 1},
+ {name: 'varName', label: '循环变量名', type: 'text', default: 'i'}
+ ],
+ compile: (ctx, node) => {
+ const v = ctx.ident(node, 'varName') || 'i';
+ return [
+ `for (let ${v} = ${ctx.expr(node, 'from')}; ${v} <= ${ctx.expr(node, 'to')}; ${v} += ${ctx.expr(node, 'by')}) {`,
+ ctx.chain(node, 'exec', 1),
+ `}`
+ ];
+ }
+ },
+ {
+ id: 'control-while',
+ category: '流程控制',
+ title: '重复执行 当…',
+ inputs: [
+ {name: 'exec', label: '', kind: 'exec'},
+ {name: 'condition', label: '条件', kind: 'data'}
+ ],
+ outputs: [{name: 'exec', label: '', kind: 'exec'}],
+ params: [{name: 'condition', label: '条件(无连线时)', type: 'code', default: 'true'}],
+ compile: (ctx, node) => [
+ `while (${ctx.expr(node, 'condition')}) {`,
+ ctx.chain(node, 'exec', 1),
+ `}`
+ ]
+ },
+ {
+ id: 'control-for-each',
+ category: '流程控制',
+ title: '遍历列表…',
+ inputs: [
+ {name: 'exec', label: '', kind: 'exec'},
+ {name: 'list', label: '列表', kind: 'data'}
+ ],
+ outputs: [{name: 'exec', label: '', kind: 'exec'}],
+ params: [
+ {name: 'list', label: '列表(无连线时)', type: 'code', default: '[1, 2, 3]'},
+ {name: 'varName', label: '元素变量名', type: 'text', default: 'item'}
+ ],
+ compile: (ctx, node) => {
+ const v = ctx.ident(node, 'varName') || 'item';
+ return [
+ `for (const ${v} of ${ctx.expr(node, 'list')}) {`,
+ ctx.chain(node, 'exec', 1),
+ `}`
+ ];
+ }
+ },
+ {
+ id: 'control-break',
+ category: '流程控制',
+ title: '跳出循环',
+ inputs: [{name: 'exec', label: '', kind: 'exec'}],
+ params: [],
+ compile: () => ['break;']
+ },
+ {
+ id: 'control-continue',
+ category: '流程控制',
+ title: '继续下一次循环',
+ inputs: [{name: 'exec', label: '', kind: 'exec'}],
+ params: [],
+ compile: () => ['continue;']
+ },
+ {
+ id: 'control-return',
+ category: '流程控制',
+ title: '返回值',
+ inputs: [
+ {name: 'exec', label: '', kind: 'exec'},
+ {name: 'value', label: '返回值', kind: 'data'}
+ ],
+ params: [{name: 'value', label: '返回值(无连线时)', type: 'code', default: 'null'}],
+ compile: (ctx, node) => [`return ${ctx.expr(node, 'value')};`]
+ },
+ {
+ id: 'control-wait',
+ category: '流程控制',
+ title: '等待…秒(异步)',
+ inputs: [
+ {name: 'exec', label: '', kind: 'exec'},
+ {name: 'seconds', label: '秒数', kind: 'data'}
+ ],
+ outputs: [{name: 'exec', label: '', kind: 'exec'}],
+ params: [{name: 'seconds', label: '秒数', type: 'number', default: 1}],
+ compile: (ctx, node) => [
+ `await new Promise(r => setTimeout(r, ${ctx.expr(node, 'seconds')} * 1000));`,
+ ...ctx.chainStatements(node)
+ ]
+ },
+ {
+ id: 'control-try-catch',
+ category: '流程控制',
+ title: '尝试 / 捕获错误',
+ inputs: [{name: 'exec', label: '', kind: 'exec'}],
+ outputs: [
+ {name: 'exec', label: '尝试', kind: 'exec'},
+ {name: 'execCatch', label: '捕获', kind: 'exec'}
+ ],
+ params: [{name: 'errVar', label: '错误变量名', type: 'text', default: 'e'}],
+ compile: (ctx, node) => {
+ const v = ctx.ident(node, 'errVar') || 'e';
+ return [
+ 'try {',
+ ctx.chain(node, 'exec', 1),
+ `} catch (${v}) {`,
+ ctx.chain(node, 'execCatch', 1),
+ '}'
+ ];
+ }
+ },
+ {
+ id: 'control-comment',
+ category: '流程控制',
+ title: '注释(仅文档)',
+ inputs: [{name: 'exec', label: '', kind: 'exec'}],
+ outputs: [{name: 'exec', label: '', kind: 'exec'}],
+ params: [{name: 'text', label: '注释内容', type: 'text', default: '说明…', multiline: true}],
+ compile: (ctx, node) => [`/* ${String(ctx.param(node, 'text') || '').replace('*/', '* /')} */`, ...ctx.chainStatements(node)]
+ },
+
+ // ============================== 变量 ==============================
+ {
+ id: 'data-set-var',
+ category: '变量',
+ title: '设置变量',
+ inputs: [
+ {name: 'exec', label: '', kind: 'exec'},
+ {name: 'value', label: '值', kind: 'data'}
+ ],
+ outputs: [{name: 'exec', label: '', kind: 'exec'}],
+ params: [
+ {name: 'name', label: '变量名', type: 'text', default: 'myVar'},
+ {name: 'value', label: '值(无连线时)', type: 'code', default: '0'},
+ {name: 'scope', label: '声明方式', type: 'select', default: 'let',
+ options: ['let', 'const', 'var', '赋值(不声明)']}
+ ],
+ compile: (ctx, node) => {
+ const name = ctx.ident(node, 'name') || 'myVar';
+ const val = ctx.expr(node, 'value');
+ const how = ctx.param(node, 'scope') || 'let';
+ return [how === '赋值(不声明)' ? `${name} = ${val};` : `${how} ${name} = ${val};`];
+ }
+ },
+ {
+ id: 'data-get-var',
+ category: '变量',
+ title: '读取变量',
+ outputs: [{name: 'value', label: '值', kind: 'data'}],
+ params: [{name: 'name', label: '变量名', type: 'text', default: 'myVar'}],
+ isExpression: true,
+ compileExpr: (ctx, node) => ctx.ident(node, 'name') || 'undefined'
+ },
+ {
+ id: 'data-literal',
+ category: '变量',
+ title: '字面量',
+ outputs: [{name: 'value', label: '值', kind: 'data'}],
+ params: [
+ {name: 'literalType', label: '类型', type: 'select', default: 'number',
+ options: ['number', 'string', 'boolean', 'null', 'undefined', '对象/数组(JSON]']},
+ {name: 'value', label: '值', type: 'code', default: '0'}
+ ],
+ isExpression: true,
+ compileExpr: (ctx, node) => {
+ const t = ctx.param(node, 'literalType');
+ const v = ctx.param(node, 'value');
+ if (t === 'number') return `(${v === '' || v == null ? 0 : v})`;
+ if (t === 'string') return lit(String(v == null ? '' : v));
+ if (t === 'boolean') return String(!!v);
+ if (t === 'null') return 'null';
+ if (t === 'undefined') return 'undefined';
+ return `(${v || '{}'})`; // 对象/数组:直接当 JS 表达式
+ }
+ },
+ {
+ id: 'data-object-field',
+ category: '变量',
+ title: '取对象字段',
+ inputs: [{name: 'object', label: '对象', kind: 'data'}],
+ outputs: [{name: 'value', label: '值', kind: 'data'}],
+ params: [
+ {name: 'object', label: '对象(无连线时)', type: 'code', default: '{}'},
+ {name: 'field', label: '字段名', type: 'text', default: 'name'},
+ {name: 'optional', label: '可选链 ?.', type: 'bool', default: false}
+ ],
+ isExpression: true,
+ compileExpr: (ctx, node) => {
+ const f = ctx.ident(node, 'field') || 'x';
+ return `${ctx.expr(node, 'object')}${ctx.param(node, 'optional') ? '?.' : '.'}${f}`;
+ }
+ },
+ {
+ id: 'data-array-index',
+ category: '变量',
+ title: '取数组元素',
+ inputs: [
+ {name: 'array', label: '数组', kind: 'data'},
+ {name: 'index', label: '下标', kind: 'data'}
+ ],
+ outputs: [{name: 'value', label: '值', kind: 'data'}],
+ params: [
+ {name: 'array', label: '数组(无连线时)', type: 'code', default: '[]'},
+ {name: 'index', label: '下标', type: 'number', default: 0}
+ ],
+ isExpression: true,
+ compileExpr: (ctx, node) => `${ctx.expr(node, 'array')}[${ctx.expr(node, 'index')}]`
+ },
+
+ // ============================== 运算 ==============================
+ {
+ id: 'op-math',
+ category: '运算',
+ title: '算术运算',
+ inputs: [
+ {name: 'a', label: 'A', kind: 'data'},
+ {name: 'b', label: 'B', kind: 'data'}
+ ],
+ outputs: [{name: 'value', label: '结果', kind: 'data'}],
+ params: [
+ {name: 'a', label: 'A', type: 'code', default: '0'},
+ {name: 'b', label: 'B', type: 'code', default: '0'},
+ {name: 'operator', label: '运算符', type: 'select', default: '+',
+ options: ['+', '-', '*', '/', '%', '**']}
+ ],
+ isExpression: true,
+ compileExpr: (ctx, node) => `(${ctx.expr(node, 'a')} ${ctx.param(node, 'operator')} ${ctx.expr(node, 'b')})`
+ },
+ {
+ id: 'op-compare',
+ category: '运算',
+ title: '比较',
+ inputs: [
+ {name: 'a', label: 'A', kind: 'data'},
+ {name: 'b', label: 'B', kind: 'data'}
+ ],
+ outputs: [{name: 'value', label: '结果', kind: 'data'}],
+ params: [
+ {name: 'a', label: 'A', type: 'code', default: '0'},
+ {name: 'b', label: 'B', type: 'code', default: '0'},
+ {name: 'operator', label: '运算符', type: 'select', default: '===',
+ options: ['===', '!==', '==', '!=', '<', '>', '<=', '>=']}
+ ],
+ isExpression: true,
+ compileExpr: (ctx, node) => `(${ctx.expr(node, 'a')} ${ctx.param(node, 'operator')} ${ctx.expr(node, 'b')})`
+ },
+ {
+ id: 'op-logic',
+ category: '运算',
+ title: '逻辑运算',
+ inputs: [
+ {name: 'a', label: 'A', kind: 'data'},
+ {name: 'b', label: 'B', kind: 'data'}
+ ],
+ outputs: [{name: 'value', label: '结果', kind: 'data'}],
+ params: [
+ {name: 'a', label: 'A', type: 'code', default: 'true'},
+ {name: 'b', label: 'B', type: 'code', default: 'true'},
+ {name: 'operator', label: '运算符', type: 'select', default: '&&',
+ options: ['&&', '||']}
+ ],
+ isExpression: true,
+ compileExpr: (ctx, node) => `(${ctx.expr(node, 'a')} ${ctx.param(node, 'operator')} ${ctx.expr(node, 'b')})`
+ },
+ {
+ id: 'op-not',
+ category: '运算',
+ title: '取反 !',
+ inputs: [{name: 'a', label: 'A', kind: 'data'}],
+ outputs: [{name: 'value', label: '结果', kind: 'data'}],
+ params: [{name: 'a', label: 'A', type: 'code', default: 'false'}],
+ isExpression: true,
+ compileExpr: (ctx, node) => `(!(${ctx.expr(node, 'a')}))`
+ },
+ {
+ id: 'op-ternary',
+ category: '运算',
+ title: '三元判断',
+ inputs: [
+ {name: 'condition', label: '条件', kind: 'data'},
+ {name: 'ifTrue', label: '真值', kind: 'data'},
+ {name: 'ifFalse', label: '假值', kind: 'data'}
+ ],
+ outputs: [{name: 'value', label: '结果', kind: 'data'}],
+ params: [
+ {name: 'condition', label: '条件', type: 'code', default: 'true'},
+ {name: 'ifTrue', label: '真值', type: 'code', default: '1'},
+ {name: 'ifFalse', label: '假值', type: 'code', default: '0'}
+ ],
+ isExpression: true,
+ compileExpr: (ctx, node) => `(${ctx.expr(node, 'condition')} ? (${ctx.expr(node, 'ifTrue')}) : (${ctx.expr(node, 'ifFalse')}))`
+ },
+ {
+ id: 'op-math-fn',
+ category: '运算',
+ title: '数学函数',
+ inputs: [
+ {name: 'a', label: '参数', kind: 'data'},
+ {name: 'b', label: '第二参数(可选)', kind: 'data'}
+ ],
+ outputs: [{name: 'value', label: '结果', kind: 'data'}],
+ params: [
+ {name: 'a', label: '参数', type: 'code', default: '0'},
+ {name: 'b', label: '第二参数(可选)', type: 'code', default: ''},
+ {name: 'fn', label: '函数', type: 'select', default: 'round',
+ options: ['abs', 'ceil', 'floor', 'round', 'trunc', 'sqrt', 'cbrt', 'random',
+ 'min', 'max', 'pow', 'sin', 'cos', 'tan', 'atan2', 'log', 'log2', 'log10', 'exp',
+ 'sign', 'hypot']}
+ ],
+ isExpression: true,
+ compileExpr: (ctx, node) => {
+ const fn = ctx.param(node, 'fn') || 'round';
+ const a = ctx.expr(node, 'a');
+ const b = ctx.param(node, 'b');
+ if (b === '' || b === null) {
+ if (['min', 'max', 'pow', 'atan2', 'hypot'].includes(fn)) return `Math.${fn}(${a})`;
+ return `Math.${fn}(${a})`;
+ }
+ return `Math.${fn}(${a}, ${ctx.expr(node, 'b')})`;
+ }
+ },
+ {
+ id: 'op-string-fn',
+ category: '运算',
+ title: '字符串操作',
+ inputs: [
+ {name: 'str', label: '字符串', kind: 'data'},
+ {name: 'arg', label: '参数(可选)', kind: 'data'}
+ ],
+ outputs: [{name: 'value', label: '结果', kind: 'data'}],
+ params: [
+ {name: 'str', label: '字符串', type: 'code', default: "'文本'"},
+ {name: 'arg', label: '参数(可选)', type: 'code', default: ''},
+ {name: 'fn', label: '操作', type: 'select', default: 'length',
+ options: ['length', 'toUpperCase', 'toLowerCase', 'trim', 'concat', 'includes',
+ 'indexOf', 'substring', 'slice', 'replace', 'replaceAll', 'split',
+ 'startsWith', 'endsWith', 'padStart', 'padEnd', 'repeat', 'charAt']}
+ ],
+ isExpression: true,
+ compileExpr: (ctx, node) => {
+ const fn = ctx.param(node, 'fn') || 'length';
+ const s = ctx.expr(node, 'str');
+ const arg = ctx.param(node, 'arg');
+ const noArg = ['length', 'toUpperCase', 'toLowerCase', 'trim'];
+ if (noArg.includes(fn) || arg === '' || arg === null) {
+ return fn === 'length' ? `${s}.length` : `${s}.${fn}()`;
+ }
+ return `${s}.${fn}(${ctx.expr(node, 'arg')})`;
+ }
+ },
+ {
+ id: 'op-template-string',
+ category: '运算',
+ title: '模板字符串',
+ inputs: [{name: 'parts', label: '拼接值(可多个)', kind: 'data', multi: true}],
+ outputs: [{name: 'value', label: '结果', kind: 'data'}],
+ params: [{name: 'text', label: '模板(${} 内放表达式)', type: 'code', default: '你好,${name}'}],
+ isExpression: true,
+ compileExpr: (ctx, node) => '`' + String(ctx.param(node, 'text') || '')
+ .replace(/`/g, '\\`').replace(/\$\{/g, '${') + '`'
+ },
+ {
+ id: 'op-json',
+ category: '运算',
+ title: 'JSON 序列化/解析',
+ inputs: [{name: 'value', label: '值', kind: 'data'}],
+ outputs: [{name: 'value', label: '结果', kind: 'data'}],
+ params: [
+ {name: 'value', label: '值(无连线时)', type: 'code', default: '{}'},
+ {name: 'mode', label: '模式', type: 'select', default: 'stringify',
+ options: ['stringify', 'parse']}
+ ],
+ isExpression: true,
+ compileExpr: (ctx, node) => ctx.param(node, 'mode') === 'parse' ?
+ `JSON.parse(${ctx.expr(node, 'value')})` :
+ `JSON.stringify(${ctx.expr(node, 'value')})`
+ },
+ {
+ id: 'op-spread',
+ category: '运算',
+ title: '展开运算符 …',
+ inputs: [{name: 'value', label: '值', kind: 'data'}],
+ outputs: [{name: 'value', label: '结果', kind: 'data'}],
+ params: [{name: 'value', label: '值(无连线时)', type: 'code', default: '[]'}],
+ isExpression: true,
+ compileExpr: (ctx, node) => `...(${ctx.expr(node, 'value')})`
+ },
+
+ // ============================== 函数 ==============================
+ {
+ id: 'func-define',
+ category: '函数',
+ title: '定义函数(子图)',
+ outputs: [{name: 'exec', label: '', kind: 'exec'}],
+ params: [
+ {name: 'name', label: '函数名', type: 'text', default: 'myFunction'},
+ {name: 'args', label: '参数名(逗号分隔)', type: 'text', default: ''},
+ {name: 'isAsync', label: 'async 函数', type: 'bool', default: false},
+ {name: 'bodyGraph', label: '函数体(双击编辑)', type: 'graph'}
+ ],
+ isFunction: true,
+ compile: () => [] // 函数定义在编译器顶层展开(见 compile.js)
+ },
+ {
+ id: 'func-call',
+ category: '函数',
+ title: '调用函数',
+ inputs: [
+ {name: 'exec', label: '', kind: 'exec'},
+ {name: 'args', label: '实参(可多个)', kind: 'data', multi: true}
+ ],
+ outputs: [{name: 'exec', label: '', kind: 'exec'}],
+ params: [
+ {name: 'funcNodeId', label: '目标函数节点', type: 'text', default: ''},
+ {name: 'argsText', label: '实参(无连线时,逗号分隔)', type: 'code', default: ''}
+ ],
+ compile: (ctx, node) => [
+ `${ctx.funcName(node)}(${ctx.argsList(node)});`,
+ ...ctx.chainStatements(node)
+ ]
+ },
+ {
+ id: 'func-call-expr',
+ category: '函数',
+ title: '调用函数(表达式)',
+ inputs: [{name: 'args', label: '实参(可多个)', kind: 'data', multi: true}],
+ outputs: [{name: 'value', label: '结果', kind: 'data'}],
+ params: [
+ {name: 'funcNodeId', label: '目标函数节点', type: 'text', default: ''},
+ {name: 'argsText', label: '实参(无连线时)', type: 'code', default: ''}
+ ],
+ isExpression: true,
+ compileExpr: (ctx, node) => `${ctx.funcName(node)}(${ctx.argsList(node)})`
+ },
+ {
+ id: 'func-arrow',
+ category: '函数',
+ title: '箭头函数(当回调用)',
+ inputs: [{name: 'body', label: '函数体(子图)', kind: 'data'}],
+ outputs: [{name: 'value', label: '函数', kind: 'data'}],
+ params: [
+ {name: 'args', label: '参数名(逗号分隔)', type: 'text', default: ''},
+ {name: 'isAsync', label: 'async', type: 'bool', default: false},
+ {name: 'bodyGraph', label: '函数体(双击编辑)', type: 'graph'}
+ ],
+ isExpression: true,
+ compileExpr: (ctx, node) => `(${ctx.argsOfArrow(node)}) => ${ctx.bodyOfArrow(node)}`
+ },
+
+ // ============================== Scratch 交互 ==============================
+ {
+ id: 'sc-say',
+ category: 'Scratch 交互',
+ title: '角色说…',
+ inputs: [
+ {name: 'exec', label: '', kind: 'exec'},
+ {name: 'target', label: '目标角色', kind: 'data'},
+ {name: 'text', label: '文本', kind: 'data'}
+ ],
+ outputs: [{name: 'exec', label: '', kind: 'exec'}],
+ params: [
+ {name: 'target', label: '目标角色(无连线=当前)', type: 'code', default: ''},
+ {name: 'text', label: '文本', type: 'code', default: "'你好'"}
+ ],
+ compile: (ctx, node) => {
+ const tgt = ctx.param(node, 'target');
+ const call = tgt === '' || tgt == null ?
+ `vm.runtime.targets.find(t => t.isOriginal && !t.isStage)?.postSpriteInfo({say: ${ctx.expr(node, 'text')}, sayType: 'say'});` :
+ `(${tgt}).postSpriteInfo({say: ${ctx.expr(node, 'text')}, sayType: 'say'});`;
+ return [call, ...ctx.chainStatements(node)];
+ }
+ },
+ {
+ id: 'sc-broadcast',
+ category: 'Scratch 交互',
+ title: '广播消息',
+ inputs: [
+ {name: 'exec', label: '', kind: 'exec'},
+ {name: 'name', label: '名称', kind: 'data'}
+ ],
+ outputs: [{name: 'exec', label: '', kind: 'exec'}],
+ params: [{name: 'name', label: '广播名称', type: 'text', default: '消息1'}],
+ compile: (ctx, node) => [
+ `vm.runtime.startHats('event_whenbroadcastreceived', { BROADCAST_OPTION: ${ctx.expr(node, 'name')} });`,
+ ...ctx.chainStatements(node)
+ ]
+ },
+ {
+ id: 'sc-get-var',
+ category: 'Scratch 交互',
+ title: '读取 Scratch 变量',
+ outputs: [{name: 'value', label: '值', kind: 'data'}],
+ params: [
+ {name: 'name', label: '变量名', type: 'text', default: '我的变量'},
+ {name: 'target', label: '目标(空=全部查找)', type: 'code', default: ''}
+ ],
+ isExpression: true,
+ compileExpr: (ctx, node) => {
+ const t = ctx.param(node, 'target');
+ const scope = (t === '' || t == null) ?
+ 'vm.runtime.targets.find(t2 => t2.isOriginal && !t2.isStage)' : String(t);
+ return `(${scope}?.lookupVariableByName?.(${ctx.paramStr(node, 'name')})?.value)`;
+ }
+ },
+ {
+ id: 'sc-set-var',
+ category: 'Scratch 交互',
+ title: '设置 Scratch 变量',
+ inputs: [
+ {name: 'exec', label: '', kind: 'exec'},
+ {name: 'value', label: '值', kind: 'data'}
+ ],
+ outputs: [{name: 'exec', label: '', kind: 'exec'}],
+ params: [
+ {name: 'name', label: '变量名', type: 'text', default: '我的变量'},
+ {name: 'value', label: '值', type: 'code', default: '0'},
+ {name: 'target', label: '目标(空=全部查找)', type: 'code', default: ''}
+ ],
+ compile: (ctx, node) => {
+ const t = ctx.param(node, 'target');
+ const scope = (t === '' || t == null) ?
+ 'vm.runtime.targets.find(t2 => t2.isOriginal && !t2.isStage)' : String(t);
+ return [`${scope}?.lookupVariableByName?.(${ctx.paramStr(node, 'name')})?.set?.(${ctx.expr(node, 'value')});`,
+ ...ctx.chainStatements(node)];
+ }
+ },
+ {
+ id: 'sc-get-target',
+ category: 'Scratch 交互',
+ title: '获取角色/舞台对象',
+ outputs: [{name: 'value', label: '对象', kind: 'data'}],
+ params: [
+ {name: 'which', label: '对象', type: 'select', default: '第一个角色',
+ options: ['第一个角色', '舞台', '全部角色列表']}
+ ],
+ isExpression: true,
+ compileExpr: (ctx, node) => {
+ switch (ctx.param(node, 'which')) {
+ case '舞台': return 'vm.runtime.getTargetForStage()';
+ case '全部角色列表': return 'vm.runtime.targets.filter(t => t.isOriginal && !t.isStage)';
+ default: return 'vm.runtime.targets.find(t => t.isOriginal && !t.isStage)';
+ }
+ }
+ },
+ {
+ id: 'sc-stage-size',
+ category: 'Scratch 交互',
+ title: '舞台尺寸',
+ outputs: [
+ {name: 'width', label: '宽', kind: 'data'},
+ {name: 'height', label: '高', kind: 'data'}
+ ],
+ params: [],
+ isExpression: true,
+ compileExpr: (ctx, node) => {
+ if (node.__outPort === 'height') return 'vm.runtime.stageHeight';
+ return 'vm.runtime.stageWidth';
+ }
+ },
+ {
+ id: 'sc-timer',
+ category: 'Scratch 交互',
+ title: '计时器值',
+ outputs: [{name: 'value', label: '秒', kind: 'data'}],
+ params: [],
+ isExpression: true,
+ compileExpr: () => 'vm.runtime.ioDevices.clock.projectTimer()'
+ },
+ {
+ id: 'sc-reset-timer',
+ category: 'Scratch 交互',
+ title: '重置计时器',
+ inputs: [{name: 'exec', label: '', kind: 'exec'}],
+ outputs: [{name: 'exec', label: '', kind: 'exec'}],
+ params: [],
+ compile: (ctx, node) => ['vm.runtime.ioDevices.clock.resetProjectTimer();', ...ctx.chainStatements(node)]
+ },
+ {
+ id: 'sc-create-clone',
+ category: 'Scratch 交互',
+ title: '克隆角色',
+ inputs: [
+ {name: 'exec', label: '', kind: 'exec'},
+ {name: 'target', label: '目标', kind: 'data'}
+ ],
+ outputs: [{name: 'exec', label: '', kind: 'exec'}],
+ params: [
+ {name: 'target', label: '目标(空=第一个角色)', type: 'code', default: ''}
+ ],
+ compile: (ctx, node) => {
+ const t = ctx.param(node, 'target');
+ const tgt = (t === '' || t == null) ? 'vm.runtime.targets.find(t2 => t2.isOriginal && !t2.isStage)' : String(t);
+ return [`${tgt}.clone();`, ...ctx.chainStatements(node)];
+ }
+ },
+ {
+ id: 'sc-get-answer',
+ category: 'Scratch 交互',
+ title: '读取「回答」',
+ outputs: [{name: 'value', label: '值', kind: 'data'}],
+ params: [],
+ isExpression: true,
+ compileExpr: () => 'vm.runtime._pristineAnswer'
+ },
+
+ // ============================== DOM / UI ==============================
+ {
+ id: 'dom-console',
+ category: 'DOM/UI',
+ title: '控制台输出',
+ inputs: [
+ {name: 'exec', label: '', kind: 'exec'},
+ {name: 'value', label: '内容', kind: 'data', multi: true}
+ ],
+ outputs: [{name: 'exec', label: '', kind: 'exec'}],
+ params: [
+ {name: 'value', label: '内容(无连线时)', type: 'code', default: "'日志'"},
+ {name: 'level', label: '级别', type: 'select', default: 'log',
+ options: ['log', 'info', 'warn', 'error', 'debug']}
+ ],
+ compile: (ctx, node) => [
+ `console.${ctx.param(node, 'level') || 'log'}(${ctx.argsList(node, 'value')});`,
+ ...ctx.chainStatements(node)
+ ]
+ },
+ {
+ id: 'dom-alert',
+ category: 'DOM/UI',
+ title: '弹出警告框',
+ inputs: [
+ {name: 'exec', label: '', kind: 'exec'},
+ {name: 'text', label: '文本', kind: 'data'}
+ ],
+ outputs: [{name: 'exec', label: '', kind: 'exec'}],
+ params: [{name: 'text', label: '文本', type: 'code', default: "'提示'"}],
+ compile: (ctx, node) => [`alert(${ctx.expr(node, 'text')});`, ...ctx.chainStatements(node)]
+ },
+ {
+ id: 'dom-prompt',
+ category: 'DOM/UI',
+ title: '输入框(返回输入值)',
+ inputs: [{name: 'text', label: '提示文本', kind: 'data'}],
+ outputs: [{name: 'value', label: '输入值', kind: 'data'}],
+ params: [
+ {name: 'text', label: '提示文本', type: 'code', default: "'输入:'"},
+ {name: 'defaultValue', label: '默认值', type: 'code', default: "''"}
+ ],
+ isExpression: true,
+ compileExpr: (ctx, node) => `prompt(${ctx.expr(node, 'text')}, ${ctx.expr(node, 'defaultValue')})`
+ },
+ {
+ id: 'dom-query',
+ category: 'DOM/UI',
+ title: '查找 DOM 元素',
+ outputs: [{name: 'value', label: '元素', kind: 'data'}],
+ params: [
+ {name: 'selector', label: 'CSS 选择器', type: 'text', default: 'button'},
+ {name: 'mode', label: '模式', type: 'select', default: 'querySelector',
+ options: ['querySelector', 'querySelectorAll']}
+ ],
+ isExpression: true,
+ compileExpr: (ctx, node) => ctx.param(node, 'mode') === 'querySelectorAll' ?
+ `Array.from(document.querySelectorAll(${ctx.paramStr(node, 'selector')}))` :
+ `document.querySelector(${ctx.paramStr(node, 'selector')})`
+ },
+ {
+ id: 'dom-set-style',
+ category: 'DOM/UI',
+ title: '设置元素样式/属性',
+ inputs: [
+ {name: 'exec', label: '', kind: 'exec'},
+ {name: 'element', label: '元素', kind: 'data'},
+ {name: 'value', label: '值', kind: 'data'}
+ ],
+ outputs: [{name: 'exec', label: '', kind: 'exec'}],
+ params: [
+ {name: 'element', label: '元素(无连线时)', type: 'code', default: 'document.body'},
+ {name: 'prop', label: '属性名', type: 'text', default: 'textContent'},
+ {name: 'value', label: '值', type: 'code', default: "''"},
+ {name: 'target', label: '写到', type: 'select', default: '属性(=)',
+ options: ['属性(=)', 'style.样式', 'classList.add', 'classList.remove', 'dataset']}
+ ],
+ compile: (ctx, node) => {
+ const el = ctx.expr(node, 'element');
+ const prop = ctx.ident(node, 'prop') || 'textContent';
+ const val = ctx.expr(node, 'value');
+ let call;
+ switch (ctx.param(node, 'target')) {
+ case 'style.样式': call = `${el}.style.${prop} = ${val};`; break;
+ case 'classList.add': call = `${el}.classList.add(${ctx.paramStr(node, 'prop')});`; break;
+ case 'classList.remove': call = `${el}.classList.remove(${ctx.paramStr(node, 'prop')});`; break;
+ case 'dataset': call = `${el}.dataset.${prop} = ${val};`; break;
+ default: call = `${el}[${ctx.paramStr(node, 'prop')}] = ${val};`;
+ }
+ return [call, ...ctx.chainStatements(node)];
+ }
+ },
+ {
+ id: 'dom-create-element',
+ category: 'DOM/UI',
+ title: '创建元素并加入页面',
+ inputs: [
+ {name: 'exec', label: '', kind: 'exec'},
+ {name: 'text', label: '文本内容(可选)', kind: 'data'}
+ ],
+ outputs: [{name: 'exec', label: '', kind: 'exec'}],
+ params: [
+ {name: 'tag', label: '标签名', type: 'text', default: 'div'},
+ {name: 'text', label: '文本内容', type: 'code', default: "''"},
+ {name: 'parent', label: '挂载到(空=body)', type: 'code', default: ''}
+ ],
+ compile: (ctx, node) => {
+ const tag = ctx.ident(node, 'tag') || 'div';
+ const parent = ctx.param(node, 'parent');
+ const p = (parent === '' || parent == null) ? 'document.body' : String(parent);
+ return [
+ `(() => { const el = document.createElement(${q(tag)}); el.textContent = ${ctx.expr(node, 'text')}; ${p}.appendChild(el); })();`,
+ ...ctx.chainStatements(node)
+ ];
+ }
+ },
+
+ // ============================== 网络 / 存储 / 高级 ==============================
+ {
+ id: 'net-fetch',
+ category: '网络/存储',
+ title: 'fetch 网络请求(异步)',
+ inputs: [
+ {name: 'exec', label: '', kind: 'exec'},
+ {name: 'url', label: 'URL', kind: 'data'},
+ {name: 'body', label: '请求体(可选)', kind: 'data'}
+ ],
+ outputs: [
+ {name: 'exec', label: '', kind: 'exec'},
+ {name: 'value', label: '结果', kind: 'data'}
+ ],
+ params: [
+ {name: 'url', label: 'URL', type: 'text', default: 'https://api.example.com'},
+ {name: 'method', label: '方法', type: 'select', default: 'GET',
+ options: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH']},
+ {name: 'body', label: '请求体(可选)', type: 'code', default: ''},
+ {name: 'respType', label: '响应处理', type: 'select', default: 'json',
+ options: ['json', 'text', '无(原始Response]']},
+ {name: 'resultVar', label: '结果存入变量', type: 'text', default: 'fetchResult'}
+ ],
+ compile: (ctx, node) => {
+ const method = ctx.param(node, 'method') || 'GET';
+ const bodyPart = ['POST', 'PUT', 'PATCH'].includes(method) ?
+ `, body: JSON.stringify(${ctx.expr(node, 'body') || 'null'})` : '';
+ const rt = ctx.param(node, 'respType');
+ const rtPart = rt === 'json' ? '.then(r => r.json())' :
+ (rt === 'text' ? '.then(r => r.text())' : '');
+ const v = ctx.ident(node, 'resultVar') || 'fetchResult';
+ return [
+ `${v} = await fetch(${ctx.expr(node, 'url')}, {method: ${q(method)}${bodyPart}})${rtPart};`,
+ ...ctx.chainStatements(node)
+ ];
+ }
+ },
+ {
+ id: 'storage-get',
+ category: '网络/存储',
+ title: '读取 localStorage',
+ outputs: [{name: 'value', label: '值', kind: 'data'}],
+ params: [
+ {name: 'key', label: '键名', type: 'text', default: 'myKey'},
+ {name: 'mode', label: '模式', type: 'select', default: '原样',
+ options: ['原样', '解析JSON']}
+ ],
+ isExpression: true,
+ compileExpr: (ctx, node) => {
+ const get = `localStorage.getItem(${ctx.paramStr(node, 'key')})`;
+ return ctx.param(node, 'mode') === '解析JSON' ? `JSON.parse(${get})` : get;
+ }
+ },
+ {
+ id: 'storage-set',
+ category: '网络/存储',
+ title: '写入 localStorage',
+ inputs: [
+ {name: 'exec', label: '', kind: 'exec'},
+ {name: 'value', label: '值', kind: 'data'}
+ ],
+ outputs: [{name: 'exec', label: '', kind: 'exec'}],
+ params: [
+ {name: 'key', label: '键名', type: 'text', default: 'myKey'},
+ {name: 'value', label: '值', type: 'code', default: "''"},
+ {name: 'mode', label: '模式', type: 'select', default: '原样',
+ options: ['原样', '序列化JSON']}
+ ],
+ compile: (ctx, node) => {
+ const v = ctx.param(node, 'mode') === '序列化JSON' ?
+ `JSON.stringify(${ctx.expr(node, 'value')})` : ctx.expr(node, 'value');
+ return [`localStorage.setItem(${ctx.paramStr(node, 'key')}, ${v});`, ...ctx.chainStatements(node)];
+ }
+ },
+ {
+ id: 'misc-set-timeout',
+ category: '网络/存储',
+ title: '定时器(子图回调)',
+ outputs: [{name: 'exec', label: '', kind: 'exec'}],
+ params: [
+ {name: 'mode', label: '模式', type: 'select', default: 'setTimeout',
+ options: ['setTimeout', 'setInterval']},
+ {name: 'ms', label: '毫秒', type: 'number', default: 1000},
+ {name: 'bodyGraph', label: '回调(双击编辑)', type: 'graph'}
+ ],
+ isEvent: true,
+ compile: (ctx, node) => `${ctx.param(node, 'mode') || 'setTimeout'}(() => {
+${ctx.subGraph(node, 'bodyGraph', 1)}
+}, ${ctx.param(node, 'ms') || 1000});`
+ },
+ {
+ id: 'misc-random',
+ category: '网络/存储',
+ title: '随机数',
+ inputs: [
+ {name: 'min', label: '最小', kind: 'data'},
+ {name: 'max', label: '最大', kind: 'data'}
+ ],
+ outputs: [{name: 'value', label: '值', kind: 'data'}],
+ params: [
+ {name: 'min', label: '最小(无连线时)', type: 'number', default: 1},
+ {name: 'max', label: '最大(无连线时)', type: 'number', default: 10},
+ {name: 'mode', label: '模式', type: 'select', default: '整数范围',
+ options: ['整数范围', '0~1 小数', 'UUID']}
+ ],
+ isExpression: true,
+ compileExpr: (ctx, node) => {
+ switch (ctx.param(node, 'mode')) {
+ case '0~1 小数': return 'Math.random()';
+ case 'UUID': return 'crypto.randomUUID()';
+ default: return `Math.floor(Math.random() * ((${ctx.expr(node, 'max')}) - (${ctx.expr(node, 'min')}) + 1) + (${ctx.expr(node, 'min')}))`;
+ }
+ }
+ },
+ {
+ id: 'misc-expression',
+ category: '网络/存储',
+ title: '★ 任意 JS 表达式',
+ outputs: [{name: 'value', label: '结果', kind: 'data'}],
+ params: [{name: 'code', label: 'JS 表达式', type: 'code',
+ default: 'Date.now()', multiline: true}],
+ isExpression: true,
+ compileExpr: (ctx, node) => `(${ctx.param(node, 'code') || 'undefined'})`
+ },
+ {
+ id: 'misc-statement',
+ category: '网络/存储',
+ title: '★ 任意 JS 语句',
+ inputs: [{name: 'exec', label: '', kind: 'exec'}],
+ outputs: [{name: 'exec', label: '', kind: 'exec'}],
+ params: [{name: 'code', label: 'JS 语句', type: 'code',
+ default: '// 在此写任意 JS', multiline: true}],
+ compile: (ctx, node) => [String(ctx.param(node, 'code') || '').trim() || ';']
+ },
+ {
+ id: 'misc-await',
+ category: '网络/存储',
+ title: 'await 表达式(异步)',
+ inputs: [{name: 'value', label: 'Promise', kind: 'data'}],
+ outputs: [{name: 'value', label: '结果', kind: 'data'}],
+ params: [{name: 'value', label: 'Promise(无连线时)', type: 'code', default: 'Promise.resolve(1)'}],
+ isExpression: true,
+ compileExpr: (ctx, node) => `(await (${ctx.expr(node, 'value')}))`
+ },
+ {
+ id: 'misc-promise-all',
+ category: '网络/存储',
+ title: 'Promise.all',
+ inputs: [{name: 'value', label: 'Promise 列表', kind: 'data'}],
+ outputs: [{name: 'value', label: '结果', kind: 'data'}],
+ params: [{name: 'value', label: '列表(无连线时)', type: 'code', default: '[]'}],
+ isExpression: true,
+ compileExpr: (ctx, node) => `(await Promise.all(${ctx.expr(node, 'value')}))`
+ },
+
+ // ============================== 扩展专用(积木定义) ==============================
+ {
+ id: 'ext-define-block',
+ category: '扩展积木',
+ title: '定义积木(子图=积木逻辑)',
+ outputs: [{name: 'exec', label: '', kind: 'exec'}],
+ params: [
+ {name: 'opcode', label: '积木 opcode', type: 'text', default: 'myBlock'},
+ {name: 'text', label: '积木文本([参数] 占位)', type: 'text', default: '我的积木 [A]'},
+ {name: 'blockType', label: '积木类型', type: 'select', default: 'command',
+ options: ['command', 'reporter', 'boolean']},
+ {name: 'args', label: '参数定义(JSON数组)', type: 'code',
+ default: '[{"type": "input_value", "name": "A", "default": "1"}]'},
+ {name: 'bodyGraph', label: '积木逻辑(双击编辑)', type: 'graph'}
+ ],
+ isExtensionBlock: true,
+ compile: () => [] // 由 compile.js 顶层展开
+ },
+ {
+ id: 'ext-block-arg',
+ category: '扩展积木',
+ title: '积木参数值',
+ outputs: [{name: 'value', label: '值', kind: 'data'}],
+ params: [{name: 'argName', label: '参数名', type: 'text', default: 'A'}],
+ isExpression: true,
+ onlyInBlockBody: true,
+ compileExpr: (ctx, node) => `args[${ctx.paramStr(node, 'argName')}]`
+ },
+
+ // ============================== 插件专用 ==============================
+ {
+ id: 'addon-api',
+ category: '插件 API',
+ title: 'addon API 对象',
+ outputs: [{name: 'value', label: 'addon', kind: 'data'}],
+ params: [],
+ isExpression: true,
+ addonOnly: true,
+ compileExpr: () => 'addon'
+ },
+ {
+ id: 'addon-tab',
+ category: '插件 API',
+ title: 'addon.tab(编辑器 API)',
+ outputs: [{name: 'value', label: 'tab', kind: 'data'}],
+ params: [],
+ isExpression: true,
+ addonOnly: true,
+ compileExpr: () => 'addon.tab'
+ },
+ {
+ id: 'addon-scratch',
+ category: '插件 API',
+ title: 'addon.scratch(vm 等)',
+ outputs: [{name: 'value', label: '对象', kind: 'data'}],
+ params: [
+ {name: 'member', label: '成员', type: 'select', default: 'vm',
+ options: ['vm', 'blocks', 'renderer']}
+ ],
+ isExpression: true,
+ addonOnly: true,
+ compileExpr: (ctx, node) => `addon.scratch.${ctx.param(node, 'member') || 'vm'}`
+ },
+ {
+ id: 'addon-settings-get',
+ category: '插件 API',
+ title: '读取插件设置项',
+ outputs: [{name: 'value', label: '值', kind: 'data'}],
+ params: [{name: 'settingId', label: '设置 ID', type: 'text', default: 'mySetting'}],
+ isExpression: true,
+ addonOnly: true,
+ compileExpr: (ctx, node) => `addon.settings.get(${ctx.paramStr(node, 'settingId')})`
+ },
+ {
+ id: 'addon-wait',
+ category: '插件 API',
+ title: '等待条件成立(轮询)',
+ inputs: [{name: 'condition', label: '条件', kind: 'data'}],
+ outputs: [{name: 'value', label: '结果', kind: 'data'}],
+ params: [
+ {name: 'condition', label: '条件(无连线时)', type: 'code', default: 'true'},
+ {name: 'interval', label: '轮询间隔(ms)', type: 'number', default: 100}
+ ],
+ isExpression: true,
+ addonOnly: true,
+ compileExpr: (ctx, node) => `(await (async () => { while (!(${ctx.expr(node, 'condition')})) await new Promise(r => setTimeout(r, ${ctx.param(node, 'interval') || 100})); })())`
+ },
+ {
+ id: 'addon-wait-for-element',
+ category: '插件 API',
+ title: '等待 DOM 元素出现',
+ outputs: [{name: 'value', label: '元素', kind: 'data'}],
+ params: [
+ {name: 'selector', label: 'CSS 选择器', type: 'text', default: 'button'},
+ {name: 'mode', label: '模式', type: 'select', default: 'waitForElement',
+ options: ['waitForElement']}
+ ],
+ isExpression: true,
+ addonOnly: true,
+ compileExpr: (ctx, node) => `(await addon.tab.waitForElement(${ctx.paramStr(node, 'selector')}))`
+ },
+ {
+ id: 'addon-append-css',
+ category: '插件 API',
+ title: '注入自定义 CSS',
+ outputs: [{name: 'value', label: 'style元素', kind: 'data'}],
+ params: [{name: 'css', label: 'CSS 文本', type: 'code', default: 'body{color:red}', multiline: true}],
+ isExpression: true,
+ addonOnly: true,
+ compileExpr: (ctx, node) => `(() => { const s = document.createElement('style'); s.textContent = ${ctx.paramStr(node, 'css')}; document.head.appendChild(s); return s; })()`
+ },
+ {
+ id: 'addon-msg',
+ category: '插件 API',
+ title: '翻译文本 msg()',
+ inputs: [{name: 'text', label: '默认文本', kind: 'data'}],
+ outputs: [{name: 'value', label: '结果', kind: 'data'}],
+ params: [{name: 'text', label: '默认文本', type: 'code', default: "'我的文本'"}],
+ isExpression: true,
+ addonOnly: true,
+ compileExpr: (ctx, node) => `msg(${ctx.expr(node, 'text')})`
+ }
+];
+
+// 索引与分类
+const TYPE_MAP = new Map(NODE_TYPES.map(t => [t.id, t]));
+const CATEGORIES = [...new Set(NODE_TYPES.map(t => t.category))];
+
+const getType = id => TYPE_MAP.get(id);
+
+export {NODE_TYPES, TYPE_MAP, CATEGORIES, getType, lit, q};
diff --git a/src/lib/visual-node-engine/parse.js b/src/lib/visual-node-engine/parse.js
new file mode 100644
index 00000000000..25fde5c053c
--- /dev/null
+++ b/src/lib/visual-node-engine/parse.js
@@ -0,0 +1,211 @@
+/**
+ * 可视化节点编辑器 · 解析器(JS → graph)
+ *
+ * 两级策略:
+ * 1. 完美往返:编译产物头部有 /* VE-GRAPH v1 * / 注释,
+ * 直接还原完整节点图(含全部参数/坐标/连线)。
+ * 2. 外部代码导入:逐语句扫描 → misc-statement(任意 JS 语句)节点串;
+ * 识别常见事件特征(PROJECT_START / broadcast / addEventListener …)
+ * 生成对应事件节点,其余语句挂在其 exec 链上。
+ */
+import {createGraph, createNode, addNode, connect} from './graph-model.js';
+
+/** 从代码提取 VE-GRAPH 头 */
+const extractVeGraph = code => {
+ const m = code.match(/\/\*\s*VE-GRAPH v1 ([^*]+?)\s*\*\//);
+ if (!m) return null;
+ try {
+ const data = JSON.parse(decodeURIComponent(m[1]));
+ if (data && data.graph && Array.isArray(data.graph.nodes)) {
+ return data; // {mode, meta, graph}
+ }
+ } catch (e) { /* 损坏则回退普通导入 */ }
+ return null;
+};
+
+/** 简易语句切分:按顶层 ; 与 {} 分块(不追求完整 JS 语法) */
+const splitStatements = code => {
+ const out = [];
+ let buf = '';
+ let depth = 0;
+ let inStr = null;
+ let inLine = false;
+ let inBlock = false;
+ for (let i = 0; i < code.length; i++) {
+ const c = code[i];
+ const next = code[i + 1];
+ if (inLine) {
+ if (c === '\n') inLine = false;
+ buf += c;
+ continue;
+ }
+ if (inBlock) {
+ buf += c;
+ if (c === '*' && next === '/') { inBlock = false; buf += next; i++; }
+ continue;
+ }
+ if (c === '/' && next === '/') { inLine = true; buf += c; continue; }
+ if (c === '/' && next === '*') { inBlock = true; buf += c; continue; }
+ if (inStr) {
+ buf += c;
+ if (c === '\\') { buf += next || ''; i++; continue; }
+ if (c === inStr || (inStr === '`' && c === '`')) {
+ if (c === inStr) inStr = null;
+ }
+ continue;
+ }
+ if (c === '"' || c === "'" || c === '`') { inStr = c; buf += c; continue; }
+ if (c === '{' || c === '[' || c === '(') { depth++; buf += c; continue; }
+ if (c === '}' || c === ']' || c === ')') { depth--; buf += c; continue; }
+ if (c === '\n' && depth === 0 && buf.trim() &&
+ /[)}\]'"`]$/.test(buf.trim())) {
+ out.push(buf.trim());
+ buf = '';
+ continue;
+ }
+ if (c === ';' && depth === 0) {
+ buf += c;
+ out.push(buf.trim());
+ buf = '';
+ continue;
+ }
+ buf += c;
+ }
+ if (buf.trim()) out.push(buf.trim());
+ return out.filter(Boolean);
+};
+
+/** 事件特征识别:返回事件节点 typeId 或 null */
+const sniffEvent = stmt => {
+ if (/PROJECT_START/.test(stmt)) return 'event-green-flag';
+ if (/PROJECT_STOP_ALL/.test(stmt)) return 'event-stop';
+ if (/PROJECT_CHANGED/.test(stmt)) return 'event-project-changed';
+ if (/BROADCAST_MESSAGE_RECEIVED/.test(stmt)) {
+ const m = stmt.match(/BROADCAST_MESSAGE_RECEIVED_(\w*)/);
+ return {type: 'event-broadcast', name: m ? m[1] : '消息1'};
+ }
+ if (/KEY_PRESSED/.test(stmt)) {
+ const m = stmt.match(/k\s*===\s*['"](.+?)['"]/);
+ return {type: 'event-key', key: m ? m[1] : 'a'};
+ }
+ if (/TARGET_CLICKED/.test(stmt)) return 'event-sprite-click';
+ if (/BEFORE_STEP/.test(stmt)) return 'event-tick';
+ if (/addEventListener\s*\(\s*['"](\w+)['"]/.test(stmt)) {
+ const m = stmt.match(/querySelector(?:All)?\s*\(\s*['"](.+?)['"]/);
+ const ev = stmt.match(/addEventListener\s*\(\s*['"](\w+)['"]/);
+ if (m && ev) return {type: 'event-dom', selector: m[1], event: ev[1]};
+ }
+ return null;
+};
+
+/** 事件命中后:提取包装语句的函数体内部语句(尽力而为) */
+const extractBodyStmts = stmt => {
+ // 匹配 (...) => { body } 或 function () { body } 的最深 { body }(尾部)
+ const m = stmt.match(/(?:=>|function\s*\([^)]*\))\s*\{([\s\S]*)\}\s*\);?\s*$/);
+ if (!m) return [];
+ const inner = m[1];
+ if (!inner.trim()) return [];
+ return splitStatements(inner);
+};
+
+/** 外部代码 → 图(尽力而为) */
+const importCode = (code, mode) => {
+ const graph = createGraph();
+ const stmts = splitStatements(code);
+ let anchorX = 40;
+ let anchorY = 60;
+ let lastExecNode = null;
+ let fallbackEvent = null;
+ let eventCount = 0;
+
+ // 先找事件特征语句,把其余语句挂到最近事件
+ const entries = [];
+ for (const stmt of stmts) {
+ const ev = sniffEvent(stmt);
+ entries.push({stmt, ev});
+ }
+
+ for (const {stmt, ev} of entries) {
+ if (ev) {
+ const spec = typeof ev === 'string' ? {type: ev} : ev;
+ const node = createNode(spec.type, anchorX, anchorY, {
+ name: spec.name, key: spec.key,
+ selector: spec.selector, event: spec.event
+ });
+ // 清洗 null 参数
+ for (const k of Object.keys(node.params)) {
+ if (node.params[k] === undefined) delete node.params[k];
+ }
+ addNode(graph, node);
+ lastExecNode = node;
+ eventCount++;
+ anchorY += 90;
+ // 包装语句的函数体内部语句 → misc-statement 链
+ let innerAnchor = lastExecNode;
+ for (const inner of extractBodyStmts(stmt)) {
+ const sNode = createNode('misc-statement', anchorX + 280, anchorY - 90, {code: inner});
+ addNode(graph, sNode);
+ if (innerAnchor) connect(graph, innerAnchor.id, 'exec', sNode.id, 'exec');
+ innerAnchor = sNode;
+ anchorY += 80;
+ }
+ continue;
+ }
+ // 普通语句 → misc-statement
+ const node = createNode('misc-statement', anchorX + 280, anchorY, {code: stmt});
+ addNode(graph, node);
+ if (lastExecNode) {
+ connect(graph, lastExecNode.id, 'exec', node.id, 'exec');
+ anchorY += 80;
+ } else {
+ // 还没有事件:先攒着,最后挂 fallback 事件
+ if (!fallbackEvent) {
+ fallbackEvent = createNode('event-start', anchorX, anchorY - 90, {});
+ addNode(graph, fallbackEvent);
+ eventCount++;
+ }
+ connect(graph, fallbackEvent.id, 'exec', node.id, 'exec');
+ anchorY += 80;
+ }
+ }
+ if (eventCount === 0) {
+ // 全是散语句:补一个启动事件
+ fallbackEvent = createNode('event-start', 40, 40, {});
+ addNode(graph, fallbackEvent);
+ // 挂到已有第一个语句
+ const firstStmt = graph.nodes.find(n => n.type === 'misc-statement');
+ if (firstStmt) connect(graph, fallbackEvent.id, 'exec', firstStmt.id, 'exec');
+ }
+ return {graph, partial: true};
+};
+
+/** 主入口:js 代码 → {graph, meta, mode, partial} */
+const parse = code => {
+ const ve = extractVeGraph(code);
+ if (ve) {
+ return {
+ graph: ve.graph,
+ meta: ve.meta || {},
+ mode: ve.mode || 'extension',
+ partial: false
+ };
+ }
+ const sniffed = /export const manifest/.test(code) ? 'addon' :
+ (/Scratch\.extensions\.register/.test(code) ? 'extension' : null);
+ const mode = sniffed || 'extension';
+ const res = importCode(code, mode);
+ // addon 代码:尽力提取 manifest 字段
+ let meta = {};
+ const nameM = code.match(/name:\s*['"]([^'"]+)['"]/);
+ const descM = code.match(/description:\s*['"]([^'"]+)['"]/);
+ if (nameM) meta.name = nameM[1];
+ if (descM) meta.description = descM[1];
+ return {
+ graph: res.graph,
+ meta,
+ mode,
+ partial: true
+ };
+};
+
+export {parse, extractVeGraph, splitStatements};
diff --git a/src/lib/visual-node-engine/templates.js b/src/lib/visual-node-engine/templates.js
new file mode 100644
index 00000000000..db8456cef5c
--- /dev/null
+++ b/src/lib/visual-node-engine/templates.js
@@ -0,0 +1,67 @@
+/**
+ * 可视化节点编辑器 · 模板与示例图
+ */
+
+/** 新扩展的起始图 */
+const extensionStarterGraph = mode => ({
+ nodes: [
+ {id: 'evt1', type: 'event-start', x: 60, y: 80, params: {}},
+ {id: 'stmt1', type: 'misc-statement', x: 380, y: 80,
+ params: {code: "console.log('扩展已启动');"}}
+ ],
+ edges: [
+ {from: {node: 'evt1', port: 'exec'}, to: {node: 'stmt1', port: 'exec'}, order: 0}
+ ]
+});
+
+/** 新插件的起始图 */
+const addonStarterGraph = () => ({
+ nodes: [
+ {id: 'evt1', type: 'event-start', x: 60, y: 80, params: {}},
+ {id: 'stmt1', type: 'dom-console', x: 380, y: 80,
+ params: {value: "'插件已运行'", level: 'log'}}
+ ],
+ edges: [
+ {from: {node: 'evt1', port: 'exec'}, to: {node: 'stmt1', port: 'exec'}, order: 0}
+ ]
+});
+
+/** 插件默认 manifest 元信息 */
+const defaultMeta = mode => mode === 'addon' ? {
+ name: '我的插件',
+ description: '由可视化插件编辑器生成',
+ enabledByDefault: false,
+ settings: [],
+ css: ''
+} : {
+ name: '我的扩展',
+ id: 'myExtension',
+ description: ''
+};
+
+/** 示例:带积木的扩展图(供「载入示例」) */
+const extensionDemoGraph = () => ({
+ nodes: [
+ {id: 'blk1', type: 'ext-define-block', x: 60, y: 60, params: {
+ opcode: 'sayHello',
+ text: '打个招呼 [TEXT]',
+ blockType: 'command',
+ args: '[{"type": "input_value", "name": "TEXT", "default": "你好"}]',
+ bodyGraph: {
+ nodes: [
+ {id: 'b1', type: 'misc-statement', x: 60, y: 60,
+ params: {code: "console.log('积木参数 TEXT =', args.TEXT); return;"}}
+ ],
+ edges: []
+ }
+ }},
+ {id: 'evt1', type: 'event-green-flag', x: 60, y: 300, params: {}},
+ {id: 'stmt1', type: 'misc-statement', x: 400, y: 300,
+ params: {code: "console.log('绿旗被点击!');"}}
+ ],
+ edges: [
+ {from: {node: 'evt1', port: 'exec'}, to: {node: 'stmt1', port: 'exec'}, order: 0}
+ ]
+});
+
+export {extensionStarterGraph, addonStarterGraph, defaultMeta, extensionDemoGraph};
diff --git a/src/reducers/modals.js b/src/reducers/modals.js
index 90dd871f554..9b1c151b980 100644
--- a/src/reducers/modals.js
+++ b/src/reducers/modals.js
@@ -32,6 +32,8 @@ const MODAL_PROJECT_METADATA = 'projectMetadataModal';
const MODAL_HELP = 'helpModal';
const MODAL_VARIABLE_MANAGER = 'variableManagerModal';
const MODAL_PROJECT_ASSETS_MANAGER = 'projectAssetsManagerModal';
+const MODAL_VISUAL_EXTENSION_EDITOR = 'visualExtensionEditor';
+const MODAL_VISUAL_ADDON_EDITOR = 'visualAddonEditor';
const initialState = {
[MODAL_BACKDROP_LIBRARY]: false,
@@ -65,6 +67,8 @@ const initialState = {
[MODAL_HELP]: false,
[MODAL_VARIABLE_MANAGER]: false,
[MODAL_PROJECT_ASSETS_MANAGER]: false,
+ [MODAL_VISUAL_EXTENSION_EDITOR]: false,
+ [MODAL_VISUAL_ADDON_EDITOR]: false,
projectMetadataView: 'project',
helpEntry: null
};
@@ -225,6 +229,18 @@ const openProjectAssetsManagerModal = function () {
const closeProjectAssetsManagerModal = function () {
return closeModal(MODAL_PROJECT_ASSETS_MANAGER);
};
+const openVisualExtensionEditor = function () {
+ return openModal(MODAL_VISUAL_EXTENSION_EDITOR);
+};
+const closeVisualExtensionEditor = function () {
+ return closeModal(MODAL_VISUAL_EXTENSION_EDITOR);
+};
+const openVisualAddonEditor = function () {
+ return openModal(MODAL_VISUAL_ADDON_EDITOR);
+};
+const closeVisualAddonEditor = function () {
+ return closeModal(MODAL_VISUAL_ADDON_EDITOR);
+};
const openSimpleDialog = function (dialogConfig) {
return {
type: 'scratch-gui/modals/SHOW_SIMPLE_DIALOG',
@@ -343,6 +359,10 @@ export {
closeVariableManagerModal,
openProjectAssetsManagerModal,
closeProjectAssetsManagerModal,
+ openVisualExtensionEditor,
+ closeVisualExtensionEditor,
+ openVisualAddonEditor,
+ closeVisualAddonEditor,
closeBackdropLibrary,
closeCostumeLibrary,
closeExtensionLibrary,