Skip to content

Commit

Permalink
fix: translation wasn't working with context menu
Browse files Browse the repository at this point in the history
  • Loading branch information
ghiscoding committed Sep 17, 2021
1 parent e278c02 commit 889e443
Show file tree
Hide file tree
Showing 8 changed files with 125 additions and 162 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ <h3 class="title is-3">
<span class="icon mdi mdi-minus"></span>
<span>Dynamically Remove Last Column</span>
</button>
<button class="button is-small" data-test="hide-duration-btn" onclick.delegate="hideDurationColumnDynamically()">
<button class="button is-small" data-test="hide-finish-btn" onclick.delegate="hideFinishColumnDynamically()">
<span class="icon mdi mdi-eye-off-outline"></span>
<span>Dynamically Hide "Duration"</span>
<span>Dynamically Hide "Finish"</span>
</button>
<button class="button is-small" data-test="add-item-btn" onclick.delegate="addItem()"
title="Clear Filters &amp; Sorting to see it better">
Expand Down
25 changes: 19 additions & 6 deletions examples/webpack-demo-vanilla-bundle/src/examples/example07.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,10 @@ export class Example7 {
initializeGrid() {
this.columnDefinitions = [
{
id: 'title', nameKey: 'TITLE', field: 'title', filterable: true, editor: { model: Editors.longText, required: true, alwaysSaveOnEnterKey: true },
id: 'title', nameKey: 'TITLE', field: 'title', filterable: true,
editor: { model: Editors.longText, required: true, alwaysSaveOnEnterKey: true },
// formatter: this.taskTranslateFormatter.bind(this),
// params: { useFormatterOuputToFilter: true }
},
{
id: 'action', name: 'Action', field: 'action', minWidth: 60, maxWidth: 60,
Expand Down Expand Up @@ -96,7 +99,7 @@ export class Example7 {
{
id: 'duration', nameKey: 'DURATION', field: 'duration', sortable: true, filterable: true,
type: 'number', editor: { model: Editors.text, alwaysSaveOnEnterKey: true, },
formatter: (_row: number, _cell: number, value: any) => value > 1 ? `${value} days` : `${value} day`,
formatter: this.dayDurationTranslateFormatter.bind(this)
},
{
id: 'percentComplete', nameKey: 'PERCENT_COMPLETE', field: 'percentComplete', type: 'number',
Expand Down Expand Up @@ -307,7 +310,7 @@ export class Example7 {
}

changeCompletedOption(dataContext: any, newValue: boolean) {
console.log('change', dataContext, newValue)
console.log('change', dataContext, newValue);
if (dataContext && dataContext.hasOwnProperty('completed')) {
dataContext.completed = newValue;
this.sgb?.gridService.updateItem(dataContext);
Expand Down Expand Up @@ -337,7 +340,7 @@ export class Example7 {
tempDataset.push({
id: i,
title: 'Task ' + i,
duration: Math.round(Math.random() * 25),
duration: i === 4 ? 0 : Math.round(Math.random() * 25),
percentComplete: Math.round(Math.random() * 100),
start: new Date(2009, 0, 1),
finish: new Date(2009, 0, 5),
Expand Down Expand Up @@ -431,6 +434,14 @@ export class Example7 {
this.selectedLanguageFile = `${this.selectedLanguage}.json`;
}

dayDurationTranslateFormatter(_row, _cell, value) {
return this.translateService.translate('X_DAY_PLURAL', { x: value, plural: value > 1 ? 's' : '' }) ?? '';
}

taskTranslateFormatter(_row, _cell, value) {
return this.translateService.translate('TASK_X', { x: value }) ?? '';
}

dynamicallyAddTitleHeader() {
const newCol = {
id: `title${this.duplicateTitleHeaderCount++}`,
Expand All @@ -442,6 +453,8 @@ export class Example7 {
// validator: myCustomTitleValidator, // use a custom validator
},
sortable: true, minWidth: 100, filterable: true,
// formatter: this.taskTranslateFormatter.bind(this),
// params: { useFormatterOuputToFilter: true },
};

// you can dynamically add your column to your column definitions
Expand Down Expand Up @@ -479,12 +492,12 @@ export class Example7 {
*/
}

hideDurationColumnDynamically() {
hideFinishColumnDynamically() {
// -- you can hide by one Id or multiple Ids:
// hideColumnById(id, options), hideColumnByIds([ids], options)
// you can also provide options, defaults are: { autoResizeColumns: true, triggerEvent: true, hideFromColumnPicker: false, hideFromGridMenu: false }

this.sgb.gridService.hideColumnById('duration');
this.sgb.gridService.hideColumnById('finish');

// or with multiple Ids and extra options
// this.sgb.gridService.hideColumnByIds(['duration', 'finish'], { autoResizeColumns: false, hideFromColumnPicker: true, hideFromGridMenu: false });
Expand Down
128 changes: 12 additions & 116 deletions packages/common/src/controls/__tests__/gridMenuControl.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -917,7 +917,7 @@ describe('GridMenuControl', () => {
control.columns = columnsMock;
control.init();
expect(SharedService.prototype.gridOptions.gridMenu!.customItems).toEqual([
{ iconCssClass: 'fa fa-times', title: 'Dégeler les colonnes/rangées', disabled: false, command: 'clear-pinning', positionOrder: 52 },
{ iconCssClass: 'fa fa-times', title: 'Dégeler les colonnes/rangées', titleKey: 'CLEAR_PINNING', disabled: false, command: 'clear-pinning', positionOrder: 52 },
]);
});

Expand All @@ -928,9 +928,9 @@ describe('GridMenuControl', () => {
control.init();
control.init(); // calling 2x register to make sure it doesn't duplicate commands
expect(SharedService.prototype.gridOptions.gridMenu!.customItems).toEqual([
{ iconCssClass: 'fa fa-filter text-danger', title: 'Supprimer tous les filtres', disabled: false, command: 'clear-filter', positionOrder: 50 },
{ iconCssClass: 'fa fa-random', title: 'Basculer la ligne des filtres', disabled: false, command: 'toggle-filter', positionOrder: 53 },
{ iconCssClass: 'fa fa-refresh', title: 'Rafraîchir les données', disabled: false, command: 'refresh-dataset', positionOrder: 57 }
{ iconCssClass: 'fa fa-filter text-danger', title: 'Supprimer tous les filtres', titleKey: 'CLEAR_ALL_FILTERS', disabled: false, command: 'clear-filter', positionOrder: 50 },
{ iconCssClass: 'fa fa-random', title: 'Basculer la ligne des filtres', titleKey: 'TOGGLE_FILTER_ROW', disabled: false, command: 'toggle-filter', positionOrder: 53 },
{ iconCssClass: 'fa fa-refresh', title: 'Rafraîchir les données', titleKey: 'REFRESH_DATASET', disabled: false, command: 'refresh-dataset', positionOrder: 57 }
]);
});

Expand All @@ -941,7 +941,7 @@ describe('GridMenuControl', () => {
control.init();
control.init(); // calling 2x register to make sure it doesn't duplicate commands
expect(SharedService.prototype.gridOptions.gridMenu!.customItems).toEqual([
{ iconCssClass: 'fa fa-filter text-danger', title: 'Supprimer tous les filtres', disabled: false, command: 'clear-filter', positionOrder: 50 }
{ iconCssClass: 'fa fa-filter text-danger', title: 'Supprimer tous les filtres', titleKey: 'CLEAR_ALL_FILTERS', disabled: false, command: 'clear-filter', positionOrder: 50 }
]);
});

Expand All @@ -952,7 +952,7 @@ describe('GridMenuControl', () => {
control.init();
control.init(); // calling 2x register to make sure it doesn't duplicate commands
expect(SharedService.prototype.gridOptions.gridMenu!.customItems).toEqual([
{ iconCssClass: 'fa fa-random', title: 'Basculer la ligne des filtres', disabled: false, command: 'toggle-filter', positionOrder: 53 },
{ iconCssClass: 'fa fa-random', title: 'Basculer la ligne des filtres', titleKey: 'TOGGLE_FILTER_ROW', disabled: false, command: 'toggle-filter', positionOrder: 53 },
]);
});

Expand All @@ -963,7 +963,7 @@ describe('GridMenuControl', () => {
control.init();
control.init(); // calling 2x register to make sure it doesn't duplicate commands
expect(SharedService.prototype.gridOptions.gridMenu!.customItems).toEqual([
{ iconCssClass: 'fa fa-refresh', title: 'Rafraîchir les données', disabled: false, command: 'refresh-dataset', positionOrder: 57 }
{ iconCssClass: 'fa fa-refresh', title: 'Rafraîchir les données', titleKey: 'REFRESH_DATASET', disabled: false, command: 'refresh-dataset', positionOrder: 57 }
]);
});

Expand All @@ -974,7 +974,7 @@ describe('GridMenuControl', () => {
control.init();
control.init(); // calling 2x register to make sure it doesn't duplicate commands
expect(SharedService.prototype.gridOptions.gridMenu!.customItems).toEqual([
{ iconCssClass: 'fa fa-random', title: 'Basculer la ligne de pré-en-tête', disabled: false, command: 'toggle-preheader', positionOrder: 53 }
{ iconCssClass: 'fa fa-random', title: 'Basculer la ligne de pré-en-tête', titleKey: 'TOGGLE_PRE_HEADER_ROW', disabled: false, command: 'toggle-preheader', positionOrder: 53 }
]);
});

Expand All @@ -994,7 +994,7 @@ describe('GridMenuControl', () => {
control.init();
control.init(); // calling 2x register to make sure it doesn't duplicate commands
expect(SharedService.prototype.gridOptions.gridMenu!.customItems).toEqual([
{ iconCssClass: 'fa fa-unsorted text-danger', title: 'Supprimer tous les tris', disabled: false, command: 'clear-sorting', positionOrder: 51 }
{ iconCssClass: 'fa fa-unsorted text-danger', title: 'Supprimer tous les tris', titleKey: 'CLEAR_ALL_SORTING', disabled: false, command: 'clear-sorting', positionOrder: 51 }
]);
});

Expand All @@ -1014,7 +1014,7 @@ describe('GridMenuControl', () => {
control.init();
control.init(); // calling 2x register to make sure it doesn't duplicate commands
expect(SharedService.prototype.gridOptions.gridMenu!.customItems).toEqual([
{ iconCssClass: 'fa fa-download', title: 'Exporter en format CSV', disabled: false, command: 'export-csv', positionOrder: 54 }
{ iconCssClass: 'fa fa-download', title: 'Exporter en format CSV', titleKey: 'EXPORT_TO_CSV', disabled: false, command: 'export-csv', positionOrder: 54 }
]);
});

Expand All @@ -1034,7 +1034,7 @@ describe('GridMenuControl', () => {
control.init();
control.init(); // calling 2x register to make sure it doesn't duplicate commands
expect(SharedService.prototype.gridOptions.gridMenu!.customItems).toEqual([
{ iconCssClass: 'fa fa-file-excel-o text-success', title: 'Exporter vers Excel', disabled: false, command: 'export-excel', positionOrder: 55 }
{ iconCssClass: 'fa fa-file-excel-o text-success', title: 'Exporter vers Excel', titleKey: 'EXPORT_TO_EXCEL', disabled: false, command: 'export-excel', positionOrder: 55 }
]);
});

Expand All @@ -1045,7 +1045,7 @@ describe('GridMenuControl', () => {
control.init();
control.init(); // calling 2x register to make sure it doesn't duplicate commands
expect(SharedService.prototype.gridOptions.gridMenu!.customItems).toEqual([
{ iconCssClass: 'fa fa-download', title: 'Exporter en format texte (délimité par tabulation)', disabled: false, command: 'export-text-delimited', positionOrder: 56 }
{ iconCssClass: 'fa fa-download', title: 'Exporter en format texte (délimité par tabulation)', titleKey: 'EXPORT_TO_TAB_DELIMITED', disabled: false, command: 'export-text-delimited', positionOrder: 56 }
]);
});

Expand All @@ -1059,117 +1059,14 @@ describe('GridMenuControl', () => {
});
});

// describe('adding Grid Menu Custom Items', () => {
// const customItemsMock = [{
// iconCssClass: 'fa fa-question-circle',
// titleKey: 'HELP',
// disabled: false,
// command: 'help',
// positionOrder: 99
// }];

// beforeEach(() => {
// const copyGridOptionsMock = {
// ...gridOptionsMock,
// enableTextExport: true,
// gridMenu: {
// commandLabels: gridOptionsMock.gridMenu.commandLabels,
// customItems: customItemsMock,
// hideClearFrozenColumnsCommand: true,
// hideExportCsvCommand: false,
// hideExportExcelCommand: false,
// hideExportTextDelimitedCommand: true,
// hideRefreshDatasetCommand: true,
// hideSyncResizeButton: true,
// hideToggleFilterCommand: true,
// hideTogglePreHeaderCommand: true
// }
// } as unknown as GridOption;

// jest.spyOn(SharedService.prototype, 'dataView', 'get').mockReturnValue(dataViewStub);
// jest.spyOn(SharedService.prototype, 'slickGrid', 'get').mockReturnValue(gridStub);
// jest.spyOn(SharedService.prototype, 'gridOptions', 'get').mockReturnValue(gridOptionsMock);
// jest.spyOn(SharedService.prototype, 'allColumns', 'get').mockReturnValue(columnsMock);
// jest.spyOn(SharedService.prototype, 'visibleColumns', 'get').mockReturnValue(columnsMock);
// jest.spyOn(SharedService.prototype, 'columnDefinitions', 'get').mockReturnValue(columnsMock);
// jest.spyOn(SharedService.prototype, 'gridOptions', 'get').mockReturnValue(copyGridOptionsMock);
// });

// afterEach(() => {
// control.dispose();
// });

// xit('should have user grid menu custom items', () => {
// control.register();
// expect(SharedService.prototype.gridOptions.gridMenu!.customItems).toEqual([
// { command: 'export-csv', disabled: false, iconCssClass: 'fa fa-download', positionOrder: 54, title: 'Exporter en format CSV' },
// // { command: 'export-excel', disabled: false, iconCssClass: 'fa fa-file-excel-o text-success', positionOrder: 54, title: 'Exporter vers Excel' },
// { command: 'help', disabled: false, iconCssClass: 'fa fa-question-circle', positionOrder: 99, title: 'Aide', titleKey: 'HELP' },
// ]);
// });

// xit('should have same user grid menu custom items even when grid menu extension is registered multiple times', () => {
// control.register();
// control.register();
// expect(SharedService.prototype.gridOptions.gridMenu!.customItems).toEqual([
// { command: 'export-csv', disabled: false, iconCssClass: 'fa fa-download', positionOrder: 54, title: 'Exporter en format CSV' },
// // { command: 'export-excel', disabled: false, iconCssClass: 'fa fa-file-excel-o text-success', positionOrder: 54, title: 'Exporter vers Excel' },
// { command: 'help', disabled: false, iconCssClass: 'fa fa-question-circle', positionOrder: 99, title: 'Aide', titleKey: 'HELP' },
// ]);
// });
// });

// describe('refreshBackendDataset method', () => {
// afterEach(() => {
// jest.spyOn(SharedService.prototype, 'gridOptions', 'get').mockReturnValue(gridOptionsMock);
// });

// xit('should throw an error when backendServiceApi is not provided in the grid options', () => {
// const copyGridOptionsMock = { ...gridOptionsMock, backendServiceApi: {} } as unknown as GridOption;
// jest.spyOn(SharedService.prototype, 'gridOptions', 'get').mockReturnValue(copyGridOptionsMock);
// expect(() => control.refreshBackendDataset()).toThrowError(`BackendServiceApi requires at least a "process" function and a "service" defined`);
// });

// xit('should call the backend service API to refresh the dataset', (done) => {
// const now = new Date();
// const query = `query { users (first:20,offset:0) { totalCount, nodes { id,name,gender,company } } }`;
// const processResult = {
// data: { users: { nodes: [] }, pageInfo: { hasNextPage: true }, totalCount: 0 },
// metrics: { startTime: now, endTime: now, executionTime: 0, totalItemCount: 0 }
// };
// const preSpy = jest.spyOn(gridOptionsMock.backendServiceApi as BackendServiceApi, 'preProcess');
// const postSpy = jest.spyOn(gridOptionsMock.backendServiceApi as BackendServiceApi, 'postProcess');
// const promise = new Promise((resolve) => setTimeout(() => resolve(processResult), 1));
// const processSpy = jest.spyOn(gridOptionsMock.backendServiceApi as BackendServiceApi, 'process').mockReturnValue(promise);
// jest.spyOn(gridOptionsMock.backendServiceApi!.service, 'buildQuery').mockReturnValue(query);

// control.refreshBackendDataset({ enableAddRow: true });

// expect(preSpy).toHaveBeenCalled();
// expect(processSpy).toHaveBeenCalled();
// promise.then(() => {
// expect(postSpy).toHaveBeenCalledWith(processResult);
// done();
// });
// });
// });

describe('executeGridMenuInternalCustomCommands method', () => {
beforeEach(() => {
jest.spyOn(gridStub, 'getOptions').mockReturnValue(gridOptionsMock);
jest.spyOn(SharedService.prototype, 'allColumns', 'get').mockReturnValue(columnsMock);
jest.spyOn(SharedService.prototype, 'visibleColumns', 'get').mockReturnValue(columnsMock.slice(0, 1));
});

// afterEach(() => {
// jest.clearAllMocks();
// control.eventHandler.unsubscribeAll();
// mockGridMenuAddon.onCommand = new Slick.Event();
// });

it('should call "clearFrozenColumns" when the command triggered is "clear-pinning"', () => {
// const onCommandMock = jest.fn();
// gridOptionsMock.gridMenu.onCommand = onCommandMock;
const setOptionsSpy = jest.spyOn(gridStub, 'setOptions');
const setColumnsSpy = jest.spyOn(gridStub, 'setColumns');
const copyGridOptionsMock = { ...gridOptionsMock, gridMenu: { commandLabels: gridOptionsMock.gridMenu.commandLabels, hideClearFrozenColumnsCommand: false, } } as unknown as GridOption;
Expand All @@ -1182,7 +1079,6 @@ describe('GridMenuControl', () => {
document.querySelector('.slick-grid-menu-button').dispatchEvent(new Event('click', { bubbles: true, cancelable: true, composed: false }));
control.menuElement.querySelector<HTMLInputElement>('.slick-grid-menu-item[data-command=clear-pinning]').dispatchEvent(clickEvent);

// expect(onCommandMock).toHaveBeenCalled();
expect(setColumnsSpy).toHaveBeenCalled();
expect(setOptionsSpy).toHaveBeenCalledWith({ frozenColumn: -1, frozenRow: -1, frozenBottom: false, enableMouseWheelScrollHandler: false });
});
Expand Down
Loading

0 comments on commit 889e443

Please sign in to comment.