create-provider-effect.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. scope.ast.set(options.namespace || name || '', {
  31. kind: ASTKind.VariableDeclarationList,
  32. declarations: options.parse(value, {
  33. node,
  34. scope,
  35. options,
  36. name,
  37. formValues,
  38. form,
  39. }),
  40. });
  41. };
  42. return [
  43. {
  44. event: DataEvent.onValueInit,
  45. effect: ((params) => {
  46. const { context } = params;
  47. const scope = getScope(context.node);
  48. const disposable = options.onInit?.({
  49. node: context.node,
  50. scope,
  51. options,
  52. name: params.name,
  53. formValues: params.formValues,
  54. form: params.form,
  55. });
  56. transformValueToAST(params);
  57. return () => {
  58. disposable?.dispose();
  59. };
  60. }) as Effect,
  61. },
  62. {
  63. event: DataEvent.onValueChange,
  64. effect: ((params) => {
  65. transformValueToAST(params);
  66. }) as Effect,
  67. },
  68. ];
  69. }