use-node-loading.tsx 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /**
  2. * Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
  3. * SPDX-License-Identifier: MIT
  4. */
  5. import { useEffect, useState } from 'react';
  6. import { FlowNodeFormData, FormModelV2, useNodeRender } from '@flowgram.ai/fixed-layout-editor';
  7. interface NodeStatus {
  8. loading: boolean;
  9. className: string;
  10. }
  11. const NodeStatusKey = 'status';
  12. export const useNodeStatus = () => {
  13. const { node } = useNodeRender();
  14. const formModel = node.getData(FlowNodeFormData).getFormModel<FormModelV2>();
  15. const formStatus = formModel.getValueIn<NodeStatus>(NodeStatusKey);
  16. const [loading, setLoading] = useState(formStatus?.loading ?? false);
  17. const [className, setClassName] = useState(formStatus?.className ?? '');
  18. // 初始化表单值
  19. useEffect(() => {
  20. const initSize = formModel.getValueIn<{ width: number; height: number }>(NodeStatusKey);
  21. if (!initSize) {
  22. formModel.setValueIn(NodeStatusKey, {
  23. loading: false,
  24. });
  25. }
  26. }, [formModel]);
  27. // 同步表单外部值变化:初始化/undo/redo/协同
  28. useEffect(() => {
  29. const disposer = formModel.onFormValuesChange(({ name }) => {
  30. if (name !== NodeStatusKey && name !== '') {
  31. return;
  32. }
  33. const newStatus = formModel.getValueIn<NodeStatus>(NodeStatusKey);
  34. if (!newStatus) {
  35. return;
  36. }
  37. setLoading(newStatus.loading);
  38. setClassName(newStatus.className);
  39. });
  40. return () => disposer.dispose();
  41. }, [formModel]);
  42. return {
  43. loading,
  44. className,
  45. };
  46. };