You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

76 lines
2.4 KiB

export type MultiSelectOption = {
id: string;
value?: string | number;
label?: string;
is_exclusive?: boolean;
};
/**
* Determine if an option is mutually exclusive (مانعةالجمع) with the other
* options of its question.
*
* ⚠️ Single Source of Truth: exclusivity is configured in the live database
* (via the admin dashboard) and delivered by the backend as the
* `is_exclusive` flag on every option. No hardcoded slug/suffix heuristics.
*/
export function isExclusiveOption(option: MultiSelectOption | string): boolean {
if (!option || typeof option !== "object") return false;
return option.is_exclusive === true;
}
/**
* Resolves toggling an option in a multi-select context with automatic mutual exclusion (مانعةالجمع).
*
* Behavior:
* 1. If an exclusive option is selected:
* - All other selected options are automatically cleared (deselected).
* - Only the exclusive option remains selected.
* 2. If an exclusive option is deselected:
* - It is removed, leaving an empty selection.
* 3. If a regular (non-exclusive) option is selected while an exclusive option was active:
* - The exclusive option is automatically cleared (deselected).
* - The new regular option is selected.
* 4. Respects maxSelect limit for regular options.
*/
export function resolveMultiOptionToggle({
currentSelected,
optionId,
options = [],
maxSelect,
}: {
currentSelected: string[];
optionId: string;
options?: MultiSelectOption[];
maxSelect?: number;
}): string[] {
const targetOption = options.find((o) => o.id === optionId) || { id: optionId };
const isExclusive = isExclusiveOption(targetOption);
const isAlreadySelected = currentSelected.includes(optionId);
// Case 1: Toggling an exclusive option
if (isExclusive) {
if (isAlreadySelected) {
return [];
}
return [optionId];
}
// Case 2: Toggling a regular option that is already selected -> remove it
if (isAlreadySelected) {
return currentSelected.filter((id) => id !== optionId);
}
// Case 3: Adding a regular option that was NOT selected:
// First, filter out any exclusive option(s) from current selection
const cleanSelected = currentSelected.filter((id) => {
const opt = options.find((o) => o.id === id) || { id };
return !isExclusiveOption(opt);
});
// Check maxSelect limit
if (maxSelect && cleanSelected.length >= maxSelect) {
return cleanSelected;
}
return [...cleanSelected, optionId];
}