tachybase_todo/packages/client/src/schema-initializer/SchemaInitializerProvider.tsx

56 lines
1.6 KiB
TypeScript
Raw Normal View History

2022-02-22 11:17:24 +08:00
import { isPlainObj } from '@formily/shared';
import React, { createContext, useContext } from 'react';
2022-02-17 23:56:39 +08:00
import { SchemaComponentOptions } from '../schema-component';
2022-02-22 11:17:24 +08:00
import { initializes as globals, items } from './Initializers';
import { SchemaInitializer } from './SchemaInitializer';
2022-02-17 23:56:39 +08:00
2022-02-22 11:17:24 +08:00
const SchemaInitializerContext = createContext(null);
export interface SchemaInitializerProviderProps {
2022-02-22 23:40:08 +08:00
components?: any;
2022-02-22 11:17:24 +08:00
initializers?: Record<string, any>;
}
export const useSchemaInitializer = (name: string) => {
const initializers = useContext(SchemaInitializerContext);
const render = (component?: any, props?: any) => {
return component && React.createElement(component, props);
};
if (!name) {
return { exists: false, render };
}
const initializer = initializers?.[name];
if (!initializer) {
return { exists: false, render };
}
if (isPlainObj(initializer)) {
return {
exists: true,
render: (props?: any) => {
const component = (initializer as any).component || SchemaInitializer.Button;
return render(component, { ...initializer, ...props });
},
};
}
return {
exists: true,
render: (props?: any) => render(initializer, props),
};
};
export const SchemaInitializerProvider: React.FC<SchemaInitializerProviderProps> = (props) => {
2022-02-22 23:40:08 +08:00
const { initializers, components, children } = props;
2022-02-22 11:17:24 +08:00
return (
<SchemaInitializerContext.Provider value={{ ...globals, ...initializers }}>
2022-02-22 23:40:08 +08:00
<SchemaComponentOptions components={{ ...items, ...components }}>{children}</SchemaComponentOptions>
2022-02-22 11:17:24 +08:00
</SchemaInitializerContext.Provider>
);
2022-02-17 23:56:39 +08:00
};