Kaynağa Gözat

feat(material): inputs values tree (#688)

* feat(material): inputs values tree

* fix: plain object

* fix: ts check
Yiwei Mao 4 ay önce
ebeveyn
işleme
c84a791f05

+ 3 - 2
packages/materials/form-materials/src/components/batch-outputs/index.tsx

@@ -5,6 +5,7 @@
 
 import React from 'react';
 
+import { I18n } from '@flowgram.ai/editor';
 import { Button, Input } from '@douyinfe/semi-ui';
 import { IconDelete, IconPlus } from '@douyinfe/semi-icons';
 
@@ -46,8 +47,8 @@ export function BatchOutputs(props: PropsType) {
           </UIRow>
         ))}
       </UIRows>
-      <Button disabled={readonly} icon={<IconPlus />} size="small" onClick={add}>
-        Add
+      <Button disabled={readonly} icon={<IconPlus />} size="small" onClick={() => add()}>
+        {I18n.t('Add')}
       </Button>
     </div>
   );

+ 1 - 0
packages/materials/form-materials/src/components/index.ts

@@ -26,3 +26,4 @@ export * from './display-inputs-values';
 export * from './assign-rows';
 export * from './assign-row';
 export * from './blur-input';
+export * from './inputs-values-tree';

+ 71 - 0
packages/materials/form-materials/src/components/inputs-values-tree/hooks/use-child-list.tsx

@@ -0,0 +1,71 @@
+/**
+ * Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
+ * SPDX-License-Identifier: MIT
+ */
+
+import { useMemo } from 'react';
+
+import { isPlainObject } from 'lodash';
+
+import { FlowValueUtils } from '@/shared';
+import { useObjectList } from '@/hooks';
+
+interface ListItem {
+  id: string;
+  key?: string;
+  value?: any;
+}
+
+export function useChildList(
+  value?: any,
+  onChange?: (value: any) => void
+): {
+  canAddField: boolean;
+  list: ListItem[];
+  add: (key?: string) => void;
+  updateKey: (id: string, key: string) => void;
+  updateValue: (id: string, value: any) => void;
+  remove: (id: string) => void;
+} {
+  const canAddField = useMemo(() => {
+    if (!isPlainObject(value)) {
+      return false;
+    }
+
+    if (FlowValueUtils.isFlowValue(value)) {
+      // Constant Object Value Can Add child fields
+      return FlowValueUtils.isConstant(value) && value?.schema?.type === 'object';
+    }
+
+    return true;
+  }, [value]);
+
+  const objectListValue = useMemo(() => {
+    if (isPlainObject(value)) {
+      if (FlowValueUtils.isFlowValue(value)) {
+        return undefined;
+      }
+      return value;
+    }
+    return undefined;
+  }, [value]);
+
+  console.log('debugger objectListValue', objectListValue);
+
+  const { list, add, updateKey, updateValue, remove } = useObjectList<any>({
+    value: objectListValue,
+    onChange: (value) => {
+      onChange?.(value);
+    },
+    sortIndexKey: (value) => (FlowValueUtils.isFlowValue(value) ? 'extra.index' : ''),
+  });
+
+  return {
+    canAddField,
+    list,
+    add,
+    updateKey,
+    updateValue,
+    remove,
+  };
+}

+ 56 - 0
packages/materials/form-materials/src/components/inputs-values-tree/index.tsx

