npm package: @munichremarkets/universal-simulator
Description: This package provides the _Universal Simulator_ widget by Munich Re Markets for integration into your website.
Latest version: 3.0.2

# Munich Re Markets Universal Simulator Widget

This package provides the _Universal Simulator_ widget by Munich Re Markets for integration into your website.

## Installation

If you use NPM as a package manager, run

```shell
  npm install --save @munichremarkets/universal-simulator
```

And if you use Yarn:

```shell
  yarn add @munichremarkets/universal-simulator
```

## Integration

The Universal Simulator widget provides a (plain JavaScript) rendering API in the form of the `renderUniversalSimulator` function
that is used to display the widget on the page and pass data to the widget.
This function additionally returns an object containing an `unmount` and `rerender` function which you can respectively use
to unmount the widget or rerender the widget with new parameters during runtime

### Importing from NPM

The Universal Simulator package contains JavaScript (ES5) code in both ECMAScript and UMD (Universal Module Definition)
module formats, so you need to use a bundler that supports either of these formats, such as Webpack or Rollup. Using
ES6-style imports, your code might look like this:

```javascript
import { renderUniversalSimulator } from '@munichremarkets/universal-simulator';
```

TypeScript declaration files (`.d.ts`) are also included in the package, providing typings and enhanced IDE support for
the rendering API.

### Rendering the widget

In order to render the widget, you need to invoke the `renderUniversalSimulator` rendering function that is made available as
described above. The following data needs to be provided when invoking the rendering function:

- A target DOM element (typically a `<div>` element) into which the widget should be rendered
- A configuration object providing data to the widget, see section "Configuring the widget" below

The rendering function returns an object containing both an `unmount` and `rerender` function for the widget.

For example, a call to the rendering function might look like this (ES6):

```javascript
const target = document.getElementById('widget-target');

renderUniversalSimulator(target, {
    /* configuration data, see below */
}).then(() => {
    /* code to be executed when the rendering is complete */
});
```

Please make sure to invoke the rendering function after the DOM has been loaded, e.g. by putting the call into
a `<script>` tag at the end of the `<body>` or into a `DOMContentLoaded` event handler.

- **Note:** You need to make sure that the `process.env` object is available (not just `process.env.NODE_ENV`), e.g.
  using Webpack's [Define Plugin](https://webpack.js.org/plugins/define-plugin/).

### Unmounting the widget

The Object returned by the rendering function contains an `unmount` function you can use as a cleanup function. This function can be used to unmount the
widget like this:

```javascript
const target = document.getElementById('widget-target');

renderUniversalSimulator(target, {
    /* configuration data, see below */
}).then(({ unmount }) => {
    /* use `unmount` e.g. in an event listener */
});
```

### Rerendering the widget

The Object returned by the rendering function contains an `rerender` you can use as a way to rerender the widget with new parameters during runtime. This function can be used to rerender the
widget like this:

```javascript
const target = document.getElementById('widget-target');

renderUniversalSimulator(target, {
    /* configuration data, see below */
}).then(({ rerender }) => {
    /* use `rerender` e.g. in an event listener and pass the new configuration data, see paragraph 'Configuring the widget' */
});
```

Please note that some parameters might not be reevaluated on rerender.

### Configuring the widget

The configuration object passed to `renderUniversalSimulator` can contain the following properties (example values):

