-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
564 lines (527 loc) · 19.7 KB
/
index.ts
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
require("./index.scss");
require("datatables.net-dt/css/jquery.dataTables.css");
require("datatables.net");
//@ts-ignore (jquery _does_ expose a default. In es6, it's the one we should use)
import $ from "jquery";
import { escape } from "lodash-es";
import { cloneDeep } from "lodash-es";
import { Plugin, DownloadInfo } from "../";
import {
drawSvgStringAsElement,
drawFontAwesomeIconAsSvg,
addClass,
removeClass,
} from "../";
import { Yasr } from "../";
import * as faTableIcon from "@fortawesome/free-solid-svg-icons/faTable";
import { DeepReadonly } from "ts-essentials";
import Parser from "../parsers";
import { TableXResults } from "../TableXResults";
const ColumnResizer = require("column-resizer");
const DEFAULT_PAGE_SIZE = 50;
export interface PluginConfig {
openIriInNewWindow: boolean;
tableConfig: DataTables.Settings;
includeControls: boolean;
excludeColumnsFromCompactView: string[];
uriHrefAdapter?: (uri: string) => string;
bindingSetAdapter?: (binding: Parser.Binding) => Parser.Binding;
}
export interface PersistentConfig {
pageSize?: number;
compact?: boolean;
isEllipsed?: boolean;
}
type DataRow = [number, ...(Parser.BindingValue | "")[]];
function expand(this: HTMLDivElement, event: MouseEvent) {
addClass(this, "expanded");
event.preventDefault();
}
export class TableX implements Plugin<PluginConfig> {
private config: DeepReadonly<PluginConfig>;
private persistentConfig: PersistentConfig = {};
private yasr: Yasr;
private tableControls: Element | undefined;
private tableEl: HTMLTableElement | undefined;
private dataTable: DataTables.Api | undefined;
private tableFilterField: HTMLInputElement | undefined;
private tableSizeField: HTMLSelectElement | undefined;
private tableCompactSwitch: HTMLInputElement | undefined;
private tableEllipseSwitch: HTMLInputElement | undefined;
private tableResizer:
| {
reset: (options: {
disable: boolean;
onResize?: () => void;
partialRefresh?: boolean;
headerOnly?: boolean;
}) => void;
onResize: () => {};
}
| undefined;
// public helpReference = "https://github.com/sparna-git/sparnatural-yasgui-plugins";
public label = "Table";
public priority = 10;
// ***** TableX MODIFICATION
private results: Parser | undefined;
// ***** end TableX MODIFICATION
public getIcon() {
return drawSvgStringAsElement(drawFontAwesomeIconAsSvg(faTableIcon));
}
constructor(yasr: Yasr) {
this.yasr = yasr;
this.results = undefined;
//TODO read options from constructor
this.config = TableX.defaults;
}
// ***** TableX MODIFICATION
private postProcessRawResults(
results: Parser | undefined
): Parser | undefined {
if (results) {
return new TableXResults(results, this.config.bindingSetAdapter);
}
}
// ***** end TableX MODIFICATION
public static defaults: PluginConfig = {
openIriInNewWindow: true,
includeControls: false,
tableConfig: {
dom: "tip", // tip: Table, Page Information and Pager, change to ipt for showing pagination on top
pageLength: DEFAULT_PAGE_SIZE, //default page length
lengthChange: true, //allow changing page length
data: [],
columns: [],
order: [],
deferRender: true,
orderClasses: false,
language: {
paginate: {
first: "<<", // Have to specify these two due to TS defs, <<
last: ">>", // Have to specify these two due to TS defs, >>
next: ">", // >
previous: "<", // <
},
},
},
excludeColumnsFromCompactView: [],
uriHrefAdapter: undefined,
};
private getRows(): DataRow[] {
if (!this.results) return [];
const bindings = this.results.getBindings();
if (!bindings) return [];
// Vars decide the columns
const vars = this.results.getVariables();
// Use "" as the empty value, undefined will throw runtime errors
return bindings.map((binding, rowId) => [
rowId + 1,
...vars.map((variable) => binding[variable] ?? ""),
]);
}
private getUriLinkFromBinding(
binding: Parser.BindingValue,
prefixes?: { [key: string]: string }
) {
// ***** TableX MODIFICATION
const href = this.config.uriHrefAdapter
? this.config.uriHrefAdapter(binding.value)
: binding.value;
let visibleString = binding.value;
// ***** TableX MODIFICATION
let prefixed = false;
if (prefixes) {
for (const prefixLabel in prefixes) {
if (visibleString.indexOf(prefixes[prefixLabel]) == 0) {
visibleString =
prefixLabel + ":" + href.substring(prefixes[prefixLabel].length);
prefixed = true;
break;
}
}
}
// Hide brackets when prefixed or compact
const hideBrackets = prefixed || this.persistentConfig.compact;
return `${hideBrackets ? "" : "<"}<a class='iri' target='${
this.config.openIriInNewWindow ? "_blank" : "_self"
}'${
this.config.openIriInNewWindow ? " ref='noopener noreferrer'" : ""
} href='${href}'>${visibleString}</a>${hideBrackets ? "" : ">"}`;
}
// ***** TableX MODIFICATION
private getLabelledUriLinkFromBinding(binding: any) {
const href = this.config.uriHrefAdapter
? this.config.uriHrefAdapter(binding.value)
: binding.value;
let visibleString = binding.label;
// Hide brackets when prefixed or compact
return `<a class='iri' target='${
this.config.openIriInNewWindow ? "_blank" : "_self"
}'${
this.config.openIriInNewWindow ? " ref='noopener noreferrer'" : ""
} href='${href}'>${visibleString}</a>`;
}
// ***** end TableX MODIFICATION
private getCellContent(
binding: Parser.BindingValue,
prefixes?: { [label: string]: string }
): string {
let content: string;
if (binding.type == "uri") {
content = `<span>${this.getUriLinkFromBinding(binding, prefixes)}</span>`;
// ***** TableX MODIFICATION
} else if (binding.type == "x-labelled-uri") {
content = `<span>${this.getLabelledUriLinkFromBinding(binding)}</span>`;
// ***** end TableX MODIFICATION
} else {
content = `<span class='nonIri'>${this.formatLiteral(
binding,
prefixes
)}</span>`;
}
return `<div>${content}</div>`;
}
private formatLiteral(
literalBinding: Parser.BindingValue,
prefixes?: { [key: string]: string }
) {
let stringRepresentation = escape(literalBinding.value);
// Return now when in compact mode.
if (this.persistentConfig.compact) return stringRepresentation;
if (literalBinding["xml:lang"]) {
stringRepresentation = `"${stringRepresentation}"<sup>@${literalBinding["xml:lang"]}</sup>`;
} else if (literalBinding.datatype) {
const dataType = this.getUriLinkFromBinding(
{ type: "uri", value: literalBinding.datatype },
prefixes
);
stringRepresentation = `"${stringRepresentation}"<sup>^^${dataType}</sup>`;
}
return stringRepresentation;
}
private getColumns(): DataTables.ColumnSettings[] {
if (!this.results) return [];
const prefixes = this.yasr.getPrefixes();
return [
// this is the special row number column, which is hidden when in "compact mode"
{
name: "",
searchable: false,
width: `${this.getSizeFirstColumn()}px`,
type: "num",
orderable: false,
visible: this.persistentConfig.compact !== true,
render: (data: number, type: any) =>
type === "filter" || type === "sort" || !type
? data
: `<div class="rowNumber">${data}</div>`,
}, //prepend with row numbers column
...this.results?.getVariables().map((name) => {
return <DataTables.ColumnSettings>{
name: name,
title: name,
visible: (this.persistentConfig.compact)?(this.config.excludeColumnsFromCompactView.indexOf(name) == -1):true,
render: (
data: Parser.BindingValue | "",
type: any,
_row: any,
_meta: DataTables.CellMetaSettings
) => {
// Handle empty rows
if (data === "") return data;
if (type === "filter" || type === "sort" || !type) {
// ***** TableX MODIFICATION
// for sorting : sort on label and not on URI
if(data.type == "x-labelled-uri") {
return data.label;
} else {
return data.value;
}
// ***** end TableX MODIFICATION
}
return this.getCellContent(data, prefixes);
},
};
}),
];
}
private getSizeFirstColumn() {
const numResults = this.results?.getBindings()?.length || 0;
return numResults.toString().length * 8;
}
public draw(persistentConfig: PersistentConfig) {
// ***** TableX MODIFICATION
this.results = this.postProcessRawResults(this.yasr.results);
// in addition, replace all references to this.yasr.results to to this.results
// ***** end TableX MODIFICATION
this.persistentConfig = { ...this.persistentConfig, ...persistentConfig };
this.tableEl = document.createElement("table");
const rows = this.getRows();
const columns = this.getColumns();
if (rows.length <= (persistentConfig?.pageSize || DEFAULT_PAGE_SIZE)) {
this.yasr.pluginControls;
addClass(this.yasr.rootEl, "isSinglePage");
} else {
removeClass(this.yasr.rootEl, "isSinglePage");
}
if (this.dataTable) {
this.destroyResizer();
this.dataTable.destroy(true);
this.dataTable = undefined;
}
this.yasr.resultsEl.appendChild(this.tableEl);
// reset some default config properties as they couldn't be initialized beforehand
const dtConfig: DataTables.Settings = {
...(cloneDeep(this.config.tableConfig) as unknown as DataTables.Settings),
pageLength: persistentConfig?.pageSize
? persistentConfig.pageSize
: DEFAULT_PAGE_SIZE,
data: rows,
columns: columns,
};
this.dataTable = $(this.tableEl).DataTable(dtConfig);
this.tableEl.style.removeProperty("width");
this.tableEl.style.width = this.tableEl.clientWidth + "px";
const widths = Array.from(this.tableEl.querySelectorAll("th")).map(
(h) => h.offsetWidth - 26
);
this.tableResizer = new ColumnResizer.default(this.tableEl, {
widths:
this.persistentConfig.compact === true
? widths
: [this.getSizeFirstColumn(), ...widths.slice(1)],
partialRefresh: true,
onResize:
this.persistentConfig.isEllipsed !== false && this.setEllipsisHandlers,
headerOnly: true,
});
// DataTables uses the rendered style to decide the widths of columns.
// Before a draw remove the ellipseTable styling
if (this.persistentConfig.isEllipsed !== false) {
this.dataTable?.on("preDraw", () => {
this.tableResizer?.reset({ disable: true });
removeClass(this.tableEl, "ellipseTable");
this.tableEl?.style.removeProperty("width");
this.tableEl?.style.setProperty(
"width",
this.tableEl.clientWidth + "px"
);
return true; // Indicate it should re-render
});
// After a draw
this.dataTable?.on("draw", () => {
if (!this.tableEl) return;
// Width of table after render, removing width will make it fall back to 100%
let targetSize = this.tableEl.clientWidth;
this.tableEl.style.removeProperty("width");
// Let's make sure the new size is not bigger
if (targetSize > this.tableEl.clientWidth)
targetSize = this.tableEl.clientWidth;
this.tableEl?.style.setProperty("width", `${targetSize}px`);
// Enable the re-sizer
this.tableResizer?.reset({
disable: false,
partialRefresh: true,
onResize: this.setEllipsisHandlers,
headerOnly: true,
});
// Re-add the ellipsis
addClass(this.tableEl, "ellipseTable");
// Check if cells need the ellipsisHandlers
this.setEllipsisHandlers();
});
}
this.drawControls();
// Draw again but with the events
if (this.persistentConfig.isEllipsed !== false) {
addClass(this.tableEl, "ellipseTable");
this.setEllipsisHandlers();
}
// if (this.tableEl.clientWidth > width) this.tableEl.parentElement?.style.setProperty("overflow", "hidden");
}
private setEllipsisHandlers = () => {
this.dataTable?.cells({ page: "current" }).every((rowIdx, colIdx) => {
const cell = this.dataTable?.cell(rowIdx, colIdx);
if (cell?.data() === "") return;
const cellNode = cell?.node() as HTMLTableCellElement;
if (cellNode) {
const content = cellNode.firstChild as HTMLDivElement;
if (
(content.firstElementChild?.getBoundingClientRect().width || 0) >
content.getBoundingClientRect().width
) {
if (!content.classList.contains("expandable")) {
addClass(content, "expandable");
content.addEventListener("click", expand, { once: true });
}
} else {
if (content.classList.contains("expandable")) {
removeClass(content, "expandable");
content.removeEventListener("click", expand);
}
}
}
});
};
private handleTableSearch = (event: KeyboardEvent) => {
this.dataTable
?.search((event.target as HTMLInputElement).value)
.draw("page");
};
private handleTableSizeSelect = (event: Event) => {
const pageLength = parseInt((event.target as HTMLSelectElement).value);
// Set page length
this.dataTable?.page.len(pageLength).draw("page");
// Store in persistentConfig
this.persistentConfig.pageSize = pageLength;
this.yasr.storePluginConfig("table", this.persistentConfig);
};
private handleSetCompactToggle = (event: Event) => {
// Store in persistentConfig
this.persistentConfig.compact = (event.target as HTMLInputElement).checked;
// Update the table
this.draw(this.persistentConfig);
this.yasr.storePluginConfig("table", this.persistentConfig);
};
private handleSetEllipsisToggle = (event: Event) => {
// Store in persistentConfig
this.persistentConfig.isEllipsed = (
event.target as HTMLInputElement
).checked;
// Update the table
this.draw(this.persistentConfig);
this.yasr.storePluginConfig("table", this.persistentConfig);
};
/**
* Draws controls on each update
*/
drawControls() {
// Remove old header
this.removeControls();
this.tableControls = document.createElement("div");
this.tableControls.className = "tableControls";
if (this.config.includeControls) {
// Compact switch
const toggleWrapper = document.createElement("div");
const switchComponent = document.createElement("label");
const textComponent = document.createElement("span");
textComponent.innerText = "Simple view";
addClass(textComponent, "label");
switchComponent.appendChild(textComponent);
addClass(switchComponent, "switch");
toggleWrapper.appendChild(switchComponent);
this.tableCompactSwitch = document.createElement("input");
switchComponent.addEventListener("change", this.handleSetCompactToggle);
this.tableCompactSwitch.type = "checkbox";
switchComponent.appendChild(this.tableCompactSwitch);
this.tableCompactSwitch.defaultChecked = !!this.persistentConfig.compact;
this.tableControls.appendChild(toggleWrapper);
// Ellipsis switch
const ellipseToggleWrapper = document.createElement("div");
const ellipseSwitchComponent = document.createElement("label");
const ellipseTextComponent = document.createElement("span");
ellipseTextComponent.innerText = "Ellipse";
addClass(ellipseTextComponent, "label");
ellipseSwitchComponent.appendChild(ellipseTextComponent);
addClass(ellipseSwitchComponent, "switch");
ellipseToggleWrapper.appendChild(ellipseSwitchComponent);
this.tableEllipseSwitch = document.createElement("input");
ellipseSwitchComponent.addEventListener(
"change",
this.handleSetEllipsisToggle
);
this.tableEllipseSwitch.type = "checkbox";
ellipseSwitchComponent.appendChild(this.tableEllipseSwitch);
this.tableEllipseSwitch.defaultChecked =
this.persistentConfig.isEllipsed !== false;
this.tableControls.appendChild(ellipseToggleWrapper);
// Create table filter
this.tableFilterField = document.createElement("input");
this.tableFilterField.className = "tableFilter";
this.tableFilterField.placeholder = "Filter query results";
this.tableFilterField.setAttribute("aria-label", "Filter query results");
this.tableControls.appendChild(this.tableFilterField);
this.tableFilterField.addEventListener("keyup", this.handleTableSearch);
}
// Create page wrapper
const pageSizerWrapper = document.createElement("div");
pageSizerWrapper.className = "pageSizeWrapper";
// Create label for page size element
const pageSizerLabel = document.createElement("span");
pageSizerLabel.textContent = "Page size: ";
pageSizerLabel.className = "pageSizerLabel";
pageSizerWrapper.appendChild(pageSizerLabel);
// Create page size element
this.tableSizeField = document.createElement("select");
this.tableSizeField.className = "tableSizer";
// Create options for page sizer
const options = [10, 50, 100, 1000, -1];
for (const option of options) {
const element = document.createElement("option");
element.value = option + "";
// -1 selects everything so we should call it All
element.innerText = option > 0 ? option + "" : "All";
// Set initial one as selected
if (this.dataTable?.page.len() === option) element.selected = true;
this.tableSizeField.appendChild(element);
}
pageSizerWrapper.appendChild(this.tableSizeField);
this.tableSizeField.addEventListener("change", this.handleTableSizeSelect);
this.tableControls.appendChild(pageSizerWrapper);
this.yasr.pluginControls.appendChild(this.tableControls);
}
download(filename?: string) {
return {
getData: () => this.yasr.results?.asCsv() || "",
contentType: "text/csv",
title: "Download result",
filename: `${filename || "queryResults"}.csv`,
} as DownloadInfo;
}
public canHandleResults() {
return (
!!this.yasr.results &&
this.yasr.results.getVariables() &&
this.yasr.results.getVariables().length > 0
);
}
private removeControls() {
// Unregister listeners and remove references to old fields
this.tableFilterField?.removeEventListener("keyup", this.handleTableSearch);
this.tableFilterField = undefined;
this.tableSizeField?.removeEventListener(
"change",
this.handleTableSizeSelect
);
this.tableSizeField = undefined;
this.tableCompactSwitch?.removeEventListener(
"change",
this.handleSetCompactToggle
);
this.tableCompactSwitch = undefined;
this.tableEllipseSwitch?.removeEventListener(
"change",
this.handleSetEllipsisToggle
);
this.tableEllipseSwitch = undefined;
// Empty controls
while (this.tableControls?.firstChild)
this.tableControls.firstChild.remove();
this.tableControls?.remove();
}
private destroyResizer() {
if (this.tableResizer) {
this.tableResizer.reset({ disable: true });
window.removeEventListener("resize", this.tableResizer.onResize);
this.tableResizer = undefined;
}
}
destroy() {
this.removeControls();
this.destroyResizer();
// According to datatables docs, destroy(true) will also remove all events
this.dataTable?.destroy(true);
this.dataTable = undefined;
removeClass(this.yasr.rootEl, "isSinglePage");
}
}