/
neo-table-viewer.js
401 lines (355 loc) · 12.2 KB
/
neo-table-viewer.js
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
import { html, LitElement } from 'https://cdn.jsdelivr.net/gh/lit/dist@2.6.1/all/lit-all.min.js';
export class MyTable extends LitElement {
static get properties() {
return {
errorMessage: { type: String },
};
}
static getMetaConfig() {
// plugin contract information
return {
controlName: 'neo-table-viewer',
fallbackDisableSubmit: false,
description: 'Display object as a table',
iconUrl: "group-control",
groupName: 'Visual Data',
version: '1.3',
properties: {
dataobject: {
type: 'string',
title: 'Object',
description: 'JSON or XML data variable'
},
datatype: {
title: 'Object Data Type',
type: 'string',
enum: ['JSON', 'XML'],
showAsRadio: true,
verticalLayout: true,
defaultValue: 'JSON',
},
replaceKeys: {
type: 'string',
title: 'Rename keys JSON',
description: 'Use key-value pairs to rename columns e.g. {"keyMappings": {"oldKey1": "newKey1","oldKey2": "newKey2"}}'
},
pageItemLimit: {
type: 'string',
enum: ['5', '10', '15', '30', '50', '100'],
title: 'Page Item Limit',
description: 'Number of items to show per page',
defaultValue: '5',
}
},
events: ["ntx-value-change"],
standardProperties: {
fieldLabel: true,
readOnly: true,
required: true,
description: true,
},
};
}
static properties = {
dataobject: '',
datatype: '',
replaceKeys: '',
prefDateFormat: '',
pageItemLimit: { type: Number },
currentPage: { type: Number },
};
static get properties() {
return {
itemsPerPage: { type: Number },
currentPage: { type: Number },
};
}
constructor() {
super();
this.dataobject = '';
this.replaceKeys = '';
this.prefDateFormat = '';
this.pageItemLimit = "5";
this.currentPage = 1;
this.errorMessage = '';
}
preprocessDoubleEscapedJson(jsonString) {
// Replace double-escaped sequences with single-escaped sequences
let normalizedJsonString = jsonString.replace(/\\\\/g, '\\');
normalizedJsonString = normalizedJsonString.replace(/"/ig, '"');
// Normalize the key names by removing extra spaces after colons in the keys
normalizedJsonString = normalizedJsonString.replace(/:\\"/g, ': \\"');
return normalizedJsonString;
}
parseDataObject() {
let data;
this.errorMessage = '';
if (!this.datatype) {
this.errorMessage = "Object data type not configured, please update the plugin properties and specify the data type.";
console.error(this.errorMessage);
return null;
}
// Check if dataobject is empty or undefined
if (!this.dataobject) {
console.error("No JSON data provided.");
return null;
}
if (this.datatype === 'JSON') {
try {
// Preprocess the JSON string to handle double escaping and normalize key names
const processedData = this.preprocessDoubleEscapedJson(this.dataobject);
data = JSON.parse(processedData);
// Additional check if data is still a string indicating further encoding
if (typeof data === 'string') {
data = JSON.parse(data);
}
data = this.replaceUnicodeRegex(data); // Apply Unicode replacements
} catch (e) {
this.errorMessage = "Error parsing JSON data.";
console.error(this.errorMessage, e);
data = null;
}
} else if (this.datatype === 'XML') {
try {
data = this.parseXmlDataObject();
} catch (e) {
this.errorMessage = "Error parsing XML data.";
console.error(this.errorMessage, e);
data = null;
}
} else {
this.errorMessage = `Unsupported data type: ${this.datatype}.`;
console.error(this.errorMessage);
data = null;
}
if (this.replaceKeys && data) {
data = this.renameKeys(data);
}
return data;
}
renameKeys(data) {
// Parse the JSON string to get the key mappings
const keyMappings = JSON.parse(this.replaceKeys).keyMappings;
// Map over each object in data array and replace keys as necessary
const newData = data.map(obj => {
const newObj = {};
for (const key in obj) {
const newKey = keyMappings[key] || key; // Get the new key if it exists in the map, otherwise use the old key
newObj[newKey] = obj[key];
}
return newObj;
});
// Check for any old keys left unmapped
const unmappedKeys = Object.keys(keyMappings).filter(oldKey => !Object.values(data).some(obj => obj.hasOwnProperty(oldKey)));
if (unmappedKeys.length > 0) {
console.warn('The following old keys are not found in the data and will not be renamed:', unmappedKeys);
}
return newData;
}
replaceUnicodeRegex(input) {
const unicodeRegex = /_x([0-9A-F]{4})_/g;
return JSON.parse(JSON.stringify(input).replace(unicodeRegex, (match, p1) => String.fromCharCode(parseInt(p1, 16))));
}
parseXmlDataObject() {
let xmlString = this.dataobject.replace(/"/g, '"').replace(/_x([\dA-F]{4})_/gi, (match, p1) => String.fromCharCode(parseInt(p1, 16)));
// Remove XML declaration if present
xmlString = xmlString.replace(/<\?xml.*?\?>/, '');
const parser = new DOMParser();
const xmlDocument = parser.parseFromString(xmlString, 'text/xml');
const items = xmlDocument.querySelector('RepeaterData > Items').children;
const data = [];
for (let i = 0; i < items.length; i++) {
const row = {};
const fields = items[i].children;
for (let j = 0; j < fields.length; j++) {
const field = fields[j];
const fieldName = field.nodeName;
let fieldValue = field.textContent;
fieldValue = fieldValue.replace(/_x([\dA-F]{4})_/gi, (match, p1) => String.fromCharCode(parseInt(p1, 16)));
row[fieldName] = fieldValue;
}
data.push(row);
}
if (this.replaceKeys && data) {
return this.renameKeys(data);
}
return data;
}
changePage(newPage) {
if (newPage > 0 && newPage <= this.totalPages) {
this.currentPage = newPage;
this.requestUpdate();
}
}
renderField(field) {
if (Array.isArray(field)) {
return html`
<table class="table mb-2 p-1">
<tbody>
${field.map(item => html`
<tr>
<td>${this.renderField(item)}</td>
</tr>
`)}
</tbody>
</table>
`;
} else if (typeof field === 'object' && field !== null) {
// Check if the object contains nested JSON
if (Object.values(field).some(value => Array.isArray(value))) {
return html`
${Object.entries(field).map(([key, value]) => {
if (Array.isArray(value)) {
return html`
<tr>
<td class="nested-table">
<table class="table mb-2 p-1">
<tbody>
<tr>
<th>${key}</th>
</tr>
${value.map(item => html`
<tr>
<td>${this.renderField(item)}</td>
</tr>
`)}
</tbody>
</table>
</td>
</tr>
`;
} else {
return html`
<tr>
<th>${key}</th>
<td>${this.renderField(value)}</td>
</tr>
`;
}
})}
`;
} else {
// Render simple object
return html`
<ul class="nested-list">
${Object.entries(field).map(([key, value]) => html`
<li>${value !== null ? value : '-'}</li>
`)}
</ul>
`;
}
} else {
return field !== null ? field : '-';
}
}
renderNestedTable(data) {
return html`
<table class="table mb-2 p-1">
<tbody>
${Object.entries(data).map(([key, value]) => html`
<tr>
<th>${key}</th>
<td>
${Array.isArray(value) ? this.renderNestedTable(value) : value}
</td>
</tr>
`)}
</tbody>
</table>
`;
}
render() {
const data = this.parseDataObject();
// Display error message if present
if (this.errorMessage) {
return html`<p class="error-message">${this.errorMessage}</p>`;
}
if (!data || data.length === 0) {
return html`
<div class="alert alert-secondary" role="alert">
No Data Found
</div>
`;
}
const startIndex = (this.currentPage - 1) * parseInt(this.pageItemLimit, 10);
const endIndex = startIndex + parseInt(this.pageItemLimit, 10);
const paginatedData = data.slice(startIndex, endIndex);
const totalPages = Math.ceil(data.length / parseInt(this.pageItemLimit, 10));
this.totalPages = totalPages; // Assign to component property
// Calculate the range of pages to display
const maxPagesToShow = 5;
const pageRange = Math.min(totalPages, maxPagesToShow);
let startPage = Math.max(1, this.currentPage - Math.floor(pageRange / 2));
const endPage = Math.min(totalPages, startPage + pageRange - 1);
// Adjust startPage if it exceeds the valid range
if (endPage - startPage + 1 < pageRange) {
startPage = Math.max(1, endPage - pageRange + 1);
}
return html`
<style>
.page-txt-link {
width: 100px;
text-align:center;
}
.page-num-link {
width: 45px;
text-align:center;
}
.neo-table {
-moz-user-select: text;
-khtml-user-select: text;
-webkit-user-select: text;
-ms-user-select: text;
user-select: text;
}
</style>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
<div class="table-responsive-md overflow-auto">
<table class="neo-table table table-striped">
<thead>
<tr>
${Object.keys(data[0]).map(header => html`<th class="text-nowrap">${header}</th>`)}
</tr>
</thead>
<tbody>
${paginatedData.map(row => html`
<tr>
${Object.values(row).map(value => html`
<td>
${Array.isArray(value) ? this.renderNestedTable(value) : value}
</td>
`)}
</tr>
`)}
</tbody>
</table>
</div>
<div class="row">
${totalPages > 1 ? html`
<nav aria-label="Page navigation">
<ul class="pagination justify-content-center">
<li class="page-item ${this.currentPage === 1 ? 'disabled' : ''}">
<a class="page-link page-txt-link" href="#" @click="${() => this.changePage(1)}">First</a>
</li>
<li class="page-item ${this.currentPage === 1 ? 'disabled' : ''}">
<a class="page-link page-txt-link" href="#" @click="${() => this.changePage(this.currentPage - 1)}">Previous</a>
</li>
${Array.from({ length: endPage - startPage + 1 }, (_, i) => i + startPage).map(page => html`
<li class="page-item ${page === this.currentPage ? 'active' : ''}">
<a class="page-link page-num-link" href="#" @click="${() => this.changePage(page)}">${page}</a>
</li>
`)}
<li class="page-item ${this.currentPage === totalPages ? 'disabled' : ''}">
<a class="page-link page-txt-link" href="#" @click="${() => this.changePage(this.currentPage + 1)}">Next</a>
</li>
<li class="page-item ${this.currentPage === totalPages ? 'disabled' : ''}">
<a class="page-link page-txt-link" href="#" @click="${() => this.changePage(totalPages)}">Last</a>
</li>
</ul>
</nav>
` : ''}
</div>
`;
}
}
customElements.define('neo-table-viewer', MyTable);