import { getLabel } from "./getLabel"; import { selectEmptyOptions } from "../config/constants"; import type { TOptionType, TSelectValue, TSelectUserValue } from "../config/types"; type TGetInitialValueParams = { value?: TSelectUserValue; isMulti?: boolean; options?: TOptionType[]; }; /** * Computes the initial value for the select component. * Converts raw value(s) into the shape expected by `react‑select`. * @returns {TSelectUserValue} */ export const getInitialValue = ({ value, isMulti = false, options = selectEmptyOptions, }: TGetInitialValueParams): TSelectValue => { // value isn't provided if (!value) { return null; } if (isMulti) { // [ "str", "str" ] if (Array.isArray(value) && value.every((item) => typeof item === "string")) { return value.map((text) => ({ label: getLabel(options, text), value: text, })); } // "str" if (typeof value === "string") { return [ { label: getLabel(options, value), value, }, ]; } // valid array if (Array.isArray(value) && value.every((item) => typeof item === "object" && "label" in item && "value" in item && typeof item.label === "string" && typeof item.value === "string")) { return value as TSelectValue; } // Invalid value return null; } // Single string value if (typeof value === "string" && value.length) { return { label: getLabel(options, value), value }; } // Single IOptionType object (already in correct format) if (typeof value === "object" && value !== null && !Array.isArray(value) && "value" in value) { return value as TOptionType; } // Invalid value for single select console.debug(`[Select] Value has incorrect format and become "null"`); return null; };