```
{
    // Base URL of universal simulator backend
    // Mandatory
    // May optionally end in '/'
    backendBaseUrl: 'https://some-url',

    // Base URL of the universal simulator backend simulation api. If not defined, backendBaseUrl is used.
    // Only use this for highly specialized scenarios requiring a custom API endpoint
    // Most applications should rely on the default backend configuration
    // Optional
    // May optionally end in '/'
    simulationBackendBaseUrl: 'https://some-url',

    // ID of the screen flow for the universal simulator product to use
    // Mandatory
    flowId: 'some-uuid',

    // Locale to use for localized texts
    // Mandatory
    // Currently available locales: Locale.DeDe, Locale.EnUs, Locale.EnGb
    locale: Locale.DeDe,

    // ID of the universal simulator product to use
    // Mandatory
    productId: 'some-uuid',

    // Whether to render the widget in the debug mode or not
    // Optional, default: false
    // Set this to true to render JSON validation errors
    debugModeEnabled: false,

    // Whether to skip the input screen and directly display the output screen in the customer flow
    // Optional, default: false
    // Set this to true to skip to the output screen
    skipToOutputScreen: false,

    // Provides a json of key-value pairs to set parameter values for customer flow screens.
    // Optional, use with care. Intended for the use in customer flow output screens without controls
    // Set this to provide parameter values without requiring user input
    customProductParameters: { Guarantee: 'stringValue', InitialDeposit: 12 },

    // Provide some default display options, currently only to specify if the expert view sidebar starts in collapsed state
    // Optional. displayOptions.sidebarInitiallyCollapsed defaults to false if not set.
    displayOptions: { sidebarInitiallyCollapsed: true },

    // Function called when issues occur during network requests to the universal simulator backend. The function is called with the HTTP error code (if existing).
    // This allows you to apply side effects like showing a notification to the user...etc.
    // Optional, default: undefined
    // httpErrorCode can be a number or undefined (ex: when the host cannot be reached)
    onNetworkError: httpErrorCode => {},
}

```

The following things should be considered to ensure that the widget works as intended.

**Note:** Providing data that does not adhere to the documented API of the widget may lead to unexpected behavior or the
widget not working altogether.

### Text override mechanism

Some texts that are displayed by the widget can be overridden by providing the `textOverrides` option in the
configuration object. It expects an object in the form of

```
{
    'some.overridable.key': {
        [Locale.DeDe]: 'Some german text',
        [Locale.EnUs]: 'Some american english text',
        [Locale.EnGb]: 'Some british english text',
    },
    'some.other.key': { /* ... */ }
}
```

where `some.overridable.key` is a localization key specified by the widget.

**Note:** The override mechanism is entirely optional. If it is omitted, default texts are used instead.

#### Semantic markup

Some texts can contain basic semantic HTML markup sanitized before displaying. The following tags are allowed
and will be displayed as bold, italic, underlined, etc.: `strong`, `b`, `em`, `i`, `u`, `br`, `p`.

**Note:** HTML tags cannot contain attributes. If provided anyway, they are removed during sanitization (
e.g. `<em class="some-classname">some text</em>` will be converted to `<em>some text</em>`).

#### Interpolation

In some cases, texts might need to include dynamic values (e.g. monetary values or percentages). Such values can be
referenced in the text using `{{someVariable}}`, where `someVariable` is a predefined name specific to the respective
text key and will be replaced with the actual value during runtime.

#### Empty default text

In some cases default texts might be empty, which will cause the enclosing markup element (e.g. an information icon with
accompanying text label) to purposefully not be displayed in the widget. This is a mechanism to remove markup elements
entirely when the text that they usually display is missing. In these cases, a text override can be supplied to make the
element visible again.

### Mandatory and optional fields in the configuration

- When using TypeScript, your IDE should automatically indicate which fields are mandatory/optional via the provided
  typings.
- When using plain JavaScript, please refer to the section above regarding mandatory/optional fields.
- The widget will perform a schema validation on the provided configuration and will fail to render if the validation
  fails. In this case you can then find additional information on why the validation failed in the console of your
  browser.

### Providing enumeration values in the configuration

Enumerations can be directly imported from the widget library. This works with both plain JavaScript and TypeScript. For
instance, the `Locale` enumeration can be used like this:

```javascript
import { renderUniversalSimulator, Locale } from '@munichremarkets/universal-simulator';

const target = document.getElementById('widget-target');
renderUniversalSimulator(target, { locale: Locale.EnUs, ... });
```

Although other ways of providing an enumeration value are technically possible (e.g. numerical or string values), it is
considered improper usage and may stop working at any point.

## Styling

### Framework

The Universal Simulator widget uses the Tailwind framework for styling internally.

### Adaptation of styling

By default, the styling of the widget automatically adapts to the styling of your website to a certain extent. However,
you can still customize the appearance if necessary.

#### Automatic styling

##### Fonts

Since the widget does not define its own font, any font you define in the DOM tree above the widget will automatically
be used within the widget.

##### Spacings

Font sizes and most of the spacings are defined in units of `rem` (root `em`), so these sizes will automatically be set
relative to the font size of your website's `<body>` element.

##### Width

The widget will automatically fill the full width of its parent element.

##### Theming

###### Primary theming API: Overriding theme colors & CSS variables

