variable-plugin.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import {
  2. ASTKind,
  3. definePluginCreator,
  4. FixedLayoutPluginContext,
  5. FlowNodeVariableData,
  6. getNodeForm,
  7. PluginCreator,
  8. } from '@flowgram.ai/fixed-layout-editor';
  9. import { createASTFromJSONSchema } from './utils';
  10. export interface VariablePluginOptions {}
  11. export const createVariablePlugin: PluginCreator<VariablePluginOptions> = definePluginCreator<
  12. VariablePluginOptions,
  13. FixedLayoutPluginContext
  14. >({
  15. onInit(ctx, options) {
  16. const flowDocument = ctx.document;
  17. /**
  18. * Listens to the creation of nodes and synchronizes outputs data to the variable engine
  19. * 监听节点的创建,并将 outputs 数据同步给变量引擎
  20. */
  21. flowDocument.onNodeCreate(({ node }) => {
  22. const form = getNodeForm(node);
  23. const variableData = node.getData<FlowNodeVariableData>(FlowNodeVariableData);
  24. const syncOutputs = (value: any) => {
  25. if (!value) {
  26. variableData.public.ast.remove('outputs');
  27. return;
  28. }
  29. const typeAST = createASTFromJSONSchema(value);
  30. if (typeAST) {
  31. const title = form?.getValueIn('title') || node.id;
  32. variableData.public.ast.set('outputs', {
  33. kind: ASTKind.VariableDeclaration,
  34. meta: {
  35. title: `${title}.outputs`,
  36. },
  37. key: `${node.id}.outputs`,
  38. type: typeAST,
  39. });
  40. return;
  41. } else {
  42. variableData.public.ast.remove('outputs');
  43. }
  44. };
  45. if (form) {
  46. syncOutputs(form.getValueIn('outputs'));
  47. // Listen outputs change
  48. form.onFormValuesChange(props => {
  49. if (props.name.match(/^outputs/)) {
  50. syncOutputs(form.getValueIn('outputs'));
  51. }
  52. });
  53. }
  54. });
  55. },
  56. });