Skip to content

Commit

Permalink
Merge pull request #1604 from merico-dev/panel-addon
Browse files Browse the repository at this point in the history
feat: add panelAddon plugin
  • Loading branch information
GerilLeto authored Jan 16, 2025
2 parents 4271700 + e14de1e commit 2e1ec8f
Show file tree
Hide file tree
Showing 14 changed files with 178 additions and 23 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { EmotionSx } from '@mantine/emotion';
import { observer } from 'mobx-react-lite';
import { ReactNode } from 'react';
import { PanelContextProvider } from '~/contexts/panel-context';
import { PanelAddonProvider } from '~/components/plugins/panel-addon';
import { PanelRenderModelInstance } from '~/model';
import { DescriptionPopover } from './description-popover';
import './panel-render-base.css';
Expand All @@ -20,7 +21,6 @@ const baseStyle: EmotionSx = { border: '1px solid #e9ecef' };

export const PanelRenderBase = observer(({ panel, panelStyle, dropdownContent }: IPanelBase) => {
const { ref, downloadPanelScreenshot } = useDownloadPanelScreenshot(panel);
const titleHeight = panel.title.show ? '60px' : '28px';
return (
<PanelContextProvider
value={{
Expand All @@ -40,12 +40,14 @@ export const PanelRenderBase = observer(({ panel, panelStyle, dropdownContent }:
...panelStyle,
}}
>
<Box className="panel-description-popover-wrapper">
<DescriptionPopover />
</Box>
{dropdownContent}
<PanelTitleBar />
<PanelVizSection panel={panel} />
<PanelAddonProvider>
<Box className="panel-description-popover-wrapper">
<DescriptionPopover />
</Box>
{dropdownContent}
<PanelTitleBar />
<PanelVizSection panel={panel} />
</PanelAddonProvider>
</Box>
</PanelContextProvider>
);
Expand Down
33 changes: 30 additions & 3 deletions dashboard/src/components/panel/panel-render/viz/viz.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
import { useElementSize } from '@mantine/hooks';
import { get } from 'lodash';
import { createPortal } from 'react-dom';

import { Box } from '@mantine/core';
import { observer } from 'mobx-react-lite';
import { ReactNode, useContext } from 'react';
import { useConfigVizInstanceService } from '~/components/panel/use-config-viz-instance-service';
import { ServiceLocatorProvider } from '~/components/plugins/service/service-locator/use-service-locator';
import {
ServiceLocatorProvider,
useServiceLocator,
} from '~/components/plugins/service/service-locator/use-service-locator';
import { WidthAndHeight } from '~/components/plugins/viz-manager/components';
import { ErrorBoundary } from '~/utils';
import { useRenderPanelContext } from '../../../../contexts';
import { IViewPanelInfo, PluginContext } from '../../../plugins';
import { usePanelAddonSlot } from '~/components/plugins/panel-addon';
import { LayoutStateContext, useRenderPanelContext } from '../../../../contexts';
import { IViewPanelInfo, PluginContext, tokens } from '../../../plugins';
import { PluginVizViewComponent } from '../../plugin-adaptor';
import './viz.css';

Expand Down Expand Up @@ -40,6 +45,7 @@ function usePluginViz(data: TPanelData, measure: WidthAndHeight): ReactNode | nu
variables={variables}
vizManager={vizManager}
/>
<PanelVizAddons />
</ServiceLocatorProvider>
);
} catch (e) {
Expand All @@ -64,3 +70,24 @@ export const Viz = observer(function _Viz({ data }: IViz) {
</div>
);
});

export const PanelVizAddons = () => {
const sl = useServiceLocator();
const instance = sl.getRequired(tokens.instanceScope.vizInstance);
const { inEditMode } = useContext(LayoutStateContext);
const addonManager = sl.getRequired(tokens.panelAddonManager);
const panelRoot = usePanelAddonSlot();
if (!panelRoot) {
return null;
}
return createPortal(
<>
{addonManager.createPanelAddonNode({
viz: instance,
isInEditMode: inEditMode,
})}
</>,
panelRoot,
'addon',
);
};
2 changes: 2 additions & 0 deletions dashboard/src/components/plugins/panel-addon/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './panel-addon-manager';
export * from './panel-addon-context';
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import React, { useId } from 'react';

const PanelAddonContext = React.createContext<{ addonSlotId: string | null }>({ addonSlotId: null });

export function PanelAddonProvider({ children }: { children: React.ReactNode }) {
const id = `panel-addon-slot-${useId()}`;
return (
<PanelAddonContext.Provider value={{ addonSlotId: id }}>
<div style={{ position: 'static', top: 0, left: 0 }} id={id}></div>
{children}
</PanelAddonContext.Provider>
);
}

export function usePanelAddonSlot() {
const { addonSlotId } = React.useContext(PanelAddonContext);
if (!addonSlotId) {
return null;
}
return document.getElementById(addonSlotId);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { IPanelAddon, IPanelAddonRenderProps, IPluginManager } from '~/types/plugin';
import React from 'react';

export class PanelAddonManager {
constructor(private pluginManager: IPluginManager) {}

createPanelAddonNode(props: IPanelAddonRenderProps) {
const addons = this.pluginManager.installedPlugins
.flatMap((it) => it.manifest.panelAddon)
.filter((it) => !!it) as IPanelAddon[];
const nodes = addons.map((addon) => {
return React.createElement(addon.addonRender, { ...props, key: addon.name });
});
return <>{nodes}</>;
}
}
7 changes: 5 additions & 2 deletions dashboard/src/components/plugins/plugin-context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { createContext } from 'react';
import { Blue, Green, Orange, Red, RedGreen, YellowBlue } from '~/components/plugins/colors';
import { InstanceMigrator } from '~/components/plugins/instance-migrator';
import { token } from '~/components/plugins/service/service-locator';
import { PanelAddonManager } from '~/components/plugins/panel-addon';

import { PanelModelInstance } from '~/dashboard-editor/model/panels';
import {
Expand Down Expand Up @@ -39,12 +40,12 @@ import { HorizontalBarChartVizComponent } from './viz-components/horizontal-bar-
import { MericoEstimationChartVizComponent } from './viz-components/merico-estimation-chart';
import { MericoStatsVizComponent } from './viz-components/merico-stats';
import { MericoHeatmapVizComponent } from './viz-components/merico-heatmap';
import _ from 'lodash';

export interface IPluginContextProps {
pluginManager: IPluginManager;
vizManager: VizManager;
colorManager: IColorManager;
panelAddonManager: PanelAddonManager;
}

const basicColors = [
Expand Down Expand Up @@ -170,6 +171,7 @@ export const tokens = {
pluginManager: token<IPluginManager>('pluginManager'),
vizManager: token<VizManager>('vizManager'),
colorManager: token<IColorManager>('colorManager'),
panelAddonManager: token<PanelAddonManager>('panelAddonManager'),
instanceScope: {
panelModel: token<PanelModelInstance>('panelModel'),
vizInstance: token<VizInstance>('vizInstance'),
Expand All @@ -189,7 +191,8 @@ export const createPluginContext = (): IPluginContextProps => {
}
const vizManager = new VizManager(pluginManager);
const colorManager = new ColorManager(pluginManager);
return { pluginManager, vizManager, colorManager };
const panelAddonManager = new PanelAddonManager(pluginManager);
return { pluginManager, vizManager, colorManager, panelAddonManager };
};

export const PluginContext = createContext<IPluginContextProps>(createPluginContext());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export function useTopLevelServices(pluginContext: IPluginContextProps) {
return services
.provideValue(tokens.pluginManager, pluginContext.pluginManager)
.provideValue(tokens.vizManager, pluginContext.vizManager)
.provideValue(tokens.panelAddonManager, pluginContext.panelAddonManager)
.provideValue(tokens.colorManager, pluginContext.colorManager);
}, []);
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { EChartsInstance } from 'echarts-for-react';
import ReactEChartsCore from 'echarts-for-react/lib/core';
import * as echarts from 'echarts/core';
import _, { defaults } from 'lodash';
import { useLatest } from 'ahooks';
import { observer } from 'mobx-react-lite';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { useStorageData } from '~/components/plugins/hooks';
Expand Down Expand Up @@ -33,13 +34,15 @@ function Chart({
height,
interactionManager,
variables,
onChartRenderFinished,
}: {
conf: ICartesianChartConf;
data: TPanelData;
width: number;
height: number;
interactionManager: IVizInteractionManager;
variables: ITemplateVariable[];
onChartRenderFinished: (chartOptions: unknown) => void;
}) {
const rowDataMap = useRowDataMap(data, conf.x_axis_data_key);

Expand All @@ -60,13 +63,18 @@ function Chart({
}, [conf, data]);

const echartsRef = React.useRef<EChartsInstance>();
const onRenderFinishedRef = useLatest(onChartRenderFinished);
const handleEChartsFinished = useCallback(() => {
onRenderFinishedRef.current(echartsRef.current?.getOption());
}, []);
const onEvents = useMemo(() => {
return {
click: handleSeriesClick,
finished: handleEChartsFinished,
};
}, [handleSeriesClick]);

const onChartReady = (echartsInstance: EChartsInstance) => {
const handleChartReady = (echartsInstance: EChartsInstance) => {
echartsRef.current = echartsInstance;
updateRegressionLinesColor(echartsInstance);
};
Expand All @@ -85,7 +93,7 @@ function Chart({
option={option}
style={{ width, height }}
onEvents={onEvents}
onChartReady={onChartReady}
onChartReady={handleChartReady}
notMerge
theme="merico-light"
/>
Expand All @@ -109,11 +117,16 @@ export const VizCartesianChart = observer(({ context, instance }: VizViewProps)
const finalHeight = Math.max(0, getBoxContentHeight(height) - topStatsHeight - bottomStatsHeight);
const finalWidth = getBoxContentWidth(width);

function handleChartRenderFinished(chartOptions: unknown) {
instance.messageChannels.getChannel('viz').emit('rendered', chartOptions);
}

return (
<DefaultVizBox width={width} height={height}>
<StatsAroundViz onHeightChange={setTopStatsHeight} value={conf.stats.top} context={context} />

<Chart
onChartRenderFinished={handleChartRenderFinished}
variables={variables}
width={finalWidth}
height={finalHeight}
Expand Down
1 change: 0 additions & 1 deletion dashboard/src/contexts/layout-state-context.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import _ from 'lodash';
import React from 'react';

export interface ILayoutStateContext {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import '~/components/panel/panel-render/panel-render-base.css';
import { PanelVizSection } from '~/components/panel/panel-render/viz/panel-viz-section';
import { useRenderPanelContext } from '~/contexts';
import { ErrorBoundary } from '~/utils';
import { PanelAddonProvider } from '~/components/plugins/panel-addon';

const PreviewTitleBar = observer(() => {
const { panel } = useRenderPanelContext();
Expand Down Expand Up @@ -38,11 +39,13 @@ export const PreviewPanel = observer(() => {
height: '450px !important',
}}
>
<Box className="panel-description-popover-wrapper">
<DescriptionPopover />
</Box>
<PreviewTitleBar />
<PanelVizSection panel={panel} />
<PanelAddonProvider>
<Box className="panel-description-popover-wrapper">
<DescriptionPopover />
</Box>
<PreviewTitleBar />
<PanelVizSection panel={panel} />
</PanelAddonProvider>
</Box>
</ErrorBoundary>
);
Expand Down
8 changes: 5 additions & 3 deletions dashboard/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { ButtonProps } from '@mantine/core';
import './init-dayjs';
import './i18n';

export const getVersion = () =>
import('../package.json').then(({ version }) => {
Expand All @@ -16,9 +18,6 @@ export * from './model';
export * from './api-caller/request';
export type { AnyObject } from './types/utils';

import './init-dayjs';
import './i18n';

// NOTE: keep it align with global.d.ts
export interface IDashboardConfig {
basename: string;
Expand All @@ -29,3 +28,6 @@ export interface IDashboardConfig {
monacoPath: string;
searchButtonProps: ButtonProps;
}

export { pluginManager } from './components/plugins';
export { type IPanelAddon, type IPanelAddonRenderProps } from './types/plugin';
15 changes: 15 additions & 0 deletions dashboard/src/types/plugin/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ export type TranslationPatch = {
lang: 'en' | 'zh';
resources: Record<string, any>;
}[];

export interface VizComponent {
name: string;
displayName?: string;
Expand All @@ -130,9 +131,20 @@ export interface IConfigMigrator extends IPanelScopeConfigMigrator {
migrate(ctx: IConfigMigrationContext): Promise<void>;
}

export interface IPanelAddonRenderProps {
viz: VizInstance;
isInEditMode: boolean;
}

export interface IPanelAddon {
name: string;
addonRender: React.ComponentType<IPanelAddonRenderProps>;
}

export interface IPluginManifest {
viz: VizComponent[];
color: IColorPaletteItem[];
panelAddon?: IPanelAddon[];
}

export interface IDashboardPlugin {
Expand Down Expand Up @@ -208,7 +220,9 @@ export interface IVizTriggerManager {
retrieveTrigger(id: string): Promise<ITrigger | undefined>;

watchTriggerSnapshotList(callback: (triggerList: ITriggerSnapshot<AnyObject>[]) => void): () => void;

needMigration(): Promise<boolean>;

runMigration(): Promise<void>;
}

Expand Down Expand Up @@ -242,6 +256,7 @@ export interface IVizOperationManager {
retrieveTrigger(operationId: string): Promise<IDashboardOperation | undefined>;

runMigration(): Promise<void>;

needMigration(): Promise<boolean>;
}

Expand Down
1 change: 1 addition & 0 deletions website/src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { SQLSnippetPage } from './pages/sql-snippet-page';
import { StatusPage } from './pages/status-page';
import { MantineProviders } from './utils/mantine-providers';
import('./utils/configure-monaco-editor');
import './utils/install-dashboard-website-plugin';

// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
ReactDOM.createRoot(document.getElementById('root')!).render(
Expand Down
Loading

0 comments on commit 2e1ec8f

Please sign in to comment.