import { Action, ModuleWithPermissions } from "../permissions"; import { cloneElement, createElement, Fragment, ReactElement } from "react"; export class TableOptions { private _components: ReactElement[]; private _hasPermissionToModule: (params: { module: M; action: Action; data?: any; }) => boolean; constructor( hasPermissionToModule: (params: { module: M; action: Action; data?: any; }) => boolean, ) { this._hasPermissionToModule = hasPermissionToModule; this._components = []; } addOption(component: ReactElement | null, module?: M, action?: Action): void { if (!component || (module && action && !this._hasPermissionToModule({ module, action }))) return; this._components.push(component); } getComponents(): ReactElement[] { return this._components; } getOptions(): ReactElement | null { if (this._components.length === 0) return null; const response: ReactElement[] = this._components.map((option, index) => cloneElement(option, { key: option.key ?? index }), ); return createElement(Fragment, {}, response); } } export function getTableOptions(params: { hasPermissionToModule: (params: { module: M; action: Action; data?: any; }) => boolean; options: { component: ReactElement | null; module?: ModuleWithPermissions; action?: Action }[]; }): ReactElement | null { const tableOptions = new TableOptions(params.hasPermissionToModule); params.options.forEach((option) => tableOptions.addOption(option.component, option.module, option.action)); return tableOptions.getOptions(); } export function getTableComponents(params: { hasPermissionToModule: (params: { module: M; action: Action; data?: any; }) => boolean; options: { component: ReactElement | null; module?: ModuleWithPermissions; action?: Action }[]; }): ReactElement[] { const tableOptions = new TableOptions(params.hasPermissionToModule); params.options.forEach((option) => tableOptions.addOption(option.component, option.module, option.action)); return tableOptions.getComponents(); }