|
| 1 | +import React, { useEffect, useState, useCallback } from 'react'; |
| 2 | +import { IPublicModelPluginContext, IPublicEnumPluginRegisterLevel, IPublicModelWindow, IPublicModelEditorView } from '@alilc/lowcode-types'; |
| 3 | + |
| 4 | +/** |
| 5 | + * 高阶组件(HOC):为组件提供 view 插件上下文。 |
| 6 | + * |
| 7 | + * @param {React.ComponentType} Component - 需要被封装的组件。 |
| 8 | + * @param {string|string[]} viewName - 视图名称或视图名称数组,用于过滤特定的视图插件上下文。 |
| 9 | + * @returns {React.ComponentType} 返回封装后的组件。 |
| 10 | + * |
| 11 | + * @example |
| 12 | + * // 用法示例(函数组件): |
| 13 | + * const EnhancedComponent = ProvideViewPluginContext(MyComponent, "viewName"); |
| 14 | + */ |
| 15 | +export const ProvideViewPluginContext = (Component: any, viewName?: string | string[]) => { |
| 16 | + // 创建一个新的函数组件,以便在其中使用 Hooks |
| 17 | + return function WithPluginContext(props: { |
| 18 | + [key: string]: any; |
| 19 | + |
| 20 | + pluginContext?: IPublicModelPluginContext; |
| 21 | + }) { |
| 22 | + const getPluginContextFun = useCallback((editorWindow?: IPublicModelWindow | null) => { |
| 23 | + if (!editorWindow?.currentEditorView) { |
| 24 | + return null; |
| 25 | + } |
| 26 | + if (viewName) { |
| 27 | + const items = editorWindow?.editorViews.filter(d => (d as any).viewName === viewName || (Array.isArray(viewName) && viewName.includes((d as any).viewName))); |
| 28 | + return items[0]; |
| 29 | + } else { |
| 30 | + return editorWindow.currentEditorView; |
| 31 | + } |
| 32 | + }, []); |
| 33 | + |
| 34 | + const { workspace } = props.pluginContext || {}; |
| 35 | + const [pluginContext, setPluginContext] = useState<IPublicModelEditorView | null>(getPluginContextFun(workspace?.window)); |
| 36 | + |
| 37 | + useEffect(() => { |
| 38 | + if (workspace?.window) { |
| 39 | + const ctx = getPluginContextFun(workspace.window); |
| 40 | + ctx && setPluginContext(ctx); |
| 41 | + } |
| 42 | + return workspace?.onChangeActiveEditorView(() => { |
| 43 | + const ctx = getPluginContextFun(workspace.window); |
| 44 | + ctx && setPluginContext(ctx); |
| 45 | + }); |
| 46 | + }, [workspace, getPluginContextFun]); |
| 47 | + |
| 48 | + if (props.pluginContext?.registerLevel !== IPublicEnumPluginRegisterLevel.Workspace || !props.pluginContext) { |
| 49 | + return <Component {...props} />; |
| 50 | + } |
| 51 | + |
| 52 | + return <Component {...props} pluginContext={pluginContext} />; |
| 53 | + }; |
| 54 | +}; |
0 commit comments