@luigi-project/client 2.28.1-dev.202603190049 → 2.28.1-dev.202603191108

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,2155 @@
1
+ /**
2
+ * @private
3
+ * @abstract
4
+ */
5
+ class LuigiClientBase {
6
+ /**
7
+ * @private
8
+ */
9
+ constructor() {
10
+ this.promises = {};
11
+ }
12
+ /**
13
+ * Returns the promises object
14
+ * @private
15
+ */
16
+ setPromise(name, value) {
17
+ this.promises[name] = value;
18
+ }
19
+ /**
20
+ * Sets the promises object
21
+ * @private
22
+ */
23
+ getPromise(name) {
24
+ return this.promises[name];
25
+ }
26
+ }
27
+
28
+ /** @private */
29
+ class Helpers {
30
+ /** @private */
31
+ constructor() {
32
+ this.listeners = [];
33
+ this.origin = '';
34
+
35
+ const helperListener = function (evt) {
36
+ if (!evt.data.msg) {
37
+ return;
38
+ }
39
+ if (evt.data.msg === 'custom') {
40
+ const message = this.convertCustomMessageInternalToUser(evt.data);
41
+ this.listeners
42
+ .filter((listener) => listener.name === message.id)
43
+ .map((listener) => listener.eventFn(message, listener.listenerId));
44
+ } else {
45
+ this.listeners
46
+ .filter((listener) => listener.name === evt.data.msg)
47
+ .map((listener) => listener.eventFn(evt, listener.listenerId));
48
+ }
49
+ }.bind(this);
50
+
51
+ window.addEventListener('message', helperListener);
52
+ }
53
+
54
+ convertCustomMessageInternalToUser(internalMessage) {
55
+ return internalMessage.data;
56
+ }
57
+
58
+ convertCustomMessageUserToInternal(message) {
59
+ return {
60
+ msg: 'custom',
61
+ data: message
62
+ };
63
+ }
64
+
65
+ convertStorageMessageToInternal(message) {
66
+ return {
67
+ msg: 'storage',
68
+ data: message
69
+ };
70
+ }
71
+
72
+ /**
73
+ * Registers a post message listener
74
+ * Don't forget to remove the event listener at the end of
75
+ * your eventFn if you do not need it anymore.
76
+ * @private
77
+ * @param {string} name - event name
78
+ * @param {function} eventFn - callback function
79
+ * @returns {string} listener id
80
+ */
81
+ addEventListener(name, eventFn) {
82
+ const listenerId = this.getRandomId();
83
+ this.listeners.push({
84
+ name,
85
+ eventFn,
86
+ listenerId
87
+ });
88
+ return listenerId;
89
+ }
90
+
91
+ /**
92
+ * Removes a post message listener
93
+ * @private
94
+ * @param {string} id - listenerId
95
+ */
96
+ removeEventListener(id) {
97
+ const listenerExists = Boolean(this.listeners.find((l) => l.listenerId === id));
98
+ if (listenerExists) {
99
+ this.listeners = this.listeners.filter((l) => l.listenerId !== id);
100
+ return true;
101
+ }
102
+ return false;
103
+ }
104
+
105
+ /**
106
+ * Creates a random Id
107
+ * @private
108
+ */
109
+ getRandomId() {
110
+ return window.crypto.getRandomValues(new Uint32Array(1))[0];
111
+ }
112
+
113
+ /**
114
+ * Simple function check.
115
+ * @private
116
+ * @param {function} item
117
+ * @returns {boolean}
118
+ */
119
+ isFunction(item) {
120
+ return typeof item === 'function';
121
+ }
122
+
123
+ /**
124
+ * Simple object check.
125
+ * @private
126
+ * @param {Object} item
127
+ * @returns {boolean}
128
+ */
129
+ isObject(item) {
130
+ return Object.prototype.toString.call(item) === '[object Object]';
131
+ }
132
+
133
+ getLuigiCoreDomain() {
134
+ return this.origin;
135
+ }
136
+
137
+ setLuigiCoreDomain(origin) {
138
+ // protect against "null" string set by at least Chrome browser when file protocol used
139
+ if (origin && origin !== 'null') {
140
+ this.origin = origin;
141
+ }
142
+ }
143
+
144
+ setTargetOrigin(origin) {
145
+ this.setLuigiCoreDomain(origin);
146
+ }
147
+
148
+ sendPostMessageToLuigiCore(msg) {
149
+ if (this.origin) {
150
+ // protect against potential postMessage problems, since origin value may be set incorrectly
151
+ try {
152
+ window.parent.postMessage(msg, this.origin);
153
+ } catch (error) {
154
+ console.warn('Unable to post message ' + msg + ' to Luigi Core from origin ' + this.origin + ': ' + error);
155
+ }
156
+ } else {
157
+ console.warn(
158
+ 'There is no target origin set. You can specify the target origin by calling LuigiClient.setTargetOrigin("targetorigin") in your micro frontend.'
159
+ );
160
+ }
161
+ }
162
+
163
+ /**
164
+ * Checks if given path contains intent navigation special syntax
165
+ * @param {string} path - path to be checked
166
+ */
167
+ hasIntent(path) {
168
+ return !!path && path.toLowerCase().includes('#?intent=');
169
+ }
170
+
171
+ deSanitizeParamsMap(paramsMap) {
172
+ return Object.entries(paramsMap).reduce((sanitizedMap, paramPair) => {
173
+ sanitizedMap[this.deSanitizeParam(paramPair[0])] = this.deSanitizeParam(paramPair[1]);
174
+ return sanitizedMap;
175
+ }, {});
176
+ }
177
+
178
+ deSanitizeParam(param = '') {
179
+ return String(param)
180
+ .replaceAll('&lt;', '<')
181
+ .replaceAll('&gt;', '>')
182
+ .replaceAll('&quot;', '"')
183
+ .replaceAll('&#39;', "'")
184
+ .replaceAll('&sol;', '/');
185
+ }
186
+ }
187
+
188
+ const helpers = new Helpers();
189
+
190
+ var version = "2.28.0";
191
+
192
+ /**
193
+ * @summary Use the functions and parameters to define the Lifecycle of listeners, navigation nodes, and Event data.
194
+ * @augments LuigiClientBase
195
+ * @name Lifecycle
196
+ * @class
197
+ */
198
+ class LifecycleManager extends LuigiClientBase {
199
+ /** @private */
200
+ constructor() {
201
+ super();
202
+ this.luigiInitialized = false;
203
+ this.defaultContextKeys = ['context', 'internal', 'nodeParams', 'pathParams', 'searchParams'];
204
+ this.setCurrentContext(
205
+ this.defaultContextKeys.reduce(function (acc, key) {
206
+ acc[key] = {};
207
+ return acc;
208
+ }, {})
209
+ );
210
+
211
+ this._onContextUpdatedFns = {};
212
+ this._onInactiveFns = {};
213
+ this._onInitFns = {};
214
+ this.authData = {};
215
+
216
+ if (!this._isDeferInitDefined()) {
217
+ this.luigiClientInit();
218
+ }
219
+ }
220
+
221
+ /**
222
+ * Check if the html head element contains the attribute "defer-luigi-init"
223
+ * @private
224
+ * @memberof Lifecycle
225
+ */
226
+ _isDeferInitDefined() {
227
+ return window.document.head.hasAttribute('defer-luigi-init');
228
+ }
229
+
230
+ /**
231
+ * Check if the html head element contains the attribute "disable-tpc-check"
232
+ * @private
233
+ * @memberof Lifecycle
234
+ */
235
+ _isTpcCheckDisabled() {
236
+ return (
237
+ window.document.head.hasAttribute('disable-tpc-check') ||
238
+ this.currentContext?.internal?.thirdPartyCookieCheck?.disabled
239
+ );
240
+ }
241
+
242
+ /**
243
+ * Check if LuigiClient is initialized
244
+ * @returns {boolean} client initialized state
245
+ * @since 1.12.0
246
+ * @memberof Lifecycle
247
+ * @example
248
+ * const init = LuigiClient.isLuigiClientInitialized()
249
+ */
250
+ isLuigiClientInitialized() {
251
+ return this.luigiInitialized;
252
+ }
253
+
254
+ /**
255
+ * Starts the handshake with Luigi Core and thereafter results in initialization of Luigi Client. It is always ran by default when importing the Luigi Client package in your micro frontend. Note that when using `defer-luigi-init` to defer default initialization, you will need to initialize the handshake using this function manually wherever needed.
256
+ * @since 1.12.0
257
+ * @memberof Lifecycle
258
+ * @example
259
+ * LuigiClient.luigiClientInit()
260
+ */
261
+ luigiClientInit() {
262
+ if (this.luigiInitialized) {
263
+ console.warn('Luigi Client has been already initialized');
264
+ return;
265
+ }
266
+ /**
267
+ * Save context data every time navigation to a different node happens
268
+ * @private
269
+ */
270
+ const setContext = (rawData) => {
271
+ for (let index = 0; index < this.defaultContextKeys.length; index++) {
272
+ let key = this.defaultContextKeys[index];
273
+ try {
274
+ if (typeof rawData[key] === 'string') {
275
+ rawData[key] = JSON.parse(rawData[key]);
276
+ }
277
+ } catch (e) {
278
+ console.info('unable to parse luigi context data for', key, rawData[key], e);
279
+ }
280
+ }
281
+ this.setCurrentContext(rawData);
282
+ };
283
+
284
+ const setAuthData = (eventPayload) => {
285
+ if (eventPayload) {
286
+ this.authData = eventPayload;
287
+ }
288
+ };
289
+
290
+ helpers.addEventListener('luigi.init', (e) => {
291
+ setContext(e.data);
292
+ setAuthData(e.data.authData);
293
+ helpers.setLuigiCoreDomain(e.origin);
294
+ this.luigiInitialized = true;
295
+ this._notifyInit(e.origin);
296
+ this._tpcCheck();
297
+ helpers.sendPostMessageToLuigiCore({ msg: 'luigi.init.ok' });
298
+ });
299
+
300
+ helpers.addEventListener('luigi-client.inactive-microfrontend', (e) => {
301
+ this._notifyInactive(e.origin);
302
+ });
303
+
304
+ helpers.addEventListener('luigi.auth.tokenIssued', (e) => {
305
+ setAuthData(e.data.authData);
306
+ });
307
+
308
+ helpers.addEventListener('luigi.navigate', (e) => {
309
+ setContext(e.data);
310
+ if (!this.currentContext.internal.isNavigateBack && !this.currentContext.withoutSync) {
311
+ const previousHash = window.location.hash;
312
+ history.replaceState({ luigiInduced: true }, '', e.data.viewUrl);
313
+ window.dispatchEvent(new PopStateEvent('popstate', { state: 'luiginavigation' }));
314
+ if (window.location.hash !== previousHash) {
315
+ window.dispatchEvent(new HashChangeEvent('hashchange'));
316
+ }
317
+ }
318
+ // pass additional data to context to enable micro frontend developer to act on internal routing change
319
+ if (this.currentContext.withoutSync) {
320
+ Object.assign(this.currentContext.context, {
321
+ viewUrl: e.data.viewUrl ? e.data.viewUrl : undefined,
322
+ pathParams: e.data.pathParams ? e.data.pathParams : undefined
323
+ });
324
+ }
325
+ // execute the context change listener if set by the micro frontend
326
+ this._notifyUpdate();
327
+ helpers.sendPostMessageToLuigiCore({ msg: 'luigi.navigate.ok' });
328
+ });
329
+
330
+ /**
331
+ * Get context once initially
332
+ * @private
333
+ */
334
+ window.parent.postMessage(
335
+ {
336
+ msg: 'luigi.get-context',
337
+ clientVersion: version
338
+ },
339
+ '*'
340
+ );
341
+ }
342
+
343
+ _tpcCheck() {
344
+ if (this._isTpcCheckDisabled()) {
345
+ return;
346
+ }
347
+
348
+ let tpc = 'enabled';
349
+ let cookies = document.cookie;
350
+ let luigiCookie;
351
+ if (cookies) {
352
+ luigiCookie = cookies
353
+ .split(';')
354
+ .map((cookie) => cookie.trim())
355
+ .find((cookie) => cookie === 'luigiCookie=true');
356
+ }
357
+ if (luigiCookie === 'luigiCookie=true') {
358
+ document.cookie = 'luigiCookie=; Max-Age=-99999999; SameSite=None; Secure';
359
+ }
360
+ document.cookie = 'luigiCookie=true; SameSite=None; Secure';
361
+ cookies = document.cookie;
362
+ if (cookies) {
363
+ luigiCookie = cookies
364
+ .split(';')
365
+ .map((cookie) => cookie.trim())
366
+ .find((cookie) => cookie === 'luigiCookie=true');
367
+ }
368
+ if (luigiCookie === 'luigiCookie=true') {
369
+ document.cookie = 'luigiCookie=; Max-Age=-99999999; SameSite=None; Secure';
370
+ window.parent.postMessage({ msg: 'luigi.third-party-cookie', tpc }, '*');
371
+ } else {
372
+ tpc = 'disabled';
373
+ window.parent.postMessage({ msg: 'luigi.third-party-cookie', tpc }, '*');
374
+ console.warn('Third party cookies are not supported!');
375
+ }
376
+ }
377
+
378
+ /**
379
+ * Iterates over an object and executes all top-level functions
380
+ * with a given payload.
381
+ * @private
382
+ * @memberof Lifecycle
383
+ */
384
+ _callAllFns(objWithFns, payload, origin) {
385
+ for (let id in objWithFns) {
386
+ if (objWithFns.hasOwnProperty(id) && helpers.isFunction(objWithFns[id])) {
387
+ objWithFns[id](payload, origin);
388
+ }
389
+ }
390
+ }
391
+
392
+ /**
393
+ * Notifies all context init listeners.
394
+ * @private
395
+ * @memberof Lifecycle
396
+ */
397
+ _notifyInit(origin) {
398
+ this._callAllFns(this._onInitFns, this.currentContext.context, origin);
399
+ }
400
+
401
+ /**
402
+ * Notifies all context update listeners.
403
+ * @private
404
+ * @memberof Lifecycle
405
+ */
406
+ _notifyUpdate() {
407
+ this._callAllFns(this._onContextUpdatedFns, this.currentContext.context);
408
+ }
409
+
410
+ /**
411
+ * Notifies all inactive listeners.
412
+ * @private
413
+ * @memberof Lifecycle
414
+ */
415
+ _notifyInactive() {
416
+ this._callAllFns(this._onInactiveFns);
417
+ }
418
+
419
+ /**
420
+ * @private
421
+ * @memberof Lifecycle
422
+ */
423
+ setCurrentContext(value) {
424
+ this.currentContext = value;
425
+ }
426
+
427
+ /**
428
+ * Registers a listener called with the context object and the Luigi Core domain as soon as Luigi is instantiated. Defer your application bootstrap if you depend on authentication data coming from Luigi.
429
+ * @param {Lifecycle~initListenerCallback} initFn - the function that is called once Luigi is initialized, receives current context and origin as parameters
430
+ * @param {boolean} disableTpcCheck - if set to `true` third party cookie check will be disabled via LuigiClient.
431
+ * @memberof Lifecycle
432
+ * @example
433
+ * const initListenerId = LuigiClient.addInitListener((context) => storeContextToMF(context))
434
+ */
435
+ addInitListener(initFn, disableTpcCheck) {
436
+ const id = helpers.getRandomId();
437
+ this._onInitFns[id] = initFn;
438
+ if (disableTpcCheck) {
439
+ document.head.setAttribute('disable-tpc-check', '');
440
+ }
441
+ if (this.luigiInitialized && helpers.isFunction(initFn)) {
442
+ initFn(this.currentContext.context, helpers.getLuigiCoreDomain());
443
+ }
444
+ return id;
445
+ }
446
+
447
+ /**
448
+ * Callback of the addInitListener <br><br>
449
+ * Type: [Function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function)
450
+ * @callback Lifecycle~initListenerCallback
451
+ * @kind function
452
+ * @param {Object} context - current context data
453
+ * @param {string} origin - Luigi Core URL
454
+ */
455
+ /**
456
+ * Removes an init listener.
457
+ * @param {string} id - the id that was returned by the `addInitListener` function
458
+ * @memberof Lifecycle
459
+ * @example
460
+ * LuigiClient.removeInitListener(initListenerId)
461
+ */
462
+ removeInitListener(id) {
463
+ if (this._onInitFns[id]) {
464
+ this._onInitFns[id] = undefined;
465
+ return true;
466
+ }
467
+ return false;
468
+ }
469
+
470
+ /**
471
+ * Registers a listener called with the context object when the URL is changed. For example, you can use this when changing environments in a context switcher in order for the micro frontend to do an API call to the environment picked.
472
+ * @param {function} contextUpdatedFn - the listener function called each time Luigi context changes
473
+ * @memberof Lifecycle
474
+ * @example
475
+ * const updateListenerId = LuigiClient.addContextUpdateListener((context) => storeContextToMF(context))
476
+ */
477
+ addContextUpdateListener(contextUpdatedFn) {
478
+ const id = helpers.getRandomId();
479
+ this._onContextUpdatedFns[id] = contextUpdatedFn;
480
+ if (this.luigiInitialized && helpers.isFunction(contextUpdatedFn)) {
481
+ contextUpdatedFn(this.currentContext.context);
482
+ }
483
+ return id;
484
+ }
485
+
486
+ /**
487
+ * Removes a context update listener.
488
+ * @param {string} id - the id that was returned by the `addContextUpdateListener` function
489
+ * @memberof Lifecycle
490
+ * @example
491
+ * LuigiClient.removeContextUpdateListener(updateListenerId)
492
+ */
493
+ removeContextUpdateListener(id) {
494
+ if (this._onContextUpdatedFns[id]) {
495
+ this._onContextUpdatedFns[id] = undefined;
496
+ return true;
497
+ }
498
+ return false;
499
+ }
500
+
501
+ /**
502
+ * Registers a listener called upon micro frontend inactivity. This happens when a new micro frontend gets shown while keeping the old one cached.
503
+ * Gets called when:
504
+ * - navigating with **preserveView**
505
+ * - navigating from or to a **viewGroup**
506
+ *
507
+ * Does not get called when navigating normally, or when `openAsModal` or `openAsSplitView` are used.
508
+ * Once the micro frontend turns back into active state, the `addContextUpdateListener` receives an updated context.
509
+ * @param {function} inactiveFn - the listener function called each time a micro frontend turns into an inactive state
510
+ * @memberof Lifecycle
511
+ * @example
512
+ * LuigiClient.addInactiveListener(() => mfIsInactive = true)
513
+ * const inactiveListenerId = LuigiClient.addInactiveListener(() => mfIsInactive = true)
514
+ */
515
+ addInactiveListener(inactiveFn) {
516
+ const id = helpers.getRandomId();
517
+ this._onInactiveFns[id] = inactiveFn;
518
+ return id;
519
+ }
520
+
521
+ /**
522
+ * Removes a listener for inactive micro frontends.
523
+ * @param {string} id - the id that was returned by the `addInactiveListener` function
524
+ * @memberof Lifecycle
525
+ * @example
526
+ * LuigiClient.removeInactiveListener(inactiveListenerId)
527
+ */
528
+ removeInactiveListener(id) {
529
+ if (this._onInactiveFns[id]) {
530
+ this._onInactiveFns[id] = undefined;
531
+ return true;
532
+ }
533
+ return false;
534
+ }
535
+
536
+ /**
537
+ * Registers a listener called when the micro frontend receives a custom message.
538
+ * @param {string} customMessageId - the custom message id
539
+ * @param {Lifecycle~customMessageListenerCallback} customMessageListener - the function that is called when the micro frontend receives the corresponding event
540
+ * @memberof Lifecycle
541
+ * @since 0.6.2
542
+ * @example
543
+ * const customMsgId = LuigiClient.addCustomMessageListener('myapp.project-updated', (data) => doSomething(data))
544
+ */
545
+ addCustomMessageListener(customMessageId, customMessageListener) {
546
+ return helpers.addEventListener(customMessageId, (customMessage, listenerId) => {
547
+ return customMessageListener(customMessage, listenerId);
548
+ });
549
+ }
550
+
551
+ /**
552
+ * Callback of the customMessageListener <br><br>
553
+ * Type: [Function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function)
554
+ * @callback Lifecycle~customMessageListenerCallback
555
+ * @kind function
556
+ * @param {Object} customMessage - custom message object
557
+ * @param {string} customMessage.id - message id
558
+ * @param {*} customMessage.MY_DATA_FIELD - any other message data field
559
+ * @param {string} listenerId - custom message listener id to be used for unsubscription
560
+ */
561
+ /**
562
+ * Removes a custom message listener.
563
+ * @param {string} id - the id that was returned by the `addInitListener` function
564
+ * @memberof Lifecycle
565
+ * @since 0.6.2
566
+ * @example
567
+ * LuigiClient.removeCustomMessageListener(customMsgId)
568
+ */
569
+ removeCustomMessageListener(id) {
570
+ return helpers.removeEventListener(id);
571
+ }
572
+
573
+ /**
574
+ * Returns the currently valid access token.
575
+ * @returns {string} current access token
576
+ * @memberof Lifecycle
577
+ * @example
578
+ * const accessToken = LuigiClient.getToken()
579
+ */
580
+ getToken() {
581
+ return this.authData.accessToken;
582
+ }
583
+
584
+ /**
585
+ * Returns the context object. Typically it is not required as the {@link #addContextUpdateListener addContextUpdateListener()} receives the same values.
586
+ * @returns {Object} current context data
587
+ * @memberof Lifecycle
588
+ * @example
589
+ * const context = LuigiClient.getContext()
590
+ */
591
+ getContext() {
592
+ return this.getEventData();
593
+ }
594
+
595
+ /**
596
+ * Returns the context object. It is an alias function for getContext().
597
+ * @returns {Object} current context data
598
+ * @memberof Lifecycle
599
+ * @deprecated
600
+ */
601
+ getEventData() {
602
+ return this.currentContext.context;
603
+ }
604
+
605
+ /**
606
+ * Returns a list of active feature toggles
607
+ * @returns {Array} a list of feature toggle names
608
+ * @memberof Lifecycle
609
+ * @since 1.4.0
610
+ * @example
611
+ * const activeFeatureToggleList = LuigiClient.getActiveFeatureToggles()
612
+ */
613
+ getActiveFeatureToggles() {
614
+ return this.currentContext.internal.activeFeatureToggleList ?? [];
615
+ }
616
+
617
+ /**
618
+ * Sets node parameters in Luigi Core. The parameters will be added to the URL.
619
+ * @param {Object} params
620
+ * @param {boolean} keepBrowserHistory
621
+ * @memberof Lifecycle
622
+ * @example
623
+ * LuigiClient.addNodeParams({luigi:'rocks'}, true);
624
+ */
625
+ addNodeParams(params, keepBrowserHistory = true) {
626
+ if (params) {
627
+ helpers.sendPostMessageToLuigiCore({
628
+ msg: 'luigi.addNodeParams',
629
+ data: params,
630
+ keepBrowserHistory
631
+ });
632
+ }
633
+ }
634
+
635
+ /**
636
+ * Returns the node parameters of the active URL.
637
+ * Node parameters are defined like URL query parameters but with a specific prefix allowing Luigi to pass them to the micro frontend view. The default prefix is **~** and you can use it in the following way: `https://my.luigi.app/home/products?~sort=asc&~page=3`.
638
+ * <!-- add-attribute:class:warning -->
639
+ * > **NOTE:** some special characters (`<`, `>`, `"`, `'`, `/`) in node parameters are HTML-encoded.
640
+ * @param {boolean} shouldDesanitise - defines whether the specially encoded characters should be desanitised
641
+ * @returns {Object} node parameters, where the object property name is the node parameter name without the prefix, and its value is the value of the node parameter. For example `{sort: 'asc', page: 3}`
642
+ * @memberof Lifecycle
643
+ * @example
644
+ * const nodeParams = LuigiClient.getNodeParams()
645
+ * const nodeParams = LuigiClient.getNodeParams(true)
646
+ */
647
+ getNodeParams(shouldDesanitise = false) {
648
+ return shouldDesanitise
649
+ ? helpers.deSanitizeParamsMap(this.currentContext.nodeParams)
650
+ : this.currentContext.nodeParams;
651
+ }
652
+
653
+ /**
654
+ * Returns the dynamic path parameters of the active URL.
655
+ * Path parameters are defined by navigation nodes with a dynamic **pathSegment** value starting with **:**, such as **productId**.
656
+ * All path parameters in the current navigation path (as defined by the active URL) are returned.
657
+ * <!-- add-attribute:class:warning -->
658
+ * > **NOTE:** some special characters (`<`, `>`, `"`, `'`, `/`) in path parameters are HTML-encoded.
659
+ * @returns {Object} path parameters, where the object property name is the path parameter name without the prefix, and its value is the actual value of the path parameter. For example ` {productId: 1234, ...}`
660
+ * @memberof Lifecycle
661
+ * @example
662
+ * const pathParams = LuigiClient.getPathParams()
663
+ */
664
+ getPathParams() {
665
+ return this.currentContext.pathParams;
666
+ }
667
+
668
+ /**
669
+ * Read search query parameters which are sent from Luigi Core
670
+ * @memberof Lifecycle
671
+ * @returns Core search query parameters
672
+ * @example
673
+ * LuigiClient.getCoreSearchParams();
674
+ */
675
+ getCoreSearchParams() {
676
+ return this.currentContext.searchParams || {};
677
+ }
678
+
679
+ /**
680
+ * Sends search query parameters to Luigi Core. The search parameters will be added to the URL if they are first allowed on a node level using {@link navigation-parameters-reference.md#clientpermissionsurlparameters clientPermissions.urlParameters}.
681
+
682
+ * @param {Object} searchParams
683
+ * @param {boolean} keepBrowserHistory
684
+ * @param {boolean} preventLuigiConfigUpdate - If true, the configChanged function will be triggered (since NEXTRELEASE). By default it is set to `false`.
685
+ * @memberof Lifecycle
686
+ * @example
687
+ * LuigiClient.addCoreSearchParams({luigi:'rocks'}, false);
688
+ */
689
+ addCoreSearchParams(searchParams, keepBrowserHistory = true, preventLuigiConfigUpdate = false) {
690
+ if (searchParams) {
691
+ helpers.sendPostMessageToLuigiCore({
692
+ msg: 'luigi.addSearchParams',
693
+ data: searchParams,
694
+ keepBrowserHistory,
695
+ preventLuigiConfigUpdate
696
+ });
697
+ }
698
+ }
699
+
700
+ /**
701
+ * Returns the current client permissions as specified in the navigation node or an empty object. For details, see [Node parameters](navigation-parameters-reference.md).
702
+ * @returns {Object} client permissions as specified in the navigation node
703
+ * @memberof Lifecycle
704
+ * @example
705
+ * const permissions = LuigiClient.getClientPermissions()
706
+ */
707
+ getClientPermissions() {
708
+ return this.currentContext.internal.clientPermissions || {};
709
+ }
710
+
711
+ /**
712
+ * <!-- label-success: Web App API only -->
713
+ * When the micro frontend is not embedded in the Luigi Core application and there is no init handshake you can set the target origin that is used in postMessage function calls by Luigi Client. Typically used only in custom micro-frontend frameworks that are compatible with LuigiClient API.
714
+ * @param {string} origin - target origin
715
+ * @memberof Lifecycle
716
+ * @since 0.7.3
717
+ * @example
718
+ * LuigiClient.setTargetOrigin(window.location.origin)
719
+ */
720
+ setTargetOrigin(origin) {
721
+ helpers.setTargetOrigin(origin);
722
+ }
723
+
724
+ /**
725
+ * <!-- label-success: Web App API only -->
726
+ * Sends a custom message to the Luigi Core application.
727
+ * @param {Object} message - an object containing data to be sent to the Luigi Core to process it further. This object is set as an input parameter of the custom message listener on the Luigi Core side
728
+ * @param {string} message.id - a string containing the message id
729
+ * @param {*} message.MY_DATA_FIELD - any other message data field
730
+ * @example
731
+ * LuigiClient.sendCustomMessage({id: 'environment.created', production: false})
732
+ * LuigiClient.sendCustomMessage({id: 'environment.created', data: environmentDataObj})
733
+ * @memberof Lifecycle
734
+ * @since 0.6.2
735
+ */
736
+ sendCustomMessage(message) {
737
+ const customMessageInternal = helpers.convertCustomMessageUserToInternal(message);
738
+ helpers.sendPostMessageToLuigiCore(customMessageInternal);
739
+ }
740
+
741
+ /**
742
+ * Returns the current user settings based on the selected node.
743
+ * @returns {Object} current user settings
744
+ * @since 1.7.1
745
+ * @memberof Lifecycle
746
+ * @example
747
+ * const userSettings = LuigiClient.getUserSettings()
748
+ */
749
+ getUserSettings() {
750
+ return this.currentContext.internal.userSettings;
751
+ }
752
+
753
+ /**
754
+ * Returns the current anchor based on active URL.
755
+ * @memberof Lifecycle
756
+ * @since 1.21.0
757
+ * @returns anchor of URL
758
+ * @example
759
+ * LuigiClient.getAnchor();
760
+ */
761
+ getAnchor() {
762
+ return this.currentContext.internal.anchor || '';
763
+ }
764
+
765
+ /**
766
+ * Sends anchor to Luigi Core. The anchor will be added to the URL.
767
+ * @param {string} anchor
768
+ * @since 1.21.0
769
+ * @memberof Lifecycle
770
+ * @example
771
+ * LuigiClient.setAnchor('luigi');
772
+ */
773
+ setAnchor(anchor) {
774
+ helpers.sendPostMessageToLuigiCore({
775
+ msg: 'luigi.setAnchor',
776
+ anchor
777
+ });
778
+ }
779
+
780
+ /**
781
+ * This function allows you to change node labels within the same {@link navigation-advanced.md#view-groups view group}, e.g. in your node config: `label: 'my Node {viewGroupData.vg1}'`.
782
+ * @since 2.2.0
783
+ * @param {Object} data - a data object containing the view group name and desired label
784
+ * @memberof Lifecycle
785
+ * @example LuigiClient.setViewGroupData({'vg1':' Luigi rocks!'})
786
+ */
787
+ setViewGroupData(data) {
788
+ helpers.sendPostMessageToLuigiCore({
789
+ msg: 'luigi.setVGData',
790
+ data
791
+ });
792
+ }
793
+ }
794
+ const lifecycleManager$1 = new LifecycleManager();
795
+
796
+ /**
797
+ * @summary Split view allows to open a micro frontend in a split screen in the lower part of the content area. Open it by calling `const splitViewHandle = LuigiClient.linkManager().openAsSplitView`. At a given time, you can open only one split view. It closes automatically when you navigate to a different route. When you call `handle.collapse()`, the split view gets destroyed. It recreates when you use `handle.expand()`. `openAsSplitView` returns an instance of the split view handle. The functions, actions, and event handlers listed below allow you to control and manage the split view.
798
+ * @augments LuigiClientBase
799
+ * @name splitView
800
+ * @since 0.6.0
801
+ * @class
802
+ */
803
+ class splitViewHandle extends LuigiClientBase {
804
+ /**
805
+ * @private
806
+ */
807
+ constructor(settings) {
808
+ super();
809
+
810
+ this.validSplitViewEvents = ['expand', 'collapse', 'resize', 'close'];
811
+
812
+ this.splitView = {
813
+ exists: true,
814
+ size: 40,
815
+ collapsed: false
816
+ };
817
+
818
+ Object.assign(this.splitView, settings);
819
+
820
+ const removeSplitViewListeners = () => {
821
+ this.splitView.listeners.forEach((id) => helpers.removeEventListener(id));
822
+ };
823
+
824
+ this.splitView.listeners = [
825
+ helpers.addEventListener(`luigi.navigation.splitview.internal`, (e) => {
826
+ Object.assign(this.splitView, e.data.data);
827
+ })
828
+ ];
829
+ this.on('resize', (newSize) => {
830
+ this.splitView.size = newSize;
831
+ });
832
+ this.on('close', removeSplitViewListeners);
833
+ }
834
+ /*
835
+ * @private
836
+ */
837
+ sendSplitViewEvent(action, data) {
838
+ helpers.sendPostMessageToLuigiCore({
839
+ msg: `luigi.navigation.splitview.${action}`,
840
+ data
841
+ });
842
+ }
843
+
844
+ /**
845
+ * Collapses the split view
846
+ * @memberof splitView
847
+ * @since 0.6.0
848
+ * @example
849
+ * splitViewHandle.collapse();
850
+ */
851
+ collapse() {
852
+ this.sendSplitViewEvent('collapse');
853
+ }
854
+ /**
855
+ * Expands the split view
856
+ * @memberof splitView
857
+ * @since 0.6.0
858
+ * @example
859
+ * splitViewHandle.expand();
860
+ */
861
+ expand() {
862
+ this.sendSplitViewEvent('expand');
863
+ }
864
+
865
+ /**
866
+ * Closes and destroys the split view
867
+ * @memberof splitView
868
+ * @since 0.6.0
869
+ * @example
870
+ * splitViewHandle.close();
871
+ */
872
+ close() {
873
+ this.sendSplitViewEvent('close');
874
+ }
875
+ /**
876
+ * Sets the height of the split view
877
+ * @memberof splitView
878
+ * @param {number} value - lower height in percent
879
+ * @since 0.6.0
880
+ * @example
881
+ * splitViewHandle.setSize(60);
882
+ */
883
+ setSize(value) {
884
+ this.sendSplitViewEvent('resize', value);
885
+ }
886
+ /**
887
+ * Registers a listener for split view events
888
+ * @memberof splitView
889
+ * @param {('expand'|'collapse'|'resize'|'close')} name - event name
890
+ * @param {function} callback - gets called when this event gets triggered by Luigi
891
+ * @returns {string} listener id
892
+ * @since 0.6.0
893
+ * @example
894
+ * const listenerId = splitViewHandle.on('expand', () => {});
895
+ * const listenerId = splitViewHandle.on('collapse', () => {});
896
+ * const listenerId = splitViewHandle.on('resize', () => {});
897
+ * const listenerId = splitViewHandle.on('close', () => {});
898
+ **/
899
+ on(name, callback) {
900
+ if (!this.validSplitViewEvents.includes(name)) {
901
+ console.warn(name + ' is not a valid split view event');
902
+ return false;
903
+ }
904
+ const id = helpers.addEventListener(`luigi.navigation.splitview.${name}.ok`, (e) => {
905
+ const filterParam = typeof e.data.data == 'number' ? e.data.data : undefined;
906
+ callback(filterParam);
907
+ });
908
+ this.splitView.listeners.push(id);
909
+ return id;
910
+ }
911
+ /**
912
+ * Unregisters a split view listener
913
+ * @memberof splitView
914
+ * @param {string} id - listener id
915
+ * @since 0.6.0
916
+ * @example
917
+ * splitViewHandle.removeEventListener(listenerId);
918
+ */
919
+ removeEventListener(id) {
920
+ return helpers.removeEventListener(id);
921
+ }
922
+
923
+ /**
924
+ * Gets the split view status
925
+ * @memberof splitView
926
+ * @returns {boolean} true if a split view is loaded
927
+ * @since 0.6.0
928
+ * @example
929
+ * splitViewHandle.exists();
930
+ */
931
+ exists() {
932
+ return this.splitView.exists;
933
+ }
934
+ /**
935
+ * Reads the size of the split view
936
+ * @memberof splitView
937
+ * @returns {number} height in percent
938
+ * @since 0.6.0
939
+ * @example
940
+ * splitViewHandle.getSize();
941
+ */
942
+ getSize() {
943
+ return this.splitView.size;
944
+ }
945
+ /**
946
+ * Reads the collapse status
947
+ * @memberof splitView
948
+ * @returns {boolean} true if the split view is currently collapsed
949
+ * @since 0.6.0
950
+ * @example
951
+ * splitViewHandle.isCollapsed();
952
+ */
953
+ isCollapsed() {
954
+ return this.splitView.collapsed;
955
+ }
956
+ /**
957
+ * Reads the expand status
958
+ * @memberof splitView
959
+ * @returns {boolean} true if the split view is currently expanded
960
+ * @since 0.6.0
961
+ * @example
962
+ * splitViewHandle.isExpanded();
963
+ */
964
+ isExpanded() {
965
+ return !this.splitView.collapsed;
966
+ }
967
+ }
968
+
969
+ /**
970
+ * @summary The Link Manager allows you to navigate to another route. Use it instead of an internal router to:
971
+ - Provide routing inside micro frontends.
972
+ - Reflect the route.
973
+ - Keep the navigation state in Luigi.
974
+ * @augments LuigiClientBase
975
+ * @name linkManager
976
+ * @class
977
+ */
978
+ let linkManager$1 = class linkManager extends LuigiClientBase {
979
+ /**
980
+ * @private
981
+ */
982
+ constructor(values) {
983
+ super();
984
+ Object.assign(this, values);
985
+
986
+ this.options = {
987
+ preserveView: false,
988
+ nodeParams: {},
989
+ errorSkipNavigation: false,
990
+ fromContext: null,
991
+ fromClosestContext: false,
992
+ fromVirtualTreeRoot: false,
993
+ fromParent: false,
994
+ relative: false,
995
+ link: '',
996
+ newTab: false,
997
+ preserveQueryParams: false,
998
+ anchor: '',
999
+ preventContextUpdate: false,
1000
+ preventHistoryEntry: false
1001
+ };
1002
+ }
1003
+
1004
+ /**
1005
+ * Navigates to the given path in the application hosted by Luigi. It contains either a full absolute path or a relative path without a leading slash that uses the active route as a base. This is the standard navigation.
1006
+ * @memberof linkManager
1007
+ * @param {string} path - path to be navigated to
1008
+ * @param {string} sessionId - current Luigi **sessionId**
1009
+ * @param {boolean} preserveView - preserve a view by setting it to `true`. It keeps the current view opened in the background and opens the new route in a new frame. Use the {@link #goBack goBack()} function to navigate back. You can use this feature across different levels. Preserved views are discarded as soon as you use the standard {@link #navigate navigate()} function instead of {@link #goBack goBack()}
1010
+ * @param {Object} modalSettings - opens a view in a modal. Use these settings to configure the modal's title and size
1011
+ * @param {string} modalSettings.title - modal title. By default, it is the node label. If there is no label, it is left empty
1012
+ * @param {('fullscreen'|'l'|'m'|'s')} [modalSettings.size="l"] - size of the modal
1013
+ * @param {string} modalSettings.width - updates the `width` of the modal. Allowed units are 'px', '%', 'rem', 'em', 'vh' and 'vw'.
1014
+ * @param {string} modalSettings.height - updates the `height` of the modal. Allowed units are 'px', '%', 'rem', 'em', 'vh' and 'vw'.
1015
+ * @param {boolean} modalSettings.keepPrevious - lets you open multiple modals. Keeps the previously opened modal and allows to open another modal on top of the previous one. By default the previous modals are discarded.
1016
+ * @param {string} modalSettings.closebtn_data_testid - lets you specify a `data_testid` for the close button. Default value is `lui-modal-index-0`. If multiple modals are opened the index will be increased per modal.
1017
+ * @param {Object} splitViewSettings - opens a view in a split view. Use these settings to configure the split view's behaviour
1018
+ * @param {string} splitViewSettings.title - split view title. By default, it is the node label. If there is no label, it is left empty
1019
+ * @param {number} [splitViewSettings.size=40] - height of the split view in percent
1020
+ * @param {boolean} [splitViewSettings.collapsed=false] - creates split view but leaves it closed initially
1021
+ * @param {Object} drawerSettings - opens a view in a drawer. Use these settings to configure if the drawer has a header, backdrop and size
1022
+ * @param {any} drawerSettings.header - by default, the header is visible. The default title is the node label, but the header could also be an object with a `title` attribute allowing you to specify your own title. An 'x' icon is displayed to close the drawer view
1023
+ * @param {boolean} drawerSettings.backdrop - by default, it is set to `false`. If it is set to `true` the rest of the screen has a backdrop
1024
+ * @param {('l'|'m'|'s'|'xs')} [drawerSettings.size="s"] - size of the drawer
1025
+ * @example
1026
+ * LuigiClient.linkManager().navigate('/overview')
1027
+ * LuigiClient.linkManager().navigate('users/groups/stakeholders')
1028
+ * LuigiClient.linkManager().navigate('/settings', null, true) // preserve view
1029
+ * LuigiClient.linkManager().navigate('#?Intent=Sales-order?id=13') // intent navigation
1030
+ */
1031
+ navigate(path, sessionId, preserveView, modalSettings, splitViewSettings, drawerSettings) {
1032
+ if (this.options.errorSkipNavigation) {
1033
+ this.options.errorSkipNavigation = false;
1034
+ return;
1035
+ }
1036
+ if (modalSettings && splitViewSettings && drawerSettings) {
1037
+ console.warn(
1038
+ 'modalSettings, splitViewSettings and drawerSettings cannot be used together. Only modal setting will be taken into account.'
1039
+ );
1040
+ }
1041
+
1042
+ this.options.preserveView = preserveView;
1043
+ const relativePath = path[0] !== '/';
1044
+
1045
+ if (path === '/' && (modalSettings || splitViewSettings || drawerSettings)) {
1046
+ console.warn('Navigation with an absolute path prevented.');
1047
+ return;
1048
+ }
1049
+ const navigationOpenMsg = {
1050
+ msg: 'luigi.navigation.open',
1051
+ sessionId: sessionId,
1052
+ params: Object.assign(this.options, {
1053
+ link: path,
1054
+ relative: relativePath,
1055
+ intent: helpers.hasIntent(path),
1056
+ modal: modalSettings,
1057
+ splitView: splitViewSettings,
1058
+ drawer: drawerSettings
1059
+ })
1060
+ };
1061
+ helpers.sendPostMessageToLuigiCore(navigationOpenMsg);
1062
+ }
1063
+
1064
+ /**
1065
+ * Updates path of the modalPathParam when internal navigation occurs.
1066
+ * @memberof linkManager
1067
+ * @param {string} path
1068
+ * @param {boolean} addHistoryEntry - adds an entry in the history
1069
+ * @param {Object} [modalSettings] - opens a view in a modal. Use these settings to configure the modal's title and size
1070
+ * @since 1.21.0
1071
+ * @example
1072
+ * LuigiClient.linkManager().updateModalPathInternalNavigation('microfrontend')
1073
+ */
1074
+ updateModalPathInternalNavigation(path, modalSettings = {}, addHistoryEntry = false) {
1075
+ if (!path) {
1076
+ console.warn('Updating path of the modal upon internal navigation prevented. No path specified.');
1077
+ return;
1078
+ }
1079
+
1080
+ const navigationOpenMsg = {
1081
+ msg: 'luigi.navigation.updateModalDataPath',
1082
+ params: Object.assign(this.options, {
1083
+ link: path,
1084
+ modal: modalSettings,
1085
+ history: addHistoryEntry
1086
+ })
1087
+ };
1088
+ helpers.sendPostMessageToLuigiCore(navigationOpenMsg);
1089
+ }
1090
+
1091
+ /**
1092
+ * Offers an alternative way of navigating with intents. This involves specifying a semanticSlug and an object containing
1093
+ * parameters.
1094
+ * This method internally generates a URL of the form `#?intent=<semantic object>-<action>?<param_name>=<param_value>` through the given
1095
+ * input arguments. This then follows a call to the original `linkManager.navigate(...)` function.
1096
+ * Consequently, the following calls shall have the exact same effect:
1097
+ * - linkManager().navigateToIntent('Sales-settings', {project: 'pr2', user: 'john'})
1098
+ * - linkManager().navigate('/#?intent=Sales-settings?project=pr2&user=john')
1099
+ * @param {string} semanticSlug - concatenation of semantic object and action connected with a dash (-), i.e.: `<semanticObject>-<action>`
1100
+ * @param {Object} params - an object representing all the parameters passed, i.e.: `{param1: '1', param2: 2, param3: 'value3'}`
1101
+ * @example
1102
+ * LuigiClient.linkManager().navigateToIntent('Sales-settings', {project: 'pr2', user: 'john'})
1103
+ * LuigiClient.linkManager().navigateToIntent('Sales-settings')
1104
+ */
1105
+ navigateToIntent(semanticSlug, params = {}) {
1106
+ let newPath = '#?intent=';
1107
+ newPath += semanticSlug;
1108
+ if (params && Object.keys(params)?.length) {
1109
+ const paramList = Object.entries(params);
1110
+ // append parameters to the path if any
1111
+ if (paramList.length > 0) {
1112
+ newPath += '?';
1113
+ for (const [key, value] of paramList) {
1114
+ newPath += key + '=' + value + '&';
1115
+ }
1116
+ // trim potential excessive ampersand & at the end
1117
+ newPath = newPath.slice(0, -1);
1118
+ }
1119
+ }
1120
+ this.navigate(newPath);
1121
+ }
1122
+
1123
+ /**
1124
+ * Opens a view in a modal. You can specify the modal's title and size. If you don't specify the title, it is the node label. If there is no node label, the title remains empty. The default size of the modal is `l`, which means 80%. You can also use `m` (60%) and `s` (40%) to set the modal size. Optionally, use it in combination with any of the navigation functions.
1125
+ * @memberof linkManager
1126
+ * @param {string} path - navigation path
1127
+ * @param {Object} [modalSettings] - opens a view in a modal. Use these settings to configure the modal's title and size
1128
+ * @param {string} modalSettings.title - modal title. By default, it is the node label. If there is no label, it is left empty
1129
+ * @param {('fullscreen'|'l'|'m'|'s')} [modalSettings.size="l"] - size of the modal
1130
+ * @param {string} modalSettings.width - updates the `width` of the modal. Allowed units are 'px', '%', 'rem', 'em', 'vh' and 'vw'
1131
+ * @param {string} modalSettings.height - updates the `height` of the modal. Allowed units are 'px', '%', 'rem', 'em', 'vh' and 'vw'
1132
+ * @param {boolean} modalSettings.keepPrevious - lets you open multiple modals. Keeps the previously opened modal and allows to open another modal on top of the previous one. By default the previous modals are discarded
1133
+ * @param {string} modalSettings.closebtn_data_testid - lets you specify a `data_testid` for the close button. Default value is `lui-modal-index-0`. If multiple modals are opened the index will be increased per modal
1134
+ * @returns {promise} which is resolved when closing the modal. By using LuigiClient.linkManager().goBack({ foo: 'bar' }) to close the modal you have access to the `goBackContext` when the promise will be resolved.
1135
+ * @example
1136
+ * LuigiClient.linkManager().openAsModal('projects/pr1/users', {title:'Users', size:'m'}).then((res) => {
1137
+ * // Logic to execute when the modal will be closed
1138
+ * console.log(res.data) //=> {foo: 'bar'}
1139
+ * });
1140
+ */
1141
+ openAsModal(path, modalSettings = {}) {
1142
+ helpers.addEventListener('luigi.navigation.modal.close', (e, listenerId) => {
1143
+ const promise = this.getPromise('modal');
1144
+ if (promise) {
1145
+ promise.resolveFn({ ...e.data, goBackValue: e.data?.data });
1146
+ this.setPromise('modal', undefined);
1147
+ }
1148
+ helpers.removeEventListener(listenerId);
1149
+ });
1150
+ const modalPromise = {};
1151
+ modalPromise.promise = new Promise((resolve, reject) => {
1152
+ modalPromise.resolveFn = resolve;
1153
+ modalPromise.rejectFn = reject;
1154
+ });
1155
+ this.setPromise('modal', modalPromise);
1156
+ this.navigate(path, 0, true, modalSettings);
1157
+ return modalPromise.promise;
1158
+ }
1159
+
1160
+ /**
1161
+ * <!-- label-success: Web App API only -->
1162
+ * Updates the current title and size of a modal. If `routing.showModalPathInUrl` is set to `true`, the URL will be updated with the modal settings data.
1163
+ * In addition, you can specify if a new history entry will be created with the updated URL.
1164
+ * @memberof linkManager
1165
+ * @param {Object} updatedModalSettings - possibility to update the active modal
1166
+ * @param {Object} updatedModalSettings.title - update the `title` of the active modal
1167
+ * @param {Object} updatedModalSettings.size - update the `size` of the active modal
1168
+ * @param {string} updatedModalSettings.width - updates the `width` of the modal. Allowed units are 'px', '%', 'rem', 'em', 'vh' and 'vw'
1169
+ * @param {string} updatedModalSettings.height - updates the `height` of the modal. Allowed units are 'px', '%', 'rem', 'em', 'vh' and 'vw'
1170
+ * @param {boolean} addHistoryEntry - adds an entry in the history, by default it's `false`.
1171
+ * @example
1172
+ * LuigiClient.linkManager().updateModalSettings({title:'LuigiModal', size:'l'});
1173
+ */
1174
+ updateModalSettings(updatedModalSettings = {}, addHistoryEntry = false) {
1175
+ const message = {
1176
+ msg: 'luigi.navigation.updateModalSettings',
1177
+ updatedModalSettings,
1178
+ addHistoryEntry
1179
+ };
1180
+ helpers.sendPostMessageToLuigiCore(message);
1181
+ }
1182
+
1183
+ /**
1184
+ * Opens a view in a split view. You can specify the split view's title and size. If you don't specify the title, it is the node label. If there is no node label, the title remains empty. The default size of the split view is `40`, which means 40% height of the split view.
1185
+ * @memberof linkManager
1186
+ * @param {string} path - navigation path
1187
+ * @param {Object} splitViewSettings - opens a view in a split view. Use these settings to configure the split view's behaviour
1188
+ * @param {string} splitViewSettings.title - split view title. By default, it is the node label. If there is no label, it is left empty
1189
+ * @param {number} [splitViewSettings.size=40] - height of the split view in percent
1190
+ * @param {boolean} [splitViewSettings.collapsed=false] - opens split view in collapsed state
1191
+ * @returns {Object} instance of the SplitView. It provides Event listeners and you can use the available functions to control its behavior.
1192
+ * @see {@link splitView} for further documentation about the returned instance
1193
+ * @since 0.6.0
1194
+ * @example
1195
+ * const splitViewHandle = LuigiClient.linkManager().openAsSplitView('projects/pr1/logs', {title: 'Logs', size: 40, collapsed: true});
1196
+ */
1197
+ openAsSplitView(path, splitViewSettings = {}) {
1198
+ this.navigate(path, 0, true, undefined, splitViewSettings);
1199
+ return new splitViewHandle(splitViewSettings);
1200
+ }
1201
+
1202
+ /**
1203
+ * Opens a view in a drawer. You can specify the size of the drawer, whether the drawer has a header, and whether a backdrop is active in the background. By default, the header is shown. The backdrop is not visible and has to be activated. The size of the drawer is set to `s` by default, which means 25% of the micro frontend size. You can also use `l`(75%), `m`(50%) or `xs`(15.5%). Optionally, use it in combination with any of the navigation functions.
1204
+ * @memberof linkManager
1205
+ * @param {string} path - navigation path
1206
+ * @param {Object} drawerSettings - opens a view in a drawer. Use these settings to configure if the drawer has a header, backdrop and size.
1207
+ * @param {any} drawerSettings.header - by default, the header is visible. The default title is the node label, but the header could also be an object with a `title` attribute allowing you to specify your own title. An 'x' icon is displayed to close the drawer view.
1208
+ * @param {boolean} drawerSettings.backdrop - by default, it is set to `false`. If it is set to `true` the rest of the screen has a backdrop.
1209
+ * @param {('l'|'m'|'s'|'xs')} [drawerSettings.size="s"] - size of the drawer
1210
+ * @param {boolean} [drawerSettings.overlap=true] - enable resizing of main microfrontend iFrame after drawer open
1211
+ * @since 1.6.0
1212
+ * @example
1213
+ * LuigiClient.linkManager().openAsDrawer('projects/pr1/drawer', {header:true, backdrop:true, size:'s'});
1214
+ * LuigiClient.linkManager().openAsDrawer('projects/pr1/drawer', {header:{title:'My drawer component'}, backdrop:true, size:'xs'});
1215
+ */
1216
+ openAsDrawer(path, drawerSettings = {}) {
1217
+ this.navigate(path, 0, true, undefined, undefined, drawerSettings);
1218
+ }
1219
+
1220
+ /**
1221
+ * Sets the current navigation context to that of a specific parent node which has the {@link navigation-configuration.md navigationContext} field declared in the navigation configuration. This navigation context is then used by the `navigate` function.
1222
+ * @memberof linkManager
1223
+ * @param {string} navigationContext
1224
+ * @returns {linkManager} link manager instance
1225
+ * @example
1226
+ * LuigiClient.linkManager().fromContext('project').navigate('/settings')
1227
+ */
1228
+ fromContext(navigationContext) {
1229
+ const navigationContextInParent =
1230
+ this.currentContext.context.parentNavigationContexts &&
1231
+ this.currentContext.context.parentNavigationContexts.indexOf(navigationContext) !== -1;
1232
+ if (navigationContextInParent) {
1233
+ this.options.fromContext = navigationContext;
1234
+ } else {
1235
+ this.options.errorSkipNavigation = true;
1236
+ console.error('Navigation not possible, navigationContext ' + navigationContext + ' not found.');
1237
+ }
1238
+ return this;
1239
+ }
1240
+
1241
+ /**
1242
+ * Sets the current navigation context which is then used by the `navigate` function. This has to be a parent navigation context, it is not possible to use the child navigation contexts.
1243
+ * @memberof linkManager
1244
+ * @returns {linkManager} link manager instance
1245
+ * @example
1246
+ * LuigiClient.linkManager().fromClosestContext().navigate('/users/groups/stakeholders')
1247
+ */
1248
+ fromClosestContext() {
1249
+ const hasParentNavigationContext = this.currentContext?.context.parentNavigationContexts.length > 0;
1250
+ if (hasParentNavigationContext) {
1251
+ this.options.fromContext = null;
1252
+ this.options.fromClosestContext = true;
1253
+ } else {
1254
+ console.error('Navigation not possible, no parent navigationContext found.');
1255
+ }
1256
+ return this;
1257
+ }
1258
+
1259
+ /**
1260
+ * Sets the current navigation base to the parent node that is defined as virtualTree. This method works only when the currently active micro frontend is inside a virtualTree.
1261
+ * @memberof linkManager
1262
+ * @returns {linkManager} link manager instance
1263
+ * @since 1.0.1
1264
+ * @example
1265
+ * LuigiClient.linkManager().fromVirtualTreeRoot().navigate('/users/groups/stakeholders')
1266
+ */
1267
+ fromVirtualTreeRoot() {
1268
+ this.options.fromContext = null;
1269
+ this.options.fromClosestContext = false;
1270
+ this.options.fromVirtualTreeRoot = true;
1271
+ return this;
1272
+ }
1273
+
1274
+ /**
1275
+ * Enables navigating to sibling nodes without knowing the absolute path.
1276
+ * @memberof linkManager
1277
+ * @returns {linkManager} link manager instance
1278
+ * @since 1.0.1
1279
+ * @example
1280
+ * LuigiClient.linkManager().fromParent().navigate('/sibling')
1281
+ */
1282
+ fromParent() {
1283
+ this.options.fromParent = true;
1284
+ return this;
1285
+ }
1286
+
1287
+ /**
1288
+ * Sends node parameters to the route. The parameters are used by the `navigate` function. Use it optionally in combination with any of the navigation functions and receive it as part of the context object in Luigi Client.
1289
+ * @memberof linkManager
1290
+ * @param {Object} nodeParams
1291
+ * @returns {linkManager} link manager instance
1292
+ * @example
1293
+ * LuigiClient.linkManager().withParams({foo: "bar"}).navigate("path")
1294
+ *
1295
+ * // Can be chained with context setting functions such as:
1296
+ * LuigiClient.linkManager().fromContext("currentTeam").withParams({foo: "bar"}).navigate("path")
1297
+ */
1298
+ withParams(nodeParams) {
1299
+ if (nodeParams) {
1300
+ Object.assign(this.options.nodeParams, nodeParams);
1301
+ }
1302
+ return this;
1303
+ }
1304
+
1305
+ /**
1306
+ * <!-- label-success: Web App API only -->
1307
+ * Sets options to customise route changing behaviour. The parameters are used by the `navigate` function. Use it optionally in combination with any of the navigation functions and receive it as part of the context object in Luigi Client.
1308
+ * @memberof linkManager
1309
+ * @param {Object} options - navigation options
1310
+ * @param {boolean} options.preventHistoryEntry - by default, it is set to `false`. If it is set to `true`, there is no browser history being kept.
1311
+ * @param {boolean} options.preventContextUpdate - by default, it is set to `false`. If it is set to `true`, there is no context update being triggered.
1312
+ * @returns {linkManager} link manager instance
1313
+ * @since 1.25.0
1314
+ * @example
1315
+ * LuigiClient.linkManager().withOptions(
1316
+ * { preventContextUpdate:true, preventHistoryEntry: true }
1317
+ * ).navigate('/overview')
1318
+ */
1319
+ withOptions(options) {
1320
+ if (!helpers.isObject(options)) return this;
1321
+
1322
+ if (options['preventHistoryEntry'] !== undefined) {
1323
+ this.options.preventHistoryEntry = options['preventHistoryEntry'];
1324
+ }
1325
+
1326
+ if (options['preventContextUpdate'] !== undefined) {
1327
+ this.options.preventContextUpdate = options['preventContextUpdate'];
1328
+ }
1329
+
1330
+ return this;
1331
+ }
1332
+
1333
+ /** @lends linkManager */
1334
+ /**
1335
+ * Checks if the path you can navigate to exists in the main application. For example, you can use this helper method conditionally to display a DOM element like a button.
1336
+ * @memberof linkManager
1337
+ * @param {string} path - path which existence you want to check
1338
+ * @returns {promise} a promise which resolves to a Boolean variable specifying whether the path exists or not
1339
+ * @example
1340
+ * let pathExists;
1341
+ * LuigiClient
1342
+ * .linkManager()
1343
+ * .pathExists('projects/pr2')
1344
+ * .then(
1345
+ * (pathExists) => { }
1346
+ * );
1347
+ */
1348
+ pathExists(path) {
1349
+ const currentId = helpers.getRandomId();
1350
+ const pathExistsPromises = this.getPromise('pathExistsPromises') || {};
1351
+ pathExistsPromises[currentId] = {
1352
+ resolveFn: function () {},
1353
+ then: function (resolveFn) {
1354
+ this.resolveFn = resolveFn;
1355
+ }
1356
+ };
1357
+ this.setPromise('pathExistsPromises', pathExistsPromises);
1358
+
1359
+ // register event listener, which will be cleaned up after this usage
1360
+ helpers.addEventListener(
1361
+ 'luigi.navigation.pathExists.answer',
1362
+ function (e, listenerId) {
1363
+ const data = e.data.data;
1364
+ const pathExistsPromises = this.getPromise('pathExistsPromises') || {};
1365
+ if (data.correlationId === currentId) {
1366
+ if (pathExistsPromises[data.correlationId]) {
1367
+ pathExistsPromises[data.correlationId].resolveFn(data.pathExists);
1368
+ delete pathExistsPromises[data.correlationId];
1369
+ this.setPromise('pathExistsPromises', pathExistsPromises);
1370
+ }
1371
+ helpers.removeEventListener(listenerId);
1372
+ }
1373
+ }.bind(this)
1374
+ );
1375
+
1376
+ const pathExistsMsg = {
1377
+ msg: 'luigi.navigation.pathExists',
1378
+ data: Object.assign(this.options, {
1379
+ id: currentId,
1380
+ link: path,
1381
+ intent: helpers.hasIntent(path),
1382
+ relative: path[0] !== '/'
1383
+ })
1384
+ };
1385
+ helpers.sendPostMessageToLuigiCore(pathExistsMsg);
1386
+ return pathExistsPromises[currentId];
1387
+ }
1388
+
1389
+ /**
1390
+ * Checks if there is one or more preserved views. You can use it to show a **back** button.
1391
+ * @memberof linkManager
1392
+ * @returns {boolean} indicating if there is a preserved view you can return to
1393
+ */
1394
+ hasBack() {
1395
+ return !!this.currentContext.internal.modal || this.currentContext.internal.viewStackSize !== 0;
1396
+ }
1397
+
1398
+ /**
1399
+ * Discards the active view and navigates back to the last visited view. Works with preserved views, and also acts as the substitute of the browser **back** button. **goBackContext** is only available when using preserved views.
1400
+ * @memberof linkManager
1401
+ * @param {any} goBackValue - data that is passed in the **goBackContext** field to the last visited view when using preserved views
1402
+ * @example
1403
+ * LuigiClient.linkManager().goBack({ foo: 'bar' });
1404
+ * LuigiClient.linkManager().goBack(true);
1405
+ */
1406
+ goBack(goBackValue) {
1407
+ helpers.sendPostMessageToLuigiCore({
1408
+ msg: 'luigi.navigation.back',
1409
+ goBackContext: goBackValue && JSON.stringify(goBackValue)
1410
+ });
1411
+ }
1412
+
1413
+ /**
1414
+ * <!-- label-success: Web App API only -->
1415
+ * Disables the navigation handling for a single navigation request.
1416
+ * It prevents Luigi Core from handling the URL change after `navigate()`.
1417
+ * Used for auto-navigation.
1418
+ * @since 0.7.7
1419
+ * @example
1420
+ * LuigiClient.linkManager().withoutSync().navigate('/projects/xy/foobar');
1421
+ * LuigiClient.linkManager().withoutSync().fromClosestContext().navigate('settings');
1422
+ */
1423
+ withoutSync() {
1424
+ this.options.withoutSync = true;
1425
+ return this;
1426
+ }
1427
+
1428
+ /**
1429
+ * <!-- label-success: Web App API only -->
1430
+ * Enables navigating to a new tab.
1431
+ * @since 1.16.0
1432
+ * @example
1433
+ * LuigiClient.linkManager().newTab().navigate('/projects/xy/foobar');
1434
+ */
1435
+ newTab() {
1436
+ this.options.newTab = true;
1437
+ return this;
1438
+ }
1439
+
1440
+ /**
1441
+ * <!-- label-success: Web App API only -->
1442
+ * Keeps the URL's query parameters for a navigation request.
1443
+ * @param {boolean} preserve - by default, it is set to `false`. If it is set to `true`, the URL's query parameters will be kept after navigation.
1444
+ * @since 1.19.0
1445
+ * @example
1446
+ * LuigiClient.linkManager().preserveQueryParams(true).navigate('/projects/xy/foobar');
1447
+ * LuigiClient.linkManager().preserveQueryParams(false).navigate('/projects/xy/foobar');
1448
+ */
1449
+ preserveQueryParams(preserve = false) {
1450
+ this.options.preserveQueryParams = preserve;
1451
+ return this;
1452
+ }
1453
+
1454
+ /**
1455
+ * Gets the luigi route associated with the current micro frontend.
1456
+ * @returns {promise} a promise which resolves to a String value specifying the current luigi route
1457
+ * @since 1.23.0
1458
+ * @example
1459
+ * LuigiClient.linkManager().getCurrentRoute();
1460
+ * LuigiClient.linkManager().fromContext('project').getCurrentRoute();
1461
+ * LuigiClient.linkManager().fromVirtualTreeRoot().getCurrentRoute();
1462
+ */
1463
+ getCurrentRoute() {
1464
+ const currentId = helpers.getRandomId();
1465
+
1466
+ const currentRoutePromise = this.getPromise('getCurrentRoute') || {};
1467
+ currentRoutePromise[currentId] = {
1468
+ resolveFn: function () {},
1469
+ then: function (resolveFn) {
1470
+ this.resolveFn = resolveFn;
1471
+ }
1472
+ };
1473
+
1474
+ this.setPromise('getCurrentRoute', currentRoutePromise);
1475
+
1476
+ helpers.addEventListener('luigi.navigation.currentRoute.answer', (e, listenerId) => {
1477
+ const data = e.data.data;
1478
+ const currentRoutePromise = this.getPromise('getCurrentRoute') || {};
1479
+
1480
+ if (data.correlationId === currentId) {
1481
+ if (currentRoutePromise[data.correlationId]) {
1482
+ currentRoutePromise[data.correlationId].resolveFn(data.route);
1483
+ delete currentRoutePromise[data.correlationId];
1484
+ this.setPromise('getCurrentRoute', currentRoutePromise);
1485
+ }
1486
+ helpers.removeEventListener(listenerId);
1487
+ }
1488
+ helpers.removeEventListener(listenerId);
1489
+ });
1490
+
1491
+ helpers.sendPostMessageToLuigiCore({
1492
+ msg: 'luigi.navigation.currentRoute',
1493
+ data: Object.assign(this.options, {
1494
+ id: currentId
1495
+ })
1496
+ });
1497
+
1498
+ return currentRoutePromise[currentId];
1499
+ }
1500
+ };
1501
+
1502
+ /**
1503
+ * @summary Use the UX Manager to manage the appearance features in Luigi.
1504
+ * @augments LuigiClientBase
1505
+ * @name uxManager
1506
+ * @class
1507
+ */
1508
+ class UxManager extends LuigiClientBase {
1509
+ /** @private */
1510
+ constructor() {
1511
+ super();
1512
+ helpers.addEventListener('luigi.current-locale-changed', (e) => {
1513
+ if (e.data.currentLocale && lifecycleManager$1.currentContext?.internal) {
1514
+ lifecycleManager$1.currentContext.internal.currentLocale = e.data.currentLocale;
1515
+ lifecycleManager$1._notifyUpdate();
1516
+ }
1517
+ });
1518
+ }
1519
+
1520
+ /**
1521
+ * Adds a backdrop with a loading indicator for the micro frontend frame. This overrides the {@link navigation-parameters-reference.md#node-parameters loadingIndicator.enabled} setting.
1522
+ * @memberof uxManager
1523
+ */
1524
+ showLoadingIndicator() {
1525
+ helpers.sendPostMessageToLuigiCore({ msg: 'luigi.show-loading-indicator' });
1526
+ }
1527
+
1528
+ /**
1529
+ * Removes the loading indicator. Use it after calling {@link #showLoadingIndicator showLoadingIndicator()} or to hide the indicator when you use the {@link navigation-parameters-reference.md#node-parameters loadingIndicator.hideAutomatically: false} node configuration.
1530
+ * @memberof uxManager
1531
+ */
1532
+ hideLoadingIndicator() {
1533
+ helpers.sendPostMessageToLuigiCore({ msg: 'luigi.hide-loading-indicator' });
1534
+ }
1535
+
1536
+ /**
1537
+ * Closes the currently opened micro frontend modal.
1538
+ * @memberof uxManager
1539
+ */
1540
+ closeCurrentModal() {
1541
+ helpers.sendPostMessageToLuigiCore({ msg: 'luigi.close-modal' });
1542
+ }
1543
+
1544
+ /**
1545
+ * Adds a backdrop to block the top and side navigation. It is based on the Fundamental UI Modal, which you can use in your micro frontend to achieve the same behavior.
1546
+ * @memberof uxManager
1547
+ */
1548
+ addBackdrop() {
1549
+ helpers.sendPostMessageToLuigiCore({ msg: 'luigi.add-backdrop' });
1550
+ }
1551
+
1552
+ /**
1553
+ * Removes the backdrop.
1554
+ * @memberof uxManager
1555
+ */
1556
+ removeBackdrop() {
1557
+ helpers.sendPostMessageToLuigiCore({ msg: 'luigi.remove-backdrop' });
1558
+ }
1559
+
1560
+ /**
1561
+ * This method informs the main application that there are unsaved changes in the current view in the iframe. It can be used to prevent navigation away from the current view, for example with form fields which were edited but not submitted. However, this functionality is not restricted to forms. If you use `withoutSync()` together with `setDirtyStatus()`, this is a special case in which the dirty state logic needs to be handled by the micro frontend. For example, if the user navigates with an Angular router, which would trigger `withoutSync()`, Angular needs to take care about dirty state, prevent the navigation and ask for permission to navigate away, through `uxManager().showConfirmationModal(settings)`.
1562
+ * @param {boolean} isDirty - indicates if there are any unsaved changes on the current page or in the component
1563
+ * @memberof uxManager
1564
+ */
1565
+ setDirtyStatus(isDirty) {
1566
+ helpers.sendPostMessageToLuigiCore({
1567
+ msg: 'luigi.set-page-dirty',
1568
+ dirty: isDirty
1569
+ });
1570
+ }
1571
+
1572
+ /**
1573
+ * Shows a confirmation modal.
1574
+ * @memberof uxManager
1575
+ * @param {Object} settings - the settings of the confirmation modal. If you don't provide any value for any of the fields, a default value is used
1576
+ * @param {('confirmation'|'success'|'warning'|'error'|'information')} settings.type - the content of the modal type. (Optional)
1577
+ * @param {string} [settings.header="Confirmation"] - the content of the modal header
1578
+ * @param {string} [settings.body="Are you sure you want to do this?"] - the content of the modal body. It supports HTML formatting elements such as `<br>`, `<b>`, `<strong>`, `<i>`, `<em>`, `<mark>`, `<small>`, `<del>`, `<ins>`, `<sub>`, `<sup>`.
1579
+ * @param {string|false} [settings.buttonConfirm="Yes"] - the label for the modal confirmation button. If set to `false`, the button will not be shown.
1580
+ * @param {string} [settings.buttonDismiss="No"] - the label for the modal dismiss button
1581
+ * @returns {promise} which is resolved when accepting the confirmation modal and rejected when dismissing it
1582
+ * @example
1583
+ * import LuigiClient from '@luigi-project/client';
1584
+ * const settings = {
1585
+ * type: "confirmation",
1586
+ * header: "Confirmation",
1587
+ * body: "Are you sure you want to do this?",
1588
+ * buttonConfirm: "Yes",
1589
+ * buttonDismiss: "No"
1590
+ * }
1591
+ * LuigiClient
1592
+ * .uxManager()
1593
+ * .showConfirmationModal(settings)
1594
+ * .then(() => {
1595
+ * // Logic to execute when the confirmation modal is dismissed
1596
+ * });
1597
+ */
1598
+ showConfirmationModal(settings) {
1599
+ helpers.addEventListener('luigi.ux.confirmationModal.hide', (e, listenerId) => {
1600
+ this.hideConfirmationModal(e.data.data);
1601
+ helpers.removeEventListener(listenerId);
1602
+ });
1603
+ helpers.sendPostMessageToLuigiCore({
1604
+ msg: 'luigi.ux.confirmationModal.show',
1605
+ data: { settings }
1606
+ });
1607
+
1608
+ const confirmationModalPromise = {};
1609
+ confirmationModalPromise.promise = new Promise((resolve, reject) => {
1610
+ confirmationModalPromise.resolveFn = resolve;
1611
+ confirmationModalPromise.rejectFn = reject;
1612
+ });
1613
+ this.setPromise('confirmationModal', confirmationModalPromise);
1614
+ return confirmationModalPromise.promise;
1615
+ }
1616
+
1617
+ /**
1618
+ * @private
1619
+ * @memberof uxManager
1620
+ * @param {Object} modal - confirmed boolean value if ok or cancel has been pressed
1621
+ */
1622
+ hideConfirmationModal(modal) {
1623
+ const promise = this.getPromise('confirmationModal');
1624
+ if (promise) {
1625
+ modal.confirmed ? promise.resolveFn() : promise.rejectFn();
1626
+ this.setPromise('confirmationModal', undefined);
1627
+ }
1628
+ }
1629
+
1630
+ /**
1631
+ * Shows an alert.
1632
+ * @memberof uxManager
1633
+ * @param {Object} settings - the settings for the alert
1634
+ * @param {string} settings.text - the content of the alert. To add a link to the content, you have to set up the link in the `links` object. The key(s) in the `links` object must be used in the text to reference the links, wrapped in curly brackets with no spaces. If you don't specify any text, the alert is not displayed
1635
+ * @param {('info'|'success'|'warning'|'error')} settings.type - sets the type of alert
1636
+ * @param {Object} settings.links - provides links data
1637
+ * @param {Object} settings.links.LINK_KEY - object containing the data for a particular link. To properly render the link in the alert message refer to the description of the **settings.text** parameter
1638
+ * @param {string} settings.links.LINK_KEY.text - text which replaces the link identifier in the alert content
1639
+ * @param {string} settings.links.LINK_KEY.url - URL to navigate when you click the link. Currently, only internal links are supported in the form of relative or absolute paths
1640
+ * @param {string} settings.links.LINK_KEY.dismissKey - dismissKey which represents the key of the link
1641
+ * @param {number} settings.closeAfter - (optional) time in milliseconds that tells Luigi when to close the Alert automatically. If not provided, the Alert will stay on until closed manually. It has to be greater than `100`
1642
+ * @returns {promise} which is resolved when the alert is dismissed
1643
+ * @example
1644
+ * import LuigiClient from '@luigi-project/client';
1645
+ * const settings = {
1646
+ * text: "Ut enim ad minim veniam, {goToHome} quis nostrud exercitation ullamco {relativePath}. Duis aute irure dolor {goToOtherProject} or {neverShowItAgain}",
1647
+ * type: 'info',
1648
+ * links: {
1649
+ * goToHome: { text: 'homepage', url: '/overview' },
1650
+ * goToOtherProject: { text: 'other project', url: '/projects/pr2' },
1651
+ * relativePath: { text: 'relative hide side nav', url: 'hideSideNav' },
1652
+ * neverShowItAgain: { text: 'Never show it again', dismissKey: 'neverShowItAgain' }
1653
+ * },
1654
+ * closeAfter: 3000
1655
+ * }
1656
+ * LuigiClient
1657
+ * .uxManager()
1658
+ * .showAlert(settings)
1659
+ * .then(() => {
1660
+ * // Logic to execute when the alert is dismissed
1661
+ * });
1662
+ */
1663
+ showAlert(settings) {
1664
+ //generate random ID
1665
+ settings.id = helpers.getRandomId();
1666
+
1667
+ helpers.addEventListener('luigi.ux.alert.hide', (e, listenerId) => {
1668
+ if (e.data.id === settings.id) {
1669
+ this.hideAlert(e.data);
1670
+ helpers.removeEventListener(listenerId);
1671
+ }
1672
+ });
1673
+
1674
+ if (settings?.closeAfter < 100) {
1675
+ console.warn(`Message with id='${settings.id}' has too small 'closeAfter' value. It needs to be at least 100ms.`);
1676
+ settings.closeAfter = undefined;
1677
+ }
1678
+ helpers.sendPostMessageToLuigiCore({
1679
+ msg: 'luigi.ux.alert.show',
1680
+ data: { settings }
1681
+ });
1682
+
1683
+ const alertPromises = this.getPromise('alerts') || {};
1684
+ alertPromises[settings.id] = {};
1685
+ alertPromises[settings.id].promise = new Promise((resolve) => {
1686
+ alertPromises[settings.id].resolveFn = resolve;
1687
+ });
1688
+ this.setPromise('alerts', alertPromises);
1689
+ return alertPromises[settings.id].promise;
1690
+ }
1691
+
1692
+ /**
1693
+ * @private
1694
+ * @memberof uxManager
1695
+ * @param {Object} alertObj
1696
+ * @param {string} alertObj.id - alert id
1697
+ * @param {string} alertObj.dismissKey - key of the link
1698
+ */
1699
+ hideAlert({ id, dismissKey }) {
1700
+ const alerts = this.getPromise('alerts');
1701
+ if (id && alerts[id]) {
1702
+ alerts[id].resolveFn(dismissKey ? dismissKey : id);
1703
+ delete alerts[id];
1704
+ this.setPromise('alerts', alerts);
1705
+ }
1706
+ }
1707
+
1708
+ /**
1709
+ * Gets the current locale.
1710
+ * @returns {string} current locale
1711
+ * @memberof uxManager
1712
+ */
1713
+ getCurrentLocale() {
1714
+ return lifecycleManager$1.currentContext?.internal?.currentLocale;
1715
+ }
1716
+
1717
+ /**
1718
+ * <!-- label-success: Web App API only -->
1719
+ * Sets current locale to the specified one.
1720
+ *
1721
+ * **NOTE:** this must be explicitly allowed on the navigation node level by setting `clientPermissions.changeCurrentLocale` to `true`. (See {@link navigation-parameters-reference.md Node parameters}.)
1722
+ *
1723
+ * @param {string} locale - locale to be set as the current locale
1724
+ * @memberof uxManager
1725
+ */
1726
+ setCurrentLocale(locale) {
1727
+ if (locale) {
1728
+ helpers.sendPostMessageToLuigiCore({
1729
+ msg: 'luigi.ux.set-current-locale',
1730
+ data: {
1731
+ currentLocale: locale
1732
+ }
1733
+ });
1734
+ }
1735
+ }
1736
+
1737
+ /**
1738
+ * <!-- label-success: Web App API only -->
1739
+ * Checks if the current micro frontend is displayed inside a split view
1740
+ * @returns {boolean} indicating if it is loaded inside a split view
1741
+ * @memberof uxManager
1742
+ * @since 0.6.0
1743
+ */
1744
+ isSplitView() {
1745
+ return lifecycleManager$1.currentContext?.internal?.splitView;
1746
+ }
1747
+
1748
+ /**
1749
+ * <!-- label-success: Web App API only -->
1750
+ * Checks if the current micro frontend is displayed inside a modal
1751
+ * @returns {boolean} indicating if it is loaded inside a modal
1752
+ * @memberof uxManager
1753
+ * @since 0.6.0
1754
+ */
1755
+ isModal() {
1756
+ return lifecycleManager$1.currentContext?.internal?.modal;
1757
+ }
1758
+
1759
+ /**
1760
+ * <!-- label-success: Web App API only -->
1761
+ * Checks if the current micro frontend is displayed inside a drawer
1762
+ * @returns {boolean} indicating if it is loaded inside a drawer
1763
+ * @memberof uxManager
1764
+ * @since 1.26.0
1765
+ */
1766
+ isDrawer() {
1767
+ return lifecycleManager$1.currentContext?.internal?.drawer;
1768
+ }
1769
+
1770
+ /**
1771
+ * Gets the current theme.
1772
+ * @returns {*} current themeObj
1773
+ * @memberof uxManager
1774
+ */
1775
+ getCurrentTheme() {
1776
+ return lifecycleManager$1.currentContext?.internal?.currentTheme;
1777
+ }
1778
+
1779
+ /**
1780
+ * <!-- label-success: Web App API only -->
1781
+ * Gets the CSS variables from Luigi Core with their key and value.
1782
+ * @returns {Object} CSS variables with their key and value.
1783
+ * @memberof uxManager
1784
+ * @since 2.3.0
1785
+ * @example LuigiClient.uxManager().getCSSVariables();
1786
+ */
1787
+ getCSSVariables() {
1788
+ return lifecycleManager$1.currentContext?.internal?.cssVariables || {};
1789
+ }
1790
+
1791
+ /**
1792
+ * <!-- label-success: Web App API only -->
1793
+ * Adds the CSS variables from Luigi Core in a <style> tag to the document <head> section.
1794
+ * @memberof uxManager
1795
+ * @since 2.3.0
1796
+ * @example LuigiClient.uxManager().applyCSS();
1797
+ */
1798
+ applyCSS() {
1799
+ document.querySelectorAll('head style[luigi-injected]').forEach((luigiInjectedStyleTag) => {
1800
+ luigiInjectedStyleTag.remove();
1801
+ });
1802
+ const vars = lifecycleManager$1.currentContext?.internal?.cssVariables;
1803
+ if (vars) {
1804
+ let cssString = ':root {\n';
1805
+ Object.keys(vars).forEach((key) => {
1806
+ const val = vars[key];
1807
+ cssString += (key.startsWith('--') ? '' : '--') + key + ':' + val + ';\n';
1808
+ });
1809
+ cssString += '}';
1810
+ const themeStyle = document.createElement('style');
1811
+ themeStyle.setAttribute('luigi-injected', true);
1812
+ themeStyle.innerHTML = cssString;
1813
+ document.head.appendChild(themeStyle);
1814
+ }
1815
+ }
1816
+ }
1817
+ const uxManager$1 = new UxManager();
1818
+
1819
+ const pendingOperation = new Map();
1820
+
1821
+ /**
1822
+ * <!-- label-success: Web App API only -->
1823
+ * StorageManager allows you to use browser local storage of key/values. Every storage operation is sent to be managed by Luigi Core.
1824
+ * The idea is that different micro frontends can share or persist items using local storage, as long as they come from the same domain and follow the [same-origin policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy).
1825
+ * Since all storage operations are asynchronous (sending an event to Luigi Core that will reply once operation is finished), all the methods return Promises.
1826
+ * @augments LuigiClientBase
1827
+ * @name storageManager
1828
+ * @class
1829
+ */
1830
+ class StorageManager extends LuigiClientBase {
1831
+ /** @private */
1832
+ constructor() {
1833
+ super();
1834
+ this.storageEventProcessor = new StorageEventProcessor();
1835
+ helpers.addEventListener('storage', (evt, listenerId) => this.storageEventProcessor.processEvent(evt, listenerId));
1836
+ }
1837
+
1838
+ /**
1839
+ * Stores an item for a specific key.
1840
+ * @memberof storageManager
1841
+ * @param {string} key - key used to identify the value
1842
+ * @param {Object} value - item to store; object must be stringifyable
1843
+ * @returns {Promise<void>} resolves an empty value when the storage operation is over. It will launch an error if storage is not supported, the value cannot be stringified, or if you are using a Luigi reserved key.
1844
+ * @example
1845
+ * LuigiClient.storageManager().setItem('keyExample','valueExample').then(() => console.log('Value stored'))
1846
+ * @since 1.6.0
1847
+ */
1848
+ setItem(key, value) {
1849
+ return new Promise((resolve, reject) => {
1850
+ this.storageEventProcessor.execute(resolve, reject, 'setItem', {
1851
+ key,
1852
+ value
1853
+ });
1854
+ });
1855
+ }
1856
+
1857
+ /**
1858
+ * Retrieves an item for a specific key.
1859
+ * @memberof storageManager
1860
+ * @param {string} key - used to identify the value
1861
+ * @returns {Promise<Object>} resolves an item retrieved from storage. It will launch an error if storage is not supported.
1862
+ * @example
1863
+ * LuigiClient.storageManager().getItem('keyExample').then((value) => console.log);
1864
+ * @since 1.6.0
1865
+ */
1866
+ getItem(key) {
1867
+ return new Promise((resolve, reject) => {
1868
+ this.storageEventProcessor.execute(resolve, reject, 'getItem', { key });
1869
+ });
1870
+ }
1871
+
1872
+ /**
1873
+ * Removes an item for a specific key.
1874
+ * @memberof storageManager
1875
+ * @param {string} key - used to identify the value
1876
+ * @returns {Promise<Object>} resolves an item just removed from storage. It will launch an error if storage is not supported or if you are using a Luigi reserved key.
1877
+ * @example
1878
+ * LuigiClient.storageManager().removeItem('keyExample').then((value) => console.log(value + ' just removed')
1879
+ * @since 1.6.0
1880
+ */
1881
+ removeItem(key) {
1882
+ return new Promise((resolve, reject) => {
1883
+ this.storageEventProcessor.execute(resolve, reject, 'removeItem', {
1884
+ key
1885
+ });
1886
+ });
1887
+ }
1888
+
1889
+ /**
1890
+ * Clears all the storage key/values.
1891
+ * @memberof storageManager
1892
+ * @returns {Promise<void>} resolves when storage clear is over.
1893
+ * @example
1894
+ * LuigiClient.storageManager().clear().then(() => console.log('storage cleared'))
1895
+ * @since 1.6.0
1896
+ */
1897
+ clear() {
1898
+ return new Promise((resolve, reject) => {
1899
+ this.storageEventProcessor.execute(resolve, reject, 'clear', {});
1900
+ });
1901
+ }
1902
+
1903
+ /**
1904
+ * Checks if a key is present in storage.
1905
+ * @memberof storageManager
1906
+ * @param {string} key - key in the storage
1907
+ * @returns {Promise<boolean>} `true` if key is present, `false` if it is not
1908
+ * @example
1909
+ * LuigiClient.storageManager().has(key).then((present) => console.log('item is present '+present))
1910
+ * @since 1.6.0
1911
+ */
1912
+ has(key) {
1913
+ return new Promise((resolve, reject) => {
1914
+ this.storageEventProcessor.execute(resolve, reject, 'has', { key });
1915
+ });
1916
+ }
1917
+
1918
+ /**
1919
+ * Gets all the keys used in the storage.
1920
+ * @memberof storageManager
1921
+ * @returns {Promise<string[]>} keys currently present in the storage
1922
+ * @example
1923
+ * LuigiClient.storageManager().getAllKeys().then((keys) => console.log('keys are '+keys))
1924
+ * @since 1.6.0
1925
+ */
1926
+ getAllKeys() {
1927
+ return new Promise((resolve, reject) => {
1928
+ this.storageEventProcessor.execute(resolve, reject, 'getAllKeys', {});
1929
+ });
1930
+ }
1931
+ }
1932
+
1933
+ class StorageEventProcessor {
1934
+ processEvent(evt, listenerId) {
1935
+ try {
1936
+ const data = evt.data.data;
1937
+ if (!pendingOperation.has(data.id)) {
1938
+ console.log('Impossible to find Promise method for message ' + data.id);
1939
+ return;
1940
+ }
1941
+ const promiseOperations = pendingOperation.get(data.id);
1942
+ if (data.status === 'ERROR') {
1943
+ promiseOperations.reject(data.result);
1944
+ } else {
1945
+ promiseOperations.resolve(data.result);
1946
+ }
1947
+ pendingOperation.delete(data.id);
1948
+ } catch (e) {
1949
+ console.error(e);
1950
+ }
1951
+ }
1952
+
1953
+ waitForSyncResult(id) {
1954
+ let start = new Date().getTime();
1955
+ while (!syncOperation.has(id)) {
1956
+ let exec = new Date().getTime() - start;
1957
+ if (exec > 10000) {
1958
+ throw 'Storage operation is taking more than 1 second...Some problem with Luigi Core communication';
1959
+ }
1960
+ }
1961
+ const result = syncOperation.get(id);
1962
+ pendingOperation.delete(id);
1963
+ return result;
1964
+ }
1965
+
1966
+ execute(resolve, reject, operation, params) {
1967
+ let id = helpers.getRandomId();
1968
+ this.createPendingOperation(id, resolve, reject);
1969
+ this.sendMessage(id, operation, params);
1970
+ }
1971
+
1972
+ createPendingOperation(id, resolve, reject) {
1973
+ pendingOperation.set(id, {
1974
+ resolve,
1975
+ reject
1976
+ });
1977
+ }
1978
+ sendMessage(id, operation, params) {
1979
+ helpers.sendPostMessageToLuigiCore({
1980
+ msg: 'storage',
1981
+ data: {
1982
+ id,
1983
+ operation,
1984
+ params
1985
+ }
1986
+ });
1987
+ }
1988
+ }
1989
+
1990
+ const storageManager$1 = new StorageManager();
1991
+
1992
+ /**
1993
+ * @name LuigiClient
1994
+ * @private
1995
+ */
1996
+ class LuigiClient {
1997
+ constructor() {
1998
+ if (window !== window.top) {
1999
+ if (window.document.head.getAttribute('disable-luigi-history-handling') !== 'true') {
2000
+ history.pushState = history.replaceState.bind(history);
2001
+ }
2002
+ if (window.document.head.getAttribute('disable-luigi-runtime-error-handling') !== 'true') {
2003
+ window.addEventListener('error', ({ filename, message, lineno, colno, error }) => {
2004
+ const msg = {
2005
+ msg: 'luigi-runtime-error-handling',
2006
+ errorObj: { filename, message, lineno, colno, error }
2007
+ };
2008
+ helpers.sendPostMessageToLuigiCore(msg);
2009
+ });
2010
+ }
2011
+ }
2012
+ }
2013
+
2014
+ addInitListener(initFn, disableTpcCheck) {
2015
+ return lifecycleManager$1.addInitListener(initFn, disableTpcCheck);
2016
+ }
2017
+ removeInitListener(id) {
2018
+ return lifecycleManager$1.removeInitListener(id);
2019
+ }
2020
+ addContextUpdateListener(contextUpdatedFn) {
2021
+ return lifecycleManager$1.addContextUpdateListener(contextUpdatedFn);
2022
+ }
2023
+ removeContextUpdateListener(id) {
2024
+ return lifecycleManager$1.removeContextUpdateListener(id);
2025
+ }
2026
+ getToken() {
2027
+ return lifecycleManager$1.getToken();
2028
+ }
2029
+ getEventData() {
2030
+ return lifecycleManager$1.getEventData();
2031
+ }
2032
+ getContext() {
2033
+ return lifecycleManager$1.getContext();
2034
+ }
2035
+ addNodeParams(params, keepBrowserHistory) {
2036
+ return lifecycleManager$1.addNodeParams(params, keepBrowserHistory);
2037
+ }
2038
+ getNodeParams(shouldDesanitise) {
2039
+ return lifecycleManager$1.getNodeParams(shouldDesanitise);
2040
+ }
2041
+ getActiveFeatureToggles() {
2042
+ return lifecycleManager$1.getActiveFeatureToggles();
2043
+ }
2044
+ getPathParams() {
2045
+ return lifecycleManager$1.getPathParams();
2046
+ }
2047
+ getCoreSearchParams() {
2048
+ return lifecycleManager$1.getCoreSearchParams();
2049
+ }
2050
+ addCoreSearchParams(searchParams, keepBrowserHistory, addCoreSearchParams) {
2051
+ return lifecycleManager$1.addCoreSearchParams(searchParams, keepBrowserHistory, addCoreSearchParams);
2052
+ }
2053
+ getClientPermissions() {
2054
+ return lifecycleManager$1.getClientPermissions();
2055
+ }
2056
+ sendCustomMessage(message) {
2057
+ return lifecycleManager$1.sendCustomMessage(message);
2058
+ }
2059
+ addCustomMessageListener(messageId, listener) {
2060
+ return lifecycleManager$1.addCustomMessageListener(messageId, listener);
2061
+ }
2062
+ removeCustomMessageListener(listenerId) {
2063
+ return lifecycleManager$1.removeCustomMessageListener(listenerId);
2064
+ }
2065
+ addInactiveListener(messageId, listener) {
2066
+ return lifecycleManager$1.addInactiveListener(messageId, listener);
2067
+ }
2068
+ removeInactiveListener(listenerId) {
2069
+ return lifecycleManager$1.removeInactiveListener(listenerId);
2070
+ }
2071
+ setTargetOrigin(origin) {
2072
+ return lifecycleManager$1.setTargetOrigin(origin);
2073
+ }
2074
+ getUserSettings() {
2075
+ return lifecycleManager$1.getUserSettings();
2076
+ }
2077
+ isLuigiClientInitialized() {
2078
+ return lifecycleManager$1.isLuigiClientInitialized();
2079
+ }
2080
+ luigiClientInit() {
2081
+ return lifecycleManager$1.luigiClientInit();
2082
+ }
2083
+ getAnchor() {
2084
+ return lifecycleManager$1.getAnchor();
2085
+ }
2086
+ setAnchor(value) {
2087
+ return lifecycleManager$1.setAnchor(value);
2088
+ }
2089
+ setViewGroupData(value) {
2090
+ return lifecycleManager$1.setViewGroupData(value);
2091
+ }
2092
+
2093
+ /**
2094
+ * @private
2095
+ */
2096
+ linkManager() {
2097
+ return new linkManager$1({
2098
+ currentContext: lifecycleManager$1.currentContext
2099
+ });
2100
+ }
2101
+ /**
2102
+ * @private
2103
+ */
2104
+ uxManager() {
2105
+ return uxManager$1;
2106
+ }
2107
+ /**
2108
+ * @private
2109
+ */
2110
+ lifecycleManager() {
2111
+ return lifecycleManager$1;
2112
+ }
2113
+ /**
2114
+ * @private
2115
+ */
2116
+ storageManager() {
2117
+ return storageManager$1;
2118
+ }
2119
+ }
2120
+ var LuigiClient$1 = LuigiClient = new LuigiClient();
2121
+
2122
+ const uxManager = LuigiClient$1.uxManager;
2123
+ const linkManager = LuigiClient$1.linkManager;
2124
+ const lifecycleManager = LuigiClient$1.lifecycleManager;
2125
+ const storageManager = LuigiClient$1.storageManager;
2126
+
2127
+ const addInitListener = LuigiClient$1.addInitListener;
2128
+ const removeInitListener = LuigiClient$1.removeInitListener;
2129
+ const addContextUpdateListener = LuigiClient$1.addContextUpdateListener;
2130
+ const removeContextUpdateListener = LuigiClient$1.removeContextUpdateListener;
2131
+ const getToken = LuigiClient$1.getToken;
2132
+ const getEventData = LuigiClient$1.getEventData;
2133
+ const getContext = LuigiClient$1.getContext;
2134
+ const addNodeParams = LuigiClient$1.addNodeParams;
2135
+ const getNodeParams = LuigiClient$1.getNodeParams;
2136
+ const getActiveFeatureToggles = LuigiClient$1.getActiveFeatureToggles;
2137
+ const getPathParams = LuigiClient$1.getPathParams;
2138
+ const getCoreSearchParams = LuigiClient$1.getCoreSearchParams;
2139
+ const addCoreSearchParams = LuigiClient$1.addCoreSearchParams;
2140
+ const getClientPermissions = LuigiClient$1.getClientPermissions;
2141
+ const sendCustomMessage = LuigiClient$1.sendCustomMessage;
2142
+ const addCustomMessageListener = LuigiClient$1.addCustomMessageListener;
2143
+ const removeCustomMessageListener = LuigiClient$1.removeCustomMessageListener;
2144
+ const addInactiveListener = LuigiClient$1.addInactiveListener;
2145
+ const removeInactiveListener = LuigiClient$1.removeInactiveListener;
2146
+ const setTargetOrigin = LuigiClient$1.setTargetOrigin;
2147
+ const getUserSettings = LuigiClient$1.getUserSettings;
2148
+ const isLuigiClientInitialized = LuigiClient$1.isLuigiClientInitialized;
2149
+ const luigiClientInit = LuigiClient$1.luigiClientInit;
2150
+ const getAnchor = LuigiClient$1.getAnchor;
2151
+ const setAnchor = LuigiClient$1.setAnchor;
2152
+ const setViewGroupData = LuigiClient$1.setViewGroupData;
2153
+
2154
+ export { addContextUpdateListener, addCoreSearchParams, addCustomMessageListener, addInactiveListener, addInitListener, addNodeParams, LuigiClient$1 as default, getActiveFeatureToggles, getAnchor, getClientPermissions, getContext, getCoreSearchParams, getEventData, getNodeParams, getPathParams, getToken, getUserSettings, isLuigiClientInitialized, lifecycleManager, linkManager, luigiClientInit, removeContextUpdateListener, removeCustomMessageListener, removeInactiveListener, removeInitListener, sendCustomMessage, setAnchor, setTargetOrigin, setViewGroupData, storageManager, uxManager };
2155
+ //# sourceMappingURL=luigi-client.mjs.map