@@ -0,0 +1,56 @@
+/**
+ * Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
+ * SPDX-License-Identifier: MIT
+ */
+
+import React from 'react';
+
+import { I18n } from '@flowgram.ai/editor';
+import { Button } from '@douyinfe/semi-ui';
+import { IconPlus } from '@douyinfe/semi-icons';
+
+import { FlowValueUtils } from '@/shared';
+import { useObjectList } from '@/hooks';
+
+import { PropsType } from './types';
+import { UITreeItems } from './styles';
+import { InputValueRow } from './row';
+
+export function InputsValuesTree(props: PropsType) {
+  const { value, onChange, readonly, hasError, constantProps } = props;
+
+  const { list, updateKey, updateValue, remove, add } = useObjectList({
+    value,
+    onChange,
+    sortIndexKey: (value) => (FlowValueUtils.isFlowValue(value) ? 'extra.index' : ''),
+  });
+
+  return (
+    <div>
+      <UITreeItems>
+        {list.map((item) => (
+          <InputValueRow
+            key={item.id}
+            keyName={item.key}
+            value={item.value}
+            onUpdateKey={(key) => updateKey(item.id, key)}
+            onUpdateValue={(value) => updateValue(item.id, value)}
+            onRemove={() => remove(item.id)}
+            readonly={readonly}
+            hasError={hasError}
+            constantProps={constantProps}
+          />
+        ))}
+      </UITreeItems>
+      <Button
+        style={{ marginTop: 10, marginLeft: 16 }}
+        disabled={readonly}
+        icon={<IconPlus />}
+        size="small"
+        onClick={add}
+      >
+        {I18n.t('Add')}
+      </Button>
+    </div>
+  );
+}

+ 163 - 0
packages/materials/form-materials/src/components/inputs-values-tree/row.tsx

@@ -0,0 +1,163 @@
+/**
+ * Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
+ * SPDX-License-Identifier: MIT
+ */
+
+import React, { useState } from 'react';
+
+import { I18n } from '@flowgram.ai/editor';
+import { IconButton, Input } from '@douyinfe/semi-ui';
+import { IconChevronDown, IconChevronRight, IconDelete } from '@douyinfe/semi-icons';
+
+import { ConstantInputStrategy } from '@/components/constant-input';
+
+import { PropsType } from './types';
+import {
+  IconAddChildren,
+  UIActions,
+  UICollapseTrigger,
+  UICollapsible,
+  UIRow,
+  UITreeItemLeft,
+  UITreeItemMain,
+  UITreeItemRight,
+  UITreeItems,
+} from './styles';
+import { useChildList } from './hooks/use-child-list';
+import { InjectDynamicValueInput } from '../dynamic-value-input';
+import { BlurInput } from '../blur-input';
+
+const AddObjectChildStrategy: ConstantInputStrategy = {
+  hit: (schema) => schema.type === 'object',
+  Renderer: () => (
+    <Input
+      size="small"
+      disabled
+      style={{ pointerEvents: 'none' }}
+      value={I18n.t('Configure via child fields')}
+    />
+  ),
+};
+
+export function InputValueRow(
+  props: {
+    keyName?: string;
+    value?: any;
+    onUpdateKey: (key: string) => void;
+    onUpdateValue: (value: any) => void;
+    onRemove?: () => void;
+    $isLast?: boolean;
+    $level?: number;
+  } & Pick<PropsType, 'constantProps' | 'hasError' | 'readonly'>
+) {
+  const {
+    keyName,
+    value,
+    $level = 0,
+    onUpdateKey,
+    onUpdateValue,
+    $isLast,
+    onRemove,
+    constantProps,
+    hasError,
+    readonly,
+  } = props;
+  const [collapse, setCollapse] = useState(false);
+
+  const { canAddField, list, add, updateKey, updateValue, remove } = useChildList(
+    value,
+    onUpdateValue
+  );
+
+  const hasChildren = canAddField && list.length > 0;
+
+  const flowDisplayValue = hasChildren ? { type: 'constant', schema: { type: ' object' } } : value;
+
+  return (
+    <>
+      <UITreeItemLeft $isLast={$isLast} $showLine={$level > 0} $showCollapse={hasChildren}>
+        {hasChildren && (
+          <UICollapseTrigger onClick={() => setCollapse((_collapse) => !_collapse)}>
+            {collapse ? <IconChevronDown size="small" /> : <IconChevronRight size="small" />}
+          </UICollapseTrigger>
+        )}
+      </UITreeItemLeft>
+      <UITreeItemRight>
+        <UITreeItemMain>
+          <UIRow>
+            <BlurInput
+              style={{ width: 100, minWidth: 100, maxWidth: 100 }}
+              disabled={readonly}
+              size="small"
+              value={keyName}
+              onChange={(v) => onUpdateKey?.(v)}
+              placeholder={I18n.t('Input Key')}
+            />
+            <InjectDynamicValueInput
+              style={{ flexGrow: 1 }}
+              readonly={readonly}
+              value={flowDisplayValue}
+              onChange={(v) => onUpdateValue(v)}
+              hasError={hasError}
+              constantProps={{
+                ...constantProps,
+                strategies: [
+                  ...(hasChildren ? [AddObjectChildStrategy] : []),
+                  ...(constantProps?.strategies || []),
+                ],
+              }}
+            />
+            <UIActions>
+              {canAddField && (
+                <IconButton
+                  disabled={readonly}
+                  size="small"
+                  theme="borderless"
+                  icon={<IconAddChildren />}
+                  onClick={() => {
+                    add();
+                    setCollapse(true);
+                  }}
+                />
+              )}
+              <IconButton
+                disabled={readonly}
+                theme="borderless"
+                icon={<IconDelete size="small" />}
+                size="small"
+                onClick={() => onRemove?.()}
+              />
+            </UIActions>
+          </UIRow>
+        </UITreeItemMain>
+        {hasChildren && (
+          <UICollapsible $collapse={collapse}>
+            <UITreeItems $shrink={true}>
+              {list.map((_item, index) => (
+                <InputValueRow
+                  readonly={readonly}
+                  hasError={hasError}
+                  constantProps={constantProps}
+                  key={_item.id}
+                  keyName={_item.key}
+                  value={_item.value}
+                  $level={$level + 1} // 传递递增的层级
+                  onUpdateValue={(_v) => {
+                    updateValue(_item.id, _v);
+                  }}
+                  onUpdateKey={(k) => {
+                    updateKey(_item.id, k);
+                  }}
+                  onRemove={() => {
+                    remove(_item.id);
+                  }}
+                  $isLast={index === list.length - 1}
+                />
+              ))}
+            </UITreeItems>
+          </UICollapsible>
+        )}
+      </UITreeItemRight>
+    </>
+  );
+}

