Просмотр исходного кода

chore: simplify variable use in demo

sanmaopep 10 месяцев назад
Родитель
Сommit
5b6434eb6a

+ 14 - 12
apps/demo-fixed-layout/src/plugins/variable-plugin/utils.ts

@@ -1,5 +1,5 @@
 import { get } from 'lodash-es';
-import { ASTKind, type ASTNodeJSON } from '@flowgram.ai/fixed-layout-editor';
+import { ASTFactory, type ASTNodeJSON } from '@flowgram.ai/fixed-layout-editor';
 
 import { type JsonSchema } from '../../typings';
 
@@ -18,26 +18,28 @@ export function createASTFromJSONSchema(jsonSchema: JsonSchema): ASTNodeJSON | u
 
   switch (type) {
     case 'object':
-      return {
-        kind: ASTKind.Object,
+      return ASTFactory.createObject({
         properties: sortProperties(jsonSchema.properties || {}).map(([key, _property]) => ({
           key,
           type: createASTFromJSONSchema(_property),
           meta: { description: _property.description },
         })),
-      };
-
+      });
     case 'array':
-      return {
-        kind: ASTKind.Array,
+      return ASTFactory.createArray({
         items: createASTFromJSONSchema(jsonSchema.items!),
-      };
+      });
+    case 'string':
+      return ASTFactory.createString();
+    case 'number':
+      return ASTFactory.createNumber();
+    case 'boolean':
+      return ASTFactory.createBoolean();
+    case 'integer':
+      return ASTFactory.createInteger();
 
     default:
       // Camel case to variable-core type
-      return {
-        kind: type.charAt(0).toUpperCase() + type.slice(1),
-        enum: jsonSchema.enum,
-      };
+      return;
   }
 }

+ 2 - 23
apps/demo-fixed-layout/src/plugins/variable-plugin/variable-selector/index.tsx

@@ -4,7 +4,6 @@ import { type TreeNodeData } from '@douyinfe/semi-ui/lib/es/tree';
 import { TreeSelect } from '@douyinfe/semi-ui';
 
 import { type JsonSchema } from '../../../typings';
