useRule.ts 1004 B

1234567891011121314151617181920212223242526272829303132333435
  1. /**
  2. * Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
  3. * SPDX-License-Identifier: MIT
  4. */
  5. import { useMemo } from 'react';
  6. import { JsonSchemaUtils, JsonSchemaBasicType } from '@flowgram.ai/json-schema';
  7. import { useScopeAvailable } from '@flowgram.ai/editor';
  8. import { IFlowRefValue } from '@/typings';
  9. import { IRules } from '../types';
  10. import { defaultRules } from '../constants';
  11. export function useRule(left?: IFlowRefValue, userRules?: IRules) {
  12. const available = useScopeAvailable();
  13. const rules = useMemo(() => ({ ...defaultRules, ...(userRules || {}) }), [userRules]);
  14. const variable = useMemo(() => {
  15. if (!left) return undefined;
  16. return available.getByKeyPath(left.content);
  17. }, [available, left]);
  18. const rule = useMemo(() => {
  19. if (!variable) return undefined;
  20. const schema = JsonSchemaUtils.astToSchema(variable.type, { drilldown: false });
  21. return rules[schema?.type as JsonSchemaBasicType];
  22. }, [variable?.type, rules]);
  23. return { rule };
  24. }