+ 128 - 0
packages/materials/form-materials/src/components/inputs-values-tree/styles.tsx

@@ -0,0 +1,128 @@
+/**
+ * Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
+ * SPDX-License-Identifier: MIT
+ */
+
+import React from 'react';
+
+import styled, { css } from 'styled-components';
+import Icon from '@douyinfe/semi-icons';
+
+export const UIContainer = styled.div``;
+
+export const UIRow = styled.div`
+  display: flex;
+  align-items: flex-start;
+  gap: 5px;
+`;
+
+export const UICollapseTrigger = styled.div`
+  cursor: pointer;
+  margin-right: 5px;
+`;
+
+export const UITreeItems = styled.div<{ $shrink?: boolean }>`
+  display: grid;
+  grid-template-columns: auto 1fr;
+
+  ${({ $shrink }) =>
+    $shrink &&
+    css`
+      padding-left: 3px;
+      margin-top: 10px;
+    `}
+`;
+
+export const UITreeItemLeft = styled.div<{
+  $isLast?: boolean;
+  $showLine?: boolean;
+  $showCollapse?: boolean;
+}>`
+  grid-column: 1;
+  position: relative;
+  width: 16px;
+
+  ${({ $showLine, $isLast, $showCollapse }) => {
+    let height = $isLast ? '24px' : '100%';
+    let width = $showCollapse ? '12px' : '30px';
+
+    return (
+      $showLine &&
+      css`
+        &::before {
+          /* 竖线 */
+          content: '';
+          height: ${height};
+          position: absolute;
+          left: -14px;
+          top: -16px;
+          width: 1px;
+          background: #d9d9d9;
+          display: block;
+        }
+
+        &::after {
+          /* 横线 */
+          content: '';
+          position: absolute;
+          left: -14px; // 横线起点和竖线对齐
+          top: 8px; // 跟随你的行高调整
+          width: ${width}; // 横线长度
+          height: 1px;
+          background: #d9d9d9;
+          display: block;
+        }
+      `
+    );
+  }}
+`;
+
+export const UITreeItemRight = styled.div`
+  grid-column: 2;
+  margin-bottom: 10px;
+
+  &:last-child {
+    margin-bottom: 0px;
+  }
+`;
+
+export const UITreeItemMain = styled.div<{}>`
+  display: flex;
+  flex-direction: column;
+  gap: 10px;
+  position: relative;
+`;
+
+export const UICollapsible = styled.div<{ $collapse?: boolean }>`
+  display: none;
+
+  ${({ $collapse }) =>
+    $collapse &&
+    css`
+      display: block;
+    `}
+`;
+
+export const UIActions = styled.div`
+  white-space: nowrap;
+`;
+
+const iconAddChildrenSvg = (
+  <svg
+    className="icon-icon icon-icon-coz_add_node "
+    width="1em"
+    height="1em"
+    viewBox="0 0 24 24"
+    fill="currentColor"
+    xmlns="http://www.w3.org/2000/svg"
+  >
+    <path
+      fillRule="evenodd"
+      clipRule="evenodd"
+      d="M11 6.49988C11 8.64148 9.50397 10.4337 7.49995 10.8884V15.4998C7.49995 16.0521 7.94767 16.4998 8.49995 16.4998H11.208C11.0742 16.8061 11 17.1443 11 17.4998C11 17.8554 11.0742 18.1936 11.208 18.4998H8.49995C6.8431 18.4998 5.49995 17.1567 5.49995 15.4998V10.8884C3.49599 10.4336 2 8.64145 2 6.49988C2 4.0146 4.01472 1.99988 6.5 1.99988C8.98528 1.99988 11 4.0146 11 6.49988ZM6.5 8.99988C7.88071 8.99988 9 7.88059 9 6.49988C9 5.11917 7.88071 3.99988 6.5 3.99988C5.11929 3.99988 4 5.11917 4 6.49988C4 7.88059 5.11929 8.99988 6.5 8.99988Z"
+    ></path>
+    <path d="M17.5 12.4999C18.0523 12.4999 18.5 12.9476 18.5 13.4999V16.4999H21.5C22.0523 16.4999 22.5 16.9476 22.5 17.4999C22.5 18.0522 22.0523 18.4999 21.5 18.4999H18.5V21.4999C18.5 22.0522 18.0523 22.4999 17.5 22.4999C16.9477 22.4999 16.5 22.0522 16.5 21.4999V18.4999H13.5C12.9477 18.4999 12.5 18.0522 12.5 17.4999C12.5 16.9476 12.9477 16.4999 13.5 16.4999H16.5V13.4999C16.5 12.9476 16.9477 12.4999 17.5 12.4999Z"></path>
+  </svg>
+);
+
+export const IconAddChildren = () => <Icon size="small" svg={iconAddChildrenSvg} />;

