import { useState } from 'react'; import { SourceState } from '@wix/bex-core'; import type { CollectionOptimisticActionsBaseParams, FiltersMap, OptionalFiltersMap, SchemaSource, } from '@wix/bex-core'; import { useWixPatternsContainer } from '@wix/bex-core/react'; import type { EditableTableState, EditableTablePermissions, EditableTableMutationHandlers, } from '../state/EditableTable'; import type { CellType } from '../state/EditableTable/types'; import type { FieldsSourceProvider } from '../components/fieldsSourceProvider'; import { useEditableTableCollection as useOpenEditableTableCollection, type EditableTableCollectionConfig, } from '../hooks/useEditableTableCollection'; import { SchemaState } from '../components/SchemaSource/SchemaState'; import { schemaCollectionConfig, type SchemaCollectionOptions, } from './schemaCollectionOptions'; import { sourceMutations } from './sourceMutations'; import { attachesItself } from './usePlatformizedSource'; export type SchemaEditableTableCollectionOptions< T, F extends FiltersMap = OptionalFiltersMap, > = SchemaCollectionOptions & { permissions?: EditableTablePermissions; /** Row write handlers. Default: derived from the source's backend * (`create`/`update`/`bulkDelete`). */ mutations?: EditableTableMutationHandlers; optimisticActionParams?: Partial>; /** Additional cell types to register alongside the built-in ones. */ extraCellTypes?: CellType[]; }; /** An editable-table collection driven by a source: query config, columns, * field management, and row writes all come from the source. */ export function useEditableTableCollection< T, F extends FiltersMap = OptionalFiltersMap, >( source: SchemaSource, options?: SchemaEditableTableCollectionOptions, ): EditableTableState { const container = useWixPatternsContainer(); const [{ fieldsProvider, sourceState }] = useState<{ fieldsProvider: FieldsSourceProvider; sourceState: SourceState; }>(() => { const holder = new SourceState({ container, source }); if (attachesItself(source)) { // The schema attach path loads it otherwise; the derived row mutations // read the loaded backend. void holder.load(); return { fieldsProvider: source, sourceState: holder }; } return { fieldsProvider: new SchemaState({ sourceState: holder }), sourceState: holder, }; }); const { permissions, mutations, optimisticActionParams, extraCellTypes, ...rest } = options ?? ({} as SchemaEditableTableCollectionOptions); const state = useOpenEditableTableCollection({ ...schemaCollectionConfig(source, rest), permissions, mutations: mutations ?? sourceMutations(sourceState), optimisticActionParams, extraCellTypes, } as unknown as EditableTableCollectionConfig); useState(() => fieldsProvider.setOnTable(state.toolbar)); return state; }