Use HOC for reader context usage

This commit is contained in:
schroda
2024-12-21 03:46:55 +01:00
parent 34f484a946
commit f5642af219
27 changed files with 997 additions and 459 deletions

View 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} />;
});