Support multi source options of node's arg

This commit is contained in:
codetypes committed 2026-01-13 11:49:42 +08:00
1 parent 2f4176857e
commit 6f9097f73d
7 files changed
+234 -143

No files matched your search

+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "behavior3editor", "name": "behavior3editor",
"version": "1.8.12", "version": "1.9.0",
"lockfileVersion": 2, "lockfileVersion": 2,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "behavior3editor", "name": "behavior3editor",
"version": "1.8.12", "version": "1.9.0",
"hasInstallScript": true, "hasInstallScript": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "behavior3editor", "name": "behavior3editor",
"version": "1.8.12", "version": "1.9.0",
"main": "dist-electron/main/index.js", "main": "dist-electron/main/index.js",
"description": "行为树编辑器", "description": "行为树编辑器",
"author": "zhandouxiaojiji & codetypes", "author": "zhandouxiaojiji & codetypes",
+184 -134
View File
@@ -11,6 +11,7 @@ import {
Divider, Divider,
Flex, Flex,
Form, Form,
FormInstance,
Input, Input,
InputNumber, InputNumber,
Select, Select,
@@ -26,7 +27,7 @@ import Markdown from "react-markdown";
import { useDebounceCallback } from "usehooks-ts"; import { useDebounceCallback } from "usehooks-ts";
import { useShallow } from "zustand/react/shallow"; import { useShallow } from "zustand/react/shallow";
import { ExpressionEvaluator } from "../behavior3/src/behavior3"; import { ExpressionEvaluator } from "../behavior3/src/behavior3";
import { EditNode, EditTree, useWorkspace } from "../contexts/workspace-context"; import { EditNode, EditorStore, EditTree, useWorkspace } from "../contexts/workspace-context";
import { import {
hasArgOptions, hasArgOptions,
ImportDecl, ImportDecl,
@@ -43,12 +44,14 @@ import {
import { import {
checkNodeArgValue, checkNodeArgValue,
checkOneof, checkOneof,
getNodeArgOptions,
getNodeArgRawType, getNodeArgRawType,
isNodeArgArray, isNodeArgArray,
isNodeArgOptional, isNodeArgOptional,
isValidChildren, isValidChildren,
isValidVariableName, isValidVariableName,
isVariadic, isVariadic,
NodeDefs,
parseExpr, parseExpr,
} from "../misc/b3util"; } from "../misc/b3util";
import { message } from "../misc/hooks"; import { message } from "../misc/hooks";
@@ -554,52 +557,21 @@ const validateArg = (
return Promise.resolve(value); return Promise.resolve(value);
}; };
const NodeInspector: FC = () => { const updateFormWithNode = (
const workspace = useWorkspace( form: FormInstance,
useShallow((state) => ({ {
allFiles: state.allFiles, editingNode,
editing: state.editing, nodeDefs,
editingNode: state.editingNode!, }: {
fileTree: state.fileTree, editingNode: EditNode;
groupDefs: state.groupDefs, nodeDefs: NodeDefs;
nodeDefs: state.nodeDefs,
usingGroups: state.usingGroups,
usingVars: state.usingVars,
onEditingNode: state.onEditingNode,
relative: state.relative,
}))
);
const { t } = useTranslation();
const [form] = Form.useForm();
const validateFieldsLater = useDebounceCallback(
() => form.validateFields({ recursive: true }),
100
);
const submit = () => {
if (form.isFieldsValidating()) {
setTimeout(() => {
submit();
}, 10);
return;
} }
if (form.getFieldsError().some((e) => e.errors.length > 0)) { ) => {
const data = workspace.editingNode.data; const data = editingNode.data;
const editor = workspace.editing!; const def = nodeDefs.get(data.name);
const name = `${editor.data.prefix}${data.id} ${data.name}`; const t = i18n.t;
message.error(t("node.editFailed", { name }));
}
form.submit();
};
// set form values
useEffect(() => {
const data = workspace.editingNode.data;
const def = workspace.nodeDefs.get(workspace.editingNode.data.name);
form.resetFields(); form.resetFields();
form.setFieldValue("id", workspace.editingNode.prefix + data.id); form.setFieldValue("id", editingNode.prefix + data.id);
form.setFieldValue("name", data.name); form.setFieldValue("name", data.name);
form.setFieldValue("type", def.type); form.setFieldValue("type", def.type);
form.setFieldValue("desc", data.desc || def.desc); form.setFieldValue("desc", data.desc || def.desc);
@@ -654,90 +626,21 @@ const NodeInspector: FC = () => {
form.setFieldValue(`output.${i}`, data.output?.[i]); form.setFieldValue(`output.${i}`, data.output?.[i]);
} }
}); });
validateFieldsLater();
}, [workspace.editingNode]);
// auto complete for node
const nodeOptions = useMemo(() => {
const options: OptionType[] = [];
workspace.nodeDefs.forEach((e) => {
options.push({ label: `${e.name}(${e.desc})`, value: e.name });
});
return options;
}, [workspace.nodeDefs]);
// auto complete for input and output
const inoutVarOptions = useMemo(() => {
const options: OptionType[] = [];
const filter: Record<string, boolean> = {};
const collect = (node?: NodeData) => {
if (node) {
const def = workspace.nodeDefs.get(node.name);
node.input?.forEach((v, i) => {
let desc: string;
const inputDef = def.input;
if (inputDef?.length && i >= inputDef.length && isVariadic(inputDef, -1)) {
desc = inputDef[inputDef.length - 1];
} else {
desc = inputDef?.[i] ?? "<unknown>";
}
if (!filter[v]) {
options.push({ label: `${v}(${desc})`, value: v });
filter[v] = true;
}
});
node.output?.forEach((v, i) => {
let desc: string;
const outputDef = def.output;
if (outputDef?.length && i >= outputDef.length && isVariadic(outputDef, -1)) {
desc = outputDef[outputDef.length - 1];
} else {
desc = outputDef?.[i] ?? "<unknown>";
}
if (!filter[v]) {
options.push({ label: `${v}(${desc})`, value: v });
filter[v] = true;
}
});
node.children?.forEach((child) => collect(child));
}
}; };
if (workspace.usingVars) {
Object.values(workspace.usingVars).forEach((v) => { const createNodeFromForm = (
if (!filter[v.name]) { form: FormInstance,
options.push({ label: `${v.name}(${v.desc})`, value: v.name }); {
filter[v.name] = true; editingNode,
nodeDefs,
}: {
editingNode: EditNode;
nodeDefs: NodeDefs;
} }
}); ) => {
} else { const def = nodeDefs.get(editingNode.data.name);
collect(workspace.editing?.data.root);
}
return options;
}, [workspace.editing, workspace.usingVars]);
// auto complete for subtree
const subtreeOptions = useMemo(() => {
const options: OptionType[] = [];
workspace.allFiles.forEach((file) => {
const value = workspace.relative(file.path);
const desc = ""; //fileNode.desc ? `(${fileNode.desc})` : "";
options.push({
label: `${value}${desc}`,
value: value,
});
});
options.sort((a, b) => a.value.localeCompare(b.value));
return options;
}, [workspace.allFiles, workspace.fileTree]);
const editingNode = workspace.editingNode;
const def = workspace.nodeDefs.get(editingNode.data.name);
const disabled = editingNode.disabled;
// update value
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const finish = (values: any) => {
const data = {} as NodeData; const data = {} as NodeData;
const values = form.getFieldsValue();
data.$id = editingNode.data.$id; data.$id = editingNode.data.$id;
data.id = editingNode.data.id; data.id = editingNode.data.id;
data.name = values.name; data.name = values.name;
@@ -812,9 +715,154 @@ const NodeInspector: FC = () => {
} else { } else {
data.output = []; data.output = [];
} }
return data;
};
const createInOutOptions = ({
nodeDefs,
usingVars,
editing,
}: {
nodeDefs: NodeDefs;
usingVars: Record<string, VarDecl> | null;
editing: EditorStore | undefined;
}) => {
const options: OptionType[] = [];
const filter: Record<string, boolean> = {};
const collect = (node?: NodeData) => {
if (node) {
const def = nodeDefs.get(node.name);
node.input?.forEach((v, i) => {
let desc: string;
const inputDef = def.input;
if (inputDef?.length && i >= inputDef.length && isVariadic(inputDef, -1)) {
desc = inputDef[inputDef.length - 1];
} else {
desc = inputDef?.[i] ?? "<unknown>";
}
if (!filter[v]) {
options.push({ label: `${v}(${desc})`, value: v });
filter[v] = true;
}
});
node.output?.forEach((v, i) => {
let desc: string;
const outputDef = def.output;
if (outputDef?.length && i >= outputDef.length && isVariadic(outputDef, -1)) {
desc = outputDef[outputDef.length - 1];
} else {
desc = outputDef?.[i] ?? "<unknown>";
}
if (!filter[v]) {
options.push({ label: `${v}(${desc})`, value: v });
filter[v] = true;
}
});
node.children?.forEach((child) => collect(child));
}
};
if (usingVars) {
Object.values(usingVars).forEach((v) => {
if (!filter[v.name]) {
options.push({ label: `${v.name}(${v.desc})`, value: v.name });
filter[v.name] = true;
}
});
} else {
collect(editing?.data.root);
}
return options;
};
const NodeInspector: FC = () => {
const workspace = useWorkspace(
useShallow((state) => ({
allFiles: state.allFiles,
editing: state.editing,
editingNode: state.editingNode!,
fileTree: state.fileTree,
groupDefs: state.groupDefs,
nodeDefs: state.nodeDefs,
usingGroups: state.usingGroups,
usingVars: state.usingVars,
onEditingNode: state.onEditingNode,
relative: state.relative,
}))
);
const { t } = useTranslation();
const [form] = Form.useForm();
const validateFieldsLater = useDebounceCallback(
() => form.validateFields({ recursive: true }),
100
);
const [nodeArgs, setNodeArgs] = useState<Record<string, unknown>>(
workspace.editingNode.data.args ?? {}
);
const submit = () => {
setNodeArgs(createNodeFromForm(form, workspace).args ?? {});
if (form.isFieldsValidating()) {
setTimeout(() => {
submit();
}, 10);
return;
}
if (form.getFieldsError().some((e) => e.errors.length > 0)) {
const data = workspace.editingNode.data;
const editor = workspace.editing!;
const name = `${editor.data.prefix}${data.id} ${data.name}`;
message.error(t("node.editFailed", { name }));
}
form.submit();
};
// set form values
useEffect(() => {
updateFormWithNode(form, workspace);
validateFieldsLater();
}, [workspace.editingNode]);
// auto complete for node
const nodeOptions = useMemo(
() =>
Array.from(workspace.nodeDefs.entries()).map(([name, def]) => {
return { label: `${name}(${def.desc})`, value: name };
}),
[workspace.nodeDefs]
);
// auto complete for input and output
const inoutVarOptions = useMemo(
() => createInOutOptions(workspace),
[workspace.editing, workspace.usingVars]
);
// auto complete for subtree
const subtreeOptions = useMemo(() => {
const options: OptionType[] = [];
workspace.allFiles.forEach((file) => {
const value = workspace.relative(file.path);
const desc = ""; //fileNode.desc ? `(${fileNode.desc})` : "";
options.push({
label: `${value}${desc}`,
value: value,
});
});
options.sort((a, b) => a.value.localeCompare(b.value));
return options;
}, [workspace.allFiles, workspace.fileTree]);
const editingNode = workspace.editingNode;
const def = workspace.nodeDefs.get(editingNode.data.name);
const disabled = editingNode.disabled;
const finish = () => {
workspace.editing?.dispatch?.("updateNode", { workspace.editing?.dispatch?.("updateNode", {
data: data, data: createNodeFromForm(form, workspace),
} as EditNode); } as EditNode);
}; };
@@ -833,7 +881,7 @@ const NodeInspector: FC = () => {
prefix: editingNode.prefix, prefix: editingNode.prefix,
disabled: editingNode.disabled, disabled: editingNode.disabled,
}); });
finish(form.getFieldsValue()); finish();
} else { } else {
submit(); submit();
} }
@@ -841,7 +889,7 @@ const NodeInspector: FC = () => {
const changeSubtree = () => { const changeSubtree = () => {
if (form.getFieldValue("path") !== editingNode.data.path) { if (form.getFieldValue("path") !== editingNode.data.path) {
finish(form.getFieldsValue()); finish();
} else { } else {
submit(); submit();
} }
@@ -1182,7 +1230,7 @@ const NodeInspector: FC = () => {
() => ({ () => ({
validator(_, value) { validator(_, value) {
return validateArg( return validateArg(
editingNode.data, createNodeFromForm(form, workspace),
arg, arg,
value, value,
workspace.usingVars workspace.usingVars
@@ -1215,12 +1263,14 @@ const NodeInspector: FC = () => {
disabled={disabled} disabled={disabled}
onBlur={submit} onBlur={submit}
onChange={submit} onChange={submit}
options={(arg.options ?? []).map((option) => { options={(getNodeArgOptions(arg, nodeArgs) ?? []).map(
(option) => {
return { return {
value: option.value, value: option.value,
label: `${option.name}(${option.value})`, label: `${option.name}(${option.value})`,
}; };
})} }
)}
filterOption={(value, option) => { filterOption={(value, option) => {
value = value.toUpperCase(); value = value.toUpperCase();
return !!option?.label return !!option?.label
@@ -1280,7 +1330,7 @@ const NodeInspector: FC = () => {
({ getFieldValue, setFieldValue, isFieldValidating, validateFields }) => ({ ({ getFieldValue, setFieldValue, isFieldValidating, validateFields }) => ({
async validator(_, value) { async validator(_, value) {
return validateArg( return validateArg(
editingNode.data, createNodeFromForm(form, workspace),
arg, arg,
value, value,
workspace.usingVars workspace.usingVars
@@ -1344,7 +1394,7 @@ const NodeInspector: FC = () => {
disabled={disabled} disabled={disabled}
onBlur={submit} onBlur={submit}
onChange={submit} onChange={submit}
options={(arg.options ?? []).map((option) => { options={(getNodeArgOptions(arg, nodeArgs) ?? []).map((option) => {
return { return {
value: option.value, value: option.value,
label: `${option.name}(${option.value})`, label: `${option.name}(${option.value})`,
+8
View File
@@ -137,6 +137,14 @@ body {
outline: none; outline: none;
} }
.ant-select-dropdown .ant-select-item-option-selected {
background-color: var(--b3-color-selected) !important;
}
.ant-select-dropdown .ant-select-item-option-active {
background-color: var(--b3-color-selected) !important;
}
.ant-form-item .ant-form-item-explain { .ant-form-item .ant-form-item-explain {
font-size: small; font-size: small;
} }
+1 -1
View File
@@ -1,6 +1,6 @@
import { NodeDef } from "../behavior3/src/behavior3"; import { NodeDef } from "../behavior3/src/behavior3";
export const VERSION = "1.8.10"; export const VERSION = "1.9.0";
export const keyWords = ["true", "false", "null", "undefined", "NaN", "Infinity"]; export const keyWords = ["true", "false", "null", "undefined", "NaN", "Infinity"];
+37 -4
View File
@@ -69,9 +69,28 @@ export const initWorkdir = (path: string, handler: typeof alertError) => {
const nodeDefData = readJson(`${workdir}/node-config.b3-setting`) as NodeDef[]; const nodeDefData = readJson(`${workdir}/node-config.b3-setting`) as NodeDef[];
const groups: Set<string> = new Set(); const groups: Set<string> = new Set();
nodeDefs = new NodeDefs(); nodeDefs = new NodeDefs();
for (const v of nodeDefData) { for (const node of nodeDefData) {
nodeDefs.set(v.name, v); node.args?.forEach((arg) => {
v.group?.forEach((g) => groups.add(g)); if (arg.options && !arg.options[0].source) {
arg.options = [
{
source: arg.options as unknown as Array<{ name: string; value: unknown }>,
},
];
}
arg.options?.forEach((option) => {
Object.keys(option.match ?? {}).forEach((key) => {
if (!node.args?.find((v) => v.name === key)) {
console.error(
`match key '${key}' in arg '${arg.name}' of ` +
`node '${node.name}' is not found in args`
);
}
});
});
});
nodeDefs.set(node.name, node);
node.group?.forEach((g) => groups.add(g));
} }
groupDefs = Array.from(groups).sort(); groupDefs = Array.from(groups).sort();
}; };
@@ -207,6 +226,19 @@ export const isNodeArgOptional = (arg: NodeArg) => {
return arg.type.includes("?"); return arg.type.includes("?");
}; };
export const getNodeArgOptions = (arg: NodeArg, args: Record<string, unknown>) => {
if (!arg.options) {
return;
}
const defaultMatch = arg.options.find((option) => !option.match);
if (defaultMatch) {
return defaultMatch.source;
}
return arg.options.find((entry) =>
Object.entries(entry.match!).every(([key, value]) => value.includes(args[key]))
)?.source;
};
export const checkNodeArgValue = ( export const checkNodeArgValue = (
data: NodeData, data: NodeData,
arg: NodeArg, arg: NodeArg,
@@ -264,7 +296,8 @@ export const checkNodeArgValue = (
} }
if (hasArgOptions(arg)) { if (hasArgOptions(arg)) {
const found = !!arg.options?.find((option) => option.value === value); const options = getNodeArgOptions(arg, data.args ?? {});
const found = !!options?.find((option) => option.value === value);
const isOptional = value === undefined && isNodeArgOptional(arg); const isOptional = value === undefined && isNodeArgOptional(arg);
if (!(found || isOptional)) { if (!(found || isOptional)) {
error(`'${arg.name}=${JSON.stringify(value)}' is not a one of the option values`); error(`'${arg.name}=${JSON.stringify(value)}' is not a one of the option values`);