-
Notifications
You must be signed in to change notification settings - Fork 8.2k
/
plugin.ts
402 lines (372 loc) · 13.7 KB
/
plugin.ts
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
/*
* 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 { i18n } from '@kbn/i18n';
import { filter, map } from 'rxjs/operators';
import { createHashHistory } from 'history';
import { BehaviorSubject } from 'rxjs';
import {
AppMountParameters,
AppUpdater,
DEFAULT_APP_CATEGORIES,
ScopedHistory,
} from '@kbn/core/public';
import {
createKbnUrlStateStorage,
createKbnUrlTracker,
createStartServicesGetter,
Storage,
withNotifyOnErrors,
} from '@kbn/kibana-utils-plugin/public';
import type { UnifiedSearchPublicPluginStart } from '@kbn/unified-search-plugin/public';
import type {
PluginInitializerContext,
CoreSetup,
CoreStart,
Plugin,
ApplicationStart,
SavedObjectsClientContract,
} from '@kbn/core/public';
import type { UiActionsStart, UiActionsSetup } from '@kbn/ui-actions-plugin/public';
import type { SavedObjectsStart } from '@kbn/saved-objects-plugin/public';
import type { FieldFormatsStart } from '@kbn/field-formats-plugin/public';
import type {
Setup as InspectorSetup,
Start as InspectorStart,
} from '@kbn/inspector-plugin/public';
import type { DataPublicPluginSetup, DataPublicPluginStart } from '@kbn/data-plugin/public';
import type { DataViewsPublicPluginStart } from '@kbn/data-views-plugin/public';
import type { ExpressionsSetup, ExpressionsStart } from '@kbn/expressions-plugin/public';
import type { EmbeddableSetup, EmbeddableStart } from '@kbn/embeddable-plugin/public';
import type { SavedObjectTaggingOssPluginStart } from '@kbn/saved-objects-tagging-oss-plugin/public';
import type { NavigationPublicPluginStart as NavigationStart } from '@kbn/navigation-plugin/public';
import type { SharePluginSetup, SharePluginStart } from '@kbn/share-plugin/public';
import type { UrlForwardingSetup, UrlForwardingStart } from '@kbn/url-forwarding-plugin/public';
import type { PresentationUtilPluginStart } from '@kbn/presentation-util-plugin/public';
import type { ScreenshotModePluginStart } from '@kbn/screenshot-mode-plugin/public';
import type { HomePublicPluginSetup } from '@kbn/home-plugin/public';
import type { SpacesPluginStart } from '@kbn/spaces-plugin/public';
import type { DataViewEditorStart } from '@kbn/data-view-editor-plugin/public';
import type { TypesSetup, TypesStart } from './vis_types';
import type { VisualizeServices } from './visualize_app/types';
import { visualizeEditorTrigger } from './triggers';
import { createVisEditorsRegistry, VisEditorsRegistry } from './vis_editors_registry';
import { showNewVisModal } from './wizard';
import { VisualizeLocatorDefinition } from '../common/locator';
import { xyDimension as xyDimensionExpressionFunction } from '../common/expression_functions/xy_dimension';
import { visDimension as visDimensionExpressionFunction } from '../common/expression_functions/vis_dimension';
import { range as rangeExpressionFunction } from '../common/expression_functions/range';
import { TypesService } from './vis_types/types_service';
import {
createVisEmbeddableFromObject,
VISUALIZE_EMBEDDABLE_TYPE,
VisualizeEmbeddableFactory,
} from './embeddable';
import {
setUISettings,
setTypes,
setApplication,
setCapabilities,
setHttp,
setSearch,
setSavedObjects,
setExpressions,
setUiActions,
setTimeFilter,
setAggs,
setChrome,
setOverlays,
setEmbeddable,
setDocLinks,
setSpaces,
setTheme,
setExecutionContext,
setFieldFormats,
setSavedObjectTagging,
} from './services';
import { VisualizeConstants } from '../common/constants';
/**
* Interface for this plugin's returned setup/start contracts.
*
* @public
*/
export type VisualizationsSetup = TypesSetup & { visEditorsRegistry: VisEditorsRegistry };
export interface VisualizationsStart extends TypesStart {
showNewVisModal: typeof showNewVisModal;
}
export interface VisualizationsSetupDeps {
data: DataPublicPluginSetup;
embeddable: EmbeddableSetup;
expressions: ExpressionsSetup;
inspector: InspectorSetup;
uiActions: UiActionsSetup;
urlForwarding: UrlForwardingSetup;
home?: HomePublicPluginSetup;
share?: SharePluginSetup;
}
export interface VisualizationsStartDeps {
data: DataPublicPluginStart;
dataViews: DataViewsPublicPluginStart;
dataViewEditor: DataViewEditorStart;
expressions: ExpressionsStart;
embeddable: EmbeddableStart;
inspector: InspectorStart;
uiActions: UiActionsStart;
application: ApplicationStart;
getAttributeService: EmbeddableStart['getAttributeService'];
navigation: NavigationStart;
presentationUtil: PresentationUtilPluginStart;
savedObjects: SavedObjectsStart;
savedObjectsClient: SavedObjectsClientContract;
spaces?: SpacesPluginStart;
savedObjectsTaggingOss?: SavedObjectTaggingOssPluginStart;
share?: SharePluginStart;
urlForwarding: UrlForwardingStart;
screenshotMode: ScreenshotModePluginStart;
fieldFormats: FieldFormatsStart;
unifiedSearch: UnifiedSearchPublicPluginStart;
}
/**
* Visualizations Plugin - public
*
* This plugin's stateful contracts are returned from the `setup` and `start` methods
* below. The interfaces for these contracts are provided above.
*
* @internal
*/
export class VisualizationsPlugin
implements
Plugin<
VisualizationsSetup,
VisualizationsStart,
VisualizationsSetupDeps,
VisualizationsStartDeps
>
{
private readonly types: TypesService = new TypesService();
private appStateUpdater = new BehaviorSubject<AppUpdater>(() => ({}));
private stopUrlTracking: (() => void) | undefined = undefined;
private currentHistory: ScopedHistory | undefined = undefined;
private isLinkedToOriginatingApp: (() => boolean) | undefined = undefined;
constructor(private initializerContext: PluginInitializerContext) {}
public setup(
core: CoreSetup<VisualizationsStartDeps, VisualizationsStart>,
{
expressions,
embeddable,
data,
home,
urlForwarding,
share,
uiActions,
}: VisualizationsSetupDeps
): VisualizationsSetup {
const {
appMounted,
appUnMounted,
stop: stopUrlTracker,
setActiveUrl,
restorePreviousUrl,
} = createKbnUrlTracker({
baseUrl: core.http.basePath.prepend(VisualizeConstants.VISUALIZE_BASE_PATH),
defaultSubUrl: '#/',
storageKey: `lastUrl:${core.http.basePath.get()}:visualize`,
navLinkUpdater$: this.appStateUpdater,
toastNotifications: core.notifications.toasts,
stateParams: [
{
kbnUrlKey: '_g',
stateUpdate$: data.query.state$.pipe(
filter(
({ changes }) => !!(changes.globalFilters || changes.time || changes.refreshInterval)
),
map(({ state }) => ({
...state,
filters: data.query.filterManager.getGlobalFilters(),
}))
),
},
],
getHistory: () => this.currentHistory!,
onBeforeNavLinkSaved: (urlToSave: string) => {
if (this.isLinkedToOriginatingApp?.()) {
return core.http.basePath.prepend(VisualizeConstants.VISUALIZE_BASE_PATH);
}
return urlToSave;
},
});
this.stopUrlTracking = () => {
stopUrlTracker();
};
const start = createStartServicesGetter(core.getStartServices);
const visEditorsRegistry = createVisEditorsRegistry();
core.application.register({
id: VisualizeConstants.APP_ID,
title: 'Visualize Library',
order: 8000,
euiIconType: 'logoKibana',
defaultPath: '#/',
category: DEFAULT_APP_CATEGORIES.kibana,
updater$: this.appStateUpdater.asObservable(),
// remove all references to visualize
mount: async (params: AppMountParameters) => {
const [coreStart, pluginsStart] = await core.getStartServices();
this.currentHistory = params.history;
// allows the urlTracker to only save URLs that are not linked to an originatingApp
this.isLinkedToOriginatingApp = () => {
return Boolean(
pluginsStart.embeddable
.getStateTransfer()
.getIncomingEditorState(VisualizeConstants.APP_ID)?.originatingApp
);
};
// make sure the index pattern list is up to date
pluginsStart.dataViews.clearCache();
appMounted();
// dispatch synthetic hash change event to update hash history objects
// this is necessary because hash updates triggered by using popState won't trigger this event naturally.
const unlistenParentHistory = params.history.listen(() => {
window.dispatchEvent(new HashChangeEvent('hashchange'));
});
/**
* current implementation uses 2 history objects:
* 1. the hash history (used for the react hash router)
* 2. and the scoped history (used for url tracking)
* this should be replaced to use only scoped history after moving legacy apps to browser routing
*/
const history = createHashHistory();
const services: VisualizeServices = {
...coreStart,
history,
kbnUrlStateStorage: createKbnUrlStateStorage({
history,
useHash: coreStart.uiSettings.get('state:storeInSessionStorage'),
...withNotifyOnErrors(coreStart.notifications.toasts),
}),
urlForwarding: pluginsStart.urlForwarding,
pluginInitializerContext: this.initializerContext,
chrome: coreStart.chrome,
data: pluginsStart.data,
core: coreStart,
dataViewEditor: pluginsStart.dataViewEditor,
dataViews: pluginsStart.dataViews,
localStorage: new Storage(localStorage),
navigation: pluginsStart.navigation,
share: pluginsStart.share,
toastNotifications: coreStart.notifications.toasts,
visualizeCapabilities: coreStart.application.capabilities.visualize,
dashboardCapabilities: coreStart.application.capabilities.dashboard,
embeddable: pluginsStart.embeddable,
stateTransferService: pluginsStart.embeddable.getStateTransfer(),
setActiveUrl,
createVisEmbeddableFromObject: createVisEmbeddableFromObject({ start }),
scopedHistory: params.history,
restorePreviousUrl,
setHeaderActionMenu: params.setHeaderActionMenu,
savedObjectsTagging: pluginsStart.savedObjectsTaggingOss?.getTaggingApi(),
presentationUtil: pluginsStart.presentationUtil,
getKibanaVersion: () => this.initializerContext.env.packageInfo.version,
spaces: pluginsStart.spaces,
visEditorsRegistry,
unifiedSearch: pluginsStart.unifiedSearch,
};
params.element.classList.add('visAppWrapper');
const { renderApp } = await import('./visualize_app');
if (pluginsStart.screenshotMode.isScreenshotMode()) {
params.element.classList.add('visEditorScreenshotModeActive');
// @ts-expect-error TS error, cannot find type declaration for scss
await import('./visualize_screenshot_mode.scss');
}
const unmount = renderApp(params, services);
return () => {
data.search.session.clear();
params.element.classList.remove('visAppWrapper');
unlistenParentHistory();
unmount();
appUnMounted();
};
},
});
urlForwarding.forwardApp('visualize', 'visualize');
if (home) {
home.featureCatalogue.register({
id: 'visualize',
title: 'Visualize Library',
description: i18n.translate('visualizations.visualizeDescription', {
defaultMessage:
'Create visualizations and aggregate data stores in your Elasticsearch indices.',
}),
icon: 'visualizeApp',
path: `/app/visualize#${VisualizeConstants.LANDING_PAGE_PATH}`,
showOnHomePage: false,
category: 'data',
});
}
if (share) {
share.url.locators.create(new VisualizeLocatorDefinition());
}
setUISettings(core.uiSettings);
setTheme(core.theme);
expressions.registerFunction(rangeExpressionFunction);
expressions.registerFunction(visDimensionExpressionFunction);
expressions.registerFunction(xyDimensionExpressionFunction);
uiActions.registerTrigger(visualizeEditorTrigger);
const embeddableFactory = new VisualizeEmbeddableFactory({ start });
embeddable.registerEmbeddableFactory(VISUALIZE_EMBEDDABLE_TYPE, embeddableFactory);
return {
...this.types.setup(),
visEditorsRegistry,
};
}
public start(
core: CoreStart,
{
data,
expressions,
uiActions,
embeddable,
savedObjects,
spaces,
savedObjectsTaggingOss,
fieldFormats,
}: VisualizationsStartDeps
): VisualizationsStart {
const types = this.types.start();
setTypes(types);
setEmbeddable(embeddable);
setApplication(core.application);
setCapabilities(core.application.capabilities);
setHttp(core.http);
setSavedObjects(core.savedObjects);
setDocLinks(core.docLinks);
setSearch(data.search);
setExpressions(expressions);
setUiActions(uiActions);
setTimeFilter(data.query.timefilter.timefilter);
setAggs(data.search.aggs);
setOverlays(core.overlays);
setExecutionContext(core.executionContext);
setChrome(core.chrome);
setFieldFormats(fieldFormats);
if (spaces) {
setSpaces(spaces);
}
if (savedObjectsTaggingOss) {
setSavedObjectTagging(savedObjectsTaggingOss);
}
return {
...types,
showNewVisModal,
};
}
public stop() {
this.types.stop();
if (this.stopUrlTracking) {
this.stopUrlTracking();
}
}
}