Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CardView - implement dataController #28688

Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`Options onDataErrorOccurred should be called when load error happens 1`] = `
[
{
"component": Any<Object>,
"error": [Error: my error],
},
]
`;
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
/* eslint-disable @typescript-eslint/no-invalid-void-type */
/* eslint-disable no-param-reassign */
/* eslint-disable spellcheck/spell-checker */
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import type { DataSource } from '@js/common/data';
import type { SubsGets } from '@ts/core/reactive/index';
import {
computed, effect, state,
} from '@ts/core/reactive/index';
import { createPromise } from '@ts/core/utils/promise';

// import { EditingController } from '../editing/controller';
// import type { Change } from '../editing/types';
import { OptionsController } from '../options_controller/options_controller';
import type { DataObject, Key } from './types';
import { normalizeDataSource, updateItemsImmutable } from './utils';

export class DataController {
private readonly loadedPromise = createPromise<void>();

private readonly dataSourceConfiguration = this.options.oneWay('dataSource');

private readonly keyExpr = this.options.oneWay('keyExpr');

public readonly dataSource = computed(
(dataSourceLike, keyExpr) => normalizeDataSource(dataSourceLike, keyExpr),
[this.dataSourceConfiguration, this.keyExpr],
);

// TODO
private readonly cacheEnabled = this.options.oneWay('cacheEnabled');

private readonly pagingEnabled = this.options.twoWay('paging.enabled');

public readonly pageIndex = this.options.twoWay('paging.pageIndex');

public readonly pageSize = this.options.twoWay('paging.pageSize');

// TODO
private readonly remoteOperations = this.options.oneWay('remoteOperations');

private readonly onDataErrorOccurred = this.options.action('onDataErrorOccurred');

private readonly _items = state<DataObject[]>([]);

public readonly items: SubsGets<DataObject[]> = this._items;

private readonly _totalCount = state(0);

public readonly totalCount: SubsGets<number> = this._totalCount;

public readonly isLoading = state(false);

public readonly pageCount = computed(
(totalCount, pageSize) => Math.ceil(totalCount / pageSize),
[this.totalCount, this.pageSize],
);

public static dependencies = [OptionsController] as const;

constructor(
private readonly options: OptionsController,
) {
effect(
(dataSource) => {
const changedCallback = (e?): void => {
this.onChanged(dataSource, e);
};
const loadingChangedCallback = (): void => {
this.isLoading.update(dataSource.isLoading());
};
const loadErrorCallback = (error: string): void => {
const callback = this.onDataErrorOccurred.unreactive_get();
callback({ error });
changedCallback();
};

if (dataSource.isLoaded()) {
changedCallback();
}
dataSource.on('changed', changedCallback);
dataSource.on('loadingChanged', loadingChangedCallback);
dataSource.on('loadError', loadErrorCallback);

return (): void => {
dataSource.off('changed', changedCallback);
dataSource.off('loadingChanged', loadingChangedCallback);
dataSource.off('loadError', loadErrorCallback);
};
},
[this.dataSource],
);

effect(
(dataSource, pageIndex, pageSize, pagingEnabled) => {
let someParamChanged = false;
if (dataSource.pageIndex() !== pageIndex) {
dataSource.pageIndex(pageIndex);
someParamChanged ||= true;
}
if (dataSource.pageSize() !== pageSize) {
dataSource.pageSize(pageSize);
someParamChanged ||= true;
}
// eslint-disable-next-line @typescript-eslint/no-unnecessary-boolean-literal-compare
if (dataSource.requireTotalCount() !== true) {
dataSource.requireTotalCount(true);
someParamChanged ||= true;
}
if (dataSource.paginate() !== pagingEnabled) {
dataSource.paginate(pagingEnabled);
someParamChanged ||= true;
}

if (someParamChanged || !dataSource.isLoaded()) {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
dataSource.load();
}
},
[this.dataSource, this.pageIndex, this.pageSize, this.pagingEnabled],
);
}

private onChanged(dataSource: DataSource, e): void {
let items = dataSource.items() as DataObject[];

if (e?.changes) {
items = this._items.unreactive_get();
items = updateItemsImmutable(items, e.changes, dataSource.store());
}

this._items.update(items);
this.pageIndex.update(dataSource.pageIndex());
this.pageSize.update(dataSource.pageSize());
this._totalCount.update(dataSource.totalCount());
this.loadedPromise.resolve();
}

public getDataKey(data: DataObject): Key {
return this.dataSource.unreactive_get().store().keyOf(data);
}

public waitLoaded(): Promise<void> {
return this.loadedPromise.promise;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export { DataController } from './data_controller';
export { defaultOptions, type Options } from './options';
export { PublicMethods } from './public_methods';
Original file line number Diff line number Diff line change
@@ -0,0 +1,235 @@
/* eslint-disable spellcheck/spell-checker */
import {
afterAll,
beforeAll,
describe, expect, it, jest,
} from '@jest/globals';
import { CustomStore } from '@js/common/data';
import DataSource from '@js/data/data_source';
import { logger } from '@ts/core/utils/m_console';
import ArrayStore from '@ts/data/m_array_store';

import type { Options } from '../options';
import { OptionsControllerMock } from '../options_controller/options_controller.mock';
import { DataController } from './data_controller';

beforeAll(() => {
jest.spyOn(logger, 'error').mockImplementation(() => {});
});
afterAll(() => {
jest.restoreAllMocks();
});

const setup = (options: Options) => {
const optionsController = new OptionsControllerMock(options);
const dataController = new DataController(optionsController);

return {
optionsController,
dataController,
};
};

describe('Options', () => {
describe('cacheEnabled', () => {
const setupForCacheEnabled = ({ cacheEnabled }) => {
const store = new ArrayStore({
data: [
{ id: 1, value: 'value 1' },
{ id: 2, value: 'value 2' },
{ id: 3, value: 'value 3' },
],
key: 'id',
});

jest.spyOn(store, 'load');

const { dataController } = setup({
cacheEnabled,
dataSource: store,
paging: {
pageSize: 1,
},
});

return { store, dataController };
};

describe('when it is false', () => {
it('should skip caching requests', () => {
const { store, dataController } = setupForCacheEnabled({
cacheEnabled: false,
});
expect(store.load).toBeCalledTimes(1);

dataController.pageIndex.update(1);
expect(store.load).toBeCalledTimes(2);

dataController.pageIndex.update(0);
expect(store.load).toBeCalledTimes(3);
});
});

describe('when it is true', () => {
it.skip('should cache previously loaded pages', () => {});
it.skip('should clear cache if not only pageIndex changed', () => {});
});
});

describe('dataSourse', () => {
describe('when it is dataSource instance', () => {
it('should pass dataSource as is', () => {
const dataSource = new DataSource({
store: [{ a: 1 }, { b: 2 }],
});

const { dataController } = setup({ dataSource });

expect(dataController.dataSource.unreactive_get()).toBe(dataSource);
});
});
describe('when it is array', () => {
it('should normalize to DataSource with given items', () => {
const data = [{ a: 1 }, { b: 2 }];
const { dataController } = setup({ dataSource: data });

const dataSource = dataController.dataSource.unreactive_get();

expect(dataSource).toBeInstanceOf(DataSource);
expect(dataSource.items()).toEqual(data);
});
});
describe('when it is empty', () => {
it('should should normalize to empty DataSource', () => {
const { dataController } = setup({});

const dataSource = dataController.dataSource.unreactive_get();

expect(dataSource).toBeInstanceOf(DataSource);
expect(dataSource.items()).toHaveLength(0);
});
});
});

describe('keyExpr', () => {
describe('when dataSource is array', () => {
it('should be passed as key to DataSource', () => {
const { dataController } = setup({
dataSource: [{ myKeyExpr: 1 }, { myKeyExpr: 2 }],
keyExpr: 'myKeyExpr',
});

const dataSource = dataController.dataSource.unreactive_get();
expect(dataSource.key()).toBe('myKeyExpr');
});
});
describe('when dataSource is DataSource instance', () => {
it('should be ignored', () => {
const { dataController } = setup({
dataSource: new ArrayStore({
key: 'storeKeyExpr',
data: [{ storeKeyExpr: 1 }, { storeKeyExpr: 2 }],
}),
keyExpr: 'myKeyExpr',
});

const dataSource = dataController.dataSource.unreactive_get();
expect(dataSource.key()).toBe('storeKeyExpr');
});
});
});

describe('onDataErrorOccurred', () => {
it('should be called when load error happens', async () => {
const onDataErrorOccurred = jest.fn();

const { dataController } = setup({
dataSource: new CustomStore({
load() {
return Promise.reject(new Error('my error'));
},
}),
onDataErrorOccurred,
});

await dataController.waitLoaded();

expect(onDataErrorOccurred).toBeCalledTimes(1);
expect(onDataErrorOccurred.mock.calls[0]).toMatchSnapshot([{
component: expect.any(Object),
}]);
});
});

describe('paging.enabled', () => {
describe('when it is true', () => {
it('should turn on pagination', () => {
const { dataController } = setup({
dataSource: [{ a: '1' }, { a: '2' }, { a: '3' }, { a: '4' }],
paging: {
enabled: true,
pageSize: 2,
},
});

const items = dataController.items.unreactive_get();
expect(items).toHaveLength(2);
});
});
describe('when it is false', () => {
it('should turn on pagination', () => {
const { dataController } = setup({
dataSource: [{ a: '1' }, { a: '2' }, { a: '3' }, { a: '4' }],
paging: {
enabled: false,
pageSize: 2,
},
});

const items = dataController.items.unreactive_get();
expect(items).toHaveLength(4);
});
});
});

describe('paging.pageIndex', () => {
it('should change current page', () => {
const { dataController, optionsController } = setup({
dataSource: [{ a: '1' }, { a: '2' }, { a: '3' }, { a: '4' }],
paging: {
pageSize: 2,
pageIndex: 1,
},
});

let items = dataController.items.unreactive_get();
expect(items).toEqual([{ a: '3' }, { a: '4' }]);

optionsController.option('paging.pageIndex', 0);
items = dataController.items.unreactive_get();
expect(items).toEqual([{ a: '1' }, { a: '2' }]);
});
});

describe('paging.pageSize', () => {
it('should change size of current page', () => {
const { dataController, optionsController } = setup({
dataSource: [{ a: '1' }, { a: '2' }, { a: '3' }, { a: '4' }],
paging: {
pageSize: 2,
},
});

let items = dataController.items.unreactive_get();
expect(items).toEqual([{ a: '1' }, { a: '2' }]);

optionsController.option('paging.pageSize', 3);
items = dataController.items.unreactive_get();
expect(items).toEqual([{ a: '1' }, { a: '2' }, { a: '3' }]);
});
});

describe.skip('remoteOperations', () => {

});
});
Loading
Loading