Certain colors (_SRI colors_) probably need to be customized. The minimal set of CSS variables that should be overridden are `element`, and the shades
of `primary` and `secondary`:

```
primary-[50-900]
secondary-[50-900]
element-[0-23]
element-other
```

The `element-*` colors are used within indicators and charts (funds, categories, ...). The `element-other` color is used
specifically for those instances where it's necessary to display an "_Other_" category in an indicator or chart.

By default, all additional colors are derived from those colors, so overriding them should already provide a good
baseline for theming.

To make sure that your settings for these variables take precedence over the defaults defined by the widget, use the CSS
selector `.sri-universal-simulator` like this:

```css
.sri-universal-simulator {
    --primary-500: red;
}
```

For more fine granular customization, you can also override individual CSS variables for each color individually.
For example:

```css
.sri-universal-simulator {
{
  /* --- Semantic Colors --- */
  --danger: #e52d2d;
  --dark: #343a40;
  --info: #0eb6c9;
  --light: #f0f5fb;
  --success: #4ad386;
  --warning: #ffc107;

  /* --- Primary Palette --- */
  --primary: #7b1fa2;
  --primary-50: #f3e5f5;
  --primary-100: #e1bee7;
  --primary-200: #ce93d8;
  --primary-300: #ba68c8;
  --primary-400: #ab47bc;
  --primary-500: #9c27b0;
  --primary-600: #8e24aa;
  --primary-700: #7b1fa2;
  --primary-800: #6a1b9a;
  --primary-900: #4a148c;

  /* --- Secondary Palette --- */
  --secondary: #175d92;
  --secondary-50: #e1ebf8;
  --secondary-100: #cddff6;
  --secondary-200: #aac9ec;
  --secondary-300: #759fc3;
  --secondary-400: #5186b0;
  --secondary-500: #175d92;
  --secondary-600: #125285;
  --secondary-700: #0b497c;
  --secondary-800: #074276;
  --secondary-900: #0e3d73;

  /* --- Data/UI Elements --- */
  --element-0: #175d92;
  --element-1: #51a7b5;
  --element-2: #d5cd43;
  --element-3: #697ee7;
  --element-4: #435463;
  --element-5: #e97c07;
  --element-6: #abadaf;
  --element-7: #c0de08;
  --element-8: #0e3d73;
  --element-9: #1e8093;
  --element-10: #96912e;
  --element-11: #4958a2;
  --element-12: #2c3741;
  --element-13: #9a5204;
  --element-14: #7c8084;
  --element-15: #9bb107;
  --element-16: #759fc3;
  --element-17: #73c7d8;
  --element-18: #ebe79a;
  --element-19: #b1bcf4;
  --element-20: #627990;
  --element-21: #f5c796;
  --element-22: #dadadb;
  --element-23: #e5f295;
  --element-other: #dadadb;
}
}
```

###### Secondary theming API: Overriding CSS classes

You can override each style of the application via CSS classes individually. Therefore, it is important to know the
basic markup of the widget, which looks like this:

```html
<!-- Passed into the rendering function by your website -->
<div>
    <div class="sri-universal-simulator">
        <!-- Widget content -->
    </div>
</div>
```

If you want to style an element within the main content of the widget, prefix all CSS rules
with `.sri-universal-simulator` to ensure that your CSS rule is more specific than the ones shipped with the widget and
hence overrides the latter.

Most of the UI component used in the widget have a corresponding CSS class name starting with the prefix `sri-us-`, so you can easily select and customize it.

For example, to style a checkbox (`.sri-us-checkbox`), use a CSS rule like this:

```css
.sri-universal-simulator .sri-us-checkbox {
    /* ... */
}
```

##### Print view

In the print view, you might want to hide certain elements on your page (e.g. header and footer), reduce page margins
etc. You can do this using a media query like this:

```css
@media print {
    header {
        display: none !important;
    }
}
```

## Layout recommendations

The Universal Simulator widget is intended for use as a _full-page_ widget. This means that the widget expects your
website to allow it to take the full width of the viewport, to have no side navigation besides the widget and to allow as much height as the widget requires.
The Widget should not be implemented inside a modal either.

## Browser support

The following browsers are supported:

- Chrome (latest version)
- Firefox (latest version)
- Safari on macOS and iOS (latest two major versions)