utils.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /**
  2. * Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
  3. * SPDX-License-Identifier: MIT
  4. */
  5. import { find, mergeWith } from 'lodash-es';
  6. import { FormFeedback, FormPathService } from '@flowgram.ai/form-core';
  7. import type { FieldError, FieldWarning, FormValidateReturn } from '@flowgram.ai/form';
  8. import { type FieldModel, FieldName } from '@flowgram.ai/form';
  9. import { DataEvent, EffectOptions, EffectReturn } from './types';
  10. export function findMatchedInMap<T = any>(
  11. field: FieldModel<any>,
  12. validateMap: Record<FieldName, T> | undefined
  13. ): T | undefined {
  14. if (!validateMap) {
  15. return;
  16. }
  17. if (validateMap[field.name]) {
  18. return validateMap[field.name];
  19. }
  20. const found = find(Object.keys(validateMap), (key) => {
  21. if (key.startsWith('regex:')) {
  22. const regex = RegExp(key.split(':')[1]);
  23. return regex.test(field.name);
  24. }
  25. return false;
  26. });
  27. if (found) {
  28. return validateMap[found];
  29. }
  30. }
  31. export function formFeedbacksToNodeCoreFormFeedbacks(
  32. formFeedbacks: FormValidateReturn
  33. ): FormFeedback[] {
  34. return formFeedbacks.map(
  35. (f: FieldError | FieldWarning) =>
  36. ({
  37. feedbackStatus: f.level,
  38. feedbackText: f.message,
  39. path: f.name,
  40. } as FormFeedback)
  41. );
  42. }
  43. export function convertGlobPath(path: string) {
  44. if (path.startsWith('/')) {
  45. const parts = FormPathService.normalize(path).slice(1).split('/');
  46. return parts.join('.');
  47. }
  48. return path;
  49. }
  50. export function mergeEffectMap(
  51. origin: Record<string, EffectOptions[]>,
  52. source: Record<string, EffectOptions[]>
  53. ) {
  54. return mergeWith(origin, source, function (objValue: EffectOptions[], srcValue: EffectOptions[]) {
  55. return (objValue || []).concat(srcValue);
  56. });
  57. }
  58. export function mergeEffectReturn(origin?: EffectReturn, source?: EffectReturn): EffectReturn {
  59. return () => {
  60. origin?.();
  61. source?.();
  62. };
  63. }
  64. export function runAndDeleteEffectReturn(
  65. effectReturnMap: Map<DataEvent, Record<string, EffectReturn>>,
  66. name: string,
  67. events: DataEvent[]
  68. ) {
  69. events.forEach((event) => {
  70. const eventMap = effectReturnMap.get(event);
  71. if (eventMap?.[name]) {
  72. eventMap[name]();
  73. delete eventMap[name];
  74. }
  75. });
  76. }