-
Notifications
You must be signed in to change notification settings - Fork 56
/
Cell.jsx
531 lines (492 loc) · 16.3 KB
/
Cell.jsx
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
/* eslint-disable react/jsx-props-no-spreading */
import React, { forwardRef, useImperativeHandle, useEffect, useState, useContext, useReducer, useRef } from 'react';
import { Grid, Paper } from '@material-ui/core';
import { useTheme } from '@nebula.js/ui/theme';
import CError from './Error';
import LongRunningQuery from './LongRunningQuery';
import Loading from './Loading';
import Header from './Header';
import Footer from './Footer';
import Supernova from './Supernova';
import useRect from '../hooks/useRect';
import useLayout, { useAppLayout } from '../hooks/useLayout';
import InstanceContext from '../contexts/InstanceContext';
import useObjectSelections from '../hooks/useObjectSelections';
import eventmixin from '../selections/event-mixin';
/**
* @interface
* @extends HTMLElement
*/
const CellElement = {
/** @type {'njs-cell'} */
className: 'njs-cell',
};
const initialState = (err) => ({
loading: false,
loaded: false,
longRunningQuery: false,
error: err ? { title: err.message } : null,
sn: null,
visualization: null,
});
const contentReducer = (state, action) => {
// console.log('content reducer', action.type);
switch (action.type) {
case 'LOADING': {
return {
...state,
loading: true,
};
}
case 'LOADED': {
return {
...state,
loaded: true,
loading: false,
longRunningQuery: false,
error: null,
sn: action.sn,
visualization: action.visualization,
};
}
case 'RENDER': {
return {
...state,
loaded: true,
loading: false,
longRunningQuery: false,
error: null,
};
}
case 'LONG_RUNNING_QUERY': {
return {
...state,
longRunningQuery: true,
};
}
case 'ERROR': {
return {
...state,
loading: false,
longRunningQuery: false,
error: action.error,
};
}
default: {
throw new Error(`Unhandled type: ${action.type}`);
}
}
};
const LoadingSn = ({ delay = 750 }) => {
const [showLoading, setShowLoading] = useState(false);
useEffect(() => {
const handle = setTimeout(() => setShowLoading(true), delay);
return () => clearTimeout(handle);
}, []);
return showLoading ? <Loading /> : null;
};
const handleModal = ({ sn, layout, model }) => {
const selections = sn && sn.component && sn.component.selections;
if (!selections || !selections.id || !model.id) {
return;
}
if (selections.id === model.id) {
if (layout && layout.qSelectionInfo && layout.qSelectionInfo.qInSelections && !selections.isModal()) {
const { targets } = sn.generator.qae.data;
const firstPropertyPath = targets[0].propertyPath;
selections.goModal(firstPropertyPath);
}
if (!layout.qSelectionInfo || !layout.qSelectionInfo.qInSelections) {
if (selections.isModal()) {
selections.noModal();
}
}
}
};
const filterData = (d) => (d.qError ? d.qError.qErrorCode === 7005 : true);
const validateInfo = (min, info, getDescription, translatedError, translatedCalcCond) =>
[...Array(min).keys()].map((i) => {
const exists = !!(info && info[i]);
const softError = exists && info[i].qError && info[i].qError.qErrorCode === 7005;
const error = exists && !softError && info[i].qError;
const delimiter = ':';
const calcCondMsg = softError && info[i].qCalcCondMsg;
const label = `${
// eslint-disable-next-line no-nested-ternary
error ? translatedError : softError ? calcCondMsg || translatedCalcCond : (exists && info[i].qFallbackTitle) || ''
}`;
const customDescription = getDescription(i);
const description = customDescription ? `${customDescription}${label.length ? delimiter : ''}` : null;
return {
description,
label,
missing: (info && !exists && !error && i >= info.length) || softError,
error,
};
});
const getInfo = (info) => (info && (Array.isArray(info) ? info : [info])) || [];
const validateTarget = (translator, layout, properties, def) => {
const minD = def.dimensions.min();
const minM = def.measures.min();
const c = def.resolveLayout(layout);
const reqDimErrors = validateInfo(
minD,
getInfo(c.qDimensionInfo),
(i) => def.dimensions.description(properties, i),
translator.get('Visualization.Invalid.Dimension'),
translator.get('Visualization.UnfulfilledCalculationCondition')
);
const reqMeasErrors = validateInfo(
minM,
getInfo(c.qMeasureInfo),
(i) => def.measures.description(properties, i),
translator.get('Visualization.Invalid.Measure'),
translator.get('Visualization.UnfulfilledCalculationCondition')
);
return {
reqDimErrors,
reqMeasErrors,
};
};
const validateCubes = (translator, targets, layout) => {
let hasUnfulfilledErrors = false;
let aggMinD = 0;
let aggMinM = 0;
let hasLayoutErrors = false;
let hasLayoutUnfulfilledCalculcationCondition = false;
const layoutErrors = [];
for (let i = 0; i < targets.length; ++i) {
const def = targets[i];
const minD = def.dimensions.min();
const minM = def.measures.min();
const c = def.resolveLayout(layout);
const d = getInfo(c.qDimensionInfo).filter(filterData); // Filter out optional calc conditions
const m = getInfo(c.qMeasureInfo).filter(filterData); // Filter out optional calc conditions
aggMinD += minD;
aggMinM += minM;
if (d.length < minD || m.length < minM) {
hasUnfulfilledErrors = true;
}
if (c.qError) {
hasLayoutErrors = true;
hasLayoutUnfulfilledCalculcationCondition = c.qError.qErrorCode === 7005;
const title =
// eslint-disable-next-line no-nested-ternary
hasLayoutUnfulfilledCalculcationCondition && c.qCalcCondMsg
? c.qCalcCondMsg
: hasLayoutUnfulfilledCalculcationCondition
? translator.get('Visualization.UnfulfilledCalculationCondition')
: translator.get('Visualization.LayoutError');
layoutErrors.push({ title, descriptions: [] });
}
}
return {
hasUnfulfilledErrors,
aggMinD,
aggMinM,
hasLayoutErrors,
layoutErrors,
};
};
const validateTargets = async (translator, layout, { targets }, model) => {
// Use a flattened requirements structure to combine all targets
const { hasUnfulfilledErrors, aggMinD, aggMinM, hasLayoutErrors, layoutErrors } = validateCubes(
translator,
targets,
layout
);
const reqDimErrors = [];
const reqMeasErrors = [];
let loopCacheProperties = null;
for (let i = 0; i < targets.length; ++i) {
const def = targets[i];
if (!hasLayoutErrors && hasUnfulfilledErrors) {
// eslint-disable-next-line no-await-in-loop
const properties = loopCacheProperties || (await model.getProperties());
loopCacheProperties = properties;
const res = validateTarget(translator, layout, properties, def);
reqDimErrors.push(...res.reqDimErrors);
reqMeasErrors.push(...res.reqMeasErrors);
}
}
const fulfilledDims = reqDimErrors.filter((e) => !(e.missing || e.error)).length;
const reqDimErrorsTitle = translator.get('Visualization.Incomplete.Dimensions', [fulfilledDims, aggMinD]);
const fulfilledMeas = reqMeasErrors.filter((e) => !(e.missing || e.error)).length;
const reqMeasErrorsTitle = translator.get('Visualization.Incomplete.Measures', [fulfilledMeas, aggMinM]);
const reqErrors = [
{ title: reqDimErrorsTitle, descriptions: [...reqDimErrors] },
{ title: reqMeasErrorsTitle, descriptions: [...reqMeasErrors] },
];
const showError = hasLayoutErrors || hasUnfulfilledErrors;
const data = hasLayoutErrors ? layoutErrors : reqErrors;
const title = hasLayoutErrors ? layoutErrors[0].title : translator.get('Visualization.Incomplete');
return [showError, { title, data }];
};
const getType = async ({ types, name, version }) => {
const SN = await types
.get({
name,
version,
})
.supernova();
return SN;
};
const loadType = async ({ dispatch, types, visualization, version, model, app, selections, nebbie, focusHandler }) => {
try {
const snType = await getType({ types, name: visualization, version });
const sn = snType.create({
model,
app,
selections,
nebbie,
focusHandler,
});
return sn;
} catch (err) {
dispatch({ type: 'ERROR', error: { title: err.message } });
}
return undefined;
};
const Cell = forwardRef(
({ halo, model, initialSnOptions, initialSnPlugins, initialError, onMount, currentId }, ref) => {
const { app, types } = halo;
const { nebbie } = halo.public;
const { disableCellPadding = false } = halo.context || {};
const { translator, language, keyboardNavigation } = useContext(InstanceContext);
const theme = useTheme();
const [cellRef, cellRect, cellNode] = useRect();
const [state, dispatch] = useReducer(contentReducer, initialState(initialError));
const [layout, { validating, canCancel, canRetry }, longrunning] = useLayout(model);
const [appLayout] = useAppLayout(app);
const [contentRef, contentRect, contentNode] = useRect();
const [snOptions, setSnOptions] = useState(initialSnOptions);
const [snPlugins, setSnPlugins] = useState(initialSnPlugins);
const [selections] = useObjectSelections(app, model);
const [hovering, setHover] = useState(false);
const hoveringDebouncer = useRef({ enter: null, leave: null });
const focusHandler = useRef({
focusToolbarButton(last) {
// eslint-disable-next-line react/no-this-in-sfc
this.emit(last ? 'focus_toolbar_last' : 'focus_toolbar_first');
},
});
useEffect(() => {
eventmixin(focusHandler.current);
}, []);
focusHandler.current.blurCallback = (resetFocus) => {
halo.root.toggleFocusOfCells();
if (resetFocus && contentNode) {
contentNode.focus();
}
};
focusHandler.current.refocusContent = () => {
state.sn.component && typeof state.sn.component.focus === 'function' && state.sn.component.focus();
};
const handleOnMouseEnter = () => {
if (hoveringDebouncer.current.leave) {
clearTimeout(hoveringDebouncer.current.leave);
}
if (hoveringDebouncer.enter) return;
hoveringDebouncer.current.enter = setTimeout(() => {
setHover(true);
hoveringDebouncer.current.enter = null;
}, 250);
};
const handleOnMouseLeave = () => {
if (hoveringDebouncer.current.enter) {
clearTimeout(hoveringDebouncer.current.enter);
}
if (hoveringDebouncer.current.leave) return;
hoveringDebouncer.current.leave = setTimeout(() => {
setHover(false);
hoveringDebouncer.current.leave = null;
}, 750);
};
const handleKeyDown = (e) => {
// Enter or space
if (['Enter', ' ', 'Spacebar'].includes(e.key)) {
halo.root.toggleFocusOfCells(currentId);
}
};
useEffect(() => {
if (initialError || !appLayout || !layout) {
return undefined;
}
const validate = async (sn) => {
const [showError, error] = await validateTargets(translator, layout, sn.generator.qae.data, model);
if (showError) {
dispatch({ type: 'ERROR', error });
} else {
dispatch({ type: 'RENDER' });
}
handleModal({ sn: state.sn, layout, model });
};
const load = async (visualization, version) => {
dispatch({ type: 'LOADING' });
const sn = await loadType({
dispatch,
types,
visualization,
version,
model,
app,
selections,
nebbie,
focusHandler: focusHandler.current,
});
if (sn) {
dispatch({ type: 'LOADED', sn, visualization });
onMount();
}
return undefined;
};
// Validate if it's still the same type
if (state.visualization === layout.visualization && state.sn) {
validate(state.sn);
return undefined;
}
// Load supernova
const withVersion = types.getSupportedVersion(layout.visualization, layout.version);
if (!withVersion) {
dispatch({
type: 'ERROR',
error: {
title: `Could not find a version of '${layout.visualization}' that supports current object version. Did you forget to register ${layout.visualization}?`,
},
});
return undefined;
}
load(layout.visualization, withVersion);
return () => {};
}, [types, state.sn, model, layout, appLayout, language]);
// Long running query
useEffect(() => {
if (!validating) {
return undefined;
}
const handle = setTimeout(() => dispatch({ type: 'LONG_RUNNING_QUERY' }), 2000);
return () => clearTimeout(handle);
}, [validating]);
// Expose cell ref api
useImperativeHandle(
ref,
() => ({
getQae() {
return state.sn.generator.qae;
},
toggleFocus(active) {
if (typeof state.sn.component.focus === 'function') {
if (active) {
state.sn.component.focus();
} else {
state.sn.component.blur();
}
}
},
setSnOptions,
setSnPlugins,
async takeSnapshot() {
const { width, height } = cellRect;
// clone layout to avoid mutation
let clonedLayout = JSON.parse(JSON.stringify(layout));
if (typeof state.sn.component.setSnapshotData === 'function') {
clonedLayout = (await state.sn.component.setSnapshotData(clonedLayout)) || clonedLayout;
}
return {
// TODO - this snapshot format needs to be documented and governed
key: String(+Date.now()),
meta: {
language: translator.language(),
theme: theme.name,
appLayout,
// direction: 'ltr',
size: {
width: Math.round(width),
height: Math.round(height),
},
},
layout: clonedLayout,
};
},
async exportImage() {
if (typeof halo.config.snapshot.capture !== 'function') {
throw new Error('Stardust embed has not been configured with snapshot.capture callback');
}
const snapshot = await this.takeSnapshot(); // eslint-disable-line
return halo.config.snapshot.capture(snapshot);
},
}),
[state.sn, contentRect, cellRect, layout, theme.name, appLayout]
);
// console.log('content', state);
let Content = null;
if (state.loading && !state.longRunningQuery) {
Content = <LoadingSn />;
} else if (state.error) {
Content = <CError {...state.error} />;
} else if (state.loaded) {
Content = (
<Supernova
key={layout.visualization}
sn={state.sn}
halo={halo}
snOptions={snOptions}
snPlugins={snPlugins}
layout={layout}
appLayout={appLayout}
/>
);
}
return (
<Paper
style={{ position: 'relative', width: '100%', height: '100%', overflow: 'hidden' }}
elevation={0}
square
className={CellElement.className}
ref={cellRef}
onMouseEnter={handleOnMouseEnter}
onMouseLeave={handleOnMouseLeave}
>
<Grid
container
direction="column"
spacing={0}
style={{
position: 'relative',
width: '100%',
height: '100%',
...(!disableCellPadding ? { padding: theme.spacing(1) } : {}),
...(state.longRunningQuery ? { opacity: '0.3' } : {}),
}}
>
{cellNode && layout && state.sn && (
<Header
layout={layout}
sn={state.sn}
anchorEl={cellNode}
hovering={hovering}
focusHandler={focusHandler.current}
>
</Header>
)}
<Grid
tabIndex={keyboardNavigation ? 0 : -1}
onKeyDown={keyboardNavigation ? handleKeyDown : null}
item
xs
style={{
height: '100%',
}}
ref={contentRef}
>
{Content}
</Grid>
<Footer layout={layout} />
</Grid>
{state.longRunningQuery && <LongRunningQuery canCancel={canCancel} canRetry={canRetry} api={longrunning} />}
</Paper>
);
}
);
export default Cell;