import { ISchema, observer } from '@formily/react';
import { Button, Dropdown, Menu } from 'antd';
import React, { createContext, useContext, useState } from 'react';
import { useCompile, useDesignable } from '../schema-component/hooks';
import { initializes, items } from './Initializers';
import {
SchemaInitializerButtonProps,
SchemaInitializerItemComponent,
SchemaInitializerItemOptions,
SchemaInitializerItemProps,
} from './types';
const defaultWrap = (s: ISchema) => s;
export const SchemaInitializerItemContext = createContext(null);
export const SchemaInitializer = () => null;
SchemaInitializer.items = items;
SchemaInitializer.initializes = initializes;
SchemaInitializer.Button = observer((props: SchemaInitializerButtonProps) => {
const {
title,
insert,
wrap = defaultWrap,
items = [],
insertPosition = 'beforeEnd',
dropdown,
component,
style,
...others
} = props;
const compile = useCompile();
let { insertAdjacent, findComponent, designable } = useDesignable();
const [visible, setVisible] = useState(false);
const insertSchema = (schema) => {
if (props.insert) {
props.insert(wrap(schema));
} else {
insertAdjacent(insertPosition, wrap(schema));
}
};
const renderItems = (items: any) => {
return items?.map((item, indexA) => {
if (item.type === 'divider') {
return
;
}
if (item.type === 'item' && item.component) {
const Component = findComponent(item.component);
return (
Component && (
)
);
}
if (item.type === 'itemGroup') {
return (
{renderItems(item.children)}
);
}
if (item.type === 'subMenu') {
return (
{renderItems(item.children)}
);
}
});
};
const menu = ;
if (!designable && props.designable !== true) {
return null;
}
return (
{
setVisible(visible);
}}
{...dropdown}
overlay={menu}
>
{component ? (
component
) : (
)}
);
});
SchemaInitializer.Item = (props: SchemaInitializerItemProps) => {
const { index, info } = useContext(SchemaInitializerItemContext);
const compile = useCompile();
const { items = [], children = info?.title, icon, onClick, ...others } = props;
if (items?.length > 0) {
const renderMenuItem = (items: SchemaInitializerItemOptions[]) => {
if (!items?.length) {
return null;
}
return items.map((item, indexA) => {
if (item.type === 'divider') {
return ;
}
if (item.type === 'itemGroup') {
return (
{renderMenuItem(item.children)}
);
}
if (item.type === 'subMenu') {
return (
{renderMenuItem(item.children)}
);
}
return (
{
onClick({ ...info, item });
}}
>
{compile(item.title)}
);
});
};
return (
// @ts-ignore
{renderMenuItem(items)}
);
}
return (
{
onClick({ ...opts, item: info });
}}
{...others}
>
{compile(children)}
);
};
SchemaInitializer.itemWrap = (component?: SchemaInitializerItemComponent) => {
return component;
};