import { injectable } from '@servicetitan/react-ioc'; import { computed, makeObservable } from 'mobx'; import { InMemoryDataSource, TableState } from '../..'; import { setFormStateValues, FormValidators } from '@servicetitan/form'; import { FormState, FieldState } from 'formstate'; import { Product, UserRole, Supplier } from './product'; import { products } from './products'; @injectable() export class TableStore { tableState = new TableState({ dataSource: this.getDataSource(), isRowUnselectable: this.isRowUnselectable, selectionLimit: 3, getFormState: this.getFormState, pageSize: 5, }); constructor() { makeObservable(this); } @computed get inEdit() { return this.tableState.inEdit.size > 0; } editAll = () => this.tableState.editAll(); saveAll = () => this.tableState.saveEditAll(); cancelAll = () => this.tableState.cancelEditAll(); private getDataSource() { return new InMemoryDataSource(products, this.idSelector, { Supplier: (value: Supplier) => Supplier[value], AvailableFor: (value: UserRole | undefined) => value && UserRole[value], }); } private idSelector(row: Product) { return row.ProductID; } private isRowUnselectable(row: Product) { return row.Discontinued; } private getFormState(row: Product) { return setFormStateValues( new FormState({ ProductID: new FieldState(0), ProductName: new FieldState('').validators(FormValidators.required), Supplier: new FieldState(Supplier.Adam), CategoryID: new FieldState(0), MadeIn: new FieldState(''), QuantityPerUnit: new FieldState(''), UnitPrice: new FieldState(0).validators( value => value <= 0 && 'Price must be positive' ), UnitsInStock: new FieldState(0), UnitsOnOrder: new FieldState(new Date()).validators( value => value > new Date() && 'Invalid date' ), Discontinued: new FieldState(false), AvailableFor: new FieldState(undefined), Package: new FieldState(undefined), }), row ); } }