import { useState } from 'react'; import { SourceState } from '@wix/bex-core'; import type { FiltersMap, OptionalFiltersMap, SchemaSource, } from '@wix/bex-core'; import { useWixPatternsContainer } from '@wix/bex-core/react'; import type { LayoutSwitchState, TableLayoutConfig, GridLayoutConfig, SpreadsheetLayoutConfig, } from '../state/LayoutSwitchState'; import type { EditableTableMutationHandlers } from '../state/EditableTable'; import type { FieldsSourceProvider } from '../components/fieldsSourceProvider'; import { useLayoutSwitchCollection as useOpenLayoutSwitchCollection, type LayoutSwitchCollectionConfig, } from '../hooks/useLayoutSwitchCollection'; import { SchemaState } from '../components/SchemaSource/SchemaState'; import { schemaCollectionConfig, type SchemaCollectionOptions, } from './schemaCollectionOptions'; import { sourceMutations } from './sourceMutations'; import { attachesItself } from './usePlatformizedSource'; export type SchemaLayoutSwitchCollectionOptions< T, F extends FiltersMap = OptionalFiltersMap, > = SchemaCollectionOptions & { table?: TableLayoutConfig; grid?: GridLayoutConfig; spreadsheet?: Omit< SpreadsheetLayoutConfig, 'createOptimisticActions' | 'mutations' > & { /** Row write handlers. Default: derived from the source's backend. */ mutations?: EditableTableMutationHandlers; }; }; /** One collection and one toolbar driven by a source, shared by every enabled * layout — the source attaches before any layout mounts, so a page opening * in grid view has its fields and filters too. */ export function useLayoutSwitchCollection< T, F extends FiltersMap = OptionalFiltersMap, >( source: SchemaSource, options?: SchemaLayoutSwitchCollectionOptions, ): LayoutSwitchState { 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 { table, grid, spreadsheet, ...rest } = options ?? ({} as SchemaLayoutSwitchCollectionOptions); const state = useOpenLayoutSwitchCollection({ ...schemaCollectionConfig(source, rest), table, grid, spreadsheet: spreadsheet ? { ...spreadsheet, mutations: spreadsheet.mutations ?? sourceMutations(sourceState), } : undefined, } as unknown as LayoutSwitchCollectionConfig); useState(() => fieldsProvider.setOnTable(state.toolbar)); return state; }