Răsfoiți Sursa

fix(material): json schema editor controlled by value (#214)

* feat: install material directly from form-materials

* fix(material): json schema editor controlled by value
Yiwei Mao 8 luni în urmă
părinte
comite
c11a995040

+ 35 - 15
packages/materials/form-materials/bin/index.js

@@ -12,7 +12,8 @@ const program = new Command();
 program
   .version('1.0.0')
   .description('Add official materials to your project')
-  .action(async () => {
+  .argument('[materialName]', 'Optional material name to skip selection (format: type/name)')
+  .action(async (materialName) => {
     console.log(chalk.bgGreenBright('Welcome to @flowgram.ai/form-materials CLI!'));
 
     const projectInfo = getProjectInfo();
@@ -23,20 +24,39 @@ program
 
     const materials = listAllMaterials();
 
-    // 2. User select one component
-    const { material } = await inquirer.prompt([
-      {
-        type: 'list',
-        name: 'material',
-        message: 'Select one material to add:',
-        choices: [
-          ...materials.map((_material) => ({
-            name: `${_material.type}/${_material.name}`,
-            value: _material,
-          })),
-        ],
-      },
-    ]);
+    let material;
+
+    // Check if materialName is provided and exists in materials
+    if (materialName) {
+      const selectedMaterial = materials.find((m) => `${m.type}/${m.name}` === materialName);
+      if (selectedMaterial) {
+        material = selectedMaterial;
+        console.log(chalk.green(`Using material: ${materialName}`));
+      } else {
+        console.log(
+          chalk.yellow(`Material "${materialName}" not found. Please select from the list:`)
+        );
+      }
+    }
+
+    // If material not found or materialName not provided, prompt user to select
+    if (!material) {
+      // User select one component
+      const result = await inquirer.prompt([
+        {
+          type: 'list',
+          name: 'material',
+          message: 'Select one material to add:',
+          choices: [
+            ...materials.map((_material) => ({
+              name: `${_material.type}/${_material.name}`,
+              value: _material,
+            })),
+          ],
+        },
+      ]);
+      material = result.material;
+    }
 
     console.log(material);
 

+ 41 - 5
packages/materials/form-materials/src/components/json-schema-editor/hooks.tsx

@@ -1,4 +1,4 @@
-import { useEffect, useMemo, useState } from 'react';
+import { useEffect, useMemo, useRef, useState } from 'react';
 
 import { PropertyValueType } from './types';
 import { JsonSchema } from '../type-selector';
@@ -28,7 +28,7 @@ export function usePropertiesEdit(
   onChange?: (value: PropertyValueType) => void
 ) {
   // Get drilldown (array.items.items...)
-  const drilldown = useMemo(() => getDrilldownSchema(value), [value?.type, value?.items]);
+  const drilldown = useMemo(() => getDrilldownSchema(value), [value, value?.type, value?.items]);
 
   const isDrilldownObject = drilldown.schema?.type === 'object';
 
@@ -37,11 +37,11 @@ export function usePropertiesEdit(
     () =>
       isDrilldownObject
         ? Object.entries(drilldown.schema?.properties || {}).map(
-            ([key, _value]) =>
+            ([name, _value]) =>
               ({
                 key: genId(),
-                name: key,
-                isPropertyRequired: value?.required?.includes(key) || false,
+                name,
+                isPropertyRequired: drilldown.schema?.required?.includes(name) || false,
                 ..._value,
               } as PropertyValueType)
           )
@@ -51,6 +51,42 @@ export function usePropertiesEdit(
 
   const [propertyList, setPropertyList] = useState<PropertyValueType[]>(initPropertyList);
 
+  const mountRef = useRef(false);
+
+  useEffect(() => {
+    // If initRef is true, it means the component has been mounted
+    if (mountRef.current) {
+      // If the value is changed, update the property list
+      setPropertyList((_list) => {
+        const nameMap = new Map<string, PropertyValueType>();
+
+        for (const _property of _list) {
+          if (_property.name) {
+            nameMap.set(_property.name, _property);
+          }
+        }
+        return Object.entries(drilldown.schema?.properties || {}).map(([name, _value]) => {
+          const _property = nameMap.get(name);
+          if (_property) {
+            return {
+              key: _property.key,
+              name,
+              isPropertyRequired: drilldown.schema?.required?.includes(name) || false,
+              ..._value,
+            };
+          }
+          return {
+            key: genId(),
+            name,
+            isPropertyRequired: drilldown.schema?.required?.includes(name) || false,
+            ..._value,
+          };
+        });
+      });
+    }
+    mountRef.current = true;
+  }, [drilldown.schema]);
+
   const updatePropertyList = (updater: (list: PropertyValueType[]) => PropertyValueType[]) => {
     setPropertyList((_list) => {
       const next = updater(_list);

+ 0 - 2
packages/materials/form-materials/src/components/json-schema-editor/index.tsx

@@ -74,8 +74,6 @@ function PropertyEdit(props: {
 }) {
   const { value, onChange: onChangeProps, onRemove, $isLast, $showLine } = props;
 
-  console.log('isLast', $isLast);
-
   const [expand, setExpand] = useState(false);
   const [collapse, setCollapse] = useState(false);