warn if a value in select no longer exists

This commit is contained in:
Kendall Garner 2025-05-18 10:59:45 -07:00
parent f068d6e4b8
commit cf74625bfc
No known key found for this signature in database
GPG key ID: 9355F387FE765C94
6 changed files with 93 additions and 11 deletions

View file

@ -0,0 +1,78 @@
import { MultiSelect, MultiSelectProps, Select, SelectProps } from '/@/renderer/components/select';
import { useTranslation } from 'react-i18next';
import { useMemo } from 'react';
export const SelectWithInvalidData = ({ data, defaultValue, ...props }: SelectProps) => {
const { t } = useTranslation();
const [fullData, hasError] = useMemo(() => {
if (typeof defaultValue === 'string') {
const missingField =
data.find((item) =>
typeof item === 'string' ? item === defaultValue : item.value === defaultValue,
) === undefined;
if (missingField) {
return [data.concat(defaultValue), true];
}
}
return [data, false];
}, [data, defaultValue]);
return (
<Select
data={fullData}
defaultValue={defaultValue}
error={
hasError
? t('error.badValue', { postProcess: 'sentenceCase', value: defaultValue })
: undefined
}
{...props}
/>
);
};
export const MultiSelectWithInvalidData = ({ data, defaultValue, ...props }: MultiSelectProps) => {
const { t } = useTranslation();
const [fullData, missing] = useMemo(() => {
if (defaultValue?.length) {
const validValues = new Set<string>();
for (const item of data) {
if (typeof item === 'string') {
validValues.add(item);
} else {
validValues.add(item.value);
}
}
const missingFields: string[] = [];
for (const value of defaultValue) {
if (!validValues.has(value)) {
missingFields.push(value);
}
}
if (missingFields.length > 0) {
return [data.concat(missingFields), missingFields];
}
}
return [data, []];
}, [data, defaultValue]);
return (
<MultiSelect
data={fullData}
defaultValue={defaultValue}
error={
missing.length
? t('error.badValue', { postProcess: 'sentenceCase', value: missing })
: undefined
}
{...props}
/>
);
};

View file

@ -5,7 +5,7 @@ import type {
import { Select as MantineSelect, MultiSelect as MantineMultiSelect } from '@mantine/core';
import styled from 'styled-components';
interface SelectProps extends MantineSelectProps {
export interface SelectProps extends MantineSelectProps {
maxWidth?: number | string;
width?: number | string;
}