-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequestConstructor.js
More file actions
588 lines (501 loc) · 24.4 KB
/
requestConstructor.js
File metadata and controls
588 lines (501 loc) · 24.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
// TODO - 🟡 - make it accessible and tackle console issues
import resourceAnalysisValidator from './resourceAnalysisValidator.js';
/**
* The "noop css tag function" is a no-operation (noop) function
* that takes a tagged template literal and returns the raw string without modification.
* This allows you to use VSCode's CSS formatting features */
const css = (strings) => strings.raw[0];
const VALID_ANALYSIS_MODES = { intervals: 'intervals', totals: 'totals' };
const VALID_TOTALS_DATE_RANGE_MODES = { liveBetween: 'liveBetween', strictlyBetween: 'strictlyBetween' };
const DIV_ID_MAP = {
updateButtonId: 'req-constructor-updateButton',
cancelButtonId: 'req-constructor-cancelButton'
};
export class RequestConstructor {
/** requestConstructor.js
* @param {Object} requestObject - The request object. Example {analysisMode: "intervals", filter: {projects: {Duration: 10}}, "intervals": {"startDate": "2024-01-01", "intervalType": "week", noOfIntervals": 5}.
* @param {Array} dataServiceModel - The filter values. Example {tables:{tableName:{labels:{},fields:[{name:"Id",labels:{en:"Id",es:"Id",pt:"Id"},type:"Number | String | Date",primaryKey:!0}]}},relationships:{tableName1:{tableName2:{foreignKey:"ProjectId"},risks:{foreignKey:"ProjectId"}}}};
* @param {string} parentDivId - The parent div ID to attach the filter UI to
* @param {Object} [options={}] - The options object.
* @param {boolean} [options.shouldFilterBeVisible=true]
* @param {Array} [options.tablesAllowed] - The tables allowed in the filter [{ tasks: ['Id', 'Status.Name'] }]
*/
state = {
analysisMode: '',
filter: {},
intervals: {},
totals: {}
};
constructor(requestObject = {}, dataServiceModel, parentDivId, options = {}) {
if (requestObject == {}) { resourceAnalysisValidator.validateRequest(requestObject); }
this.state.analysisMode = requestObject.analysisMode || VALID_ANALYSIS_MODES.intervals;
this.state.filter = requestObject.filter || {};
this.state.intervals = requestObject.intervals || {};
this.state.totals = requestObject.totals || {};
this.dataServiceModel = dataServiceModel;
this.parentDivId = parentDivId;
this._langTranslations = {};
this._lang = typeof strLanguage !== 'undefined' ? strLanguage : 'en';
this.shouldFilterBeVisible = options?.shouldFilterBeVisible;
this.tablesAllowed = options?.tablesAllowed;
this._initPromise = this.#initDependencies().then(() => {
this.initUI();
this.#applyStyles();
this.#toggleOptionsState();
this.#addEventListeners();
});
}
async #initDependencies() {
await itmGlobal.ensureDiContainerReady();
this.getTranslations = window.diContainer.get('getTranslations');
await this.#loadTranslations();
this.FilterConstructor = window.diContainer.get('FilterConstructor');
}
async #loadTranslations() {
this._langTranslations = await this.getTranslations('requestConstructor', this._lang);
}
#addEventListeners() {
document.addEventListener('resourceAnalysisRequestFulfilled', (event) => {
this.#stopSpin(DIV_ID_MAP.updateButtonId, event.detail);
});
}
initUI() {
const parentDiv = document.getElementById(this.parentDivId);
// Helper function to create a wrapper div
function createWrapper(id, className) {
const wrapper = document.createElement('div');
wrapper.id = id;
wrapper.className = className;
return wrapper;
}
const requestConstructorWrapper = createWrapper('req-constructor-wrapper', 'req-constructor-wrapper');
const requestConstructorModesWrapper = createWrapper('req-constructor-modesWrapper', 'req-constructor-modesWrapper');
// Append sections to modes wrapper
const intervalsSection = this.#createIntervalsSection();
const totalsSection = this.#createTotalsSection();
requestConstructorModesWrapper.appendChild(intervalsSection);
requestConstructorModesWrapper.appendChild(totalsSection);
// Append modes wrapper to the main wrapper
requestConstructorWrapper.appendChild(requestConstructorModesWrapper);
// Create and configure the filter wrapper div
const requestConstructorFilterWrapper = createWrapper('req-constructor-filterWrapper', 'req-constructor-filterWrapper');
requestConstructorWrapper.appendChild(requestConstructorFilterWrapper);
// Append the main wrapper to the parent div
parentDiv.appendChild(requestConstructorWrapper);
// Conditionally create and append the filter section
if (this.shouldFilterBeVisible) {
const filterSection = this.#createFilterSection(requestConstructorFilterWrapper.id);
requestConstructorFilterWrapper.appendChild(filterSection);
}
// Button div wrapper
const buttonWrapper = document.createElement('div');
buttonWrapper.className = 'req-constructor-buttonDiv-wrapper';
// Create and configure the update button
const updateButton = document.createElement('itm-button');
updateButton.type = 'primary';
updateButton.id = DIV_ID_MAP.updateButtonId;
updateButton.textContent = this._langTranslations.t('apply');
updateButton.addEventListener('click', (event) => {
event.preventDefault();
this.#startSpin (DIV_ID_MAP.updateButtonId);
this.#updateRequest();
});
// Append the update button to the parent div
buttonWrapper.appendChild(updateButton);
// Create and configure the cancel button
const cancelButton = document.createElement('itm-button');
cancelButton.type = 'secondary';
cancelButton.id = DIV_ID_MAP.cancelButtonId;
cancelButton.textContent = this._langTranslations.t('reset');
cancelButton.addEventListener('click', (event) => {
event.preventDefault();
// TODO - 🟢 - Add the cancel logic
});
buttonWrapper.appendChild(cancelButton);
parentDiv.appendChild(buttonWrapper);
// Add collapse/expand features to the mode and filter sections
const modesWrapperToggleState = this.#wrapperInitialToggleState(requestConstructorModesWrapper);
const filterWrapperToggleState = this.#wrapperInitialToggleState(requestConstructorFilterWrapper);
this.#addToggleCollapseExpandFeatures(requestConstructorModesWrapper, this.#modesWrapperTitle(modesWrapperToggleState), modesWrapperToggleState, 'mode');
this.#addToggleCollapseExpandFeatures(requestConstructorFilterWrapper, this.#filterWrapperTitle(filterWrapperToggleState), filterWrapperToggleState, 'filter');
}
#startSpin (buttonId) {
const button = document.getElementById(buttonId);
if (button) {
button.startSpin();
}
}
#stopSpin(buttonId, responseStatus) {
const button = document.getElementById(buttonId);
if (button) {
button.stopSpin({success: responseStatus.success});
}
}
#wrapperInitialToggleState(div) {
const toggleState = localStorage.getItem(div.id + 'ToggleState');
return toggleState;
}
#modesWrapperTitle(toggleState) {
if (toggleState == 'collapsed') {
return this.state.analysisMode == 'interals' ? `${this._langTranslations.t('mode')}: ${this._langTranslations.t('intervals')}` : `${this._langTranslations.t('mode')}: ${this._langTranslations.t('totals')}`;
} else {
return this._langTranslations.t('mode');
}
}
#filterWrapperTitle(toggleState) {
const areFiltersApplied = (this.state.filter && typeof this.state.filter === 'object' && Object.keys(this.state.filter).length > 0);
if (toggleState == 'collapsed') {
return areFiltersApplied ? this._langTranslations.t('filtersApplied') : this._langTranslations.t('noFiltersApplied');
}
else { return this._langTranslations.t('filter'); };
}
#applyStyles() {
const style = document.createElement('style');
style.textContent = this.#getStyles();
// TODO - 🟢 - Add the style to this element to make the style scoped
document.head.appendChild(style);
}
#createFilterSection(filterWrapperDivId) {
const filterConstructor = new this.FilterConstructor(
this.state.filter, this.dataServiceModel,
filterWrapperDivId, this.tablesAllowed, this._lang);
// TODO - 🟢 - Remove the following line making the filterConstructor a private variable
window.filterConstructor = filterConstructor; // For testing purposes
filterConstructor.element.addEventListener('filterUpdated', (event) => {
this.state.filter = event.detail;
});
return filterConstructor.element; // Assuming this returns the constructed filter section
}
#createIntervalsSection() {
const intervalsSection = document.createElement('div');
intervalsSection.id = 'req-constructor-intervalsSection';
intervalsSection.className = 'req-constructor-modeWrapper';
const constructorModeRadio = document.createElement('div');
constructorModeRadio.className = 'req-constructor-mode-radio';
const intervalsRadio = document.createElement('input');
intervalsRadio.type = 'radio';
intervalsRadio.id = 'req-constructor-intervals';
intervalsRadio.name = 'analysisMode';
intervalsRadio.value = 'intervals';
if (this.state.analysisMode === 'intervals') {
intervalsRadio.checked = true;
}
intervalsRadio.addEventListener('change', () => {
this.state.analysisMode = 'intervals';
this.#toggleOptionsState();
});
const intervalsLabel = document.createElement('label');
intervalsLabel.htmlFor = intervalsRadio.id;
intervalsLabel.className = 'req-constructor-label';
intervalsLabel.textContent = this._langTranslations.t('intervals');
constructorModeRadio.appendChild(intervalsRadio);
constructorModeRadio.appendChild(intervalsLabel);
intervalsSection.appendChild(constructorModeRadio);
const intervalOptionsWrapper = document.createElement('div');
intervalOptionsWrapper.id = 'req-constructor-intervalOptionsWrapper';
intervalOptionsWrapper.className = 'req-constructor-mode-options-wrapper';
const intervalDropdown = document.createElement('select');
intervalDropdown.id = 'req-constructor-intervalType';
intervalDropdown.className = 'req-constructor-mode-item';
['day', 'week', 'month', 'quarter'].forEach(interval => {
const option = document.createElement('option');
option.value = interval;
option.text = interval;
intervalDropdown.appendChild(option);
});
intervalDropdown.value = this.state.intervals.intervalType || 'day';
intervalDropdown.addEventListener('change', (event) => {
this.state.intervals.intervalType = event.target.value;
});
intervalOptionsWrapper.appendChild(intervalDropdown);
// TODO - 🟡 - intervals limit not working
const numberInput = document.createElement('input');
numberInput.id = 'req-constructor-noOfIntervals';
numberInput.className = 'req-constructor-mode-item';
numberInput.type = 'number';
numberInput.min = '1';
numberInput.max = '7';
numberInput.placeholder = '2';
numberInput.value = this.state.intervals.noOfIntervals || 3;
numberInput.addEventListener('change', (event) => {
this.state.intervals.noOfIntervals = event.target.value;
});
intervalOptionsWrapper.appendChild(numberInput);
const dateInput = document.createElement('input');
dateInput.id = 'req-constructor-interval-startDate';
dateInput.className = 'req-constructor-mode-item';
dateInput.type = 'date';
dateInput.value = this.state.intervals.startDate || new Date().toISOString().split('T')[0];
dateInput.addEventListener('change', (event) => {
this.state.intervals.startDate = event.target.value;
});
intervalOptionsWrapper.appendChild(dateInput);
intervalsSection.appendChild(intervalOptionsWrapper);
return intervalsSection;
}
#createTotalsSection() {
const totalsSection = document.createElement('div');
totalsSection.id = 'req-constructor-totalsSection';
totalsSection.className = 'req-constructor-modeWrapper';
const constructorModeRadio = document.createElement('div');
constructorModeRadio.className = 'req-constructor-mode-radio';
const totalsRadio = document.createElement('input');
totalsRadio.type = 'radio';
totalsRadio.id = 'req-constructor-totals';
totalsRadio.name = 'analysisMode';
totalsRadio.value = 'totals';
if (this.state.analysisMode === 'totals') {
totalsRadio.checked = true;
}
totalsRadio.addEventListener('change', () => {
this.state.analysisMode = 'totals';
this.#updateFilterStateForTotals();
this.#toggleOptionsState();
});
const totalsLabel = document.createElement('label');
totalsLabel.htmlFor = totalsRadio.id;
totalsLabel.className = 'req-constructor-label';
totalsLabel.textContent = this._langTranslations.t('totals');
constructorModeRadio.appendChild(totalsRadio);
constructorModeRadio.appendChild(totalsLabel);
totalsSection.appendChild(constructorModeRadio);
const totalOptionsWrapper = document.createElement('div');
totalOptionsWrapper.id = 'req-constructor-totalOptionsWrapper';
totalOptionsWrapper.className = 'req-constructor-mode-options-wrapper';
const totalsDateRangeModeDropdown = document.createElement('select');
totalsDateRangeModeDropdown.id = 'req-constructor-totalsDateRangeMode';
totalsDateRangeModeDropdown.className = 'req-constructor-mode-item';
Object.keys(VALID_TOTALS_DATE_RANGE_MODES).forEach(mode => {
const option = document.createElement('option');
option.value = mode;
option.text = `${mode} i18n`;
totalsDateRangeModeDropdown.appendChild(option);
});
const { totalsDateRangeMode, startDate, endDate } = this.#getTotalsDateRangeMode();
totalsDateRangeModeDropdown.value = totalsDateRangeMode;
totalsDateRangeModeDropdown.addEventListener('change', () => {
this.#updateFilterStateForTotals();
});
totalOptionsWrapper.appendChild(totalsDateRangeModeDropdown);
const startDatePicker = document.createElement('input');
startDatePicker.id = 'req-constructor-totals-startDate';
startDatePicker.className = 'req-constructor-mode-item';
startDatePicker.type = 'date';
startDatePicker.value = startDate;
startDatePicker.addEventListener('change', () => {
this.#updateFilterStateForTotals();
});
totalOptionsWrapper.appendChild(startDatePicker);
const endDatePicker = document.createElement('input');
endDatePicker.id = 'req-constructor-totals-endDate';
endDatePicker.className = 'req-constructor-mode-item';
endDatePicker.type = 'date';
endDatePicker.value = endDate;
endDatePicker.addEventListener('change', () => {
this.#updateFilterStateForTotals();
});
totalOptionsWrapper.appendChild(endDatePicker);
totalsSection.appendChild(totalOptionsWrapper);
return totalsSection;
}
#toggleOptionsState() {
const wrappers = document.querySelectorAll('.req-constructor-mode-options-wrapper');
wrappers.forEach(wrapper => {
const radio = wrapper.previousElementSibling.querySelector('input[type="radio"]');
const disabled = !radio.checked;
// if (disabled) {
// wrapper.style.display = 'none';
// } else {
// wrapper.style.display = 'flex';
// }
Array.from(wrapper.children).forEach(child => {
child.disabled = disabled;
});
});
}
#addToggleCollapseExpandFeatures(div, title, initialState = 'expanded', type) {
// Create title element
const titleElement = document.createElement('span');
titleElement.className = 'req-constructor-title';
titleElement.innerText = title;
// Create caret element
const caretElement = document.createElement('itm-caret-up-down');
caretElement.className = 'req-constructor-caret';
caretElement.value = initialState === 'collapsed' ? 'down' : 'up'; // set caret based on initialState
caretElement.title = initialState === 'collapsed' ? 'Expand' : 'Collapse';
// Append title and caret to the div
div.appendChild(titleElement);
div.appendChild(caretElement);
// Wrap the content inside a content div for smooth collapsing
const contentDiv = document.createElement('div');
contentDiv.className = 'req-constructor-content';
while (div.firstChild && div.firstChild !== titleElement && div.firstChild !== caretElement) {
contentDiv.appendChild(div.firstChild);
}
div.appendChild(contentDiv);
// Set initial state based on the parameter
if (initialState === 'collapsed') {
div.classList.add('collapsed');
div.classList.add('req-constructor-toggle-reduced-padding');
contentDiv.style.maxHeight = '0';
} else {
div.classList.remove('collapsed');
div.classList.remove('req-constructor-toggle-reduced-padding');
contentDiv.style.maxHeight = contentDiv.scrollHeight + 'px';
}
// Add event listener for the caret
caretElement.addEventListener('click', () => {
if (div.classList.contains('collapsed')) {
div.classList.remove('collapsed');
div.classList.remove('req-constructor-toggle-reduced-padding');
caretElement.innerText = '▲';
caretElement.title = 'Collapse';
contentDiv.style.maxHeight = contentDiv.scrollHeight + 'px';
localStorage.setItem(div.id + 'ToggleState', 'expanded');
} else {
div.classList.add('collapsed');
div.classList.add('req-constructor-toggle-reduced-padding');
caretElement.innerText = '▼';
caretElement.title = 'Expand';
contentDiv.style.maxHeight = '0';
localStorage.setItem(div.id + 'ToggleState', 'collapsed');
}
// Update title based on new state
titleElement.innerText = type === 'mode' ? this.#modesWrapperTitle(localStorage.getItem(div.id + 'ToggleState')) : this.#filterWrapperTitle(localStorage.getItem(div.id + 'ToggleState'));
});
// Ensure the initial maxHeight is set correctly after the content is loaded
setTimeout(() => {
if (!div.classList.contains('collapsed')) {
contentDiv.style.maxHeight = contentDiv.scrollHeight + 'px';
}
}, 0);
// Mutation Observer to watch for content changes
const observer = new MutationObserver(() => {
if (!div.classList.contains('collapsed')) {
contentDiv.style.maxHeight = contentDiv.scrollHeight + 'px';
}
});
// Observe the content changes inside the content div
observer.observe(contentDiv, { childList: true, subtree: true });
}
#updateFilterStateForTotals() {
const totalsDateRangeMode = document.getElementById('req-constructor-totalsDateRangeMode').value;
const startDate = document.getElementById('req-constructor-totals-startDate').value;
const endDate = document.getElementById('req-constructor-totals-endDate').value;
this.state.totals = { dateRangeMode: totalsDateRangeMode, startDate, endDate };
}
#getTotalsDateRangeMode() {
const totalsDateRangeMode = this.state.totals.dateRangeMode || VALID_TOTALS_DATE_RANGE_MODES.liveBetween;
const startDate = this.state.totals.startDate || new Date().toISOString().split('T')[0];
const endDate = this.state.totals.endDate || new Date().toISOString().split('T')[0];
return { totalsDateRangeMode, startDate, endDate };
}
/* LEFT OFF:
- Totals dates are already coming from the params, in state.totals. Add test cases (empty, filled)
- Possibly improve the validator to check for the totals object, dates make sense, etc.
- User selected totals must return in the event, so it saves in the template and retrieves data based on it
- Mix preFilter, filter and totals in the request object (resourceAnalysis)
*/
#updateRequest() {
const newRequestObject = {
analysisMode: this.state.analysisMode,
filter: this.state.filter,
intervals: this.state.intervals,
totals: this.state.totals
};
const event = new CustomEvent('resourceAnalysisRequestUpdated', {
detail: newRequestObject,
bubbles: true
});
document.dispatchEvent(event);
}
#getStyles() {
return css`
:root {
--req-constructor-select-border-radius: 4px;
--req-constructor-select-border-color: #999;
--req-constructor-input-border-radius: 4px;
--req-constructor-standard-select-width: 10em;
--req-constructor-standard-input-width: 8em;
--req-constructor-close-cross-fill: #6d7d8f;
--req-constructor-close-cross-fill-hover: #3a4a5c;
}
.req-constructor-modesWrapper {
border: 1px solid #ccc;
border-radius: 3px;
padding: 1.8em;
position: relative;
margin-bottom: 1em;
}
.req-constructor-filterWrapper {
border: 1px solid #ccc;
border-radius: 3px;
padding: 1.8em;
position: relative;
}
.req-constructor-toggle-reduced-padding{
padding: .8em;
}
.req-constructor-title {
position: absolute;
top: -10px;
left: 10px;
background: white;
padding: 0 5px;
}
.req-constructor-caret {
position: absolute;
top: -10px;
right: 10px;
cursor: pointer;
background: white;
padding: 0 5px;
}
.req-constructor-content {
overflow: hidden;
transition: max-height 0.3s ease-out;
}
.collapsed .req-constructor-content {
max-height: 0;
}
.req-constructor-modeWrapper {
display: flex;
align-items: center;
margin-bottom: 5px;
}
.req-constructor-mode-options-wrapper {
display: flex;
align-items: center;
margin-left: 10px;
}
.req-constructor-mode-radio{
width: 8em;
}
.req-constructor-mode-options-wrapper {
display: flex;
align-items: center;
}
.req-constructor-mode-options-wrapper select {
margin-right: .6em;
padding: 3px;
border-color: var(--req-constructor-select-border-color);
border-radius: var(--req-constructor-select-border-radius);
}
.req-constructor-mode-options-wrapper input {
margin-right: .6em;
padding: 3px;
border: 1px solid var(--req-constructor-select-border-color);
border-radius: var(--req-constructor-input-border-radius);
}
.req-constructor-label {
margin-left: .4em;
}
.req-constructor-buttonDiv-wrapper{
display: flex;
justify-content: flex-start;
margin: 1em 0;
align-items: center;
}
`;
}
}