+ {isInput && (
+
this.onPortMouseDown(e, node, port.name, true, def)}
+ onMouseUp={e => this.onPortMouseUp(e, node, port.name, true, def)}
+ />
+ )}
+
{port.label || port.name}
+ {!isInput && (
+
this.onPortMouseDown(e, node, port.name, false, def)}
+ onMouseUp={e => this.onPortMouseUp(e, node, port.name, false, def)}
+ />
+ )}
+
+ );
+ }
+
+ render () {
+ const {graph, selectedNodeId} = this.props;
+ const {pan, zoom, linkFrom, mouseWorld} = this.state;
+ // 节点宽度估:简单按节点类型固定 200~230
+ 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};
+ });
+
+ // 连线路径(世界坐标 → SVG 内直接用世界坐标,viewport transform 处理)
+ 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 dx = Math.max(30, Math.abs(b.x - a.x) / 2);
+ const path = `M ${a.x} ${a.y} C ${a.x + dx} ${a.y}, ${b.x - dx} ${b.y}, ${b.x} ${b.y}`;
+ const cls = `ve-edge-path ${fromPortDef.kind === 'exec' ? 'exec' : ''}`;
+ 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;
+ 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}
+ {def.category}
+
+
+ {(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..5c72db604fb
--- /dev/null
+++ b/src/components/visual-editor/node-inspector.jsx
@@ -0,0 +1,140 @@
+/**
+ * 可视化节点编辑器 · 属性面板(右侧)
+ * 选中节点的参数编辑(text/number/bool/select/code/graph)。
+ * graph 类型参数(子图)显示「双击节点进入编辑」提示 + 清空按钮。
+ */
+import React from 'react';
+import PropTypes from 'prop-types';
+import {getType} from '../../lib/visual-node-engine/node-types.js';
+
+class NodeInspector extends React.Component {
+ handleChange (name, value) {
+ this.props.onParamChange(this.props.node.id, name, 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} = this.props;
+ if (!node) {
+ return (
+
+
属性
+
点击节点查看参数;meta 信息在最上方。
+
+ );
+ }
+ 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,
+ 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..0d4cdfd5587
--- /dev/null
+++ b/src/components/visual-editor/node-palette.jsx
@@ -0,0 +1,80 @@
+/**
+ * 可视化节点编辑器 · 节点面板(左侧)
+ * 分类分组 + 搜索;点击添加到画布中心附近。
+ */
+import React from 'react';
+import PropTypes from 'prop-types';
+import {NODE_TYPES, CATEGORIES} from '../../lib/visual-node-engine/node-types.js';
+
+class NodePalette extends React.Component {
+ constructor (props) {
+ super(props);
+ this.state = {search: ''};
+ }
+
+ handleSearch (e) {
+ this.setState({search: e.target.value});
+ }
+
+ addItem (typeId) {
+ this.props.onAddNode(typeId);
+ }
+
+ render () {
+ const {search} = this.state;
+ const {mode} = this.props;
+ const q2 = search.trim().toLowerCase();
+ const visible = NODE_TYPES.filter(t => {
+ if (t.addonOnly && mode !== 'addon') return false;
+ if (t.onlyInBlockBody && !this.props.blockBodyContext) 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 (
+
+
+ this.handleSearch(e)}
+ />
+
+
+ {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']),
+ blockBodyContext: 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..36e5deac2ba
--- /dev/null
+++ b/src/components/visual-editor/visual-editor-modal.css
@@ -0,0 +1,373 @@
+/* 可视化节点编辑器样式 */
+.ve-modal {
+ position: fixed;
+ inset: 0;
+ z-index: 500;
+ background: #1e2330;
+ color: #e8ecf5;
+ display: flex;
+ flex-direction: column;
+ font-family: inherit;
+ direction: ltr;
+}
+
+.ve-topbar {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 8px 14px;
+ background: #151a26;
+ border-bottom: 1px solid #2a3348;
+ flex-shrink: 0;
+}
+
+.ve-title {
+ font-weight: bold;
+ font-size: 15px;
+ white-space: nowrap;
+}
+
+.ve-mode-badge {
+ font-size: 11px;
+ padding: 2px 8px;
+ border-radius: 10px;
+ background: #2d5b8e;
+ white-space: nowrap;
+}
+
+.ve-breadcrumb {
+ font-size: 12px;
+ color: #9fb3d4;
+ display: flex;
+ gap: 6px;
+ align-items: center;
+ overflow: hidden;
+ white-space: nowrap;
+}
+
+.ve-breadcrumb .ve-crumb {
+ cursor: pointer;
+ padding: 2px 6px;
+ border-radius: 4px;
+}
+
+.ve-breadcrumb .ve-crumb:hover {
+ background: #2a3348;
+ color: #fff;
+}
+
+.ve-topbar .ve-toolbar {
+ margin-left: auto;
+ display: flex;
+ gap: 8px;
+}
+
+.ve-btn {
+ background: #2d5b8e;
+ color: #fff;
+ border: none;
+ border-radius: 6px;
+ padding: 6px 12px;
+ cursor: pointer;
+ font-size: 13px;
+ white-space: nowrap;
+}
+.ve-btn:hover { background: #3670b3; }
+.ve-btn:disabled { opacity: .4; cursor: default; }
+.ve-btn.ve-btn-secondary { background: #3a4661; }
+.ve-btn.ve-btn-secondary:hover { background: #4a5a7a; }
+.ve-btn.ve-btn-danger { background: #8e2d2d; }
+.ve-btn.ve-btn-danger:hover { background: #b33a3a; }
+.ve-btn.ve-btn-success { background: #2d8e5b; }
+.ve-btn.ve-btn-success:hover { background: #3aa870; }
+
+.ve-body {
+ flex: 1;
+ display: flex;
+ min-height: 0;
+}
+
+.ve-palette {
+ width: 240px;
+ flex-shrink: 0;
+ background: #171c29;
+ border-right: 1px solid #2a3348;
+ display: flex;
+ flex-direction: column;
+}
+
+.ve-palette-search {
+ padding: 8px;
+ border-bottom: 1px solid #2a3348;
+}
+.ve-palette-search input {
+ width: 100%;
+ box-sizing: border-box;
+ background: #10141f;
+ color: #e8ecf5;
+ border: 1px solid #2a3348;
+ border-radius: 6px;
+ padding: 6px 8px;
+ font-size: 13px;
+ outline: none;
+}
+
+.ve-palette-list {
+ flex: 1;
+ overflow-y: auto;
+ padding: 6px;
+}
+
+.ve-palette-cat {
+ font-size: 11px;
+ color: #7a8db3;
+ margin: 8px 4px 4px;
+ text-transform: uppercase;
+ letter-spacing: .5px;
+}
+
+.ve-palette-item {
+ display: block;
+ width: 100%;
+ text-align: left;
+ background: #1d2536;
+ color: #cdd9ec;
+ border: 1px solid #2a3348;
+ border-radius: 6px;
+ padding: 6px 8px;
+ margin: 2px 0;
+ font-size: 12.5px;
+ cursor: grab;
+ overflow: hidden;
+ white-space: nowrap;
+ text-overflow: ellipsis;
+}
+.ve-palette-item:hover { background: #263252; color: #fff; }
+
+.ve-canvas-wrap {
+ flex: 1;
+ position: relative;
+ overflow: hidden;
+ background:
+ linear-gradient(#232b3d 1px, transparent 1px),
+ linear-gradient(90deg, #232b3d 1px, transparent 1px);
+ background-size: 40px 40px;
+ background-color: #1a2030;
+ cursor: default;
+}
+
+.ve-canvas-wrap.panning { cursor: grabbing; }
+
+.ve-viewport {
+ position: absolute;
+ top: 0;
+ left: 0;
+ transform-origin: 0 0;
+}
+
+.ve-node {
+ position: absolute;
+ background: #232c44;
+ border: 1px solid #3a4661;
+ border-radius: 8px;
+ min-width: 170px;
+ max-width: 300px;
+ box-shadow: 0 3px 10px rgba(0, 0, 0, .35);
+ user-select: none;
+}
+.ve-node.ve-node-selected { border-color: #5b9dff; box-shadow: 0 0 0 2px rgba(91, 157, 255, .35); }
+.ve-node.ve-node-event { background: #2b3a5e; border-color: #4a5f96; }
+.ve-node.ve-node-flow { background: #223a2e; border-color: #3a5f48; }
+.ve-node.ve-node-expr { background: #3a2f22; border-color: #66543a; }
+.ve-node.ve-node-func { background: #33235c; border-color: #5c4096; }
+.ve-node.ve-node-block { background: #3a2b5e; border-color: #7d5cc4; }
+.ve-node.ve-node-addon { background: #2b5e50; border-color: #4a966a; }
+
+.ve-node-title {
+ padding: 6px 10px;
+ font-size: 12.5px;
+ font-weight: bold;
+ border-bottom: 1px solid rgba(255, 255, 255, .08);
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ cursor: grab;
+}
+.ve-node-title .ve-node-id {
+ font-size: 9px;
+ opacity: .5;
+ font-weight: normal;
+}
+
+.ve-node-ports {
+ padding: 4px 0 6px;
+ display: flex;
+ flex-direction: column;
+ gap: 3px;
+}
+
+.ve-port-row {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 10.5px;
+ color: #a8b8d8;
+ padding: 0 10px;
+ position: relative;
+ height: 16px;
+}
+.ve-port-row.output { justify-content: flex-end; }
+
+.ve-port-dot {
+ width: 11px;
+ height: 11px;
+ border-radius: 6px;
+ border: 2px solid #5b9dff;
+ background: #1a2030;
+ cursor: crosshair;
+ flex-shrink: 0;
+ position: relative;
+ z-index: 2;
+}
+.ve-port-dot.exec { border-color: #eee; border-radius: 2px; }
+.ve-port-dot.expr { border-radius: 50%; }
+.ve-port-dot:hover { background: #5b9dff; }
+
+.ve-edge-svg {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ overflow: visible;
+ pointer-events: none;
+}
+.ve-edge-path {
+ stroke: #6f8fd8;
+ stroke-width: 2.5;
+ fill: none;
+ pointer-events: stroke;
+ cursor: pointer;
+}
+.ve-edge-path.exec { stroke: #d8e4ff; }
+.ve-edge-path:hover { stroke: #ff8866; }
+
+.ve-ghost-path {
+ stroke: #7aa8ff;
+ stroke-dasharray: 6 4;
+ stroke-width: 2;
+ fill: none;
+}
+
+.ve-inspector {
+ width: 280px;
+ flex-shrink: 0;
+ background: #171c29;
+ border-left: 1px solid #2a3348;
+ overflow-y: auto;
+ padding: 10px;
+ font-size: 13px;
+}
+
+.ve-inspector h4 {
+ margin: 0 0 4px;
+ font-size: 14px;
+}
+.ve-inspector .ve-insp-hint {
+ font-size: 11px;
+ color: #7a8db3;
+ margin: 4px 0 10px;
+}
+
+.ve-param {
+ margin-bottom: 10px;
+}
+.ve-param label {
+ display: block;
+ font-size: 11px;
+ color: #9fb3d4;
+ margin-bottom: 3px;
+}
+.ve-param input[type="text"],
+.ve-param input[type="number"],
+.ve-param select,
+.ve-param textarea {
+ width: 100%;
+ box-sizing: border-box;
+ background: #10141f;
+ color: #e8ecf5;
+ border: 1px solid #2a3348;
+ border-radius: 5px;
+ padding: 5px 7px;
+ font-size: 12.5px;
+ outline: none;
+ font-family: inherit;
+}
+.ve-param textarea {
+ font-family: 'Consolas', 'Menlo', monospace;
+ min-height: 60px;
+ resize: vertical;
+ white-space: pre;
+}
+.ve-param .ve-bool-row {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+}
+
+.ve-code-pane {
+ flex-shrink: 0;
+ height: 260px;
+ border-top: 1px solid #2a3348;
+ background: #131826;
+ display: flex;
+ flex-direction: column;
+}
+
+.ve-code-bar {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 6px 12px;
+ border-bottom: 1px solid #2a3348;
+ font-size: 12px;
+ flex-shrink: 0;
+}
+.ve-code-bar .ve-code-status {
+ color: #7a8db3;
+ margin-left: auto;
+}
+
+.ve-code-input {
+ flex: 1;
+ background: #10141f;
+ color: #cde3ff;
+ border: none;
+ outline: none;
+ resize: none;
+ padding: 10px 14px;
+ font-family: 'Consolas', 'Menlo', monospace;
+ font-size: 12.5px;
+ line-height: 1.5;
+ white-space: pre;
+ overflow: auto;
+ direction: ltr;
+}
+
+.ve-canvas-hint {
+ position: absolute;
+ bottom: 10px;
+ left: 12px;
+ font-size: 11px;
+ color: #5b6a8f;
+ pointer-events: none;
+}
+
+.ve-empty-note {
+ position: absolute;
+ top: 40px;
+ left: 40px;
+ color: #6f8fd8;
+ font-size: 13px;
+ 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..ab36a01c8d0
--- /dev/null
+++ b/src/components/visual-editor/visual-editor-modal.jsx
@@ -0,0 +1,450 @@
+/**
+ * 可视化编辑器主组件(扩展 / 插件)
+ * - 左:节点面板;中:节点画布;右:属性面板;底: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;
+ const metaFields = mode === 'addon' ? [
+ ['name', '插件名称'],
+ ['description', '插件描述']
+ ] : [
+ ['name', '扩展名称'],
+ ['id', '扩展 ID'],
+ ['description', '扩展描述']
+ ];
+
+ return (
+
+
+
+ {mode === 'addon' ? '可视化插件编辑器' : '可视化扩展编辑器'}
+
+
+ {mode === 'addon' ? '插件 (addon)' : '扩展 (extension)'}
+
+
+ {this.state.graphStack.map((frame, i) => (
+ this.handleBreadcrumb(i)}
+ >
+ {i > 0 ? '› ' : ''}{frame.title}
+
+ ))}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
{mode === 'addon' ? '插件信息' : '扩展信息'}
+ {metaFields.map(([k, label]) => (
+
+
+ this.handleMetaChange(k, e.target.value)}
+ />
+
+ ))}
+
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..2b6817cfc4a
--- /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..9bf249a4fba
--- /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..65e5c70a88a
--- /dev/null
+++ b/src/lib/visual-node-engine/node-types.js
@@ -0,0 +1,1187 @@
+/**
+ * 可视化节点编辑器 · 节点类型目录(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: '随机数',
+ outputs: [{name: 'value', label: '值', kind: 'data'}],
+ params: [
+ {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() * (a - b + 1) + b)';
+ }
+ }
+ },
+ {
+ 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,
From a18e75ddcf45b9f4a94c6eb8155c2b8c82d22390 Mon Sep 17 00:00:00 2001
From: PYC5635 <3653161641@qq.com>
Date: Sun, 22 Nov 2026 16:35:08 +0800
Subject: [PATCH 2/4] fix: correct modals import path in editor containers
---
src/containers/visual-addon-editor-modal.jsx | 2 +-
src/containers/visual-extension-editor-modal.jsx | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
diff --git a/src/containers/visual-addon-editor-modal.jsx b/src/containers/visual-addon-editor-modal.jsx
index 2b6817cfc4a..b9fd978539a 100644
--- a/src/containers/visual-addon-editor-modal.jsx
+++ b/src/containers/visual-addon-editor-modal.jsx
@@ -4,7 +4,7 @@
import PropTypes from 'prop-types';
import React from 'react';
import {connect} from 'react-redux';
-import {closeVisualAddonEditor} from '../../reducers/modals';
+import {closeVisualAddonEditor} from '../reducers/modals';
const VisualEditorModal = React.lazy(() => import('../components/visual-editor/visual-editor-modal.jsx'));
diff --git a/src/containers/visual-extension-editor-modal.jsx b/src/containers/visual-extension-editor-modal.jsx
index 9bf249a4fba..8b40225a96a 100644
--- a/src/containers/visual-extension-editor-modal.jsx
+++ b/src/containers/visual-extension-editor-modal.jsx
@@ -4,7 +4,7 @@
import PropTypes from 'prop-types';
import React from 'react';
import {connect} from 'react-redux';
-import {closeVisualExtensionEditor} from '../../reducers/modals';
+import {closeVisualExtensionEditor} from '../reducers/modals';
const VisualEditorModal = React.lazy(() => import('../components/visual-editor/visual-editor-modal.jsx'));
From 3e53d015857196177222cc24ab95049bd8a7da81 Mon Sep 17 00:00:00 2001
From: PYC5635 <3653161641@qq.com>
Date: Sun, 22 Nov 2026 16:44:45 +0800
Subject: [PATCH 3/4] fix: render editors without outer Suspense (lazy
containers crashed React tree); bindAll for canvas
---
src/components/gui/gui.jsx | 4 +-
src/components/visual-editor/node-canvas.jsx | 74 +++++++++++---------
2 files changed, 42 insertions(+), 36 deletions(-)
diff --git a/src/components/gui/gui.jsx b/src/components/gui/gui.jsx
index 9e6f12e2ba1..754971f1c5d 100644
--- a/src/components/gui/gui.jsx
+++ b/src/components/gui/gui.jsx
@@ -39,6 +39,8 @@ import TWRestorePointManager from '../../containers/tw-restore-point-manager.jsx
import TWUnknownPlatformModal from '../../containers/tw-unknown-platform-modal.jsx';
import TWInvalidProjectModal from '../../containers/tw-invalid-project-modal.jsx';
import MWExtensionManagerModal from '../../containers/mw-extension-manager-modal.jsx';
+import VisualExtensionEditor from '../../containers/visual-extension-editor-modal.jsx';
+import VisualAddonEditor from '../../containers/visual-addon-editor-modal.jsx';
import MWHelpModal from '../../containers/mw-help-modal.jsx';
import MWProjectThemeModal from '../../containers/mw-project-theme-modal.jsx';
import RoturSession from '../../containers/rotur-session.jsx';
@@ -75,8 +77,6 @@ const FractchWorkspace = React.lazy(() => import('../mw-fractch-workspace/fractc
// jszip). Lazy load it so it does not slow down the first editor load; it is
// only mounted when the user actually opens the git panel.
const TWGitModal = React.lazy(() => import('../../containers/mw-git-modal.jsx'));
-const VisualExtensionEditor = React.lazy(() => import('../../containers/visual-extension-editor-modal.jsx'));
-const VisualAddonEditor = React.lazy(() => import('../../containers/visual-addon-editor-modal.jsx'));
// Heavy modal / panel components that are not shown on the initial editor
// load. Lazy-loading them removes their code (and transitive dependencies)
diff --git a/src/components/visual-editor/node-canvas.jsx b/src/components/visual-editor/node-canvas.jsx
index b34e3db0bb3..ed0bce42707 100644
--- a/src/components/visual-editor/node-canvas.jsx
+++ b/src/components/visual-editor/node-canvas.jsx
@@ -5,6 +5,7 @@
*/
import React from 'react';
import PropTypes from 'prop-types';
+import bindAll from 'lodash.bindall';
import {getType} from '../../lib/visual-node-engine/node-types.js';
const PORT_COLORS_CLASS = kind => (kind === 'exec' ? 'exec' : 'expr');
@@ -26,16 +27,30 @@ const TITLE_H = 29;
class NodeCanvas extends React.Component {
constructor (props) {
super(props);
+ bindAll(this, [
+ 'toWorld',
+ 'portPos',
+ 'onWheel',
+ 'onCanvasMouseDown',
+ 'onMouseMove',
+ 'onMouseUp',
+ 'onNodeTitleMouseDown',
+ 'onPortMouseDown',
+ 'onPortMouseUp',
+ 'onEdgeClick',
+ 'onNodeMouseDown',
+ 'onNodeDoubleClick'
+ ]);
+ this.wrapRef = React.createRef();
this.state = {
pan: {x: 60, y: 40},
zoom: 1,
dragNode: null, // {id, dx, dy}
panning: false,
panStart: null,
- linkFrom: null, // {nodeId, port, isExec, x, y}(世界坐标)
+ linkFrom: null, // {nodeId, port, isInput, x, y}(世界坐标)
mouseWorld: null
};
- this.wrapRef = React.createRef();
}
// ---- 世界坐标换算 ----
@@ -61,7 +76,7 @@ class NodeCanvas extends React.Component {
};
}
- onWheel = e => {
+ onWheel (e) {
e.preventDefault();
if (e.ctrlKey || e.metaKey) {
const factor = e.deltaY > 0 ? 0.9 : 1.1;
@@ -69,16 +84,16 @@ class NodeCanvas extends React.Component {
} else {
this.setState(s => ({pan: {x: s.pan.x - e.deltaX, y: s.pan.y - e.deltaY}}));
}
- };
+ }
// ---- 画布空白:pan ----
- onCanvasMouseDown = e => {
+ onCanvasMouseDown (e) {
if (e.target === e.currentTarget || e.target.classList.contains('ve-canvas-wrap')) {
this.setState({panning: true, panStart: {x: e.clientX, y: e.clientY, base: this.state.pan}});
}
- };
+ }
- onMouseMove = e => {
+ onMouseMove (e) {
if (this.state.panning && this.state.panStart) {
this.setState({
pan: {
@@ -97,39 +112,34 @@ class NodeCanvas extends React.Component {
if (this.state.linkFrom) {
this.setState({mouseWorld: this.toWorld(e.clientX, e.clientY)});
}
- };
+ }
- onMouseUp = e => {
+ onMouseUp () {
if (this.state.panning) this.setState({panning: false, panStart: null});
if (this.state.dragNode) this.setState({dragNode: null});
if (this.state.linkFrom) {
- // 尝试在鼠标落点找端口:命中节点则由 onPortDrop 判定
this.setState({linkFrom: null, mouseWorld: null});
}
- void e;
- };
+ }
// ---- 节点拖动 ----
- onNodeTitleMouseDown = (e, node) => {
+ onNodeTitleMouseDown (e, node) {
e.stopPropagation();
const world = this.toWorld(e.clientX, e.clientY);
this.props.onSelectNode(node.id);
this.setState({dragNode: {id: node.id, dx: world.x - node.x, dy: world.y - node.y}});
- };
+ }
// ---- 端口拖拽连线 ----
- onPortMouseDown = (e, node, portName, isInput, def) => {
+ onPortMouseDown (e, node, portName, isInput, def) {
e.stopPropagation();
const pos = this.portPos(node, portName, isInput, def);
this.props.onSelectNode(node.id);
- this.setState({linkFrom: {nodeId: node.id, port: portName, isInput, x: pos.x, y: pos.y}});
- // mouseWorld 初始
const w = this.toWorld(e.clientX, e.clientY);
- this.setState({mouseWorld: w});
- // 松手在端口上:由 port onMouseUp 处理
- };
+ this.setState({linkFrom: {nodeId: node.id, port: portName, isInput, x: pos.x, y: pos.y}, mouseWorld: w});
+ }
- onPortMouseUp = (e, node, portName, isInput, def) => {
+ onPortMouseUp (e, node, portName, isInput) {
e.stopPropagation();
const link = this.state.linkFrom;
if (!link) return;
@@ -151,25 +161,24 @@ class NodeCanvas extends React.Component {
}
this.props.onConnect(fromNode, fromPort, toNode, toPort);
this.setState({linkFrom: null, mouseWorld: null});
- void def;
- };
+ }
// ---- 连线点击删除 ----
- onEdgeClick = (e, edge) => {
+ onEdgeClick (e, edge) {
e.stopPropagation();
this.props.onRemoveEdge(edge);
- };
+ }
// ---- 节点点击(选中) ----
- onNodeMouseDown = (e, node) => {
+ onNodeMouseDown (e, node) {
e.stopPropagation();
this.props.onSelectNode(node.id);
- };
+ }
- onNodeDoubleClick = (e, node) => {
+ onNodeDoubleClick (e, node) {
e.stopPropagation();
this.props.onOpenSubGraph(node.id);
- };
+ }
renderPortDot (node, def, port, isInput) {
const key = `${node.id}:${isInput ? 'i' : 'o'}:${port.name}`;
@@ -183,7 +192,7 @@ class NodeCanvas extends React.Component {
className={`ve-port-dot ${PORT_COLORS_CLASS(port.kind)}`}
title={port.label || port.name}
onMouseDown={e => this.onPortMouseDown(e, node, port.name, true, def)}
- onMouseUp={e => this.onPortMouseUp(e, node, port.name, true, def)}
+ onMouseUp={e => this.onPortMouseUp(e, node, port.name, true)}
/>
)}
{port.label || port.name}
@@ -192,7 +201,7 @@ class NodeCanvas extends React.Component {
className={`ve-port-dot ${PORT_COLORS_CLASS(port.kind)}`}
title={port.label || port.name}
onMouseDown={e => this.onPortMouseDown(e, node, port.name, false, def)}
- onMouseUp={e => this.onPortMouseUp(e, node, port.name, false, def)}
+ onMouseUp={e => this.onPortMouseUp(e, node, port.name, false)}
/>
)}
@@ -202,14 +211,12 @@ class NodeCanvas extends React.Component {
render () {
const {graph, selectedNodeId} = this.props;
const {pan, zoom, linkFrom, mouseWorld} = this.state;
- // 节点宽度估:简单按节点类型固定 200~230
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};
});
- // 连线路径(世界坐标 → SVG 内直接用世界坐标,viewport transform 处理)
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);
@@ -236,7 +243,6 @@ class NodeCanvas extends React.Component {
);
});
- // 幽灵连线
let ghost = null;
if (linkFrom && mouseWorld) {
const a = linkFrom.isInput ? mouseWorld : {x: linkFrom.x, y: linkFrom.y};
From 15445ff5c31074d76938537e9cff83a1f8121d7b Mon Sep 17 00:00:00 2001
From: PYC5635 <3653161641@qq.com>
Date: Sun, 22 Nov 2026 16:57:57 +0800
Subject: [PATCH 4/4] style: UE-style node UI via CSS Modules (bare classnames
never matched), category-color titlebars, typed ports; fix palette filtering
---
src/components/visual-editor/node-canvas.jsx | 150 +++---
.../visual-editor/node-inspector.jsx | 139 ++++--
src/components/visual-editor/node-palette.jsx | 39 +-
.../visual-editor/visual-editor-modal.css | 451 +++++++++++-------
.../visual-editor/visual-editor-modal.jsx | 43 +-
src/lib/visual-node-engine/node-types.js | 8 +-
6 files changed, 515 insertions(+), 315 deletions(-)
diff --git a/src/components/visual-editor/node-canvas.jsx b/src/components/visual-editor/node-canvas.jsx
index ed0bce42707..78716231189 100644
--- a/src/components/visual-editor/node-canvas.jsx
+++ b/src/components/visual-editor/node-canvas.jsx
@@ -1,28 +1,60 @@
/**
- * 可视化节点编辑器 · 画布
- * 平移(按住空白拖动 / 鼠标中键)、缩放(ctrl+滚轮)、节点拖动、
- * 端口拖拽连线、点选节点/连线、双击子图节点。
+ * 可视化节点编辑器 · 画布(UE 蓝图风格)
+ * 平移、Ctrl+滚轮缩放、节点拖动、端口拖拽连线、点选节点/连线、双击子图节点。
+ * 样式经 CSS Modules(styles.xxx);分类色标题栏 + 类型着色端口。
*/
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';
-const PORT_COLORS_CLASS = kind => (kind === 'exec' ? 'exec' : 'expr');
+// 分类标题栏颜色(UE 蓝图式分类色带)
+const CATEGORY_COLORS = {
+ '事件': '#2e5f9e',
+ '流程控制': '#2e7d54',
+ '变量': '#6d54a0',
+ '运算': '#a2701f',
+ '函数': '#4a5cc0',
+ 'Scratch 交互': '#d99e2b',
+ 'DOM/UI': '#b85c4e',
+ '网络/存储': '#3a8e68',
+ '扩展积木': '#8e44ad',
+ '插件 API': '#16867a'
+};
-// 节点配色 class
-const nodeClass = typeDef => {
- if (typeDef.isEvent) return 've-node-event';
- if (typeDef.isExpression) return 've-node-expr';
- if (typeDef.isFunction) return 've-node-func';
- if (typeDef.isExtensionBlock) return 've-node-block';
- if (typeDef.addonOnly) return 've-node-addon';
- return 've-node-flow';
+// 数据端口类型 → 颜色(近似 UE:exec 灰白、number 绿、string 品红、bool 红、any 青)
+const PORT_TYPE_COLORS = {
+ number: '#7ce87c',
+ string: '#ff7ce8',
+ bool: '#ff6b6b',
+ any: '#56c8f0'
};
-// 端口几何:行高 19px,节点标题 29px,顶部 padding 4px
-const PORT_H = 19;
-const TITLE_H = 29;
+const portTypeOf = (def, portName, isInput) => {
+ const list = isInput ? (def.inputs || []) : (def.outputs || []);
+ const port = list.find(p => p.name === portName);
+ if (!port) return 'any';
+ if (port.kind === 'exec') return 'exec';
+ // 从 params 定义猜类型
+ const paramDef = (def.params || []).find(p => p.name === portName);
+ if (paramDef) {
+ if (paramDef.type === 'number') return 'number';
+ if (paramDef.type === 'bool') return 'bool';
+ if (paramDef.type === 'text' && portName !== 'condition') return 'string';
+ }
+ return 'any';
+};
+
+const portDotClass = type => {
+ switch (type) {
+ case 'exec': return styles.vePortDotExec;
+ case 'number': return styles.vePortDotNumber;
+ case 'string': return styles.vePortDotString;
+ case 'bool': return styles.vePortDotBool;
+ default: return styles.vePortDotAny;
+ }
+};
class NodeCanvas extends React.Component {
constructor (props) {
@@ -45,15 +77,14 @@ class NodeCanvas extends React.Component {
this.state = {
pan: {x: 60, y: 40},
zoom: 1,
- dragNode: null, // {id, dx, dy}
+ dragNode: null,
panning: false,
panStart: null,
- linkFrom: null, // {nodeId, port, isInput, x, y}(世界坐标)
+ linkFrom: null,
mouseWorld: null
};
}
- // ---- 世界坐标换算 ----
toWorld (clientX, clientY) {
const rect = this.wrapRef.current.getBoundingClientRect();
return {
@@ -72,7 +103,7 @@ class NodeCanvas extends React.Component {
const row = isInput ? inIdx : outIdx;
return {
x: node.x + (isInput ? 0 : node.width || 200),
- y: node.y + TITLE_H + 4 + row * PORT_H + 8
+ y: node.y + 31 + 4 + row * 20 + 9
};
}
@@ -86,9 +117,8 @@ class NodeCanvas extends React.Component {
}
}
- // ---- 画布空白:pan ----
onCanvasMouseDown (e) {
- if (e.target === e.currentTarget || e.target.classList.contains('ve-canvas-wrap')) {
+ if (e.target === e.currentTarget || e.target.classList.contains(styles.veViewport)) {
this.setState({panning: true, panStart: {x: e.clientX, y: e.clientY, base: this.state.pan}});
}
}
@@ -117,12 +147,9 @@ class NodeCanvas extends React.Component {
onMouseUp () {
if (this.state.panning) this.setState({panning: false, panStart: null});
if (this.state.dragNode) this.setState({dragNode: null});
- if (this.state.linkFrom) {
- this.setState({linkFrom: null, mouseWorld: null});
- }
+ if (this.state.linkFrom) this.setState({linkFrom: null, mouseWorld: null});
}
- // ---- 节点拖动 ----
onNodeTitleMouseDown (e, node) {
e.stopPropagation();
const world = this.toWorld(e.clientX, e.clientY);
@@ -130,7 +157,6 @@ class NodeCanvas extends React.Component {
this.setState({dragNode: {id: node.id, dx: world.x - node.x, dy: world.y - node.y}});
}
- // ---- 端口拖拽连线 ----
onPortMouseDown (e, node, portName, isInput, def) {
e.stopPropagation();
const pos = this.portPos(node, portName, isInput, def);
@@ -143,19 +169,16 @@ class NodeCanvas extends React.Component {
e.stopPropagation();
const link = this.state.linkFrom;
if (!link) return;
- // 方向归一:输出 → 输入
let fromNode = link.nodeId;
let fromPort = link.port;
let toNode = node.id;
let toPort = portName;
if (link.isInput && !isInput) {
- // 从输入端口拖到输出端口:反向
fromNode = node.id;
fromPort = portName;
toNode = link.nodeId;
toPort = link.port;
} else if (link.isInput === isInput) {
- // 同向端口:无效
this.setState({linkFrom: null, mouseWorld: null});
return;
}
@@ -163,13 +186,11 @@ class NodeCanvas extends React.Component {
this.setState({linkFrom: null, mouseWorld: null});
}
- // ---- 连线点击删除 ----
onEdgeClick (e, edge) {
e.stopPropagation();
this.props.onRemoveEdge(edge);
}
- // ---- 节点点击(选中) ----
onNodeMouseDown (e, node) {
e.stopPropagation();
this.props.onSelectNode(node.id);
@@ -181,25 +202,32 @@ class NodeCanvas extends React.Component {
}
renderPortDot (node, def, port, isInput) {
+ const type = portTypeOf(def, port.name, isInput);
+ const isExec = type === 'exec';
+ const dotClass = `${styles.vePortDot} ${portDotClass(type)}`;
+ const inlineStyle = (!isExec && type !== 'any') ?
+ {borderColor: PORT_TYPE_COLORS[type]} : null;
const key = `${node.id}:${isInput ? 'i' : 'o'}:${port.name}`;
return (
{isInput && (
this.onPortMouseDown(e, node, port.name, true, def)}
onMouseUp={e => this.onPortMouseUp(e, node, port.name, true)}
/>
)}
-
{port.label || port.name}
+
{port.label || port.name}
{!isInput && (
this.onPortMouseDown(e, node, port.name, false, def)}
onMouseUp={e => this.onPortMouseUp(e, node, port.name, false)}
/>
@@ -230,13 +258,23 @@ class NodeCanvas extends React.Component {
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 dx = Math.max(30, Math.abs(b.x - a.x) / 2);
- const path = `M ${a.x} ${a.y} C ${a.x + dx} ${a.y}, ${b.x - dx} ${b.y}, ${b.x} ${b.y}`;
- const cls = `ve-edge-path ${fromPortDef.kind === 'exec' ? 'exec' : ''}`;
+ 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)}
/>
@@ -253,7 +291,7 @@ class NodeCanvas extends React.Component {
return (
-