import { nothing } from 'lit-html';
type ChooseValue = T extends undefined ? never : T;
type ChooseChild = [
condition: (value: ChooseValue) => boolean,
output: (value: ChooseValue) => LitJSX.Child,
];
/**
* Conditionally renders content based on evaluating multiple condition-output pairs against a value.
* Similar to lit-html's choose directive, evaluates each condition in order and renders the first match.
*
* @template T - The type of the value to evaluate against (defaults to undefined for no value)
* @param props.value - The value to pass to each condition and output function
* @param props.children - Single [condition, output] tuple or multiple tuple children to evaluate
* @returns The rendered JSX element from the first matching condition, or nothing if no match
*
* @example
* ```tsx
* // Multiple condition-output tuples as separate children
*
* {[
* (status) => status === 'loading',
* () => Loading...
* ]}
* {[
* (status) => status === 'error',
* (status) => Error: {status}
* ]}
* {[
* () => true, // default case
* (status) => Status: {status}
* ]}
*
* ```
*/
export function Choose(props: {
value?: T;
children: ChooseChild | ChooseChild[];
}): LitJSX.Child {
const children = Array.isArray(props.children.at(-1))
? props.children as ChooseChild[]
: [ props.children as ChooseChild ];
for (const [ condition, output ] of children) {
if (condition(props.value as ChooseValue))
return output(props.value as ChooseValue);
}
return nothing;
}