-
Notifications
You must be signed in to change notification settings - Fork 118
Expand file tree
/
Copy pathTableView.ts
More file actions
589 lines (542 loc) · 24.1 KB
/
Copy pathTableView.ts
File metadata and controls
589 lines (542 loc) · 24.1 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
589
/**
* This program and the accompanying materials are made available under the terms of the
* Eclipse Public License v2.0 which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v20.html
*
* SPDX-License-Identifier: EPL-2.0
*
* Copyright Contributors to the Zowe Project.
*
*/
import { UriPair, WebView } from "./WebView";
import { Event, EventEmitter, ExtensionContext, env } from "vscode";
import { randomUUID } from "crypto";
import { diff } from "deep-object-diff";
import { TableMediator } from "./utils/TableMediator";
import * as vscode from "vscode";
import * as fs from "fs";
export namespace Table {
/* The types of supported content for the table and how they are represented in callback functions. */
export type ContentTypes = string | number | boolean | string[];
export type RowData = Record<string | number, ContentTypes>;
export type ColData = RowData;
export type RowInfo = {
index?: number;
row: RowData;
};
/* Defines the supported callbacks and related types. */
export type CallbackTypes = "single-row" | "multi-row" | "column" | "cell";
export type SingleRowCallback = {
/** The type of callback */
typ: "single-row";
/** The callback function itself - called from within the webview container. */
fn: (view: Table.View, row: RowInfo) => void | PromiseLike<void>;
};
export type MultiRowCallback = {
/** The type of callback */
typ: "multi-row";
/** The callback function itself - called from within the webview container. */
fn: (view: Table.View, rows: Record<number, RowData>) => void | PromiseLike<void>;
};
export type CellCallback = {
/** The type of callback */
typ: "cell";
/** The callback function itself - called from within the webview container. */
fn: (view: Table.View, cell: ContentTypes) => void | PromiseLike<void>;
};
export type ColumnCallback = {
/** The type of callback */
typ: "column";
/** The callback function itself - called from within the webview container. */
fn: (view: Table.View, col: ColData) => void | PromiseLike<void>;
};
export type Callback = SingleRowCallback | MultiRowCallback | CellCallback;
/** Conditional callback function - whether an action or option should be rendered. */
export type Conditional = (data: RowData[] | RowData | ContentTypes) => boolean;
// Defines the supported actions and related types.
export type ActionKind = "primary" | "secondary" | "icon";
export type Action = {
title: string;
command: string;
type?: ActionKind;
/** Stringified function will be called from within the webview container. */
condition?: string;
callback: Callback;
};
export type ContextMenuOption = Omit<Action, "type"> & { dataType?: CallbackTypes };
// Helper types to allow passing function properties to builder/view functions.
export type ActionOpts = Omit<Action, "condition"> & { condition?: Conditional };
export type ContextMenuOpts = Omit<ContextMenuOption, "condition"> & { condition?: Conditional };
// -- Misc types --
/** Value formatter callback. Expects the exact display value to be returned. */
export type ValueFormatter = (data: { value: ContentTypes }) => string;
export type Positions = "left" | "right";
/** The column type definition. All available properties are offered for AG Grid columns. */
export type Column = {
field: string;
type?: string | string[];
cellDataType?: boolean | string;
valueFormatter?: string;
checkboxSelection?: boolean;
icons?: { [key: string]: string };
suppressNavigable?: boolean;
context?: any;
// Locking and edit variables
hide?: boolean;
lockVisible?: boolean;
lockPosition?: boolean | Positions;
suppressMovable?: boolean;
editable?: boolean;
singleClickEdit?: boolean;
filter?: boolean;
floatingFilter?: boolean;
// Headers
// "field" variable will be used as header name if not provided
headerName?: string;
headerTooltip?: string;
headerClass?: string | string[];
wrapHeaderText?: boolean;
autoHeaderHeight?: boolean;
headerCheckboxSelection?: boolean;
// Pinning
pinned?: boolean | Positions | null;
initialPinned?: boolean | Positions;
lockPinned?: boolean;
// Row dragging
rowDrag?: boolean;
dndSource?: boolean;
// Sorting
sortable?: boolean;
sort?: "asc" | "desc";
initialSort?: "asc" | "desc";
sortIndex?: number | null;
initialSortIndex?: number;
sortingOrder?: ("asc" | "desc")[];
comparator?: string;
unSortIcon?: boolean;
// Column/row spanning
colSpan?: string;
rowSpan?: string;
// Sizing
width?: number;
initialWidth?: number;
minWidth?: number;
maxWidth?: number;
flex?: number;
initialFlex?: number;
resizable?: boolean;
suppressSizeToFit?: boolean;
suppressAutoSize?: boolean;
};
export type ColumnOpts = Omit<Column, "comparator" | "colSpan" | "rowSpan" | "valueFormatter"> & {
comparator?: (valueA: any, valueB: any, nodeA: any, nodeB: any, isDescending: boolean) => number;
colSpan?: (params: any) => number;
rowSpan?: (params: any) => number;
valueFormatter?: ValueFormatter;
};
export interface SizeColumnsToFitGridStrategy {
type: "fitGridWidth";
// Default minimum width for every column (does not override the column minimum width).
defaultMinWidth?: number;
// Default maximum width for every column (does not override the column maximum width).
defaultMaxWidth?: number;
// Provide to limit specific column widths when sizing.
columnLimits?: SizeColumnsToFitGridColumnLimits[];
}
export interface SizeColumnsToFitGridColumnLimits {
colId: string;
// Minimum width for this column (does not override the column minimum width)
minWidth?: number;
// Maximum width for this column (does not override the column maximum width)
maxWidth?: number;
}
export interface SizeColumnsToFitProvidedWidthStrategy {
type: "fitProvidedWidth";
width: number;
}
export interface SizeColumnsToContentStrategy {
type: "fitCellContents";
// If true, the header won't be included when calculating the column widths.
skipHeader?: boolean;
// If not provided will auto-size all columns. Otherwise will size the specified columns.
colIds?: string[];
}
// AG Grid: Optional properties
export type GridProperties = {
/** Allow reordering and pinning columns by dragging columns from the Columns Tool Panel to the grid */
allowDragFromColumnsToolPanel?: boolean;
/** Number of pixels to add a column width after the auto-sizing calculation */
autoSizePadding?: number;
/**
* Auto-size the columns when the grid is loaded. Can size to fit the grid width, fit a provided width or fit the cell contents.
* Read once during initialization.
*/
autoSizeStrategy?: SizeColumnsToFitGridStrategy | SizeColumnsToFitProvidedWidthStrategy | SizeColumnsToContentStrategy;
/** Set to 'shift' to have shift-resize as the default resize operation */
colResizeDefault?: "shift";
/** Changes the display type of the column menu. 'new' displays the main list of menu items; 'legacy' displays a tabbed menu */
columnMenu?: "legacy" | "new";
/** Set this to `true` to enable debugging information from the grid */
debug?: boolean;
/** Set this to `true` to allow checkbox selection, no matter what row is visible. */
selectEverything?: boolean;
/** Set this to suppress row-click selection, in favor of checkbox selection. */
suppressRowClickSelection?: boolean;
/** The height in pixels for the rows containing floating filters. */
floatingFiltersHeight?: number;
/** The height in pixels for the rows containing header column groups. */
groupHeaderHeight?: number;
/** The height in pixels for the row contianing the column label header. Default provided by the AG Grid theme. */
headerHeight?: number;
/** Show/hide the "Loading" overlay */
loading?: boolean;
/** Map of key:value pairs for localizing grid text. Read once during initialization. */
localeText?: { [key: string]: string };
/** Keeps the order of columns maintained after new Column Definitions are updated. */
maintainColumnOrder?: boolean;
/** Whether the table should be split into pages. */
pagination?: boolean;
/**
* Set to `true` so that the number of rows to load per page is automatically adjusted by the grid.
* If `false`, `paginationPageSize` is used.
*/
paginationAutoPageSize?: boolean;
/** How many rows to load per page */
paginationPageSize?: number;
/**
* Set to an array of values to show the page size selector with custom list of possible page sizes.
* Set to `true` to show the page size selector with the default page sizes `[20, 50, 100]`.
* Set to `false` to hide the page size selector.
*/
paginationPageSizeSelector?: number[] | boolean;
/** If defined, rows are filtered using this text as a Quick Filter. */
quickFilterText?: string;
/** Enable selection of rows in table */
rowSelection?: "single" | "multiple";
/** Set to `true` to skip the `headerName` when `autoSize` is called by default. Read once during initialization. */
skipHeaderOnAutoSize?: boolean;
/**
* Suppresses auto-sizing columns for columns - when enabled, double-clicking a column's header's edge will not auto-size.
* Read once during initialization.
*/
suppressAutoSize?: boolean;
suppressColumnMoveAnimation?: boolean;
/** If `true`, when you dreag a column out of the grid, the column is not hidden */
suppressDragLeaveHidesColumns?: boolean;
/** If `true`, then dots in field names are not treated as deep references, allowing you to use dots in your field name if preferred. */
suppressFieldDotNotation?: boolean;
/**
* When `true`, the column menu button will always be shown.
* When `false`, the column menu button will only show when the mouse is over the column header.
* If `columnMenu = 'legacy'`, this will default to `false` instead of `true`.
*/
suppressMenuHide?: boolean;
/** Set to `true` to suppress column moving (fixed position for columns) */
suppressMovableColumns?: boolean;
};
export type ViewOpts = {
/** Actions to apply to the given row or column index */
actions: Record<number | "all", Action[]>;
/** Column definitions for the top of the table */
columns: Column[];
/** Context menu options for rows in the table */
contextOpts: Record<number | "all", ContextMenuOption[]>;
/** The row data for the table. Each row contains a set of variables corresponding to the data for each column in that row. */
rows: RowData[];
/** The display title for the table */
title?: string;
/** AG Grid-specific properties */
options?: GridProperties;
};
export type EditEvent = {
rowIndex: number;
field: string;
value: ContentTypes;
oldValue?: ContentTypes;
};
/**
* A class that acts as a controller between the extension and the table view. Based off of the {@link WebView} class.
*
* @remarks
* ## Usage
*
* To easily configure a table before creating a table view,
* use the `TableBuilder` class to prepare table data and build an instance.
*/
export class View extends WebView {
private lastUpdated: ViewOpts;
private data: ViewOpts = {
actions: {
all: [],
},
contextOpts: {
all: [],
},
rows: [],
columns: [],
title: "",
};
private onTableDataReceivedEmitter: EventEmitter<Partial<ViewOpts>> = new EventEmitter();
private onTableDisplayChangedEmitter: EventEmitter<RowData | RowData[]> = new EventEmitter();
private onTableDataEditedEmitter: EventEmitter<EditEvent> = new EventEmitter();
public onTableDisplayChanged: Event<RowData | RowData[]> = this.onTableDisplayChangedEmitter.event;
public onTableDataReceived: Event<Partial<ViewOpts>> = this.onTableDataReceivedEmitter.event;
public onTableDataEdited: Event<EditEvent> = this.onTableDataEditedEmitter.event;
private uuid: string;
public getUris(): UriPair {
return this.uris;
}
public getHtml(): string {
return this.htmlContent;
}
public constructor(context: ExtensionContext, isView?: boolean, data?: ViewOpts) {
super(data?.title ?? "Table view", "table-view", context, {
onDidReceiveMessage: (message) => this.onMessageReceived(message),
isView,
unsafeEval: true,
});
if (data) {
this.data = data;
}
}
/**
* (Receiver) message handler for the table view.
* Used to dispatch client-side updates of the table to subscribers when the table's display has changed.
*
* @param message The message received from the webview
*/
public async onMessageReceived(message: any): Promise<void> {
if (!("command" in message)) {
return;
}
switch (message.command) {
// "ontableedited" command: The table's contents were updated by the user from within the webview.
// Fires for editable columns only.
case "ontableedited":
this.onTableDataEditedEmitter.fire(message.data);
return;
// "ondisplaychanged" command: The table's layout was updated by the user from within the webview.
case "ondisplaychanged":
this.onTableDisplayChangedEmitter.fire(message.data);
return;
// "ready" command: The table view has attached its message listener and is ready to receive data.
case "ready":
await this.updateWebview();
return;
// "copy" command: Copy the data for the row that was right-clicked.
case "copy":
await env.clipboard.writeText(JSON.stringify(message.data.row));
return;
case "copy-cell":
await env.clipboard.writeText(message.data.cell);
return;
case "GET_LOCALIZATION": {
const filePath = vscode.l10n.uri?.fsPath + "";
fs.readFile(filePath, "utf8", (err, data) => {
if (err) {
// File doesn't exist, fallback to English strings
return;
}
(this.panel ?? this.view).webview.postMessage({
command: "GET_LOCALIZATION",
contents: data,
});
});
return;
}
default:
break;
}
const row: number = message.rowIndex ?? 0;
const matchingActionable = [
...(this.data.actions[row] ?? []),
...this.data.actions.all,
...(this.data.contextOpts[row] ?? []),
...this.data.contextOpts.all,
].find((action) => action.command === message.command);
if (matchingActionable != null) {
switch (matchingActionable.callback.typ) {
case "single-row":
await matchingActionable.callback.fn(this, { index: message.data.rowIndex, row: message.data.row });
break;
case "multi-row":
await matchingActionable.callback.fn(this, message.data.rows);
break;
case "cell":
await matchingActionable.callback.fn(this, message.data.cell);
break;
// TODO: Support column callbacks? (if there's enough interest)
default:
break;
}
}
}
/**
* (Sender) message handler for the table view.
* Used to send data and table layout changes to the table view to be re-rendered.
*
* @returns Whether the webview received the update that was sent
*/
private async updateWebview(): Promise<boolean> {
const result = await (this.panel ?? this.view).webview.postMessage({
command: "ondatachanged",
data: this.data,
});
if (result) {
this.onTableDataReceivedEmitter.fire(this.lastUpdated ? diff(this.lastUpdated, this.data) : this.data);
this.lastUpdated = this.data;
}
return result;
}
/**
* Access the unique ID for the table view instance.
*
* @returns The unique ID for this table view
*/
public getId(): string {
this.uuid ??= randomUUID();
return `${this.data.title}-${this.uuid.substring(0, this.uuid.indexOf("-"))}##${this.context.extension.id}`;
}
/**
* Add one or more actions to the given row.
*
* @param index The row index where the action should be displayed
* @param actions The actions to add to the given row
*
* @returns Whether the webview successfully received the new action(s)
*/
public addAction(index: number | "all", ...actions: ActionOpts[]): Promise<boolean> {
if (this.data.actions[index]) {
const existingActions = this.data.actions[index];
this.data.actions[index] = [...existingActions, ...actions.map((action) => ({ ...action, condition: action.condition?.toString() }))];
} else {
this.data.actions[index] = actions.map((action) => ({ ...action, condition: action.condition?.toString() }));
}
return this.updateWebview();
}
/**
* Add one or more context menu options to the given row.
*
* @param id The row index or column ID where the action should be displayed
* @param actions The actions to add to the given row
* @returns Whether the webview successfully received the new context menu option(s)
*/
public addContextOption(id: number | "all", ...options: ContextMenuOpts[]): Promise<boolean> {
if (this.data.contextOpts[id]) {
const existingOpts = this.data.contextOpts[id];
this.data.contextOpts[id] = [...existingOpts, ...options.map((option) => ({ ...option, condition: option.condition?.toString() }))];
} else {
this.data.contextOpts[id] = options.map((option) => ({ ...option, condition: option.condition?.toString() }));
}
return this.updateWebview();
}
/**
* Get rows of content from the table view.
* @param rows The rows of data in the table
* @returns Whether the webview successfully received the new content
*/
public getContent(): RowData[] {
return this.data.rows;
}
/**
* Add rows of content to the table view.
* @param rows The rows of data to add to the table
* @returns Whether the webview successfully received the new content
*/
public async addContent(...rows: RowData[]): Promise<boolean> {
this.data.rows.push(...rows);
return this.updateWebview();
}
/**
* Update an existing row in the table view.
* @param index The AG GRID row index to update within the table
* @param row The new row content. If `null`, the given row index will be deleted from the list of rows.
* @returns Whether the webview successfully updated the new row
*/
public async updateRow(index: number, row: RowData | null): Promise<boolean> {
if (row == null) {
this.data.rows.splice(index, 1);
} else {
this.data.rows[index] = row;
}
return this.updateWebview();
}
/**
* Adds headers to the end of the existing header list in the table view.
*
* @param headers The headers to add to the existing header list
* @returns Whether the webview successfully received the list of headers
*/
public async addColumns(...columns: ColumnOpts[]): Promise<boolean> {
this.data.columns.push(
...columns.map((col) => ({
...col,
comparator: col.comparator?.toString(),
colSpan: col.colSpan?.toString(),
rowSpan: col.rowSpan?.toString(),
valueFormatter: col.valueFormatter?.toString(),
}))
);
return this.updateWebview();
}
/**
* Sets the content for the table; replaces any pre-existing content.
*
* @param rows The rows of data to apply to the table
* @returns Whether the webview successfully received the new content
*/
public async setContent(rows: RowData[]): Promise<boolean> {
this.data.rows = rows;
return this.updateWebview();
}
/**
* Sets the headers for the table.
*
* @param headers The new headers to use for the table
* @returns Whether the webview successfully received the new headers
*/
public async setColumns(columns: ColumnOpts[]): Promise<boolean> {
this.data.columns = columns.map((col) => ({
...col,
comparator: col.comparator?.toString(),
colSpan: col.colSpan?.toString(),
rowSpan: col.rowSpan?.toString(),
valueFormatter: col.valueFormatter?.toString(),
}));
return this.updateWebview();
}
/**
* Sets the options for the table.
*
* @param opts The optional grid properties for the table
* @returns Whether the webview successfully received the new options
*/
public setOptions(opts: GridProperties): Promise<boolean> {
this.data = { ...this.data, options: this.data.options ? { ...this.data.options, ...opts } : opts };
return this.updateWebview();
}
/**
* Sets the display title for the table view.
*
* @param title The new title for the table
* @returns Whether the webview successfully received the new title
*/
public async setTitle(title: string): Promise<boolean> {
this.data.title = title;
return this.updateWebview();
}
}
export class Instance extends View {
public constructor(context: ExtensionContext, isView: boolean, data: Table.ViewOpts) {
super(context, isView, data);
}
/**
* Closes the table view and marks it as disposed.
* Removes the table instance from the mediator if it exists.
*/
public dispose(): void {
TableMediator.getInstance().removeTable(this);
super.dispose();
}
}
}