-// import { useCurrentNodeElement } from '../../hooks/use-current-node-element';
 import { useVariableTree } from './use-variable-tree';
 
 export interface VariableSelectorProps {
@@ -31,8 +30,6 @@ export const VariableSelector = ({
 }: VariableSelectorProps) => {
   const { size = 'small', emptyContent, targetSchemas, strongEqualToTargetSchema } = options || {};
 
-  // const nodeElement = useCurrentNodeElement();
-
   const treeData = useVariableTree<TreeNodeData>({
     targetSchemas,
     strongEqual: strongEqualToTargetSchema,
@@ -55,7 +52,7 @@ export const VariableSelector = ({
       label: variable.meta?.expressionTitle || variable.key || '',
       disabled,
       labelPath: [...parentFields, variable]
-        .map(_field => _field.meta?.expressionTitle || _field.key || '')
+        .map((_field) => _field.meta?.expressionTitle || _field.key || '')
         .join('.'),
       children,
     }),
@@ -66,15 +63,6 @@ export const VariableSelector = ({
       return emptyContent;
     }
 
-    // if (targetSchemas?.length) {
-    //   return (
-    //     <div>
-    //       No Variable With:
-    //       <VariableTypeTag className={s['prefix-icon']} typeSchema={targetSchemas[0]} />
-    //     </div>
-    //   );
-    // }
-
     return 'nodata';
   };
 
@@ -82,7 +70,6 @@ export const VariableSelector = ({
     <>
       <TreeSelect
         dropdownMatchSelectWidth={false}
-        // getPopupContainer={() => nodeElement}
         disabled={disabled}
         treeData={treeData}
         size={size}
@@ -92,18 +79,10 @@ export const VariableSelector = ({
           outline: hasError ? '1px solid red' : undefined,
         }}
         validateStatus={hasError ? 'error' : undefined}
-        onChange={option => {
+        onChange={(option) => {
           onChange(option as string);
         }}
         showClear
-        // renderSelectedItem={(item: TreeNodeData) => {
-        //   let label = item?.labelPath ?? value?.replace('$.', '') ?? '';
-        //   return (
-        //     <div className={s['option-select-item-container']}>
-        //       <div className={item?.labelPath ? s.text : s['error-text']}>{label}</div>
-        //     </div>
-        //   );
-        // }}
         placeholder="Select Variable..."
         emptyContent={renderEmpty()}
       />

+ 20 - 18
apps/demo-fixed-layout/src/plugins/variable-plugin/variable-selector/use-variable-tree.ts

@@ -1,10 +1,12 @@
-/* eslint-disable max-lines-per-function */
 import { useCallback, useMemo } from 'react';
 
 import {
+  ArrayType,
+  ASTFactory,
   ASTKind,
   type BaseType,
-  type ObjectType,
+  isMatchAST,
+  ObjectType,
   type UnionJSON,
   useScopeAvailable,
 } from '@flowgram.ai/fixed-layout-editor';
@@ -42,7 +44,7 @@ export function useVariableTree<TreeData>({
   const available = useScopeAvailable();
 
   const getVariableTypeIcon = useCallback((variable: VariableField) => {
-    if (variable.type?.kind === ASTKind.Array) {
+    if (isMatchAST(variable.type, ArrayType)) {
       return (
         (ArrayIcons as any)[variable.type.items?.kind.toLowerCase()] ||
         VariableTypeIcons[ASTKind.Array.toLowerCase()]
@@ -53,14 +55,14 @@ export function useVariableTree<TreeData>({
   }, []);
 
   const targetTypeAST: UnionJSON = useMemo(
-    () => ({
-      kind: ASTKind.Union,
-      types: targetSchemas.map(_targetSchema => {
-        const typeAst = createASTFromJSONSchema(_targetSchema)!;
-        return strongEqual ? typeAst : { ...typeAst, weak: true };
+    () =>
+      ASTFactory.createUnion({
+        types: targetSchemas.map((_targetSchema) => {
+          const typeAst = createASTFromJSONSchema(_targetSchema)!;
+          return strongEqual ? typeAst : { ...typeAst, weak: true };
+        }),
       }),
-    }),
-    [strongEqual, ...targetSchemas],
+    [strongEqual, ...targetSchemas]
   );
 
   const checkTypeFiltered = useCallback(
@@ -75,21 +77,21 @@ export function useVariableTree<TreeData>({
 
       return false;
     },
-    [strongEqual, targetTypeAST],
+    [strongEqual, targetTypeAST]
   );
 
   const renderVariable = (
     variable: VariableField,
-    parentFields: VariableField[] = [],
+    parentFields: VariableField[] = []
   ): TreeData | null => {
     let type = variable?.type;
 
     const isTypeFiltered = checkTypeFiltered(type);
 
     let children: TreeData[] | undefined;
-    if (type?.kind === ASTKind.Object) {
-      children = ((type as ObjectType).properties || [])
-        .map(_property => renderVariable(_property as VariableField, [...parentFields, variable]))
+    if (isMatchAST(type, ObjectType)) {
+      children = (type.properties || [])
+        .map((_property) => renderVariable(_property as VariableField, [...parentFields, variable]))
         .filter(Boolean) as TreeData[];
     }
 
@@ -98,7 +100,7 @@ export function useVariableTree<TreeData>({
     }
 
     const currPath = [
-      ...parentFields.map(_field => _field.meta?.titleKey || _field.key),
+      ...parentFields.map((_field) => _field.meta?.titleKey || _field.key),
       variable.meta?.titleKey || variable.key,
     ].join('.');
 
@@ -114,7 +116,7 @@ export function useVariableTree<TreeData>({
 
   return [
     ...available.variables
-      .filter(_v => {
+      .filter((_v) => {
         if (ignoreReadonly) {
           return !_v.meta?.readonly;
         }
@@ -123,6 +125,6 @@ export function useVariableTree<TreeData>({
       .slice(0)
       .reverse(),
   ]
-    .map(_variable => renderVariable(_variable as VariableField))
+    .map((_variable) => renderVariable(_variable as VariableField))
     .filter(Boolean) as TreeData[];
 }

+ 14 - 12
apps/demo-free-layout/src/plugins/variable-plugin/utils.ts

@@ -1,5 +1,5 @@
 import { get } from 'lodash-es';
-import { ASTKind, type ASTNodeJSON } from '@flowgram.ai/free-layout-editor';
+import { ASTFactory, type ASTNodeJSON } from '@flowgram.ai/free-layout-editor';
 
 import { type JsonSchema } from '../../typings';
 
@@ -18,26 +18,28 @@ export function createASTFromJSONSchema(jsonSchema: JsonSchema): ASTNodeJSON | u
 
   switch (type) {
     case 'object':
-      return {
-        kind: ASTKind.Object,
+      return ASTFactory.createObject({
         properties: sortProperties(jsonSchema.properties || {}).map(([key, _property]) => ({
           key,
           type: createASTFromJSONSchema(_property),
           meta: { description: _property.description },
         })),
-      };
-
+      });
     case 'array':
-      return {
-        kind: ASTKind.Array,
+      return ASTFactory.createArray({
         items: createASTFromJSONSchema(jsonSchema.items!),
-      };
+      });
+    case 'string':
+      return ASTFactory.createString();
+    case 'number':
+      return ASTFactory.createNumber();
+    case 'boolean':
+      return ASTFactory.createBoolean();
+    case 'integer':
+      return ASTFactory.createInteger();
 
     default:
       // Camel case to variable-core type
-      return {
-        kind: type.charAt(0).toUpperCase() + type.slice(1),
-        enum: jsonSchema.enum,
-      };
+      return;
   }
 }

+ 2 - 23
apps/demo-free-layout/src/plugins/variable-plugin/variable-selector/index.tsx

@@ -4,7 +4,6 @@ import { type TreeNodeData } from '@douyinfe/semi-ui/lib/es/tree';
 import { TreeSelect } from '@douyinfe/semi-ui';
 
 import { type JsonSchema } from '../../../typings';
-// import { useCurrentNodeElement } from '../../hooks/use-current-node-element';
 import { useVariableTree } from './use-variable-tree';
 
 export interface VariableSelectorProps {
@@ -31,8 +30,6 @@ export const VariableSelector = ({
 }: VariableSelectorProps) => {
   const { size = 'small', emptyContent, targetSchemas, strongEqualToTargetSchema } = options || {};
 
-  // const nodeElement = useCurrentNodeElement();
-
   const treeData = useVariableTree<TreeNodeData>({
     targetSchemas,
     strongEqual: strongEqualToTargetSchema,
@@ -55,7 +52,7 @@ export const VariableSelector = ({
       label: variable.meta?.expressionTitle || variable.key || '',
       disabled,
       labelPath: [...parentFields, variable]
-        .map(_field => _field.meta?.expressionTitle || _field.key || '')
+        .map((_field) => _field.meta?.expressionTitle || _field.key || '')
         .join('.'),
       children,
     }),
@@ -66,15 +63,6 @@ export const VariableSelector = ({
       return emptyContent;
     }
 
-    // if (targetSchemas?.length) {
-    //   return (
-    //     <div>
-    //       No Variable With:
-    //       <VariableTypeTag className={s['prefix-icon']} typeSchema={targetSchemas[0]} />
-    //     </div>
-    //   );
-    // }
-
     return 'nodata';
   };
 
@@ -82,7 +70,6 @@ export const VariableSelector = ({
     <>
       <TreeSelect
         dropdownMatchSelectWidth={false}
-        // getPopupContainer={() => nodeElement}
         disabled={disabled}
         treeData={treeData}
         size={size}
@@ -92,18 +79,10 @@ export const VariableSelector = ({
           outline: hasError ? '1px solid red' : undefined,
         }}
         validateStatus={hasError ? 'error' : undefined}
-        onChange={option => {
+        onChange={(option) => {
           onChange(option as string);
         }}
         showClear
-        // renderSelectedItem={(item: TreeNodeData) => {
-        //   let label = item?.labelPath ?? value?.replace('$.', '') ?? '';
-        //   return (
-        //     <div className={s['option-select-item-container']}>
-        //       <div className={item?.labelPath ? s.text : s['error-text']}>{label}</div>
-        //     </div>
-        //   );
-        // }}
         placeholder="Select Variable..."
         emptyContent={renderEmpty()}
       />

+ 20 - 18
apps/demo-free-layout/src/plugins/variable-plugin/variable-selector/use-variable-tree.ts

@@ -1,10 +1,12 @@
-/* eslint-disable max-lines-per-function */
 import { useCallback, useMemo } from 'react';
 
 import {
+  ArrayType,
+  ASTFactory,
   ASTKind,
   type BaseType,
-  type ObjectType,
+  isMatchAST,
+  ObjectType,
   type UnionJSON,
   useScopeAvailable,
 } from '@flowgram.ai/free-layout-editor';
@@ -42,7 +44,7 @@ export function useVariableTree<TreeData>({
   const available = useScopeAvailable();
 
   const getVariableTypeIcon = useCallback((variable: VariableField) => {
-    if (variable.type?.kind === ASTKind.Array) {
+    if (isMatchAST(variable.type, ArrayType)) {
       return (
         (ArrayIcons as any)[variable.type.items?.kind.toLowerCase()] ||
         VariableTypeIcons[ASTKind.Array.toLowerCase()]
@@ -53,14 +55,14 @@ export function useVariableTree<TreeData>({
   }, []);
 
   const targetTypeAST: UnionJSON = useMemo(
-    () => ({
-      kind: ASTKind.Union,
-      types: targetSchemas.map(_targetSchema => {
-        const typeAst = createASTFromJSONSchema(_targetSchema)!;
-        return strongEqual ? typeAst : { ...typeAst, weak: true };
+    () =>
+      ASTFactory.createUnion({
+        types: targetSchemas.map((_targetSchema) => {
+          const typeAst = createASTFromJSONSchema(_targetSchema)!;
+          return strongEqual ? typeAst : { ...typeAst, weak: true };
+        }),
       }),
-    }),
-    [strongEqual, ...targetSchemas],
+    [strongEqual, ...targetSchemas]
   );
 
   const checkTypeFiltered = useCallback(
@@ -75,21 +77,21 @@ export function useVariableTree<TreeData>({
 
       return false;
     },
-    [strongEqual, targetTypeAST],
+    [strongEqual, targetTypeAST]
   );
 
   const renderVariable = (
     variable: VariableField,
-    parentFields: VariableField[] = [],
+    parentFields: VariableField[] = []
   ): TreeData | null => {
     let type = variable?.type;
 
     const isTypeFiltered = checkTypeFiltered(type);
 
     let children: TreeData[] | undefined;
-    if (type?.kind === ASTKind.Object) {
-      children = ((type as ObjectType).properties || [])
-        .map(_property => renderVariable(_property as VariableField, [...parentFields, variable]))
+    if (isMatchAST(type, ObjectType)) {
+      children = (type.properties || [])
+        .map((_property) => renderVariable(_property as VariableField, [...parentFields, variable]))
         .filter(Boolean) as TreeData[];
     }
 
@@ -98,7 +100,7 @@ export function useVariableTree<TreeData>({
     }
 
     const currPath = [
-      ...parentFields.map(_field => _field.meta?.titleKey || _field.key),
+      ...parentFields.map((_field) => _field.meta?.titleKey || _field.key),
       variable.meta?.titleKey || variable.key,
     ].join('.');
 
@@ -114,7 +116,7 @@ export function useVariableTree<TreeData>({
 
   return [
     ...available.variables
-      .filter(_v => {
+      .filter((_v) => {
         if (ignoreReadonly) {
           return !_v.meta?.readonly;
         }
@@ -123,6 +125,6 @@ export function useVariableTree<TreeData>({
       .slice(0)
       .reverse(),
   ]
-    .map(_variable => renderVariable(_variable as VariableField))
+    .map((_variable) => renderVariable(_variable as VariableField))
     .filter(Boolean) as TreeData[];
 }