-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
Copy pathdashboard_container.tsx
907 lines (812 loc) · 30.8 KB
/
dashboard_container.tsx
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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import { METRIC_TYPE } from '@kbn/analytics';
import { Reference } from '@kbn/content-management-utils';
import type { ControlGroupContainer } from '@kbn/controls-plugin/public';
import type { I18nStart, KibanaExecutionContext, OverlayRef } from '@kbn/core/public';
import {
type PublishingSubject,
apiPublishesPanelTitle,
apiPublishesUnsavedChanges,
getPanelTitle,
PublishesViewMode,
} from '@kbn/presentation-publishing';
import { RefreshInterval } from '@kbn/data-plugin/public';
import type { DataView } from '@kbn/data-views-plugin/public';
import {
Container,
DefaultEmbeddableApi,
EmbeddableFactoryNotFoundError,
embeddableInputToSubject,
isExplicitInputWithAttributes,
PanelNotFoundError,
ViewMode,
type EmbeddableFactory,
type EmbeddableInput,
type EmbeddableOutput,
type IEmbeddable,
} from '@kbn/embeddable-plugin/public';
import type { Filter, Query, TimeRange } from '@kbn/es-query';
import { KibanaRenderContextProvider } from '@kbn/react-kibana-context-render';
import {
HasRuntimeChildState,
HasSaveNotification,
HasSerializedChildState,
TrackContentfulRender,
TracksQueryPerformance,
} from '@kbn/presentation-containers';
import { PanelPackage } from '@kbn/presentation-containers';
import { ReduxEmbeddableTools, ReduxToolsPackage } from '@kbn/presentation-util-plugin/public';
import { LocatorPublic } from '@kbn/share-plugin/common';
import { ExitFullScreenButtonKibanaProvider } from '@kbn/shared-ux-button-exit-full-screen';
import deepEqual from 'fast-deep-equal';
import { omit } from 'lodash';
import React, { createContext, useContext } from 'react';
import ReactDOM from 'react-dom';
import { batch } from 'react-redux';
import { BehaviorSubject, Subject, Subscription } from 'rxjs';
import { distinctUntilChanged, map } from 'rxjs';
import { v4 } from 'uuid';
import { PublishesSettings } from '@kbn/presentation-containers/interfaces/publishes_settings';
import { apiHasSerializableState } from '@kbn/presentation-containers/interfaces/serialized_state';
import { DashboardLocatorParams, DASHBOARD_CONTAINER_TYPE } from '../..';
import { DashboardContainerInput, DashboardPanelState } from '../../../common';
import { getReferencesForPanelId } from '../../../common/dashboard_container/persistable_state/dashboard_container_references';
import {
DASHBOARD_APP_ID,
DASHBOARD_UI_METRIC_ID,
DEFAULT_PANEL_HEIGHT,
DEFAULT_PANEL_WIDTH,
PanelPlacementStrategy,
} from '../../dashboard_constants';
import { DashboardAnalyticsService } from '../../services/analytics/types';
import { DashboardCapabilitiesService } from '../../services/dashboard_capabilities/types';
import { pluginServices } from '../../services/plugin_services';
import { placePanel } from '../panel_placement';
import { runPanelPlacementStrategy } from '../panel_placement/place_new_panel_strategies';
import { DashboardViewport } from '../component/viewport/dashboard_viewport';
import { DashboardExternallyAccessibleApi } from '../external_api/dashboard_api';
import { getDashboardPanelPlacementSetting } from '../panel_placement/panel_placement_registry';
import { dashboardContainerReducers } from '../state/dashboard_container_reducers';
import { getDiffingMiddleware } from '../state/diffing/dashboard_diffing_integration';
import { DashboardPublicState, DashboardReduxState, UnsavedPanelState } from '../types';
import {
addFromLibrary,
addOrUpdateEmbeddable,
runQuickSave,
runInteractiveSave,
showSettings,
} from './api';
import { duplicateDashboardPanel } from './api/duplicate_dashboard_panel';
import { combineDashboardFiltersWithControlGroupFilters } from './create/controls/dashboard_control_group_integration';
import { initializeDashboard } from './create/create_dashboard';
import {
DashboardCreationOptions,
dashboardTypeDisplayLowercase,
dashboardTypeDisplayName,
} from './dashboard_container_factory';
import { getPanelAddedSuccessString } from '../../dashboard_app/_dashboard_app_strings';
export interface InheritedChildInput {
filters: Filter[];
query: Query;
timeRange?: TimeRange;
timeslice?: [number, number];
refreshConfig?: RefreshInterval;
viewMode: ViewMode;
hidePanelTitles?: boolean;
id: string;
searchSessionId?: string;
syncColors?: boolean;
syncCursor?: boolean;
syncTooltips?: boolean;
executionContext?: KibanaExecutionContext;
}
type DashboardReduxEmbeddableTools = ReduxEmbeddableTools<
DashboardReduxState,
typeof dashboardContainerReducers
>;
export const DashboardContainerContext = createContext<DashboardContainer | null>(null);
export const useDashboardContainer = (): DashboardContainer => {
const dashboard = useContext<DashboardContainer | null>(DashboardContainerContext);
if (dashboard == null) {
throw new Error('useDashboardContainer must be used inside DashboardContainerContext.');
}
return dashboard!;
};
export class DashboardContainer
extends Container<InheritedChildInput, DashboardContainerInput>
implements
DashboardExternallyAccessibleApi,
TrackContentfulRender,
TracksQueryPerformance,
HasSaveNotification,
HasRuntimeChildState,
HasSerializedChildState,
PublishesSettings,
Partial<PublishesViewMode>
{
public readonly type = DASHBOARD_CONTAINER_TYPE;
// state management
public select: DashboardReduxEmbeddableTools['select'];
public getState: DashboardReduxEmbeddableTools['getState'];
public dispatch: DashboardReduxEmbeddableTools['dispatch'];
public onStateChange: DashboardReduxEmbeddableTools['onStateChange'];
public anyReducerRun: Subject<null> = new Subject();
public integrationSubscriptions: Subscription = new Subscription();
public publishingSubscription: Subscription = new Subscription();
public diffingSubscription: Subscription = new Subscription();
public controlGroup?: ControlGroupContainer;
public settings: Record<string, PublishingSubject<boolean | undefined>>;
public searchSessionId?: string;
public lastReloadRequestTime$ = new BehaviorSubject<string | undefined>(undefined);
public searchSessionId$ = new BehaviorSubject<string | undefined>(undefined);
public reload$ = new Subject<void>();
public timeRestore$: BehaviorSubject<boolean | undefined>;
public timeslice$: BehaviorSubject<[number, number] | undefined>;
public locator?: Pick<LocatorPublic<DashboardLocatorParams>, 'navigate' | 'getRedirectUrl'>;
public readonly executionContext: KibanaExecutionContext;
private domNode?: HTMLElement;
private overlayRef?: OverlayRef;
private allDataViews: DataView[] = [];
// performance monitoring
public lastLoadStartTime?: number;
public creationStartTime?: number;
public creationEndTime?: number;
public firstLoad: boolean = true;
private hadContentfulRender = false;
private scrollPosition?: number;
// cleanup
public stopSyncingWithUnifiedSearch?: () => void;
private cleanupStateTools: () => void;
// Services that are used in the Dashboard container code
private creationOptions?: DashboardCreationOptions;
private analyticsService: DashboardAnalyticsService;
private showWriteControls: DashboardCapabilitiesService['showWriteControls'];
private i18n: I18nStart;
private theme;
private chrome;
private customBranding;
public trackContentfulRender() {
if (!this.hadContentfulRender && this.analyticsService) {
this.analyticsService.reportEvent('dashboard_loaded_with_data', {});
}
this.hadContentfulRender = true;
}
private trackPanelAddMetric:
| ((type: string, eventNames: string | string[], count?: number | undefined) => void)
| undefined;
// new embeddable framework
public savedObjectReferences: Reference[] = [];
constructor(
initialInput: DashboardContainerInput,
reduxToolsPackage: ReduxToolsPackage,
initialSessionId?: string,
dashboardCreationStartTime?: number,
parent?: Container,
creationOptions?: DashboardCreationOptions,
initialComponentState?: DashboardPublicState
) {
const {
usageCollection,
embeddable: { getEmbeddableFactory },
} = pluginServices.getServices();
super(
{
...initialInput,
},
{ embeddableLoaded: {} },
getEmbeddableFactory,
parent
);
this.trackPanelAddMetric = usageCollection.reportUiCounter?.bind(
usageCollection,
DASHBOARD_UI_METRIC_ID
);
({
analytics: this.analyticsService,
settings: { theme: this.theme, i18n: this.i18n },
chrome: this.chrome,
customBranding: this.customBranding,
dashboardCapabilities: { showWriteControls: this.showWriteControls },
} = pluginServices.getServices());
this.creationOptions = creationOptions;
this.searchSessionId = initialSessionId;
this.searchSessionId$.next(initialSessionId);
this.creationStartTime = dashboardCreationStartTime;
// start diffing dashboard state
const diffingMiddleware = getDiffingMiddleware.bind(this)();
// build redux embeddable tools
const reduxTools = reduxToolsPackage.createReduxEmbeddableTools<
DashboardReduxState,
typeof dashboardContainerReducers
>({
embeddable: this,
reducers: dashboardContainerReducers,
additionalMiddleware: [diffingMiddleware],
initialComponentState,
});
this.onStateChange = reduxTools.onStateChange;
this.cleanupStateTools = reduxTools.cleanup;
this.getState = reduxTools.getState;
this.dispatch = reduxTools.dispatch;
this.select = reduxTools.select;
this.savedObjectId = new BehaviorSubject(this.getDashboardSavedObjectId());
this.publishingSubscription.add(
this.onStateChange(() => {
if (this.savedObjectId.value === this.getDashboardSavedObjectId()) return;
this.savedObjectId.next(this.getDashboardSavedObjectId());
})
);
this.publishingSubscription.add(
this.savedObjectId.subscribe(() => {
this.hadContentfulRender = false;
})
);
this.expandedPanelId = new BehaviorSubject(this.getDashboardSavedObjectId());
this.publishingSubscription.add(
this.onStateChange(() => {
if (this.expandedPanelId.value === this.getExpandedPanelId()) return;
this.expandedPanelId.next(this.getExpandedPanelId());
})
);
this.startAuditingReactEmbeddableChildren();
this.settings = {
syncColors$: embeddableInputToSubject<boolean | undefined, DashboardContainerInput>(
this.publishingSubscription,
this,
'syncColors'
),
syncCursor$: embeddableInputToSubject<boolean | undefined, DashboardContainerInput>(
this.publishingSubscription,
this,
'syncCursor'
),
syncTooltips$: embeddableInputToSubject<boolean | undefined, DashboardContainerInput>(
this.publishingSubscription,
this,
'syncTooltips'
),
};
this.timeRestore$ = embeddableInputToSubject<boolean | undefined, DashboardContainerInput>(
this.publishingSubscription,
this,
'timeRestore'
);
this.timeslice$ = embeddableInputToSubject<
[number, number] | undefined,
DashboardContainerInput
>(this.publishingSubscription, this, 'timeslice');
this.lastReloadRequestTime$ = embeddableInputToSubject<
string | undefined,
DashboardContainerInput
>(this.publishingSubscription, this, 'lastReloadRequestTime');
this.executionContext = initialInput.executionContext;
}
public getAppContext() {
const embeddableAppContext = this.creationOptions?.getEmbeddableAppContext?.(
this.getDashboardSavedObjectId()
);
return {
...embeddableAppContext,
currentAppId: embeddableAppContext?.currentAppId ?? DASHBOARD_APP_ID,
};
}
public getDashboardSavedObjectId() {
return this.getState().componentState.lastSavedId;
}
protected createNewPanelState<
TEmbeddableInput extends EmbeddableInput,
TEmbeddable extends IEmbeddable<TEmbeddableInput, any>
>(
factory: EmbeddableFactory<TEmbeddableInput, any, TEmbeddable>,
partial: Partial<TEmbeddableInput> = {},
attributes?: unknown
): {
newPanel: DashboardPanelState<TEmbeddableInput>;
otherPanels: DashboardContainerInput['panels'];
} {
const { newPanel } = super.createNewPanelState(factory, partial, attributes);
return placePanel(factory, newPanel, this.input.panels, attributes);
}
public render(dom: HTMLElement) {
if (this.domNode) {
ReactDOM.unmountComponentAtNode(this.domNode);
}
this.domNode = dom;
this.domNode.className = 'dashboardContainer';
ReactDOM.render(
<KibanaRenderContextProvider
analytics={this.analyticsService}
i18n={this.i18n}
theme={this.theme}
>
<ExitFullScreenButtonKibanaProvider
coreStart={{ chrome: this.chrome, customBranding: this.customBranding }}
>
<DashboardContainerContext.Provider value={this}>
<DashboardViewport />
</DashboardContainerContext.Provider>
</ExitFullScreenButtonKibanaProvider>
</KibanaRenderContextProvider>,
dom
);
}
public updateInput(changes: Partial<DashboardContainerInput>): void {
// block the Dashboard from entering edit mode if this Dashboard is managed.
if (
(this.getState().componentState.managed || !this.showWriteControls) &&
changes.viewMode?.toLowerCase() === ViewMode.EDIT?.toLowerCase()
) {
const { viewMode, ...rest } = changes;
super.updateInput(rest);
return;
}
super.updateInput(changes);
}
protected getInheritedInput(id: string): InheritedChildInput {
const {
query,
filters,
viewMode,
timeRange,
timeslice,
syncColors,
syncTooltips,
syncCursor,
hidePanelTitles,
refreshInterval,
executionContext,
panels,
} = this.input;
let combinedFilters = filters;
if (this.controlGroup) {
combinedFilters = combineDashboardFiltersWithControlGroupFilters(filters, this.controlGroup);
}
const hasCustomTimeRange = Boolean(
(panels[id]?.explicitInput as Partial<InheritedChildInput>)?.timeRange
);
return {
searchSessionId: this.searchSessionId,
refreshConfig: refreshInterval,
filters: combinedFilters,
hidePanelTitles,
executionContext,
syncTooltips,
syncColors,
syncCursor,
viewMode,
query,
id,
// do not pass any time information from dashboard to panel when panel has custom time range
// to avoid confusing panel which timeRange should be used
timeRange: hasCustomTimeRange ? undefined : timeRange,
timeslice: hasCustomTimeRange ? undefined : timeslice,
};
}
// ------------------------------------------------------------------------------------------------------
// Cleanup
// ------------------------------------------------------------------------------------------------------
public destroy() {
super.destroy();
this.cleanupStateTools();
this.controlGroup?.destroy();
this.diffingSubscription.unsubscribe();
this.publishingSubscription.unsubscribe();
this.integrationSubscriptions.unsubscribe();
this.stopSyncingWithUnifiedSearch?.();
if (this.domNode) ReactDOM.unmountComponentAtNode(this.domNode);
}
// ------------------------------------------------------------------------------------------------------
// Dashboard API
// ------------------------------------------------------------------------------------------------------
public runInteractiveSave = runInteractiveSave;
public runQuickSave = runQuickSave;
public showSettings = showSettings;
public addFromLibrary = addFromLibrary;
public duplicatePanel(id: string) {
duplicateDashboardPanel.bind(this)(id);
}
public canRemovePanels = () => !this.getExpandedPanelId();
public getTypeDisplayName = () => dashboardTypeDisplayName;
public getTypeDisplayNameLowerCase = () => dashboardTypeDisplayLowercase;
public savedObjectId: BehaviorSubject<string | undefined>;
public expandedPanelId: BehaviorSubject<string | undefined>;
public async replacePanel(idToRemove: string, { panelType, initialState }: PanelPackage) {
const newId = await this.replaceEmbeddable(
idToRemove,
initialState as Partial<EmbeddableInput>,
panelType,
true
);
if (this.getExpandedPanelId() !== undefined) {
this.setExpandedPanelId(newId);
}
this.setHighlightPanelId(newId);
return newId;
}
public async addNewPanel<ApiType extends unknown = unknown>(
panelPackage: PanelPackage,
displaySuccessMessage?: boolean
) {
const {
notifications: { toasts },
embeddable: { getEmbeddableFactory, reactEmbeddableRegistryHasKey },
} = pluginServices.getServices();
const onSuccess = (id?: string, title?: string) => {
if (!displaySuccessMessage) return;
toasts.addSuccess({
title: getPanelAddedSuccessString(title),
'data-test-subj': 'addEmbeddableToDashboardSuccess',
});
this.setScrollToPanelId(id);
this.setHighlightPanelId(id);
};
if (this.trackPanelAddMetric) {
this.trackPanelAddMetric(METRIC_TYPE.CLICK, panelPackage.panelType);
}
if (reactEmbeddableRegistryHasKey(panelPackage.panelType)) {
const newId = v4();
const placementSettings = {
width: DEFAULT_PANEL_WIDTH,
height: DEFAULT_PANEL_HEIGHT,
strategy: PanelPlacementStrategy.findTopLeftMostOpenSpace,
...getDashboardPanelPlacementSetting(panelPackage.panelType)?.(panelPackage.initialState),
};
const { width, height, strategy } = placementSettings;
const { newPanelPlacement, otherPanels } = runPanelPlacementStrategy(strategy, {
currentPanels: this.getInput().panels,
height,
width,
});
const newPanel: DashboardPanelState = {
type: panelPackage.panelType,
gridData: {
...newPanelPlacement,
i: newId,
},
explicitInput: {
...panelPackage.initialState,
id: newId,
},
};
this.updateInput({ panels: { ...otherPanels, [newId]: newPanel } });
onSuccess(newId, newPanel.explicitInput.title);
return await this.untilReactEmbeddableLoaded<ApiType>(newId);
}
const embeddableFactory = getEmbeddableFactory(panelPackage.panelType);
if (!embeddableFactory) {
throw new EmbeddableFactoryNotFoundError(panelPackage.panelType);
}
const initialInput = panelPackage.initialState as Partial<EmbeddableInput>;
let explicitInput: Partial<EmbeddableInput>;
let attributes: unknown;
try {
if (initialInput) {
explicitInput = initialInput;
} else {
const explicitInputReturn = await embeddableFactory.getExplicitInput(undefined, this);
if (isExplicitInputWithAttributes(explicitInputReturn)) {
explicitInput = explicitInputReturn.newInput;
attributes = explicitInputReturn.attributes;
} else {
explicitInput = explicitInputReturn;
}
}
} catch (e) {
// error likely means user canceled embeddable creation
return;
}
const newEmbeddable = await this.addNewEmbeddable(
embeddableFactory.type,
explicitInput,
attributes
);
if (newEmbeddable) {
onSuccess(newEmbeddable.id, newEmbeddable.getTitle());
}
return newEmbeddable as ApiType;
}
public getDashboardPanelFromId = async (panelId: string) => {
const {
embeddable: { reactEmbeddableRegistryHasKey },
} = pluginServices.getServices();
const panel = this.getInput().panels[panelId];
if (reactEmbeddableRegistryHasKey(panel.type)) {
const child = this.children$.value[panelId];
if (!child) throw new PanelNotFoundError();
const serialized = apiHasSerializableState(child)
? await child.serializeState()
: { rawState: {} };
return {
type: panel.type,
explicitInput: { ...panel.explicitInput, ...serialized.rawState },
gridData: panel.gridData,
references: serialized.references,
};
}
return panel;
};
public expandPanel = (panelId: string) => {
const isPanelExpanded = Boolean(this.getExpandedPanelId());
if (isPanelExpanded) {
this.setExpandedPanelId(undefined);
this.setScrollToPanelId(panelId);
return;
}
this.setExpandedPanelId(panelId);
if (window.scrollY > 0) {
this.scrollPosition = window.scrollY;
}
};
public addOrUpdateEmbeddable = addOrUpdateEmbeddable;
public forceRefresh(refreshControlGroup: boolean = true) {
this.dispatch.setLastReloadRequestTimeToNow({});
if (refreshControlGroup) {
this.controlGroup?.reload();
// only reload all panels if this refresh does not come from the control group.
this.reload$.next();
}
}
public onDataViewsUpdate$ = new Subject<DataView[]>();
public resetToLastSavedState() {
this.dispatch.resetToLastSavedInput({});
const {
explicitInput: { timeRange, refreshInterval },
componentState: {
lastSavedInput: { timeRestore: lastSavedTimeRestore },
},
} = this.getState();
if (this.controlGroup) {
this.controlGroup.resetToLastSavedState();
}
// if we are using the unified search integration, we need to force reset the time picker.
if (this.creationOptions?.useUnifiedSearchIntegration && lastSavedTimeRestore) {
const {
data: {
query: {
timefilter: { timefilter: timeFilterService },
},
},
} = pluginServices.getServices();
if (timeRange) timeFilterService.setTime(timeRange);
if (refreshInterval) timeFilterService.setRefreshInterval(refreshInterval);
}
this.resetAllReactEmbeddables();
}
public navigateToDashboard = async (
newSavedObjectId?: string,
newCreationOptions?: Partial<DashboardCreationOptions>
) => {
this.integrationSubscriptions.unsubscribe();
this.integrationSubscriptions = new Subscription();
this.stopSyncingWithUnifiedSearch?.();
const {
dashboardContentManagement: { loadDashboardState },
} = pluginServices.getServices();
if (newCreationOptions) {
this.creationOptions = { ...this.creationOptions, ...newCreationOptions };
}
const loadDashboardReturn = await loadDashboardState({ id: newSavedObjectId });
const dashboardContainerReady$ = new Subject<DashboardContainer>();
const untilDashboardReady = () =>
new Promise<DashboardContainer>((resolve) => {
const subscription = dashboardContainerReady$.subscribe((container) => {
subscription.unsubscribe();
resolve(container);
});
});
const initializeResult = await initializeDashboard({
creationOptions: this.creationOptions,
controlGroup: this.controlGroup,
untilDashboardReady,
loadDashboardReturn,
});
if (!initializeResult) return;
const { input: newInput, searchSessionId } = initializeResult;
this.searchSessionId = searchSessionId;
this.searchSessionId$.next(searchSessionId);
batch(() => {
this.dispatch.setLastSavedInput(
omit(loadDashboardReturn?.dashboardInput, 'controlGroupInput')
);
this.dispatch.setManaged(loadDashboardReturn?.managed);
if (this.controlGroup) {
this.controlGroup.setSavedState(loadDashboardReturn.dashboardInput?.controlGroupInput);
}
this.dispatch.setAnimatePanelTransforms(false); // prevents panels from animating on navigate.
this.dispatch.setLastSavedId(newSavedObjectId);
this.setExpandedPanelId(undefined);
});
this.firstLoad = true;
this.updateInput(newInput);
dashboardContainerReady$.next(this);
};
/**
* Gets all the dataviews that are actively being used in the dashboard
* @returns An array of dataviews
*/
public getAllDataViews = () => {
return this.allDataViews;
};
/**
* Use this to set the dataviews that are used in the dashboard when they change/update
* @param newDataViews The new array of dataviews that will overwrite the old dataviews array
*/
public setAllDataViews = (newDataViews: DataView[]) => {
this.allDataViews = newDataViews;
this.onDataViewsUpdate$.next(newDataViews);
};
public getExpandedPanelId = () => {
return this.getState().componentState.expandedPanelId;
};
public setExpandedPanelId = (newId?: string) => {
this.dispatch.setExpandedPanelId(newId);
};
public openOverlay = (ref: OverlayRef, options?: { focusedPanelId?: string }) => {
this.clearOverlays();
this.dispatch.setHasOverlays(true);
this.overlayRef = ref;
if (options?.focusedPanelId) {
this.setFocusedPanelId(options?.focusedPanelId);
}
};
public clearOverlays = () => {
this.dispatch.setHasOverlays(false);
this.dispatch.setFocusedPanelId(undefined);
this.controlGroup?.closeAllFlyouts();
this.overlayRef?.close();
};
public getPanelCount = () => {
return Object.keys(this.getInput().panels).length;
};
public async getPanelTitles(): Promise<string[]> {
const {
embeddable: { reactEmbeddableRegistryHasKey },
} = pluginServices.getServices();
const titles: string[] = [];
for (const [id, panel] of Object.entries(this.getInput().panels)) {
const title = await (async () => {
if (reactEmbeddableRegistryHasKey(panel.type)) {
const child = this.children$.value[id];
return apiPublishesPanelTitle(child) ? getPanelTitle(child) : '';
}
await this.untilEmbeddableLoaded(id);
const child: IEmbeddable<EmbeddableInput, EmbeddableOutput> = this.getChild(id);
if (!child) return undefined;
return child.getTitle();
})();
if (title) titles.push(title);
}
return titles;
}
public setScrollToPanelId = (id: string | undefined) => {
this.dispatch.setScrollToPanelId(id);
};
public scrollToPanel = async (panelRef: HTMLDivElement) => {
const id = this.getState().componentState.scrollToPanelId;
if (!id) return;
this.untilEmbeddableLoaded(id).then(() => {
this.setScrollToPanelId(undefined);
if (this.scrollPosition) {
panelRef.ontransitionend = () => {
// Scroll to the last scroll position after the transition ends to ensure the panel is back in the right position before scrolling
// This is necessary because when an expanded panel collapses, it takes some time for the panel to return to its original position
window.scrollTo({ top: this.scrollPosition });
this.scrollPosition = undefined;
panelRef.ontransitionend = null;
};
return;
}
panelRef.scrollIntoView({ block: 'nearest' });
});
};
public scrollToTop = () => {
window.scroll(0, 0);
};
public setHighlightPanelId = (id: string | undefined) => {
this.dispatch.setHighlightPanelId(id);
};
public highlightPanel = (panelRef: HTMLDivElement) => {
const id = this.getState().componentState.highlightPanelId;
if (id && panelRef) {
this.untilEmbeddableLoaded(id).then(() => {
panelRef.classList.add('dshDashboardGrid__item--highlighted');
// Removes the class after the highlight animation finishes
setTimeout(() => {
panelRef.classList.remove('dshDashboardGrid__item--highlighted');
}, 5000);
});
}
this.setHighlightPanelId(undefined);
};
public setFocusedPanelId = (id: string | undefined) => {
this.dispatch.setFocusedPanelId(id);
this.setScrollToPanelId(id);
};
// ------------------------------------------------------------------------------------------------------
// React Embeddable system
// ------------------------------------------------------------------------------------------------------
public registerChildApi = (api: DefaultEmbeddableApi) => {
this.children$.next({
...this.children$.value,
[api.uuid]: api as DefaultEmbeddableApi,
});
};
public saveNotification$: Subject<void> = new Subject<void>();
public getSerializedStateForChild = (childId: string) => {
const rawState = this.getInput().panels[childId].explicitInput;
const { id, ...serializedState } = rawState;
if (!rawState || Object.keys(serializedState).length === 0) return;
const references = getReferencesForPanelId(childId, this.savedObjectReferences);
return {
rawState,
// references from old installations may not be prefixed with panel id
// fall back to passing all references in these cases to preserve backwards compatability
references: references.length > 0 ? references : this.savedObjectReferences,
};
};
private restoredRuntimeState: UnsavedPanelState | undefined = undefined;
public setRuntimeStateForChild = (childId: string, state: object) => {
const runtimeState = this.restoredRuntimeState ?? {};
runtimeState[childId] = state;
this.restoredRuntimeState = runtimeState;
};
public getRuntimeStateForChild = (childId: string) => {
return this.restoredRuntimeState?.[childId];
};
public removePanel(id: string) {
const {
embeddable: { reactEmbeddableRegistryHasKey },
} = pluginServices.getServices();
const type = this.getInput().panels[id]?.type;
this.removeEmbeddable(id);
if (reactEmbeddableRegistryHasKey(type)) {
const { [id]: childToRemove, ...otherChildren } = this.children$.value;
this.children$.next(otherChildren);
}
}
public startAuditingReactEmbeddableChildren = () => {
const auditChildren = () => {
const currentChildren = this.children$.value;
let panelsChanged = false;
for (const panelId of Object.keys(currentChildren)) {
if (!this.getInput().panels[panelId]) {
delete currentChildren[panelId];
panelsChanged = true;
}
}
if (panelsChanged) this.children$.next(currentChildren);
};
// audit children when panels change
this.publishingSubscription.add(
this.getInput$()
.pipe(
map(() => Object.keys(this.getInput().panels)),
distinctUntilChanged(deepEqual)
)
.subscribe(() => auditChildren())
);
auditChildren();
};
public resetAllReactEmbeddables = () => {
this.restoredRuntimeState = undefined;
let resetChangedPanelCount = false;
const currentChildren = this.children$.value;
for (const panelId of Object.keys(currentChildren)) {
if (this.getInput().panels[panelId]) {
const child = currentChildren[panelId];
if (apiPublishesUnsavedChanges(child)) child.resetUnsavedChanges();
} else {
// if reset resulted in panel removal, we need to update the list of children
delete currentChildren[panelId];
resetChangedPanelCount = true;
}
}
if (resetChangedPanelCount) this.children$.next(currentChildren);
};
}