Skip to content

Commit

Permalink
[SharedUX] Merge similar toast messages in case of a toast-flood/storm (
Browse files Browse the repository at this point in the history
elastic#161738)

## Summary
This PR addresses the occasional toast-floods/toast-storms with a simple
catch mechanism: deduplicate/group toasts by their broad alikeness,
their text and title.

This implementation plugs in to the `global_toast_list.tsx` in Kibana's
GlobalToastList component, capturing updates on the toast update stream,
and collapses toasts before passing them further to the downstream EUI
Toast list react components.

The core idea is to not display notifications directly, but to keep the
toast notifications apart from their visual representation. This way, we
can represent more notifications with one toast on our end, if we group
rightly. The only issue then, is to clean up everything nicely when it's
time. For this we're also exporting a mapping that shows which toast ID
represents which grouped toasts.

I also changed the type `ToastInputFields` to accept rendered react
components as title/text - this will prevent attempts to unmount react
components from elements that are not displayed, thus causing React
warnings.

The close-all button is an EUI feature, which we've started discussing
[here](elastic/eui#6945), probably not part of
this PR.

## What toasts get merged?
The exact merging strategy was not settled, and it's kind of a valve,
where we trade off potential detail lost in toasts for the prevented
noise in the toast floods. The current strategy is as folows:
```
 * These toasts will be merged:
 *  - where title and text are strings, and the same (1)
 *  - where titles are the same, and texts are missing (2)
 *  - where titles are the same, and the text's mount function is the same string (3)
 *  - where titles are missing, but the texts are the same string (4)
``` 
The base merge case is `(1) & (2)`, after some discussion with @Dosant
we decided to include (3) as a compromise, where we're still merging
somewhat similar toasts, and extend the merging to `ToastsApi::addError`
where all error toasts have a MountPoint as their text. We understand
this might hide some details (e.g.: same titles, but very slightly
different MountPoints as their text) but realistically this shouldn't
really happen.

The ultimate future improvement will be (as suggested in the comments by
@jloleysens) a sort of identifier to the toast, based on which we can
group without fear of losing information. But this will require more
work on all the call-sites.
 
Relates to: elastic#161482 


![1ca12f39-75af-4d24-8906-9f27fad33c45](https://github.com/elastic/kibana/assets/4738868/b4578f2e-756d-40d0-9d24-fdffe8b9c724)


### Checklist

Delete any items that are not applicable to this PR.

- [x] [Unit or functional
tests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)
were updated or added to match the most common scenarios

### For maintainers

- [x] This was checked for breaking API changes and was [labeled
appropriately](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)

---------

Co-authored-by: Kibana Machine <[email protected]>
  • Loading branch information
2 people authored and Devon Thomson committed Aug 1, 2023
1 parent ef4ec87 commit 8ed5782
Show file tree
Hide file tree
Showing 7 changed files with 489 additions and 8 deletions.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
/*
* 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 React from 'react';
import { mount, render, shallow } from 'enzyme';
import { ReactElement, ReactNode } from 'react';

import { deduplicateToasts, TitleWithBadge, ToastWithRichTitle } from './deduplicate_toasts';
import { Toast } from '@kbn/core-notifications-browser';
import { MountPoint } from '@kbn/core-mount-utils-browser';

function toast(title: string | MountPoint, text?: string | MountPoint, id = Math.random()): Toast {
return {
id: id.toString(),
title,
text,
};
}

const fakeMountPoint = () => () => {};

describe('deduplicate toasts', () => {
it('returns an empty list for an empty input', () => {
const toasts: Toast[] = [];

const { toasts: deduplicatedToastList } = deduplicateToasts(toasts);

expect(deduplicatedToastList).toHaveLength(0);
});

it(`doesn't affect singular notifications`, () => {
const toasts: Toast[] = [
toast('A', 'B'), // single toast
toast('X', 'Y'), // single toast
];

const { toasts: deduplicatedToastList } = deduplicateToasts(toasts);

expect(deduplicatedToastList).toHaveLength(toasts.length);
verifyTextAndTitle(deduplicatedToastList[0], 'A', 'B');
verifyTextAndTitle(deduplicatedToastList[1], 'X', 'Y');
});

it(`doesn't group notifications with MountPoints for title`, () => {
const toasts: Toast[] = [
toast('A', 'B'),
toast(fakeMountPoint, 'B'),
toast(fakeMountPoint, 'B'),
toast(fakeMountPoint, fakeMountPoint),
toast(fakeMountPoint, fakeMountPoint),
];

const { toasts: deduplicatedToastList } = deduplicateToasts(toasts);

expect(deduplicatedToastList).toHaveLength(toasts.length);
});

it('groups toasts based on title + text', () => {
const toasts: Toast[] = [
toast('A', 'B'), // 2 of these
toast('X', 'Y'), // 3 of these
toast('A', 'B'),
toast('X', 'Y'),
toast('A', 'C'), // 1 of these
toast('X', 'Y'),
];

const { toasts: deduplicatedToastList } = deduplicateToasts(toasts);

expect(deduplicatedToastList).toHaveLength(3);
verifyTextAndTitle(deduplicatedToastList[0], 'A 2', 'B');
verifyTextAndTitle(deduplicatedToastList[1], 'X 3', 'Y');
verifyTextAndTitle(deduplicatedToastList[2], 'A', 'C');
});

it('groups toasts based on title, when text is not available', () => {
const toasts: Toast[] = [
toast('A', 'B'), // 2 of these
toast('A', fakeMountPoint), // 2 of these
toast('A', 'C'), // 1 of this
toast('A', 'B'),
toast('A', fakeMountPoint),
toast('A'), // but it doesn't group functions with missing texts
];

const { toasts: deduplicatedToastList } = deduplicateToasts(toasts);

expect(deduplicatedToastList).toHaveLength(4);
verifyTextAndTitle(deduplicatedToastList[0], 'A 2', 'B');
verifyTextAndTitle(deduplicatedToastList[1], 'A 2', expect.any(Function));
verifyTextAndTitle(deduplicatedToastList[2], 'A', 'C');
verifyTextAndTitle(deduplicatedToastList[3], 'A', undefined);
});
});

describe('TitleWithBadge component', () => {
it('renders with string titles', () => {
const title = 'Welcome!';

const titleComponent = <TitleWithBadge title={title} counter={5} />;
const shallowRender = shallow(titleComponent);
const fullRender = mount(titleComponent);

expect(fullRender.text()).toBe('Welcome! 5');
expect(shallowRender).toMatchSnapshot();
});
});

function verifyTextAndTitle(
{ text, title }: ToastWithRichTitle,
expectedTitle?: string,
expectedText?: string
) {
expect(getNodeText(title)).toEqual(expectedTitle);
expect(text).toEqual(expectedText);
}

function getNodeText(node: ReactNode) {
const rendered = render(node as ReactElement);
return rendered.text();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
/*
* 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 React, { ReactNode } from 'react';
import { css } from '@emotion/css';

import { EuiNotificationBadge } from '@elastic/eui';
import { Toast } from '@kbn/core-notifications-browser';
import { MountPoint } from '@kbn/core-mount-utils-browser';

/**
* We can introduce this type within this domain, to allow for react-managed titles
*/
export type ToastWithRichTitle = Omit<Toast, 'title'> & {
title?: MountPoint | ReactNode;
};

export interface DeduplicateResult {
toasts: ToastWithRichTitle[];
idToToasts: Record<string, Toast[]>;
}

interface TitleWithBadgeProps {
title: string | undefined;
counter: number;
}

/**
* Collects toast messages to groups based on the `getKeyOf` function,
* then represents every group of message with a single toast
* @param allToasts
* @return the deduplicated list of toasts, and a lookup to find toasts represented by their first toast's ID
*/
export function deduplicateToasts(allToasts: Toast[]): DeduplicateResult {
const toastGroups = groupByKey(allToasts);

const distinctToasts: ToastWithRichTitle[] = [];
const idToToasts: Record<string, Toast[]> = {};
for (const toastGroup of Object.values(toastGroups)) {
const firstElement = toastGroup[0];
idToToasts[firstElement.id] = toastGroup;
if (toastGroup.length === 1) {
distinctToasts.push(firstElement);
} else {
// Grouping will only happen for toasts whose titles are strings (or missing)
const title = firstElement.title as string | undefined;
distinctToasts.push({
...firstElement,
title: <TitleWithBadge title={title} counter={toastGroup.length} />,
});
}
}

return { toasts: distinctToasts, idToToasts };
}

/**
* Derives a key from a toast object
* these keys decide what makes between different toasts, and which ones should be merged
* These toasts will be merged:
* - where title and text are strings, and the same
* - where titles are the same, and texts are missing
* - where titles are the same, and the text's mount function is the same string
* - where titles are missing, but the texts are the same string
* @param toast The toast whose key we're deriving
*/
function getKeyOf(toast: Toast): string {
if (isString(toast.title) && isString(toast.text)) {
return toast.title + ' ' + toast.text;
} else if (isString(toast.title) && !toast.text) {
return toast.title;
} else if (isString(toast.title) && typeof toast.text === 'function') {
return toast.title + ' ' + djb2Hash(toast.text.toString());
} else if (isString(toast.text) && !toast.title) {
return toast.text;
} else {
// Either toast or text is a mount function, or both missing
return 'KEY_' + toast.id.toString();
}
}

function isString(a: string | any): a is string {
return typeof a === 'string';
}

// Based on: https://gist.github.com/eplawless/52813b1d8ad9af510d85
function djb2Hash(str: string): number {
const len = str.length;
let hash = 5381;

for (let i = 0; i < len; i++) {
// eslint-disable-next-line no-bitwise
hash = (hash * 33) ^ str.charCodeAt(i);
}
// eslint-disable-next-line no-bitwise
return hash >>> 0;
}

function groupByKey(allToasts: Toast[]) {
const toastGroups: Record<string, Toast[]> = {};
for (const toast of allToasts) {
const key = getKeyOf(toast);

if (!toastGroups[key]) {
toastGroups[key] = [toast];
} else {
toastGroups[key].push(toast);
}
}
return toastGroups;
}

const floatTopRight = css`
position: absolute;
top: -8px;
right: -8px;
`;

/**
* A component that renders a title with a floating counter
* @param title {string} The title string
* @param counter {number} The count of notifications represented
*/
export function TitleWithBadge({ title, counter }: TitleWithBadgeProps) {
return (
<React.Fragment>
{title}{' '}
<EuiNotificationBadge color="subdued" size="m" className={floatTopRight}>
{counter}
</EuiNotificationBadge>
</React.Fragment>
);
}
Loading

0 comments on commit 8ed5782

Please sign in to comment.