Skip to content

Commit

Permalink
feat: add DateTime, Birthday, Weekday, Month generators (#269)
Browse files Browse the repository at this point in the history
  • Loading branch information
ZACHSTRIVES committed Mar 14, 2024
1 parent 200bc07 commit a5045c6
Show file tree
Hide file tree
Showing 28 changed files with 766 additions and 40 deletions.
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "dummyi",
"version": "0.2.2",
"version": "0.2.3",
"private": true,
"scripts": {
"dev": "next dev",
Expand Down
6 changes: 3 additions & 3 deletions scripts/addNewGenerator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ export const ${generatorName}GeneratorDefaultOptions:${generatorName}GeneratorOp
// -------------------------------------------------------------------------------------------------------------
// generate method
export const generate = (options: any): GenerateResult => {
export const generate = (options: ${generatorName}GeneratorOptions): GenerateResult => {
// TODO: implement your own generate method here
return {
Expand All @@ -125,9 +125,9 @@ export const ${generatorName}GeneratorOptionsComponent: React.FunctionComponent<
// TODO: implement your own options component here
return (
<div>
<>
NOT IMPLEMENTED
</div>
</>
);
}`;
}
Expand Down
2 changes: 1 addition & 1 deletion src/components/DevTools/src/GenerateResultsPreviewer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ export const GenerateResultsPreviewer: React.FunctionComponent<GenerateResultsPr

return (
<div>
<Card style={{width: "400px", height: "250px"}}>
<Card style={{width: "400px", height: "250px", borderColor: isError ? "red" : null}}>
<Space>
<Tag size={'small'} type={colorMode === ColorMode.DARK ? 'solid' : 'ghost'}>{formatType}</Tag>
{isError && <Tag size={'small'} style={{color: 'red'}}>ERROR</Tag>}
Expand Down
2 changes: 1 addition & 1 deletion src/components/InputPanel/src/InputPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export const InputPanel: React.FunctionComponent<InputPanelProps> = () => {

setPanelHeight(containerHeight);

if (containerWidth > 1000) {
if (containerWidth > 900) {
setComponentSize(ComponentSize.LARGE);
} else if (containerWidth > 550) {
setComponentSize(ComponentSize.MEDIUM);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export interface DataTypeSelectModalProps {

export const DataTypeSelectModal: React.FunctionComponent<DataTypeSelectModalProps> = ({...props}) => {
const intl = useIntl();
const {Title} = Typography;
const {Title, Text} = Typography;
const dispatch = useDispatch();
const [searchText, setSearchText] = React.useState(null);
const data = useMemo(() => getGeneratorList(searchText, intl), [intl, searchText]);
Expand All @@ -34,7 +34,7 @@ export const DataTypeSelectModal: React.FunctionComponent<DataTypeSelectModalPro

// actions
const handleSelect = (item: Generator) => {
dispatch(doChangeDataType(currentTargetDataFieldId,item.type));
dispatch(doChangeDataType(currentTargetDataFieldId, item.type));
onCancel();
}

Expand Down Expand Up @@ -106,7 +106,9 @@ export const DataTypeSelectModal: React.FunctionComponent<DataTypeSelectModalPro
item.exampleLines && item.exampleLines.map((example, index) => (
<div key={index}
className={styles.dataTypeSelectModalCard__example}>
{example}
<Text ellipsis={{showTooltip: true}} type="tertiary">
{example}
</Text>
</div>
))
}
Expand Down
55 changes: 55 additions & 0 deletions src/components/Utils/src/OptionsDatetimePicker.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import React from "react";
import {ErrorTooltip, InfoTooltip} from "@/components/Utils";
import {useIntl} from "@/locale";
import {isNullOrWhiteSpace} from "@/utils/stringUtils";
import {DatePicker} from "@douyinfe/semi-ui";
import {hasValue} from "@/utils/typeUtils";

export interface OptionsDatetimePickerProps {
label: string | React.ReactNode;
type?: "date" | "dateTime" | "dateRange" | "dateTimeRange";
infoTooltip?: string | React.ReactNode;
errorMessage?: string;
value: string | number | Date | string[] | number[] | Date[];
onChange: (value: any) => void;
style?: React.CSSProperties;
required?: boolean;
}

export const OptionsDatetimePicker: React.FunctionComponent<OptionsDatetimePickerProps> = ({...props}) => {
const {label, type, infoTooltip, errorMessage, value, style, onChange, required} = props;
const intl = useIntl();

// Add a new useState to manage the validation error message
const [validationError, setValidationError] = React.useState<string | undefined>();

// Add effect to validate value when it changes or when required status changes
React.useEffect(() => {
if (required && !hasValue(value)) {
setValidationError(intl.formatMessage({id: 'error.input.isRequired'})); // Set default required error message or use props.errorMessage
} else {
setValidationError(undefined); // Clear error message when input is valid
}
}, [value, required]);

return (
<div className="generatorConfig_column">
<div className='generatorConfig_column__label'>
{label}
{infoTooltip && <InfoTooltip>
{infoTooltip}
</InfoTooltip>}
</div>
<ErrorTooltip message={validationError || errorMessage}>
<DatePicker
density="compact"
type={type}
onChange={(date, dateString) => onChange(dateString)}
value={value}
style={style}
validateStatus={!isNullOrWhiteSpace(validationError || errorMessage) ? 'error' : 'default'}
/>
</ErrorTooltip>
</div>
)
}
2 changes: 1 addition & 1 deletion src/components/Utils/src/OptionsSwitch.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export const OptionsSwitch: React.FunctionComponent<OptionsSwitchProps> = ({...p
<ErrorTooltip message={errorMessage}>
<Switch
onChange={onChange}
size={size ? size : 'default'}
size={size ? size : 'large'}
checked={value}
style={style}
/>
Expand Down
23 changes: 14 additions & 9 deletions src/constants/enums.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

// export format
export enum ExportFormatCategory {
FILE_TYPES = "file_types",
Expand All @@ -18,32 +17,38 @@ export enum ExportFormat {

export enum ValueType {
STRING = "string",
TEXT= "text",
TEXT = "text",
ONE_BIT = "1bit",
INT = "integer",
BIGINT = "bigint",
DOUBLE = "double",
BOOLEAN = "boolean",
INT_LIST = "int_list",
STRING_LIST = "string_list"
STRING_LIST = "string_list",
DATE_TIME = "date_time"
}

export enum ExportProcessStage{
export enum ExportProcessStage {
PREVIEW = "preview",
GENERATING = "generating",
COMPLETED = "completed",
}

// data types
export enum DataTypeCategory {
ALL= "all",
ALL = "all",
BASIC = "basic",
PERSON = "person",
NETWORK = "network",
COMMERCE = "commerce",
DATETIME = "datetime"
}

export enum DataType {
BIRTHDAY = "birthday",
MONTH = "month",
WEEKDAY = "weekday",
DATETIME = "datetime",
URL = "url",
DOMAINSUFFIX = "domainsuffix",
DOMAINNAME = "domainname",
Expand Down Expand Up @@ -81,18 +86,18 @@ export enum Locales {
JA_JP = "ja-JP",
}

export enum ComponentSize{
export enum ComponentSize {
SMALL = "small",
MEDIUM = "medium",
LARGE = "large",
}

export enum PreviewType{
export enum PreviewType {
TABLE = "table",
RAW = "raw"
}

export enum CollectionNodeType{
export enum CollectionNodeType {
COLLECTION = "collection",
SCHEMA = "schema"
}
Expand All @@ -102,7 +107,7 @@ export enum EndOfLineChars {
CRLF = '\r\n'
}

export enum Sex{
export enum Sex {
ALL = "all",
MALE = "male",
FEMALE = "female"
Expand Down
3 changes: 3 additions & 0 deletions src/core/formatters/CSharp/CSharp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,9 @@ export const format = (request: FormatRequest): string => {
case ValueType.ONE_BIT:
fieldType = `int${field.emptyRate !== 0 ? "?" : ""}`;
break;
case ValueType.DATE_TIME:
fieldType = `DateTime${field.emptyRate !== 0 ? "?" : ""}`
break;
// Add more cases as necessary
}
csharpCode += ` public ${fieldType} ${field.fieldName} { get; set; }\n`;
Expand Down
13 changes: 13 additions & 0 deletions src/core/formatters/CSharp/CSharpFormatterUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,20 @@ export function formatValueForCSharp(generateResult: GenerateResult, valueType:
return `new List<int> { ${value.join(", ")} }`
case ValueType.STRING_LIST:
return `new List<string> { ${value.map(item => `"${item}"`).join(', ')})} }`
case ValueType.DATE_TIME:
return `DateTime.Parse("${toCSharpDateTimeFormat(value)}")`
default:
return 'null'; // Or some other default case
}
}

export function toCSharpDateTimeFormat(date: Date): string {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的
const day = String(date.getDate()).padStart(2, '0');

const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');

return `${year}-${month}-${day} ${hours}:${minutes}`;
}
42 changes: 36 additions & 6 deletions src/core/formatters/Sql/Sql.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -61,14 +61,16 @@ const addCreateTableColumn = (field: DataField, sqlType: SqlType) => {
fieldType = (sqlType === SqlType.ORACLE || sqlType === SqlType.IBMDB2) ? "CLOB" : "TEXT";
break;
case ValueType.ONE_BIT:
fieldType = "TINYINT(1)";
break;
case ValueType.BOOLEAN:
fieldType = "TINYINT(1)";
break;
case ValueType.BIGINT:
fieldType = "BIGINT";
break;
case ValueType.DATE_TIME: // Add this line
// Define default DATETIME format, then override per SQL type if necessary
fieldType = "DATETIME";
break;
default:
fieldType = "VARCHAR(255)";
break;
Expand All @@ -77,23 +79,29 @@ const addCreateTableColumn = (field: DataField, sqlType: SqlType) => {
// Apply SQL type-specific modifications
switch (sqlType) {
case SqlType.ORACLE:
// Oracle-specific adaptations, e.g., use NUMBER instead of INT
// Oracle-specific adaptations
if (fieldType === "INT") {
fieldType = "NUMBER";
} else if (fieldType === "TINYINT(1)") {
fieldType = "NUMBER(1)";
} else if (fieldType === "DATETIME") { // Add this line
fieldType = "TIMESTAMP"; // Or DATE, depending on your needs
}
break;
case SqlType.POSTGRES:
// Postgres-specific adaptations, e.g., use BOOLEAN instead of TINYINT(1)
// Postgres-specific adaptations
if (fieldType === "TINYINT(1)") {
fieldType = "BOOLEAN";
} else if (fieldType === "DATETIME") { // Add this line
fieldType = "TIMESTAMP"; // Or TIMESTAMP WITHOUT TIME ZONE, depending on your needs
}
break;
case SqlType.SQLITE:
// SQLite uses a more dynamic type system
// SQLite adaptations
if (fieldType === "TINYINT(1)") {
fieldType = "INTEGER";
} else if (fieldType === "DATETIME") { // Add this line
fieldType = "TEXT"; // SQLite uses TEXT for date and time types
}
break;
// Add cases for other SQL types as necessary
Expand All @@ -116,7 +124,29 @@ const formatValueForSQL = (value: any, sqlType: SqlType, valueType: ValueType):
case ValueType.INT_LIST:
return `'${value.join(", ")}'`
case ValueType.STRING_LIST:
return `'${value.map(item => `"${item}"`).join(', ')}'`
return `'${value.map((item: string): string => `"${item}"`).join(', ')}'`
case ValueType.DATE_TIME:
let formattedDate: string;
// Assuming value is a JavaScript Date object for simplicity
const date = (value instanceof Date) ? value : new Date(value);

switch (sqlType) {
case SqlType.ORACLE:
// Oracle format: 'YYYY-MM-DD HH24:MI:SS'
formattedDate = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
break;
case SqlType.POSTGRES:
// PostgreSQL format: 'YYYY-MM-DD HH:MM:SS'
formattedDate = date.toISOString().slice(0, 19).replace('T', ' ');
break;
// Add additional cases for different SQL types as needed
default:
// Default to ISO format 'YYYY-MM-DD HH:MM:SS'
formattedDate = date.toISOString().slice(0, 19).replace('T', ' ');
break;
}

return `'${formattedDate}'`;
default:
return value;
}
Expand Down
3 changes: 3 additions & 0 deletions src/core/formatters/Typescript/Typescript.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,9 @@ export const format = (request: FormatRequest): string => {
case ValueType.STRING_LIST:
fieldType = 'string[]'
break;
case ValueType.DATE_TIME:
fieldType = "Date"
break;
}
output += ` ${field.fieldName}${field.emptyRate !== 0 ? "?" : ""}: ${fieldType};\n`;
});
Expand Down
Loading

0 comments on commit a5045c6

Please sign in to comment.