create-provider-effect.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /**
  2. * Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
  3. * SPDX-License-Identifier: MIT
  4. */
  5. import { FlowNodeVariableData, type Scope, ASTKind } from '@flowgram.ai/variable-plugin';
  6. import { DataEvent, type Effect, type EffectOptions } from '@flowgram.ai/node';
  7. import { FlowNodeEntity } from '@flowgram.ai/document';
  8. import { type VariableProviderAbilityOptions } from '../types';
  9. /**
  10. * 根据 VariableProvider 生成 FormV2 的 Effect
  11. * @param options
  12. * @returns
  13. */
  14. export function createEffectFromVariableProvider(
  15. options: VariableProviderAbilityOptions
  16. ): EffectOptions[] {
  17. const getScope = (node: FlowNodeEntity): Scope => {
  18. const variableData: FlowNodeVariableData = node.getData(FlowNodeVariableData);
  19. if (options.private || options.scope === 'private') {
  20. return variableData.initPrivate();
  21. }
  22. return variableData.public;
  23. };
  24. const transformValueToAST: Effect = ({ value, name, context, formValues, form }) => {
  25. if (!context) {
  26. return;
  27. }
  28. const { node } = context;
  29. const scope = getScope(node);
  30. const parsedValue = options.parse(value, {
  31. node,
  32. scope,
  33. options,
  34. name,
  35. formValues,
  36. form,
  37. });
  38. // Fix: When parsedValue is not an array, transform it to array
  39. scope.ast.set(options.namespace || name || '', {
  40. kind: ASTKind.VariableDeclarationList,
  41. declarations: Array.isArray(parsedValue) ? parsedValue : [parsedValue],
  42. });
  43. };
  44. return [
  45. {
  46. event: DataEvent.onValueInit,
  47. effect: ((params) => {
  48. const { context } = params;
  49. const scope = getScope(context.node);
  50. const disposable = options.onInit?.({
  51. node: context.node,
  52. scope,
  53. options,
  54. name: params.name,
  55. formValues: params.formValues,
  56. form: params.form,
  57. });
  58. transformValueToAST(params);
  59. return () => {
  60. disposable?.dispose();
  61. };
  62. }) as Effect,
  63. },
  64. {
  65. event: DataEvent.onValueChange,
  66. effect: ((params) => {
  67. transformValueToAST(params);
  68. }) as Effect,
  69. },
  70. ];
  71. }