Skip to content

Commit

Permalink
fix: refine form supports transformInitValues and change some resourc…
Browse files Browse the repository at this point in the history
…es display names
  • Loading branch information
MrWindlike committed Oct 30, 2024
1 parent bfcb73a commit fd3559a
Show file tree
Hide file tree
Showing 11 changed files with 58 additions and 29 deletions.
2 changes: 1 addition & 1 deletion packages/refine/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@dovetail-v2/refine",
"version": "0.1.14-alpha.3",
"version": "0.1.14-alpha.5",
"type": "module",
"files": [
"dist",
Expand Down
5 changes: 4 additions & 1 deletion packages/refine/src/components/CreateButton/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { useResource } from '@refinedev/core';
import React from 'react';
import { useTranslation } from 'react-i18next';
import { useOpenForm } from 'src/hooks/useOpenForm';
import { isFirstLetterEnglish } from 'src/utils/string';

interface CreateButtonProps {
label?: string;
Expand All @@ -21,7 +22,9 @@ export function CreateButton(props: CreateButtonProps) {
type="primary"
onClick={openForm}
>
{t('dovetail.create_resource', { resource: /^[a-zA-Z]/.test(label) ? ` ${label}` : label })}
{t('dovetail.create_resource', {
resource: isFirstLetterEnglish(label) ? ` ${label}` : label,
})}
</Button>
);
}
7 changes: 4 additions & 3 deletions packages/refine/src/components/Form/FormModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import ConfigsContext from 'src/contexts/configs';
import { WarningButtonStyle } from 'src/styles/button';
import { FullscreenModalStyle } from 'src/styles/modal';
import { SmallModalStyle } from 'src/styles/modal';
import { isFirstLetterEnglish } from 'src/utils/string';
import { RefineFormContent } from './RefineFormContent';
import useFieldsConfig from './useFieldsConfig';
import { useRefineForm } from './useRefineForm';
Expand Down Expand Up @@ -112,8 +113,8 @@ export function FormModal(props: FormModalProps) {

return {
...props.formProps,
transformInitValues: config.formConfig?.transformInitValues,
transformApplyValues,
transformInitValues: isYamlMode ? undefined : config.formConfig?.transformInitValues,
transformApplyValues: isYamlMode ? undefined : transformApplyValues,
initialValuesForCreate: isYamlMode ?
transformApplyValues(refineFormResult.formResult.getValues()) :
(props.formProps?.initialValuesForCreate || config?.initValue),
Expand Down Expand Up @@ -215,7 +216,7 @@ export function FormModal(props: FormModalProps) {
const label = config.displayName || config?.kind;

return i18n.t(id ? 'dovetail.edit_resource' : 'dovetail.create_resource', {
resource: /^[a-zA-Z]/.test(label) ? ` ${label}` : label,
resource: isFirstLetterEnglish(label) ? ` ${label}` : label,
});
}, [action, config.formConfig, config.displayName, config?.kind, i18n, id]);

Expand Down
13 changes: 9 additions & 4 deletions packages/refine/src/components/Form/YamlForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,16 @@ import { Form, Loading } from '@cloudtower/eagle';
import { css } from '@linaria/core';
import { FormAction, useResource } from '@refinedev/core';
import { Unstructured } from 'k8s-api-provider';
import React, { useMemo, useCallback, useEffect } from 'react';
import React, { useMemo, useCallback, useEffect, useContext } from 'react';
import { useTranslation } from 'react-i18next';
import ErrorContent from 'src/components/ErrorContent';
import { FormErrorAlert } from 'src/components/FormErrorAlert';
import FormLayout from 'src/components/FormLayout';
import { YamlEditorComponent } from 'src/components/YamlEditor/YamlEditorComponent';
import { BASE_INIT_VALUE } from 'src/constants/k8s';
import ConfigsContext from 'src/contexts/configs';
import { getCommonErrors } from 'src/utils/error';
import { isFirstLetterEnglish } from 'src/utils/string';
import useYamlForm from './useYamlForm';
import { YamlFormRule } from './useYamlForm';

Expand Down Expand Up @@ -61,6 +63,8 @@ export function YamlForm(props: YamlFormProps) {
} = props;
const { action: actionFromResource, resource } = useResource();
const action = actionFromProps || actionFromResource;
const configs = useContext(ConfigsContext);
const config = configs[resource?.name || ''];
const {
formProps,
saveButtonProps,
Expand All @@ -81,14 +85,15 @@ export function YamlForm(props: YamlFormProps) {
initialValuesForEdit: props.initialValuesForEdit,
rules,
successNotification(data) {
const displayName = config.displayName || resource?.meta?.kind;
return {
message: i18n.t(action === 'create' ? 'dovetail.create_success_toast' : 'dovetail.save_yaml_success_toast', {
kind: resource?.meta?.kind,
kind: isFirstLetterEnglish(displayName) ? ` ${displayName}` : displayName,
name: data?.data.id,
interpolation: {
escapeValue: false
}
}),
},
}).trim(),
type: 'success',
};
},
Expand Down
11 changes: 8 additions & 3 deletions packages/refine/src/components/Form/useReactHookForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
import get from 'lodash/get';
import has from 'lodash/has';
import React, { useEffect } from 'react';
import { DefaultValues } from 'react-hook-form';

import {
useForm as useHookForm,
Expand Down Expand Up @@ -79,6 +80,7 @@ export type UseFormProps<
*/
disableServerSideValidation?: boolean;
transformApplyValues?: (values: TVariables) => TVariables;
transformInitValues?: (values: Record<string, unknown>) => DefaultValues<TVariables>;
} & UseHookFormProps<TVariables, TContext>;

export const useForm = <
Expand All @@ -94,6 +96,7 @@ export const useForm = <
warnWhenUnsavedChanges: warnWhenUnsavedChangesProp,
disableServerSideValidation: disableServerSideValidationProp = false,
transformApplyValues,
transformInitValues,
...rest
}: UseFormProps<
TQueryFnData,
Expand Down Expand Up @@ -125,6 +128,7 @@ export const useForm = <

