npm package: @gobistories/gobi-web-integration
Description: This library will let you put your Gobi stories on your site.
Author: Gobitech AS
Latest version: 6.19.8

# Gobi Web Integration

Welcome to Gobi Web Integration. This library will let you put your Gobi stories on your site. If you don't have any
Gobi Stories yet sign up in our [Story Manager](https://studio.gobistories.com/) to get access to our production tools.

## Story Bubbles Demo

To easily test the most used options, go to the code snippet editor in our [Story Manager](https://studio.gobistories.com/).

## Troubleshooting & FAQ

#### Bubbles don't show

See the console. Can you spot any errors? Try to understand them. If there seems to be a bug in the library, please
email us.

#### Vidoes or thumbnails don't play and I see Content Security Policy errors

You may see an error similar to:

```
Refused to load media from 'https://res.cloudinary.com/gobi-technologies-as/...' because it violates the following
Content Security Policy directive: ...
```

If so, you need to update your `Content-Security-Policy` HTTP headers to include `blob:` and the sources that we use.

Sources used by our library are:

- https://api.gobistories.com/
- https://widget.gobistories.com/
- https://res.cloudinary.com/gobi-technologies-as/

Example using the fallback `default-src`:

```
default-src 'self' blob: <your other sources> https://widget.gobistories.com https://api.gobistories.com https://res.cloudinary.com/gobi-technologies-as/;
```

Example using stricter fetch directives:

```
script-src 'self': <your other sources> https://widget.gobistories.com/;
connect-src 'self': <your other sources> https://api.gobistories.com/;
media-src 'self' blob: <your other sources> https://res.cloudinary.com/gobi-technologies-as/;
img-src 'self' blob: <your other sources> https://res.cloudinary.com/gobi-technologies-as/;
```

#### My page scrolls when opening a story

If your page scrolls to the top when opening a story, this is usually caused by the height styling for the HTML tag of
your page. Removing or replaceing this with `min-height` usally solves the problem.

## Technical Documentation

### Story Bubbles

Adding bubbles to your pages and content requires three steps:

1. Load our script
1. Add a placeholder element where you want the bubbles
1. Call our code to create the bubbles

You can generate the required code within our [Story Manager](https://studio.gobistories.com/), or refer to the
documentation below.

#### **Adding bubbles with Gobi.discover()**

This is the recommended way to add story bubbles to your page. Add your placeholder where you want the bubble to
appear, add the `gobi-stories` class and specify options using data attributes:

```html
<div
  class="gobi-stories"
  data-gobi-stories="story-id another-story-id"
  data-gobi-kebab-cased-option="value"
  data-gobi-some-other-kebab-cased-option="value"
></div>
```

If you would like to configure titles or thumbnail urls per story, then you can add them as child elements:

```html
<div class="gobi-stories" data-gobi-kebab-cased-option="value" data-gobi-some-other-kebab-cased-option="value">
  <div data-gobi-story="story-id" data-gobi-title="About Us"></div>
  <div data-gobi-story="another-story-id" data-gobi-title="Our Product" data-gobi-thumbnail-url="..."></div>
</div>
```

Note that you can add new lines to title by using a new line in the HTML, or by adding `\n` with the title itself.

See the **Bubble Options** section for available options. Note that options should be converted to _kebab case_ and
prefixed with `data-gobi-`.

You can then load our script and run `gobi.discover()`:

```html
<head>
  <script src="https://widget.gobistories.com/gwi/6" async onload="gobi.discover()"></script>
</head>
```

You can pass global options to discover() that will be used for all bubbles on the page as defaults.
See **Bubble Options** for more information:

```js
gobi.discover({
  bubbleSize: '120px',
  color: 'blue',
});
```

The global options will be used when they are not overridden by individual embed options.

#### **Adding bubbles with an inline script**

Another way to add Gobi stories to your page is by using inline javascript.

```html
<head>
  <script src="https://widget.gobistories.com/gwi/6"></script>
</head>
<body>
  <div id="container"></div>
  <script>
    new gobi.Bubbles({
      container: '#container',
      stories: [
        {
          id: 'story-key',
          title: 'Some Title',
        },
        {
          id: 'another-story-key',
          title: 'Some Another Title',
        },
      ],
    });
  </script>
</body>
```

### Creating a standalone player

You can also show story player directly in the page without using bubbles.

```html
<head>
  <script src="https://widget.gobistories.com/gwi/6"></script>
</head>
<body>
  <div id="container"></div>
  <script>
    new gobi.Player({
      container: '#player-container',
      storyId: 'story-key',
      on: {
        videoPlay: function() {
          console.log('played the video!');
        },
      },
    });
  </script>
</body>
```

See **Player Options** for details.

#### Installing as a Package

[![npm version](https://badge.fury.io/js/%40gobistories%2Fgobi-web-integration.svg)](https://badge.fury.io/js/%40gobistories%2Fgobi-web-integration)

Developers may prefer to install Gobi Web Integration as a package dependency:

```sh
npm install --save @gobistories/gobi-web-integration
```

```js
import { Bubbles } from '@gobistories/gobi-web-integration';

// Create bubbles
new Bubbles({
  container: '#container',
  bubbleSize: '200px',
});

// Create a Player
new Player({
  container: '#container',
  storyName: 'story-id',
  playerOptions: {
    on: {
      videoPlay: function() {
        console.log('played the video!');
      },
    },
  },
});
```

### Browser Support

The library will work well in Chrome, Firefox, Safari, and Opera. The library lets users in IE view the story, but UX
and functionality might be a bit limited compared to modern browsers.

### Embed Options

| option                      | default      | description                                                                                                           |
| --------------------------- | ------------ | --------------------------------------------------------------------------------------------------------------------- |
| container                   | `#gobi-here` | **Required for inline javascript.** String. Query Selector for HTMLElement. Container where the module will be embed. |
| color                       | `#15d6ea`    | Any valid css color value (#000, rgb(...), rgba(...)). The color of the border around the story bubble.               |
| bubbleSize                  | `96px`       | Valid css size value, except % (10px, 10vw...). The size of the avatar aka bubble.                                    |
| hideTitle                   | `false`      | Boolean. Hides the bubble title if true (default false)                                                               |
| animatedBubble              | `false`      | Boolean. Makes the bubbles as gif animation.                                                                          |
| wrap                        | `false`      | Boolean. Add styles which allow a horizontal series of bubbles to wrap to new lines, when the screen is narrow.       |
| scroll                      | `true`       | Boolean. Show a scroll bar when stories do not fit in the page or parent container.                                   |
| isFullHeightMobile          | `true`       | Boolean. Add styles which allow making a full-screen popup. It's work only on mobile phone                            |
| showPlayIcon                | `false`      | Boolean. Add Play icon inside the bubbles                                                                             |
| playIconUrl                 | undefined    | Optional string, will show the given icon in the play bubble.                                                         |
| align                       | `center`     | String. Valid values 'left', 'right', 'end', 'start', 'center' . It sets alignment for bubbles horizontally           |
| autoSegue                   | `false`      | Boolean. Enable or disable the transition to next story in the end                                                    |
| fullscreenPlayer            | `false`      | Boolean. Set to true to remove all margins from the player when opened in popup mode                                  |
| noShade                     | `false`      | Boolean. Set to true to not apply a page background shade when the player is opened in popup mode                     |
| titleFontSize               | `12px`       | Valid css size value. By default, a size is selected based on bubbleSize between 12px and 36px.                       |
| titleFontColor              | `black`      | Any valid css color value (#000, rgb(...), rgba(...)). The color of the bubble title text.                            |
| titleFontFamily             | undefined    | Valid css font family name. Inherited from the document by default.                                                   |
| titleFontWeight             | undefined    | Valid css font weight. Inherited from the document by default.                                                        |
| inheritTextFontFamily       | `false`      | Boolean. Whether to inherit the font family from the page for bubble titles.                                          |
| inheritTextStyles           | `false`      | Boolean. Whether to inherit font family, font size, font weight and color from the page for bubble titles.            |
| zIndex                      | `2000000`    | Number. Sets the priority of the player above other content when open.                                                |
| on.loaded                   | `function`   | Function. Called when all Bubbles have loaded.                                                                        |
| on.close                    | `function`   | Function. Called when all popups are closed.                                                                          |
| **stories**                 | `[]`         | **Required for inline javascript.** Array. Data of stories.                                                           |
| stories[0...n].id           |              | **Required.** String. Identifire of story.                                                                            |
| stories[0...n].title        |              | String. Change title text of specific story.                                                                          |
| stories[0...n].thumbnailUrl |              | String. Overrides the image used for the bubble.                                                                      |
| stories[0...n].bubbleSrc    |              | **Deprecated.** Alias of `thumbnailUrl`.                                                                              |
| playerOptions               | `{}`         | Object. Provides options to the player when opening. See **Player Options** for details.                              |

## Events

`on.loaded` is called with a controller as it's first parameter. See **Opening Stories Programmatically** for more information.

## Embedded player

Creates a Player and returns an interface for managing it, and for listening to its events.

### Player Options

| option             | default     | description                                                                                                      |
| ------------------ | ----------- | ---------------------------------------------------------------------------------------------------------------- |
| container          |             | Query Selector for HTMLElement. Container where the player will be inserted.                                     |
| storyId            |             | **Required.** String. The key of the story.                                                                      |
| autoStart          | `false`     | Boolean. Add `autoplay` attributes to the video.                                                                 |
| autoStartWithSound | `false`     | Boolean. Add `autoplay` attributes to the video, and don't mute the video at the same time.                      |
| loop               | `false`     | Boolean. Add `loop` function to video.                                                                           |
| roundedCorners     | `true`      | Boolean. Enable or disable rounded corners to player element.                                                    |
| shadow             | `true`      | Boolean. Enable or disable shadow on the player element.                                                         |
| width              | `undefined` | Number. Set player width. If height is not defined it will calculate automaticaly using an aspect ratio of 16:9. |
| height             | `undefined` | Number. Set player height. If width is not defined it will calculate automaticaly using an aspect ratio of 16:9. |
| checkViewPort      | `true`      | Boolean. Enable functionality which pause player if it outside of screen view area.                              |
| playButton         | `true`      | Boolean. Enable or disable play button.                                                                          |
| transcriptButton   | `false`     | Boolean. Enable or disable button to download a transcript. Only shown if applicable.                            |
| savePosition       | `true`      | Boolean. Enable or disable save last watched chapter. It needs to confirm policy by user                         |
| useMediaProxy      | `false`     | Boolean. Enable the use of a reverse proxy hosted by Gobi for media content.                                     |
| **on**             | `[]`        | Array. Data of event listener                                                                                    |
| on.videoPlay       | `function`  | Called when the video plays.                                                                                     |
| on.videoPause      | `function`  | Called when the video pauses.                                                                                    |
| on.videoComplete   | `function`  | Called when the video completes.                                                                                 |
| on.clickPrevious   | `function`  | Called when changing to the previous chapter.                                                                    |
| on.clickNext       | `function`  | Called when changing to the next chapter.                                                                        |
| on.clipChange      | `function`  | Called when a chapter changes.                                                                                   |
| on.newIteration    | `function`  | Called when the story loops back to the beginning (requires loop to be `true`).                                  |
| on.error           | `function`  | Called when an error occurs.                                                                                     |
| on.loaded          | `function`  | Called when the video is loaded.                                                                                 |

#### Events

All events are called with the relevant chapter index as the first parameter.

### Methods

You can destroy the Gobi Player to free up resources:

```js
var player = new gobi.Player({
  container: '#player-container',
  storyId: 'story-key',
});

player.destroy();
```

## Opening Gobi Stories Programmatically

Several functions allow you to open story popups programmatically, either immediately or using a controller passed to a
callback:

| Function                           | Description                                  |
| ---------------------------------- | -------------------------------------------- |
| `openPopup(id, options)`           | Opens a story immediately without preloading |
| `renderPopups(options, callback)`  | Preloads stories for opening later           |
| `renderBubbles(options, callback)` | Displays bubbles that can be opened later    |
| `discover(options, callback)`      | Finds and renders gobi-stories embeds        |

Options are the same as **Bubble Options**.

The functions `renderPopups()` and `renderBubbles()` require a container to be specified in `options`.
The `discover()` function required elements in the dom with the class `gobi-stories` to create bubbles
or `gobi-popups` to create popups.

The function `openPopup()` does not require an element to be provided.

The callback's only argument is a controller with the properties:

| Property        | Type       | Description                                       |
| --------------- | ---------- | ------------------------------------------------- |
| `storyIds`      | `string[]` | An array of loaded story ids                      |
| `openPopup(id)` | `function` | Opens a popup story player for the given story id |

Note: The `on.loaded` bubble option is also passed a controller as it's first argument.

You can open a popup story player at any time with `openPopup()`:

```js
gobi.openPopup('story-id');
```

> **Important**: In many browsers playing a video with sound requires at least one user interaction that starts a video
> with sound. Therefore `openPopup()` must either be called by a user interaction event (such as click), or after
> this requirement has been met some other way, otherwise the video may fail to start.

To preload story data and poster images before opening a popup, call `renderPopups()` and use the controller passed to
the callback to open the story. This may provide a smoother experience, particularly on slower internet connections.

```js
gobi.renderPopups({ stories: [{ id: 'story-id' }] }, controller => {
  controller.openPopup('story-id');
});
```

If you want to show bubbles on your page and want to open them programmatically, you can use renderBubbles to create
the bubbles and get the controller with a callback:

```js
gobi.renderBubbles({ container: '#gobi-container', stories: [{ id: 'story-id' }] }, controller => {
  controller.openPopup('story-id');
});
```

If you are using `gobi.discover()` to create your bubbles, you can get a controller using the second parameter, and
use it later:

```js
let gobiController;

gobi.discover({}, controller => {
  gobiController = controller;
});

// You can now use gobiController to open stories, for example with onClick handlers.
```