Skip to content

Commit

Permalink
fix form (#362)
Browse files Browse the repository at this point in the history
  • Loading branch information
guluguluhhhh authored Nov 11, 2024
1 parent 8221b71 commit aa53c45
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 45 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,11 @@ import i18next from 'i18next';

const EditableContext = React.createContext<FormInstance<any> | null>(null);

const PRIMITIVE_VALUE_DATA_INDEX = "Item";

interface Item {
key: string;
data: any;
}

interface EditableRowProps {
Expand Down Expand Up @@ -60,15 +63,21 @@ const EditableCell: React.FC<EditableCellProps> = ({
});

useEffect(() => {
form.setFieldsValue({ ...record });
}, [editing]);
if (record && record.data != null && record.data !== "") {
if (typeof record.data === 'object') {
form.setFieldsValue({ ...record.data });
} else {
form.setFieldValue(PRIMITIVE_VALUE_DATA_INDEX, record.data);
}
}
}, [editing, record]);

const save = async () => {
form.validateFields().then(values => {
handleSave({ ...record, ...values }, true);
handleSave({ ...record, data: values }, true);
}).catch(e => {
handleSave({ ...record, ...form.getFieldsValue() }, false);
})
handleSave({ ...record, data: form.getFieldsValue() }, false);
});
};

let childNode = children;
Expand Down Expand Up @@ -110,7 +119,7 @@ const EditableCell: React.FC<EditableCellProps> = ({
onBlur={save}
onChange={(e) => handleInputChange(dataIndex, parseFloat(e.target.value))}
/>
)
);
break;
case 'boolean':
node = (
Expand Down Expand Up @@ -157,6 +166,7 @@ interface DataType {
uid: number;
new: boolean;
invalid: boolean;
data: any;
}

type ColumnTypes = Exclude<EditableTableProps['columns'], undefined>;
Expand All @@ -171,7 +181,7 @@ const ArrayForm: React.FC = ({ array, value, onChange }) => {
}
}

const [dataSource, setDataSource] = useState<DataType[]>(value || []);
const [dataSource, setDataSource] = useState<DataType[]>(initDataSource);