const useHookFormResult = useHookForm<TVariables, TContext>({
...rest,
defaultValues: transformInitValues && typeof rest.defaultValues === 'object' ? transformInitValues(rest.defaultValues) : rest.defaultValues,
});

const {
Expand Down Expand Up @@ -205,13 +209,14 @@ export const useForm = <
* get registered fields from react-hook-form
*/
const registeredFields = Object.keys(flattenObjectKeys(getValues()));
const transformedData = transformInitValues ? transformInitValues(data) : data;

/**
* set values from query result as default values
*/
registeredFields.forEach(path => {
const hasValue = has(data, path);
const dataValue = get(data, path);
const hasValue = has(transformedData, path);
const dataValue = get(transformedData, path);

/**
* set value if the path exists in the query result even if the value is null
Expand All @@ -220,7 +225,7 @@ export const useForm = <
setValue(path as Path<TVariables>, dataValue);
}
});
}, [queryResult?.data, setValue, getValues, formState.isDirty]);
}, [queryResult?.data, setValue, getValues, transformInitValues, formState.isDirty]);

useEffect(() => {
const subscription = watch((values: any, { type }: { type?: any }) => {

Check warning on line 231 in packages/refine/src/components/Form/useReactHookForm.tsx

View workflow job for this annotation

GitHub Actions / Run Test on Node 16

Unexpected any. Specify a different type

Check warning on line 231 in packages/refine/src/components/Form/useReactHookForm.tsx

View workflow job for this annotation

GitHub Actions / Run Test on Node 16

Unexpected any. Specify a different type
Expand Down
8 changes: 6 additions & 2 deletions packages/refine/src/components/Form/useRefineForm.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Unstructured } from 'k8s-api-provider';
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { isFirstLetterEnglish } from 'src/utils/string';
import { ResourceConfig } from '../../types';
import { useForm, UseFormProps } from './useReactHookForm';

Expand All @@ -20,15 +21,17 @@ export const useRefineForm = (props: {
errorNotification: false,
successNotification: () => {
const formValue = result.getValues() as Unstructured;
const resource = config.displayName || config.kind;

return {
message: i18n.t(
id ? 'dovetail.edit_resource_success' : 'dovetail.create_success_toast',
{
kind: formValue.kind,
kind: isFirstLetterEnglish(resource) ? ` ${resource}` : resource,
name: formValue.metadata.name,
interpolation: { escapeValue: false },
}
),
).trim(),
description: 'Success',
type: 'success',
};
Expand All @@ -41,6 +44,7 @@ export const useRefineForm = (props: {
},
defaultValues: config?.initValue,
transformApplyValues: config.formConfig?.transformApplyValues,
transformInitValues: config.formConfig?.transformInitValues,
...config.formConfig?.useFormProps,
});

Expand Down
3 changes: 2 additions & 1 deletion packages/refine/src/components/Table/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { InternalTableProps } from 'src/components/InternalBaseTable';
import InternalBaseTable from 'src/components/InternalBaseTable';
import { ComponentContext } from 'src/contexts';
import { ResourceModel } from 'src/models';
import { isFirstLetterEnglish } from 'src/utils/string';

interface TableProps<Model extends ResourceModel> {
tableProps: InternalTableProps<Model>;
Expand All @@ -19,7 +20,7 @@ export function Table<Model extends ResourceModel>(props: TableProps<Model>) {
const { Table: TableComponent } = useContext(ComponentContext);
const Table = TableComponent || InternalBaseTable;
const { i18n } = useTranslation();
const resourceType = /^[a-zA-Z]/.test(displayName) ? ` ${displayName}` : displayName;
const resourceType = isFirstLetterEnglish(displayName) ? ` ${displayName}` : displayName;

if (!tableProps.data?.length && !tableProps.loading) {
return <ErrorContent
Expand Down
18 changes: 12 additions & 6 deletions packages/refine/src/hooks/useDeleteModal/useDeleteModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import React, { useState, useContext } from 'react';
import { useTranslation, Trans } from 'react-i18next';
import ConfigsContext from 'src/contexts/configs';
import { SmallModalStyle } from 'src/styles/modal';
import { isFirstLetterEnglish } from 'src/utils/string';

const TextStyle = css`
margin-bottom: 4px;
Expand Down Expand Up @@ -33,9 +34,14 @@ export const useDeleteModal = (resource: string) => {
const navigation = useNavigation();
const [id, setId] = useState<string>('');
const { t } = useTranslation();
const displayName = config.displayName || config.kind;
const resourceDisplayName = isFirstLetterEnglish(displayName) ? ` ${displayName}` : displayName;

const modalProps: ModalProps = {
className: SmallModalStyle,
title: t('dovetail.delete_resource', { resource: config.kind }),
title: t('dovetail.delete_resource', {
resource: resourceDisplayName,
}),
okText: t('dovetail.delete'),
okButtonProps: {
danger: true,
Expand All @@ -49,7 +55,7 @@ export const useDeleteModal = (resource: string) => {
i18nKey="dovetail.confirm_delete_text"
tOptions={{
target: id,
kind: config.kind,
kind: resourceDisplayName,
}}
shouldUnescape={true}
>
Expand All @@ -71,23 +77,23 @@ export const useDeleteModal = (resource: string) => {
return {
message: t('dovetail.delete_success_toast', {
name: id,
kind: config.kind,
kind: resourceDisplayName,
interpolation: {
escapeValue: false
}
}),
}).trim(),
type: 'success'
};
},
errorNotification() {
return {
message: t('dovetail.delete_failed_toast', {
name: id,
kind: config.kind,
kind: resourceDisplayName,
interpolation: {
escapeValue: false
}
}),
}).trim(),
type: 'error'
};
},
Expand Down
4 changes: 2 additions & 2 deletions packages/refine/src/locales/en-US/dovetail.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
"fetch_schema_fail": "获取 schema 失败。",
"obtain_data_error": "Having trouble getting data.",
"retry": "Retry",
"create_resource": "Create{{resource}}",
"edit_resource": "Edit{{resource}}",
"create_resource": "Create {{resource}}",
"edit_resource": "Edit {{resource}}",
"state": "Status",
"name": "Name",
"pod": "Pod",
Expand Down
12 changes: 6 additions & 6 deletions packages/refine/src/locales/zh-CN/dovetail.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
"cancel": "取消",
"delete": "删除",
"create": "创建",
"delete_resource": "删除 {{resource}}",
"confirm_delete_text": "确认删除 {{kind}} <0>{{target}}</0> 吗?",
"delete_resource": "删除{{resource}}",
"confirm_delete_text": "确认删除{{kind}} <0>{{target}}</0> 吗?",
"delete_tip": "该操作无法被撤回。",
"edit": "编辑",
"namespace": "名字空间",
Expand Down Expand Up @@ -131,16 +131,16 @@
"username": "用户名",
"host": "主机",
"container_num": "容器数量",
"edit_resource_success": "编辑 {{resource}} {{name}} 成功",
"edit_resource_success": "编辑{{kind}} {{name}} 成功",
"redeploy_success_toast": "重新部署 {{kind}} {{name}} 成功",
"redeploy_failed_toast": "重新部署 {{kind}} {{name}} 失败",
"pause_success_toast": "暂停成功",
"pause_failed_toast": "暂停失败",
"resume_success_toast": "恢复成功",
"resume_failed_toast": "恢复失败",
"delete_success_toast": "删除 {{kind}} {{name}} 成功",
"delete_failed_toast": "删除 {{kind}} {{name}} 失败",
"create_success_toast": "创建 {{kind}} {{name}} 成功",
"delete_success_toast": "删除{{kind}} {{name}} 成功",
"delete_failed_toast": "删除{{kind}} {{name}} 失败",
"create_success_toast": "创建{{kind}} {{name}} 成功",
"save_yaml_success_toast": "编辑 YAML 保存成功",
"save_replicas_success_toast": "编辑预期副本数成功",
"save_replicas_failed_toast": "编辑预期副本数失败",
Expand Down
4 changes: 4 additions & 0 deletions packages/refine/src/utils/string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,7 @@ export function shortenedImage(image: string) {
.replace(/:latest$/, '')
.replace(/^(.*@sha256:)([0-9a-f]{8})[0-9a-f]+$/i, '$1$2…');
}

export function isFirstLetterEnglish(str: string) {
return /^[a-zA-Z]/.test(str);
}

0 comments on commit fd3559a

Please sign in to comment.