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';
type BuildMapToMessageSetterReturnType<T extends MapToInputTestID> = {
[MessageSetterID in keyof T]: MessageSetterFunction;
const buildMessageSetter = <T extends MapToInputTestID>(
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>(
mapToID: T,
const buildMapToMessageSetter = <
U extends string,
I extends InputIds<U>,
M extends MapToInputId<U, I>,
>(
ids: I,
messageGroupRef: MutableRefObject<MessageGroupForwardedRefContent>,
): BuildMapToMessageSetterReturnType<T> =>
Object.entries(mapToID).reduce<BuildMapToMessageSetterReturnType<T>>(
(previous, [key, id]) => {
const setter: MessageSetterFunction = (message?) => {
messageGroupRef.current.setMessage?.call(null, id, message);
};
previous[key as keyof T] = setter;
): MapToMessageSetter<M> => {
let result: MapToMessageSetter<M> = {} as MapToMessageSetter<M>;
if (ids instanceof Array) {
result = ids.reduce<MapToMessageSetter<M>>((previous, id) => {
buildMessageSetter(id, messageGroupRef, previous);
return previous;
},
{} as BuildMapToMessageSetterReturnType<T>,
);
}, result);
} else {
result = Object.entries(ids).reduce<MapToMessageSetter<M>>(
(previous, [key, id]) => {
buildMessageSetter(id, messageGroupRef, previous, key);
return previous;
},
result,
);
}
return result;
};
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