-
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathdb-table-widgets.component.ts
More file actions
429 lines (400 loc) · 13.2 KB
/
db-table-widgets.component.ts
File metadata and controls
429 lines (400 loc) · 13.2 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
import { CommonModule, Location } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatDialog, MatDialogModule } from '@angular/material/dialog';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { Title } from '@angular/platform-browser';
import { Router, RouterModule } from '@angular/router';
import { Angulartics2, Angulartics2OnModule } from 'angulartics2';
import { difference } from 'lodash-es';
import posthog from 'posthog-js';
import { UIwidgets } from 'src/app/consts/record-edit-types';
import { normalizeTableName } from 'src/app/lib/normalize';
import { TableField, Widget } from 'src/app/models/table';
import { CompanyService } from 'src/app/services/company.service';
import { ConnectionsService } from 'src/app/services/connections.service';
import { TablesService } from 'src/app/services/tables.service';
import { UiSettingsService } from 'src/app/services/ui-settings.service';
import { PlaceholderTableWidgetsComponent } from '../../../skeletons/placeholder-table-widgets/placeholder-table-widgets.component';
import { AlertComponent } from '../../../ui-components/alert/alert.component';
import { BreadcrumbsComponent } from '../../../ui-components/breadcrumbs/breadcrumbs.component';
import { WidgetComponent } from './widget/widget.component';
import { WidgetDeleteDialogComponent } from './widget-delete-dialog/widget-delete-dialog.component';
import { WidgetsEmptyStateComponent } from './widgets-empty-state/widgets-empty-state.component';
@Component({
selector: 'app-db-table-widgets',
templateUrl: './db-table-widgets.component.html',
styleUrls: ['./db-table-widgets.component.css'],
imports: [
CommonModule,
FormsModule,
MatButtonModule,
MatDialogModule,
MatIconModule,
MatInputModule,
MatSelectModule,
RouterModule,
AlertComponent,
PlaceholderTableWidgetsComponent,
BreadcrumbsComponent,
WidgetComponent,
WidgetsEmptyStateComponent,
Angulartics2OnModule,
],
})
export class DbTableWidgetsComponent implements OnInit {
protected posthog = posthog;
public connectionID: string | null = null;
public tableName: string | null = null;
public dispalyTableName: string;
public fields: string[] = [];
public fieldsCount: number;
public widgets: Widget[] = null;
public widgetTypes = Object.keys(UIwidgets);
public submitting: boolean = false;
public widgetsWithSettings: string[];
public codeEditorTheme: 'vs' | 'vs-dark' = 'vs-dark';
public paramsEditorOptions = {
minimap: { enabled: false },
lineNumbersMinChars: 3,
folding: false,
automaticLayout: true,
scrollBeyondLastLine: false,
wordWrap: 'on',
};
// JSON5-formatted default params
public defaultParams = {
Boolean: `// Display "Yes/No" buttons with configurable options:
// - allow_null: Use "false" to require selection, "true" if field can be left unspecified
// - invert_colors: Swap the color scheme (typically green=Yes, red=No becomes red=Yes, green=No)
{
"allow_null": false,
"invert_colors": false
}
`,
Code: `// provide language of code to highlight: 'html', 'css', 'typescript', 'yaml', 'markdown'
// example:
{
"language": "html"
}
`,
Color: `// Optional: Specify output format for color values
// Supported formats: "hex", "hex_hash" (default), "rgb", "hsl"
// Example configuration:
{
"format": "hex_hash" // Will display colors as "#FF5733"
}
// Format options:
// - "hex": Display as "FF5733" (no hash)
// - "hex_hash": Display as "#FF5733" (default)
// - "rgb": Display as "rgb(255, 87, 51)"
// - "hsl": Display as "hsl(9, 100%, 60%)"`,
Country: `// Configure country display options
// Example:
{
"show_flag": true,
"allow_null": false
}
`,
Date: `// Configure date display options
// formatDistanceWithinHours: Shows relative time (e.g., "2 hours ago") for dates within the specified hours
// Default: 0 hours. Set to 0 to disable relative time display
{
"formatDistanceWithinHours": 0
}`,
DateTime: `// Configure datetime display options
// formatDistanceWithinHours: Shows relative time (e.g., "2 hours ago") for dates within the specified hours
// Default: 0 hours. Set to 0 to disable relative time display
{
"formatDistanceWithinHours": 0
}`,
Default: `// No settings required`,
File: `// provide type of file: 'hex', 'base64' or 'file'
// example:
{
"type": "hex"
}
`,
Foreign_key: `// Provide settings for foreign key widget
{
"column_name": "", // copy the name of the column you selected
"referenced_column_name": "",
"referenced_table_name": ""
}
`,
Image: `// provide image height in px to dispaly in table
// prefix: optional URL prefix to prepend to image source
// example:
{
"height": 100,
"prefix": "https://example.com/images/"
}
`,
JSON: `// No settings required`,
Language: `// Configure language display options
// show_flag: Display country flag emoji next to language name
// Example:
{
"show_flag": true
}`,
Markdown: `// No settings required`,
Money: `// Configure money widget settings
// example:
{
"default_currency": "USD",
"decimal_places": 2,
"allow_negative": true
}
`,
Number: `// Configure number display with unit conversion and threshold validation
// Example units: "bytes", "meters", "seconds", "grams"
// threshold_min/threshold_max: Values outside these limits will be highlighted
{
"unit": null,
"threshold_min": null,
"threshold_max": null
}`,
Password: `// provide algorithm to encrypt your password, one of:
//sha1, sha3, sha224, sha256, sha512, sha384, bcrypt, scrypt, argon2, pbkdf2.
// example:
{
"encrypt": true,
"algorithm": "sha256"
}
`,
Phone: `// Configure international phone number widget
// example:
{
"preferred_countries": ["US", "GB", "CA"],
"enable_placeholder": true,
"phone_validation": true
}
`,
Range: `// Configure the minimum, maximum and step values for the range
// Default: min = 0, max = 100, step = 1
{
"min": 0,
"max": 100,
"step": 1
}
`,
Readonly: `// No settings required`,
Select: `// provide array of options to map database value (key 'value') in human readable value (key 'label');
// for example:
// AK => Alaska,
// CA => California
{
"allow_null": true,
"options": [
{
"value": "UA",
"label": "🇺🇦 Ukraine",
"background_color": "gold"
},
{
"value": "PL",
"label": "🇵🇱 Poland",
"background_color": "#FF1212"
},
{
"value": "US",
"label": "🇺🇸 United States",
"background_color": "rgba(100, 150, 255, 0.5)"
}
]
}`,
String: `// Optional validation for string values
// validate: Any validator.js method (e.g., "isEmail", "isURL", "isUUID", "isJSON", "isAlpha", "isNumeric")
// Full list: isEmail, isURL, isMACAddress, isIP, isIPRange, isFQDN, isBoolean, isIBAN, isBIC,
// isAlpha, isAlphanumeric, isNumeric, isPort, isLowercase, isUppercase, isAscii, isBase64,
// isHexadecimal, isHexColor, isRgbColor, isHSL, isMD5, isHash, isJWT, isJSON, isUUID,
// isMongoId, isCreditCard, isISBN, isISSN, isMobilePhone, isPostalCode, isEthereumAddress,
// isCurrency, isBtcAddress, isISO8601, isISO31661Alpha2, isISO31661Alpha3, isISO4217,
// isDataURI, isMagnetURI, isMimeType, isLatLong, isSlug, isStrongPassword, isTaxID, isVAT
// OR use "regex" with a regex parameter for custom pattern matching
{
"validate": null,
"regex": null
}`,
Textarea: `// provide number of strings to show.
{
"rows": 5
}`,
Time: `// No settings required`,
Timezone: `// Configure timezone widget options
// Uses Intl API to populate timezone list automatically
// allow_null: Allow empty/null value selection
{
"allow_null": false
}
`,
URL: `// prefix: optional URL prefix to prepend to the href
// example:
{
"prefix": "https://example.com/"
}
`,
UUID: `// Configure UUID generation version and parameters
// Available versions: "v1", "v3", "v4" (default), "v5", "v7"
// For v3/v5: provide namespace and optionally name
{
"version": "v4",
"namespace": "6ba7b810-9dad-11d1-80b4-00c04fd430c8",
"name": ""
}
`,
Email: `// No settings required`,
S3: `// Configure AWS S3 widget for file storage
// bucket: S3 bucket name (required)
// prefix: Optional path prefix for uploaded files
// region: AWS region (default: us-east-1)
// type: "file" (default) - accepts all file types, "image" - accepts only images
// aws_access_key_id_secret_name: Unique identifier of the secret containing AWS Access Key ID
// aws_secret_access_key_secret_name: Unique identifier of the secret containing AWS Secret Access Key
//
// ⚠️ IMPORTANT: DO NOT INCLUDE AWS SECRETS DIRECTLY IN WIDGET SETTINGS!
// Store your AWS credentials as secrets in Rocketadmin and reference them here by their unique identifiers to ensure security and prevent exposure of sensitive information.
{
"bucket": "your-bucket-name",
"prefix": "uploads/",
"region": "us-east-1",
"type": "file",
"aws_access_key_id_secret_name": "aws-access-key-id",
"aws_secret_access_key_secret_name": "aws-secret-access-key"
}
`,
};
constructor(
private _connections: ConnectionsService,
private _tables: TablesService,
private _location: Location,
private _uiSettings: UiSettingsService,
private _company: CompanyService,
public dialog: MatDialog,
public router: Router,
private title: Title,
private angulartics2: Angulartics2,
) {}
ngOnInit(): void {
this.connectionID = this._connections.currentConnectionID;
this.tableName = this._tables.currentTableName;
this.widgetsWithSettings = Object.entries(this.defaultParams)
.filter(([_key, value]) => value !== '// No settings required')
.map((widgetDefault) => widgetDefault[0]);
this._tables.fetchTableStructure(this.connectionID, this.tableName).subscribe((res) => {
this.fieldsCount = res.structure.length;
this.fields = res.structure.map((field: TableField) => field.column_name);
this.dispalyTableName = res.display_name || normalizeTableName(this.tableName);
this.title.setTitle(
`${this.dispalyTableName} - Field display | ${this._company.companyTabTitle || 'Rocketadmin'}`,
);
this.getWidgets();
});
this.codeEditorTheme = this._uiSettings.isDarkMode ? 'vs-dark' : 'vs';
}
get currentConnection() {
return this._connections.currentConnection;
}
getCrumbs(name: string) {
return [
{
label: name,
link: `/dashboard/${this.connectionID}`,
},
{
label: this.dispalyTableName,
link: `/dashboard/${this.connectionID}/${this.tableName}`,
},
{
label: 'UI Widgets',
link: null,
},
];
}
goBack() {
this._location.back();
}
addNewWidget() {
this.widgets.push({
field_name: '',
widget_type: 'Default',
widget_params: '// No settings required',
name: '',
description: '',
});
}
selectWidgetField(column_name: string) {
this.fields.splice(this.fields.indexOf(column_name), 1);
}
widgetTypeChange(fieldName) {
let currentWidget = this.widgets.find((widget) => widget.field_name === fieldName);
currentWidget.widget_params = this.defaultParams[currentWidget.widget_type || 'Default'];
this.widgetParamsChange({ fieldName: currentWidget.field_name, value: currentWidget.widget_params });
}
isReadOnly(type: string) {
return !this.widgetsWithSettings.includes(type);
}
widgetParamsChange(e: { fieldName: string; value: any }) {
let currentWidget = this.widgets.find((widget) => widget.field_name === e.fieldName);
currentWidget.widget_params = e.value;
}
openDeleteWidgetDialog(widgetFieldName: string) {
const dialogRef = this.dialog.open(WidgetDeleteDialogComponent, {
width: '25em',
data: widgetFieldName,
});
dialogRef.afterClosed().subscribe((action) => {
if (action === 'delete') {
this.fields.push(widgetFieldName);
this.widgets = this.widgets.filter((widget) => widget.field_name !== widgetFieldName);
this.updateWidgets(true);
}
});
}
openClearAllConfirmation() {
const dialogRef = this.dialog.open(WidgetDeleteDialogComponent, {
width: '25em',
});
dialogRef.afterClosed().subscribe((action) => {
if (action === 'delete') {
const widgetsToDelete = this.widgets.map((widget) => widget.field_name);
this.fields = [...this.fields, ...widgetsToDelete];
this.widgets = [];
this.updateWidgets(true);
}
});
}
getWidgets() {
this._tables.fetchTableWidgets(this.connectionID, this.tableName).subscribe((res) => {
const currentWidgetTypes = res.map((widget: Widget) => widget.field_name);
this.fields = difference(this.fields, currentWidgetTypes);
res.forEach((widget: Widget) => {
if (widget.widget_type === '') widget.widget_type = 'Default';
});
this.widgets = res;
});
}
updateWidgets(afterDeleteAll?: boolean) {
this.submitting = true;
this.widgets.forEach((widget) => {
if (widget.widget_type === 'Default') widget.widget_type = '';
});
this._tables.updateTableWidgets(this.connectionID, this.tableName, this.widgets).subscribe(
() => {
this.submitting = false;
this.angulartics2.eventTrack.next({
action: 'Widgets: widgets are updated successfully',
});
posthog.capture('Widgets: widgets are updated successfully');
if (!afterDeleteAll) this.router.navigate([`/dashboard/${this.connectionID}/${this.tableName}`]);
},
undefined,
() => {
this.submitting = false;
},
);
}
}