Use HOC for reader context usage
This commit is contained in:
32
src/modules/core/hoc/withPropsFrom.tsx
Normal file
32
src/modules/core/hoc/withPropsFrom.tsx
Normal file
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* Copyright (C) Contributors to the Suwayomi project
|
||||
*
|
||||
* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
import { ComponentType, forwardRef } from 'react';
|
||||
|
||||
type PropsSourceCreator<T> = () => T;
|
||||
|
||||
export const withPropsFrom = <
|
||||
ComponentProps extends Record<string, any>,
|
||||
SourceProps extends Record<string, any>[],
|
||||
SourcePropKeys extends keyof (ComponentProps | MergeObjectsArray<SourceProps>),
|
||||
>(
|
||||
Component: ComponentType<ComponentProps>,
|
||||
propsSources: { [K in keyof SourceProps]: PropsSourceCreator<SourceProps[K]> },
|
||||
sourcePropKeys: SourcePropKeys[],
|
||||
) =>
|
||||
forwardRef<HTMLElement, Omit<ComponentProps, SourcePropKeys>>((props, ref) => {
|
||||
const sourceProps = propsSources.reduce((acc, propsSource) => ({ ...acc, ...propsSource() }), {});
|
||||
|
||||
const selectedProps = Object.fromEntries(
|
||||
Object.entries(sourceProps).filter(([key]) => sourcePropKeys.includes(key as SourcePropKeys)),
|
||||
) as Pick<MergeObjectsArray<SourceProps>, SourcePropKeys>;
|
||||
|
||||
const combinedProps = { ...props, ...selectedProps } as unknown as ComponentProps;
|
||||
|
||||
return <Component {...combinedProps} ref={ref} />;
|
||||
});
|
||||
Reference in New Issue
Block a user