fix(striker-ui): make buildMapToMessageSetter() handle array ids

main
Tsu-ba-me 2 years ago
parent 5538f9bdae
commit 3b9e3c6af0
  1. 54
      striker-ui/lib/buildMapToMessageSetter.ts
  2. 16
      striker-ui/types/MapToMessageSetter.d.ts

@ -2,25 +2,49 @@ import { MutableRefObject } from 'react';
import { MessageGroupForwardedRefContent } from '../components/MessageGroup'; import { MessageGroupForwardedRefContent } from '../components/MessageGroup';
type BuildMapToMessageSetterReturnType<T extends MapToInputTestID> = { const buildMessageSetter = <T extends MapToInputTestID>(
[MessageSetterID in keyof T]: MessageSetterFunction; id: string,
messageGroupRef: MutableRefObject<MessageGroupForwardedRefContent>,
container?: MapToMessageSetter<T>,
key: string = id,
): MessageSetterFunction => {
const setter: MessageSetterFunction = (message?) => {
messageGroupRef.current.setMessage?.call(null, id, message);
};
if (container) {
container[key as keyof T] = setter;
}
return setter;
}; };
const buildMapToMessageSetter = <T extends MapToInputTestID>( const buildMapToMessageSetter = <
mapToID: T, U extends string,
I extends InputIds<U>,
M extends MapToInputId<U, I>,
>(
ids: I,
messageGroupRef: MutableRefObject<MessageGroupForwardedRefContent>, messageGroupRef: MutableRefObject<MessageGroupForwardedRefContent>,
): BuildMapToMessageSetterReturnType<T> => ): MapToMessageSetter<M> => {
Object.entries(mapToID).reduce<BuildMapToMessageSetterReturnType<T>>( let result: MapToMessageSetter<M> = {} as MapToMessageSetter<M>;
(previous, [key, id]) => {
const setter: MessageSetterFunction = (message?) => {
messageGroupRef.current.setMessage?.call(null, id, message);
};
previous[key as keyof T] = setter;
if (ids instanceof Array) {
result = ids.reduce<MapToMessageSetter<M>>((previous, id) => {
buildMessageSetter(id, messageGroupRef, previous);
return previous; return previous;
}, }, result);
{} as BuildMapToMessageSetterReturnType<T>, } else {
); result = Object.entries(ids).reduce<MapToMessageSetter<M>>(
(previous, [key, id]) => {
buildMessageSetter(id, messageGroupRef, previous, key);
return previous;
},
result,
);
}
return result;
};
export default buildMapToMessageSetter; export default buildMapToMessageSetter;

@ -0,0 +1,16 @@
type MapToMessageSetter<T extends MapToInputTestID> = {
[MessageSetterID in keyof T]: MessageSetterFunction;
};
type InputIds<T> = ReadonlyArray<T> | MapToInputTestID;
/**
* Given either:
* 1. an array of input identifiers, or
* 2. a key-value object of input indentifiers,
* transform it into a key-value object of identifiers.
*/
type MapToInputId<
U extends string,
I extends InputIds<U>,
> = I extends ReadonlyArray<U> ? { [K in I[number]]: K } : I;
Loading…
Cancel
Save