@azrico/reactgrid 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,337 @@
1
+ import '@inovua/reactdatagrid-enterprise/index.css';
2
+ import '@inovua/reactdatagrid-enterprise/theme/default-dark.css';
3
+ import './theme/styles.css';
4
+
5
+ import React, { useCallback, useState } from 'react';
6
+ import {
7
+ TypeColumn,
8
+ TypeDataGridProps,
9
+ TypeDataSource,
10
+ TypeRowDetailsInfo,
11
+ TypeRowProps,
12
+ TypeRowSelection,
13
+ } from '@inovua/reactdatagrid-community/types';
14
+ import { fix_parent_child_relations, func_selection } from './func/helpers';
15
+
16
+ import { ContextMenu } from '@azrico/controls';
17
+ import ReactDataGrid from '@inovua/reactdatagrid-enterprise';
18
+ import { TypeOnSelectionChangeArg } from '@inovua/reactdatagrid-community/types/TypeDataGridProps';
19
+ import clsx from 'clsx';
20
+ import { useResizeDetector } from 'react-resize-detector';
21
+
22
+ /* -------------------------------------------------------------------------- */
23
+ type Modify<T, R> = Omit<T, keyof R> & R;
24
+ type Writeable<Type> = {
25
+ -readonly [Key in keyof Type]: Type[Key];
26
+ };
27
+ /* -------------------------------------------------------------------------- */
28
+ export type ColumnDefinition = TypeColumn;
29
+ export type CellDefinition = any;
30
+ export type RowDefinition = any;
31
+ export type RowProps = TypeRowProps;
32
+ export type RowSelectionValue = TypeRowSelection;
33
+ export type DataRowDefinition = any;
34
+ export type DataSourceDefinition = TypeDataSource;
35
+ export type OnSelectionChangeFunc = (config: TypeOnSelectionChangeArg) => void;
36
+ export type RowDetailsFunc = (rowDetailsInfo: TypeRowDetailsInfo) => React.ReactNode;
37
+ /* -------------------------------------------------------------------------- */
38
+ type loose_column_fields = { title: string; key: string; field: string; columnName: string; name: string };
39
+ export type LooseColumnDefinition = Partial<loose_column_fields & ColumnDefinition>;
40
+ //
41
+ type columnOrString = string | LooseColumnDefinition;
42
+ type customColumnData = {
43
+ name: string;
44
+ render: (cell: any, formatterParams, onRendered) => React.ReactNode;
45
+ };
46
+ type GridOptions = Partial<TypeDataGridProps>;
47
+ /* -------------------------------------------------------------------------- */
48
+ type AzGridProps = {
49
+ columns?: columnOrString[];
50
+ rows?: any[];
51
+ licenseKey?: string;
52
+
53
+ gridOptions?: GridOptions;
54
+
55
+ tableColumnExtensions?: any[];
56
+ editableColumns?: string[];
57
+ leftColumns?: string[];
58
+ rightColumns?: string[];
59
+ customColumns?: customColumnData[];
60
+
61
+ contextMenuItems?: any[];
62
+
63
+ highlightedRow?: any;
64
+ RowDetail?: RowDetailsFunc;
65
+ get_rows?: () => any[];
66
+
67
+ selected?: RowSelectionValue;
68
+ onSelectionChange?: OnSelectionChangeFunc;
69
+ onRowsChange?: (rows: any[], options: any) => void;
70
+ onRowClick?: (rowIndex: number, row: any) => void;
71
+ onRowDoubleClick?: (rowIndex: number, row: any) => void;
72
+
73
+ dark?: boolean;
74
+ allowChildRows?: boolean;
75
+
76
+ className?: string;
77
+ };
78
+
79
+ type DataGridProps = Modify<
80
+ AzGridProps,
81
+ {
82
+ columns: ColumnDefinition[];
83
+ rows: DataRowDefinition[];
84
+ }
85
+ >;
86
+ /* -------------------------------------------------------------------------- */
87
+ const defaultOptions: GridOptions = {
88
+ rowReorderColumn: false,
89
+ resizable: true,
90
+
91
+ rowIndexColumn: true,
92
+ };
93
+ const forcedOptions: GridOptions = {
94
+ idProperty: '__table_id',
95
+ nodesProperty: '__children',
96
+ };
97
+ const defaultColumnOptions: ColumnDefinition = {
98
+ draggable: false,
99
+ lockable: false,
100
+ };
101
+
102
+ /* -------------------------------------------------------------------------- */
103
+ export function AzGrid(props: AzGridProps) {
104
+ const [pendingChanges, set_pendingChanges] = React.useState<number>(1);
105
+ const [cached_rows, set_cached_rows] = React.useState<any[]>([]);
106
+
107
+ /* -------------------------------------------------------------------------- */
108
+ /* Columns */
109
+ /* -------------------------------------------------------------------------- */
110
+ const cached_columns = React.useMemo(() => {
111
+ const final_columns: Writeable<ColumnDefinition>[] = [];
112
+ let mcols = props.columns || [];
113
+ let mcolExts = props.tableColumnExtensions || [];
114
+ let rightColumns = props.rightColumns || [];
115
+ let leftColumns = props.leftColumns || [];
116
+ let editableColumns = props.editableColumns || [];
117
+ let customColumns = props.customColumns || [];
118
+
119
+ if (!Array.isArray(mcols)) return [];
120
+ /* ------------------------------- fix columns ------------------------------ */
121
+
122
+ mcols
123
+ .map((r) => {
124
+ if (typeof r === 'string') return { field: r, header: r };
125
+ if (typeof r === 'object') {
126
+ let final_cl: Writeable<ColumnDefinition> = {
127
+ name: r.field || r.name || r.key || r.columnName,
128
+ header: r.header || r.title || r.name || '-',
129
+ width: r.width || undefined,
130
+ };
131
+ delete r.field;
132
+ delete r.key;
133
+ delete r.columnName;
134
+ final_cl = {
135
+ ...defaultColumnOptions,
136
+ ...r,
137
+ ...final_cl,
138
+ };
139
+ return final_cl;
140
+ }
141
+ return null;
142
+ })
143
+ .forEach((r) => {
144
+ if (r != null) final_columns.push(r);
145
+ });
146
+
147
+ /* ---------------------------- apply extensions ---------------------------- */
148
+ if (mcolExts && Array.isArray(mcolExts))
149
+ for (let index = 0; index < mcolExts.length; index++) {
150
+ const ext = mcolExts[index];
151
+ const ext_cl = ext.columnName || ext.name || ext.field;
152
+ const mcol = final_columns.find((s) => s.name === ext_cl);
153
+ if (!mcol) continue;
154
+ // if (ext.width) mcol.width = ext.width;
155
+ // if (ext.widthGrow) mcol.widthGrow = ext.widthGrow;
156
+ }
157
+
158
+ /* ------------------------------- frozen cols ------------------------------ */
159
+ if (Array.isArray(leftColumns)) {
160
+ for (let index = 0; index < leftColumns.length; index++) {
161
+ const r = leftColumns[index];
162
+ const mcol = final_columns.find((s) => s.name === r);
163
+ if (mcol) {
164
+ mcol.locked = 'start';
165
+ }
166
+ }
167
+ }
168
+ if (Array.isArray(rightColumns)) {
169
+ for (let index = 0; index < rightColumns.length; index++) {
170
+ const r = rightColumns[index];
171
+ const mcol = final_columns.find((s) => s.name === r);
172
+ if (mcol) {
173
+ mcol.locked = 'end';
174
+ }
175
+ }
176
+ }
177
+ /* -------------------------------- ediatable ------------------------------- */
178
+ if (Array.isArray(editableColumns)) {
179
+ for (let index = 0; index < editableColumns.length; index++) {
180
+ const r = editableColumns[index];
181
+ const mcol = final_columns.find((s) => s.name === r);
182
+ if (mcol) {
183
+ // mcol.editor = editorWrapper;
184
+ // mcol.editorOptions = {
185
+ // editOnClick: true,
186
+ // };
187
+ }
188
+ }
189
+ }
190
+ if (Array.isArray(customColumns)) {
191
+ for (let index = 0; index < customColumns.length; index++) {
192
+ const r = customColumns[index];
193
+ const mcol = final_columns.find((s) => s.name === r.name);
194
+ if (mcol) {
195
+ //@ts-ignore
196
+ mcol.render = r.render;
197
+ }
198
+ }
199
+ }
200
+
201
+ return final_columns;
202
+ }, [props.columns, props.leftColumns, props.editableColumns, props.tableColumnExtensions]);
203
+ /* -------------------------------------------------------------------------- */
204
+
205
+ /* -------------------------------------------------------------------------- */
206
+ /* Row changes */
207
+ /* -------------------------------------------------------------------------- */
208
+ React.useEffect(() => {
209
+ if (pendingChanges <= 0) return;
210
+ let new_rows: any[] = [];
211
+ if (typeof props.get_rows === 'function') {
212
+ new_rows = props.get_rows();
213
+ } else new_rows = props.rows || [];
214
+ /* -------------------------------------------------------------------------- */
215
+ if (!Array.isArray(new_rows)) new_rows = [];
216
+ /* -------------------------- fix child parent rel -------------------------- */
217
+ if (props.allowChildRows) new_rows = fix_parent_child_relations(new_rows);
218
+
219
+ set_cached_rows(new_rows);
220
+ set_pendingChanges(0);
221
+ }, [pendingChanges]);
222
+
223
+ React.useEffect(() => {
224
+ set_pendingChanges((r) => r + 1);
225
+ }, [props.rows]);
226
+
227
+ function onRowsChange(rows: any[], options: any) {
228
+ if (props.onRowsChange) props.onRowsChange(rows, options);
229
+ set_pendingChanges((r) => r + 1); //notify the cache to update rows after we made changes to them
230
+ }
231
+ /* -------------------------------------------------------------------------- */
232
+ /* -------------------------------------------------------------------------- */
233
+
234
+ return <DataGrid {...props} columns={cached_columns} rows={cached_rows} onRowsChange={onRowsChange} highlightedRow={props.highlightedRow} />;
235
+ }
236
+
237
+ /* -------------------------------------------------------------------------- */
238
+ function DataGrid(props: DataGridProps) {
239
+ const { columns, rows, highlightedRow, dark, contextMenuItems, onRowsChange } = props;
240
+
241
+ /* -------------------------------------------------------------------------- */
242
+ const gridRef = React.useRef<any>(null);
243
+ const [menuAnchorEl, set_menuAnchorEl] = React.useState<any>(null);
244
+ const [menuRow, set_menuRow] = React.useState<any>(null);
245
+
246
+ const gridID = React.useMemo(() => 'table-' + Date.now().valueOf(), []);
247
+
248
+ /* -------------------------------------------------------------------------- */
249
+ /* Create the grid */
250
+ /* -------------------------------------------------------------------------- */
251
+
252
+ const static_gridOptions = React.useMemo<GridOptions>(() => {
253
+ const firstcolumn = columns[0];
254
+
255
+ const licenseKey = props.licenseKey || get_default_key();
256
+ const events: GridOptions = {
257
+ onRowClick: onRowClick,
258
+ onRowDoubleClick: onRowDoubleClick,
259
+ onRowContextMenu: onRowContextMenu,
260
+ };
261
+ const extra_ops: GridOptions = {
262
+ onSelectionChange: props.onSelectionChange,
263
+ licenseKey: licenseKey,
264
+ treeColumn: props.allowChildRows ? firstcolumn.name : undefined,
265
+ renderRowDetails: props.RowDetail,
266
+ theme: dark ? 'default-dark' : 'default-light',
267
+ };
268
+ return { ...defaultOptions, ...events, ...extra_ops, ...props.gridOptions, ...forcedOptions };
269
+ }, [props.gridOptions]);
270
+ const dynamic_gridOptions = React.useMemo<GridOptions>(() => {
271
+ return { selected: props.selected };
272
+ }, [props.selected]);
273
+
274
+ /* ------------------------------- load events ------------------------------ */
275
+
276
+ function onCellEdit(cell: CellDefinition) {}
277
+
278
+ function onRowContextMenu(row: TypeRowProps, ev: any) {
279
+ if (func_selection.has_selection()) return;
280
+ update_menuAnchorEl(func_selection.getVirtualElement(ev.clientX, ev.clientY));
281
+ update_menuRow(row.data);
282
+ ev.preventDefault();
283
+ }
284
+ function onRowClick(row: RowProps, event) {
285
+ props.onRowClick && props.onRowClick(row.rowIndex, row.data);
286
+ }
287
+ function onRowDoubleClick(event: MouseEvent, row: RowProps) {
288
+ props.onRowDoubleClick && props.onRowDoubleClick(row.rowIndex, row.data);
289
+ }
290
+
291
+ /* ------------------------- update the selected row ------------------------ */
292
+ React.useEffect(() => {
293
+ if (highlightedRow) gridRef.current!.scrollToRow(getRowIndex(highlightedRow, rows));
294
+ }, [highlightedRow]);
295
+
296
+ /* ------------------------------- ContextMenu ------------------------------ */
297
+
298
+ function update_menuAnchorEl(el) {
299
+ if (!el) {
300
+ set_menuAnchorEl(el);
301
+ } else if (menuAnchorEl) set_menuAnchorEl(null);
302
+ }
303
+ function update_menuRow(r) {
304
+ if (!r) {
305
+ set_menuRow(r);
306
+ } else if (menuRow) set_menuRow(null);
307
+ }
308
+
309
+ /* -------------------------------------------------------------------------- */
310
+ // const { width, height, ref: resize_ref } = useResizeDetector();
311
+
312
+ return (
313
+ <div className={clsx(props.className, 'azgrid-nooverflow', 'azgrid-filler')}>
314
+ <ReactDataGrid {...static_gridOptions} {...dynamic_gridOptions} className={'azgrid-filler'} columns={columns} dataSource={rows} />
315
+ <ContextMenu menuAnchorEl={menuAnchorEl} set_menuAnchorEl={update_menuAnchorEl} menuRow={menuRow} items={contextMenuItems} />
316
+ </div>
317
+ );
318
+ }
319
+ /* -------------------------------------------------------------------------- */
320
+ function get_default_key() {
321
+ return 'ExpiryDate=2999-01-01,Z=1040577552';
322
+ }
323
+ function getRowIndex(row: any, allrows?: any[]): number {
324
+ if (!allrows) return -1;
325
+ return allrows.findIndex((s) => rowKeyGetter(s) === rowKeyGetter(row)) || -1;
326
+ }
327
+ function rowKeyGetter(row: any) {
328
+ return row.__uid;
329
+ }
330
+ function isRowSelected(row: any, highlightedRow: any) {
331
+ const rid = rowKeyGetter(row);
332
+ const highLight = rowKeyGetter(highlightedRow);
333
+ return rid != null && rid === highLight;
334
+ }
335
+
336
+ /* -------------------------------------------------------------------------- */
337
+ export default AzGrid;
@@ -0,0 +1,65 @@
1
+ type mrow = { __parent__table_id: any; __table_id: any; __children?: any[] };
2
+ //given an array of rows, fixes parent,child relations
3
+ export function fix_parent_child_relations<T extends mrow>(rows: T[]): T[] {
4
+ if (!Array.isArray(rows)) rows = [];
5
+ const child_rows: T[] = [];
6
+ const parent_rows: T[] = [];
7
+ for (let index = 0; index < rows.length; index++) {
8
+ const r = rows[index];
9
+ if (r.__parent__table_id != undefined) child_rows.push(r);
10
+ else parent_rows.push(r);
11
+ }
12
+ for (let index = 0; index < parent_rows.length; index++) {
13
+ const pr = parent_rows[index];
14
+ pr.__children = [];
15
+ }
16
+ //find parent for these children !
17
+ for (let index = 0; index < child_rows.length; index++) {
18
+ const child = child_rows[index];
19
+ const parentOfChild = parent_rows.find((s) => s.__table_id == child.__parent__table_id);
20
+ if (!parentOfChild) continue; //no parent :(
21
+ //@ts-ignore
22
+ parentOfChild.__children.push(child);
23
+ }
24
+
25
+ for (let index = 0; index < parent_rows.length; index++) {
26
+ const pr = parent_rows[index];
27
+ //@ts-ignore
28
+ if (pr.__children.length == 0) pr.__children = undefined;
29
+ }
30
+
31
+ return parent_rows;
32
+ }
33
+ export class func_selection {
34
+ static getVirtualElement(x = 0, y = 0) {
35
+ return () => ({
36
+ getBoundingClientRect: func_selection.generateGetBoundingClientRect(x, y),
37
+ });
38
+ }
39
+ static generateGetBoundingClientRect(x = 0, y = 0) {
40
+ return () => ({
41
+ width: 0,
42
+ height: 0,
43
+ top: y,
44
+ right: x,
45
+ bottom: y,
46
+ left: x,
47
+ });
48
+ }
49
+ static get_selectedText(): string {
50
+ var text: any = '';
51
+ if (window.getSelection) {
52
+ text = window.getSelection()?.toString();
53
+ } else if ((document as any).selection && (document as any).selection.type != 'Control') {
54
+ text = (document as any).selection.createRange()?.text;
55
+ }
56
+ return text || '';
57
+ }
58
+ static has_selection(): boolean {
59
+ const slct = window.getSelection();
60
+ if (slct == null) return false;
61
+ if (slct.type == null) return func_selection.get_selectedText().length !== 0;
62
+ if (slct.type === 'Range') return true;
63
+ return false;
64
+ }
65
+ }
@@ -0,0 +1,4 @@
1
+ export * from './DataGrid';
2
+
3
+ import AzGrid from './DataGrid';
4
+ export default AzGrid;
@@ -0,0 +1,26 @@
1
+ .azgrid-container {
2
+ height: 100%;
3
+ width: 100%;
4
+ }
5
+ .azgrid-borderbox {
6
+ box-sizing: border-box;
7
+ }
8
+ .azgrid-filler {
9
+ height: 100%;
10
+ width: 100%;
11
+ }
12
+ .azgrid-nooverflow {
13
+ overflow: hidden;
14
+ }
15
+ .azgrid-testborder {
16
+ border: 3px solid red;
17
+ }
18
+ .azgrid-pad50px {
19
+ padding: 50px;
20
+ }
21
+ .azgrid-nopad {
22
+ padding: 0;
23
+ }
24
+ .azgrid-nomargin {
25
+ margin: 0;
26
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,74 @@
1
+ {
2
+ "compilerOptions": {
3
+ /* Visit https://aka.ms/tsconfig.json to read more about this file */
4
+
5
+ /* Basic Options */
6
+ // "incremental": true, /* Enable incremental compilation */
7
+ "target": "ESNEXT" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */,
8
+ "module": "ESNext" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */,
9
+ // "lib": [], /* Specify library files to be included in the compilation. */
10
+ // "allowJs": true, /* Allow javascript files to be compiled. */
11
+ // "checkJs": true, /* Report errors in .js files. */
12
+ "jsx": "react" /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */,
13
+ "declaration": true /* Generates corresponding '.d.ts' file. */,
14
+ //"declarationMap": true /* Generates a sourcemap for each corresponding '.d.ts' file. */,
15
+ // "sourceMap": true, /* Generates corresponding '.map' file. */
16
+ // "outFile": "./", /* Concatenate and emit output to single file. */
17
+ "outDir": "./dist" /* Redirect output structure to the directory. */,
18
+ "rootDir": "./" /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */,
19
+ // "composite": true, /* Enable project compilation */
20
+ // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
21
+ // "removeComments": true, /* Do not emit comments to output. */
22
+ // "noEmit": true, /* Do not emit outputs. */
23
+ // "importHelpers": true, /* Import emit helpers from 'tslib'. */
24
+ // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
25
+ // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
26
+
27
+ /* Strict Type-Checking Options */
28
+ "strict": true /* Enable all strict type-checking options. */,
29
+ "noImplicitAny": false /* Raise error on expressions and declarations with an implied 'any' type. */,
30
+ // "strictNullChecks": true, /* Enable strict null checks. */
31
+ // "strictFunctionTypes": true, /* Enable strict checking of function types. */
32
+ // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
33
+ // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
34
+ // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
35
+ // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
36
+
37
+ /* Additional Checks */
38
+ // "noUnusedLocals": true, /* Report errors on unused locals. */
39
+ // "noUnusedParameters": true, /* Report errors on unused parameters. */
40
+ // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
41
+ // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
42
+ // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
43
+ // "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */
44
+
45
+ /* Module Resolution Options */
46
+ "moduleResolution": "node" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */,
47
+ // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
48
+ // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
49
+ // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
50
+ // "typeRoots": [], /* List of folders to include type definitions from. */
51
+ // "types": [], /* Type declaration files to be included in compilation. */
52
+ // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
53
+ "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
54
+ // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
55
+ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
56
+
57
+ /* Source Map Options */
58
+ // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
59
+ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
60
+ // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
61
+ // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
62
+
63
+ /* Experimental Options */
64
+ // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
65
+ // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
66
+
67
+ "resolveJsonModule": true,
68
+ /* Advanced Options */
69
+ "skipLibCheck": true /* Skip type checking of declaration files. */,
70
+ "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
71
+ },
72
+ "lib": ["esnext"],
73
+ "exclude": ["node_modules", "__tests__", "dist", "build"]
74
+ }