Files
medusa-store/packages/admin-next/dashboard/src/lib/form-helpers.ts
Kasper Fabricius Kristensen b8572165cb feat(dashboard): DataGrid improvements [4/4] (#8798)
**What**
- Changes cell state strategy from tracking from lazy to eager. This has required some changes to the API of the DataGrid component, and createDataGridColumnHelper function.
- Displays error messages in both affected cells and their rows. The row indicator also provides an option to quickly jump to an error.
- Allows the user to hide all rows and columns that don't have errors, to help quickly get an overview of the errors in a large grid.
- The first column of a DataGrid is now pinned, making it easier for a user to tell which entity they are editing.
- Fixes and improvements to column visibility menu.
- Adds a shortcuts modal that explains the different available keyboard commands.
- Updates `@tanstack/react-table` to the latest version.

Resolves CC-269
2024-08-28 19:06:38 +00:00

70 lines
1.9 KiB
TypeScript

import { castNumber } from "./cast-number"
export function transformNullableFormValue<T>(
value: T,
nullify = true
): T | undefined | null {
if (typeof value === "string" && value.trim() === "") {
return nullify ? null : undefined
}
if (Array.isArray(value) && value.length === 0) {
return nullify ? null : undefined
}
return value
}
type Nullable<T> = { [K in keyof T]: T[K] | null }
type Optional<T> = { [K in keyof T]: T[K] | undefined }
export function transformNullableFormData<
T extends Record<string, unknown>,
K extends boolean = true
>(data: T, nullify: K = true as K): K extends true ? Nullable<T> : Optional<T> {
return Object.entries(data).reduce((acc, [key, value]) => {
return {
...acc,
[key]: transformNullableFormValue(value, nullify),
}
}, {} as K extends true ? Nullable<T> : Optional<T>)
}
export function transformNullableFormNumber<K extends boolean = true>(
value?: string | number,
nullify: K = true as K
): K extends true ? number | null : number | undefined {
if (
typeof value === "undefined" ||
(typeof value === "string" && value.trim() === "")
) {
return (nullify ? null : undefined) as K extends true
? number | null
: number | undefined
}
if (typeof value === "string") {
return castNumber(value)
}
return value
}
type NullableNumbers = Record<string, number | null>
type OptionalNumbers = Record<string, number | undefined>
export function transformNullableFormNumbers<
T extends Record<string, string | number | undefined>,
K extends boolean = true
>(
data: T,
nullify: K = true as K
): K extends true ? NullableNumbers : OptionalNumbers {
return Object.entries(data).reduce((acc, [key, value]) => {
return {
...acc,
[key]: transformNullableFormNumber(value, nullify),
}
}, {} as K extends true ? NullableNumbers : OptionalNumbers)
}