+ 21 - 0
packages/materials/form-materials/src/components/inputs-values-tree/types.ts

@@ -0,0 +1,21 @@
+/**
+ * Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
+ * SPDX-License-Identifier: MIT
+ */
+
+import { IJsonSchema } from '@flowgram.ai/json-schema';
+
+import { ConstantInputStrategy } from '@/components/constant-input';
+
+export interface PropsType {
+  value?: any;
+  onChange: (value?: any) => void;
+  readonly?: boolean;
+  hasError?: boolean;
+  schema?: IJsonSchema;
+  style?: React.CSSProperties;
+  constantProps?: {
+    strategies?: ConstantInputStrategy[];
+    [key: string]: any;
+  };
+}

+ 2 - 2
packages/materials/form-materials/src/components/inputs-values/index.tsx

@@ -67,8 +67,8 @@ export function InputsValues({
           </UIRow>
         ))}
       </UIRows>
-      <Button disabled={readonly} icon={<IconPlus />} size="small" onClick={add}>
-        Add
+      <Button disabled={readonly} icon={<IconPlus />} size="small" onClick={() => add()}>
+        {I18n.t('Add')}
       </Button>
     </div>
   );

+ 18 - 5
packages/materials/form-materials/src/hooks/use-object-list/index.tsx

@@ -27,13 +27,20 @@ export function useObjectList<ValueType>({
 }: {
   value?: ObjectType<ValueType>;
   onChange: (value?: ObjectType<ValueType>) => void;
-  sortIndexKey?: string;
+  sortIndexKey?: string | ((item: ValueType | undefined) => string);
 }) {
   const [list, setList] = useState<ListItem<ValueType>[]>([]);
 
   const effectVersion = useRef(0);
   const changeVersion = useRef(0);
 
+  const getSortIndex = (value?: ValueType) => {
+    if (typeof sortIndexKey === 'function') {
+      return get(value, sortIndexKey(value)) || 0;
+    }
+    return get(value, sortIndexKey || '') || 0;
+  };
+
   useEffect(() => {
     effectVersion.current = effectVersion.current + 1;
     if (effectVersion.current === changeVersion.current) {
@@ -43,7 +50,7 @@ export function useObjectList<ValueType>({
 
     setList((_prevList) => {
       const newKeys = Object.entries(value || {})
-        .sort((a, b) => get(a[1], sortIndexKey || 0) - get(b[1], sortIndexKey || 0))
+        .sort((a, b) => getSortIndex(a[1]) - getSortIndex(b[1]))
         .map(([key]) => key);
 
       const oldKeys = _prevList.map((item) => item.key).filter(Boolean) as string[];
@@ -66,11 +73,12 @@ export function useObjectList<ValueType>({
     });
   }, [value]);
 
-  const add = () => {
+  const add = (defaultValue?: ValueType) => {
     setList((prevList) => [
       ...prevList,
       {
         id: genId(),
+        value: defaultValue,
       },
     ]);
   };
@@ -95,8 +103,13 @@ export function useObjectList<ValueType>({
             .filter((item) => item.key)
             .map((item) => [item.key!, item.value])
             .map((_res, idx) => {
-              if (isObject(_res[1]) && sortIndexKey) {
-                set(_res[1], sortIndexKey, idx);
+              const indexKey =
+                typeof sortIndexKey === 'function'
+                  ? sortIndexKey(_res[1] as ValueType | undefined)
+                  : sortIndexKey;
+
+              if (isObject(_res[1]) && indexKey) {
+                set(_res[1], indexKey, idx);
               }
               return _res;
             })

+ 3 - 3
packages/materials/form-materials/src/shared/flow-value/utils.ts

@@ -3,7 +3,7 @@
  * SPDX-License-Identifier: MIT
  */
 
-import { isArray, isObject, uniq } from 'lodash';
+import { isArray, isObject, isPlainObject, uniq } from 'lodash';
 import { IJsonSchema, JsonSchemaUtils } from '@flowgram.ai/json-schema';
 import { Scope } from '@flowgram.ai/editor';
 
@@ -77,7 +77,7 @@ export namespace FlowValueUtils {
   ): Generator<{ value: IFlowValue; path: string }> {
     const { includeTypes = ['ref', 'template'], path = '' } = options;
 
-    if (isObject(value)) {
+    if (isPlainObject(value)) {
       if (isRef(value) && includeTypes.includes('ref')) {
         yield { value, path };
         return;
@@ -170,7 +170,7 @@ export namespace FlowValueUtils {
    * @returns
    */
   export function inferJsonSchema(values: any, scope: Scope): IJsonSchema | undefined {
-    if (isObject(values)) {
+    if (isPlainObject(values)) {
       if (isConstant(values)) {
         return inferConstantJsonSchema(values);
       }