function getLocalizedText(obj: any, index: string, defaultText: string) {
const i18nObj = obj[`x-${index}-i18n`];
Expand All @@ -195,7 +205,7 @@ const ArrayForm: React.FC = ({ array, value, onChange }) => {
let translatedTitle = getLocalizedText(array, 'title', '');
defaultColumns.push({
title: translatedTitle,
dataIndex: 'Item',
dataIndex: PRIMITIVE_VALUE_DATA_INDEX,
editable: true,
required: true,
nodeType: array.type,
Expand All @@ -218,6 +228,7 @@ const ArrayForm: React.FC = ({ array, value, onChange }) => {
uid: uniqueId(),
new: true,
invalid: true,
data: array.type === 'object' ? {} : '',
};
setDataSource([...dataSource, newData]);
onChange([...dataSource, newData]);
Expand All @@ -233,11 +244,13 @@ const ArrayForm: React.FC = ({ array, value, onChange }) => {
const newData = [...dataSource];
const index = newData.findIndex((item) => row.uid === item.uid);
const item = newData[index];
const newDataValue = array.type === 'object' ? row.data : row.data[PRIMITIVE_VALUE_DATA_INDEX];
newData.splice(index, 1, {
...item,
...row,
new: false,
invalid: !valid,
data: newDataValue,
});
setDataSource(newData);
onChange(newData);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -287,9 +287,22 @@ const GlobalPluginDetail = forwardRef((props: IProps, ref) => {
current[parts[parts.length - 1]] = value;
}

function processArray(array) {
return array.map(item => {
if (item.data != null && item.data !== "") {
return item.data;
}
return item;
});
}

Object.entries(formValues).forEach(([key, value]) => {

Check warning on line 299 in frontend/src/pages/plugin/components/PluginDrawer/GlobalPluginDetail.tsx

View workflow job for this annotation

GitHub Actions / build (16.x)

[Critical] It is recommended to add polyfill for "Object.entries", This might be caused by a compatibility problem in "safari@9"
if (value !== undefined) {
buildObjectFromPath(key, value);
if (Array.isArray(value)) {
buildObjectFromPath(key, processArray(value));
} else {
buildObjectFromPath(key, value);
}
}
});

Expand All @@ -306,24 +319,19 @@ const GlobalPluginDetail = forwardRef((props: IProps, ref) => {
result += `${indent}${key}:\n`;
value.forEach((item, index) => {
if (typeof item === 'object' && !Array.isArray(item)) {
// Check if the object has only one key named "Item"
const keys = Object.keys(item);
if (keys.length === 1 && keys[0] === 'Item') {
result += `${indent} - ${quoteIfString(item.Item)}\n`;
} else {
// Handle the first key-value pair of the object directly following the '-'
let firstEntry = true;
result += `${indent} - `;
Object.entries(item).forEach(([innerKey, innerValue], i) => {
if (firstEntry) {
result += `${innerKey}: ${quoteIfString(innerValue)}`;
firstEntry = false;
} else {
result += `\n${indent} ${innerKey}: ${quoteIfString(innerValue)}`;
}
});
result += '\n';
}
// Handle the first key-value pair of the object directly following the '-'
let firstEntry = true;
result += `${indent} - `;
Object.entries(item).forEach(([innerKey, innerValue], i) => {

Check warning on line 326 in frontend/src/pages/plugin/components/PluginDrawer/GlobalPluginDetail.tsx

View workflow job for this annotation

GitHub Actions / build (16.x)

[Critical] It is recommended to add polyfill for "Object.entries", This might be caused by a compatibility problem in "safari@9"
if (firstEntry) {
result += `${innerKey}: ${quoteIfString(innerValue)}`;
firstEntry = false;
} else {
result += `\n${indent} ${innerKey}: ${quoteIfString(innerValue)}`;
}
});
result += '\n';
} else {
result += `${indent} - ${quoteIfString(item)}\n`;
}
Expand Down Expand Up @@ -351,30 +359,24 @@ const GlobalPluginDetail = forwardRef((props: IProps, ref) => {
let uidCounter = 1;
const flattenObject = (obj, parentKey = '') => {
let flatResult = {};
let currentUid = uidCounter;
Object.keys(obj).forEach(key => {
const newKey = parentKey ? `${parentKey}.${key}` : key;
if (Array.isArray(obj[key])) {
obj[key].forEach((item, index) => {
const uid = currentUid++;
const uid = uidCounter++;
const newItem = { uid, data: item === 'object' ? {} : '' };
if (typeof item === 'object' && item !== null) {
const newItem = { uid };
Object.keys(item).forEach(subKey => {
newItem[subKey] = item[subKey];
newItem.data[subKey] = item[subKey];
});
flatResult[newKey] = flatResult[newKey] || [];
flatResult[newKey].push(newItem);
} else {
const newItem = { uid, Item: item };
flatResult[newKey] = flatResult[newKey] || [];
flatResult[newKey].push(newItem);
newItem.data = item;
}
flatResult[newKey] = flatResult[newKey] || [];
flatResult[newKey].push(newItem);
});
currentUid += obj[key].length;
} else if (typeof obj[key] === 'object' && obj[key] !== null) {
Object.assign(flatResult, flattenObject(obj[key], newKey));
} else if (typeof obj[key] === 'boolean') {
flatResult[newKey] = obj[key];
} else {
flatResult[newKey] = obj[key];
}
Expand All @@ -393,13 +395,14 @@ const GlobalPluginDetail = forwardRef((props: IProps, ref) => {
if (Array.isArray(obj)) {
return obj.filter(item => {
if (item && typeof item === 'object' && !Array.isArray(item)) {
// Remove unnecessary fields for the YAML result
delete item.uid;
delete item.new;
delete item.invalid;
const keys = Object.keys(item);
const nonEmptyKeys = keys.filter(key => item[key] != null && item[key] !== "");
if (nonEmptyKeys.length === 0) {
// Remove empty data
if (typeof item.data === 'object') {
const keys = Object.keys(item.data);
const nonEmptyKeys = keys.filter(key => item.data[key] != null && item.data[key] !== "");
if (nonEmptyKeys.length === 0) {
return false;
}
} else if (!item.data && item.data !== false) {
return false;
}
}
Expand Down

0 comments on commit aa53c45

Please sign in to comment.