24.1.0 • Published 1 month ago

@atomic.io/action-cards-web-sdk v24.1.0

Weekly downloads
-
License
UNLICENSED
Repository
github
Last release
1 month ago

codecov

Web SDK - Current (24.1.0)

Introduction

The Atomic Web SDK allows you to integrate an Atomic stream container into your web app or site, presenting cards from a stream to your customers.

The current stable release is 24.1.0.

Browser support

The Atomic Web SDK supports the latest version of Chrome, Firefox, Edge (Chromium-based), Safari on macOS, Safari on iOS and Chrome on Android.

Boilerplate app

We currently do not have a boilerplate app for the Web SDK. Contact us if you are interested in this.

Installation

The current version of the Atomic Web SDK is 24.1.0, and is hosted on our CDN at https://downloads.atomic.io/web-sdk/release/24.1.0/sdk.js.

To integrate it, add the script as a source to your web page:

<html>
  ...
  <body>
    <script src="https://downloads.atomic.io/web-sdk/release/24.1.0/sdk.js"></script>
  </body>
</html>

When Atomic releases a new version of the Web SDK, you will need to manually update your scripts with a url that references the download location of the latest version.

Content Security Policy

If your website enforces a content security policy (CSP) and is using any the following directives, you will need to add the resources corresponding to that directive to your CSP in order to use the Atomic Web SDK.

DirectiveRequired Resources
frame-srcblob:
connect-srchttps://*.client-api.atomic.io wss://*.client-api.atomic.io
style-src'self' 'unsafe-inline'
font-src'self' data: https://fonts.gstatic.com
script-src'self' https://downloads.atomic.io

Setup

Before displaying a stream container or single card, you must locate your API base URL, environment ID and API key.

API host, API keys and environment id

You must specify your SDK API base URL when configuring the Atomic SDK. Locate this URL in the Atomic Workbench:

  • In the Workbench, click on the cog icon in the bottom left and select 'Settings'. On the screen that appears, look for the SDK section. Find the API host details here, and create API keys as required.
  • Alternatively, open the command palette and type API host or API keys as required.

The SDK API base URL is different to the API base URL endpoint, which is also available under Configuration. The SDK API base URL ends with client-api.atomic.io.

You can find the environment ID at the top right of the Configuration screen.

Authenticating requests with a JWT

To authenticate requests from the SDK to the Atomic Platform, you must supply an asynchronous callback which will return an authentication token (JSON Web Token or JWT) when requested. This is set by calling the setSessionDelegate method, giving it a function which resolves to a promise that supplies an authentication token.

AtomicSDK.setSessionDelegate(() => {
  return Promise.resolve('<authToken>')
})

Your callback will be invoked when the SDK requires a JWT. The token returned by your callback will be cached by the SDK and used for subsequent authenticated requests until expiry. After expiry the callback will be invoked once again to request a fresh token. The callback must return the token within 5 seconds, otherwise error handling will be triggered within the SDK. More information on the JWT structure is available in the Authentication section.

JWT Expiry interval

The expiry interval for a JWT cannot currently be configured in the Web SDK.

JWT Retry interval

An optional second parameter is available to set the retryInterval, this is the time in milliseconds that the SDK should wait before attempting a repeated request for a JWT from the session delegate in the event of a token request failing.

const retryInterval = 5000

AtomicSDK.setSessionDelegate(() => {
  return Promise.resolve('<authToken>')
}, retryInterval)

Login convenience method

To be ready to display a stream container you need to have initialised the SDK & set the Session Delegate. As of SDK 1.6.0 you can use the convenience method login to accomplish this in one call. This method has the following parameters:

  • apiHost: a string value representing your API host
  • apiKey: a string value representing your API key
  • environmentId: a string value representing your environment id
  • sessionDelegate: a function that resolves to a promise which supplies an authentication token to the SDK
  • retryInterval: (optional) a number which defines the JWT Retry interval

This method should be called in the following manner:

AtomicSDK.login(
  '<apiHost>',
  '<apiKey>',
  '<environmentId>',
  '<sessionDelegate>',
  '<retryInterval>'
)

WebSockets and HTTP API protocols

Available in SDK version 1.0.0 and above

You can specify the protocol the SDK uses to communicate with the Atomic Platform when fetching cards. This can be done by calling the setApiProtocol method before calling initialise, so that the SDK knows which protocol to use when establishing a connection to the platform:

AtomicSDK.setApiProtocol('<communicationProtocol>')

The valid options for communicationProtocol are: "http" or "webSockets". If this method is not called the SDK will default to WebSockets for communication with the Atomic Platform.

Logging out the current user

The SDK provides a method AtomicSDK.logout for clearing user-related data when a previous user logs out, or when the active user changes, so that the cache (including the JWT) is clear when a new user logs in to your app. The method also sends any pending analytics events back to the Atomic Platform.

The method accepts an optional parameter deregisterNotifications, a boolean that indicates whether the device should be deregistered for notifications upon logging out. This parameter only affects a Cordova integration at present as Web push notifications are currently not supported.

info: New log-out behaviour

As of Release 1.6.0, the following behaviours have been applied to this method:

  • After logging out, you must log in to the SDK (by calling either AtomicSDK.login or AtomicSDK.initialise & AtomicSDK.setSessionDelegate) to proceed with another user. Otherwise, the Atomic SDK will raise exceptions.
  • This method also purges all cached card data stored by the SDK and disables all SDK activities.
  • This method also invalidates existing stream containers. However, they are not removed from the page in order to allow you to choose how this will be handled. After calling AtomicSDK.logout the stream containers will display their empty feed state but users cannot take any action with them. Once you are ready you can call the stop method on your stream container instance(s) to stop the stream container and remove it from the page.

The code snippet below illustrates how to log out from the Atomic SDK & log in a new user:

// The stream container instance being displayed to the user
const instance = AtomicSDK.launch({...})
...
// Logout from the SDK, in this case passing the option to deregister notifications
await AtomicSDK.logout(true)
// Handle any logout tasks in your own app now, the stream container will display an "empty feed" UI
...
// Remove the stream container when ready
instance.stop()
...
// Log in again with a new user when ready
AtomicSDK.login('<apiHost>', '<apiKey>', '<environmentId>', '<sessionDelegate>', '<retryInterval>')
// Create a new stream container instance when ready
const instance = AtomicSDK.launch({...})

Displaying a stream container

This section applies to all types of container. Containers can be created using the launch method (launcher view) , the embed method (standalone vertical and horizontal containers), or the singleCard method (single card view). Specifics and code examples for each type of container are explained in more detail in their dedicated sections below.

Before displaying a stream container, you must initialize the SDK by calling the initialise method:

AtomicSDK.initialise('<apiHost>', '<apiKey>', '<environmentId>')

Stream container ID

First, you’ll need to locate your stream container ID.

Navigate to the Workbench, select Configuration > SDK > Stream containers. Alternatively, open the command palette and type Stream containers. Find the ID next to the stream container you are integrating.

Configuration options

Some configuration options are common for all types of container, other options are only available to a specific type of container. We mention the container type for each configuration option that is not available across all container types.

Style and presentation

A selection of UI elements can be customized within stream containers (this customization does not apply to single card views). These are configured using the enabledUiElements property on a stream container configuration object:

  • cardListToast - defaults to true. Set to false to turn off toast messages on the card list.
  • customToastContainer - defaults to false. Set to true to use an alternative toast message presentation for standalone or launcher stream containers which allows you to reposition the toast message.
  • toastConfig - an optional configuration object to customise the toast messages displayed by the SDK.
    • timeout: optionally supply a number that sets how long the toast message should be displayed for in milliseconds.
    • toastMessages: an optional object where you can set custom strings for the following properties: submittedCard, dismissedCard, snoozedCard & feedbackReceived. These will be displayed as the toast message for the respective card event.
  • cardListHeader - defaults to true. Set to false to disable the display of the title at the top of the card list.
  • customContainerHeader - can optionally supply a custom header to be displayed above the card feed when displaying a launch or embed type stream container.
    • scrollHeader: an optional boolean to control whether the custom header scrolls with the card feed, defaults to true.
    • headerElement: a string representing valid HTML to be rendered as the custom header. Styles to be applied to the header should be supplied inline on the HTML elements.
  • launcherButton - an optional configuration object for the button that toggles a launch type stream container. Accepts the following properties:
    • disabled: defaults to false. Set to true to prevent the launcher button from displaying on the page.
    • backgroundColor: a string value for a valid CSS color that will be used as the background color for the button.
    • openIconSrc: the source for the image tag displayed in the launcher button when it is in the closed state.
    • closeIconSrc: the source for the image tag displayed in the launcher button when it is in the open state.

The code snippet below shows how to initialize a launcher container type with a value for all of the enabledUiElements properties.

AtomicSDK.launch({
    ...
    enabledUiElements: {
      cardListToast: true,
      customToastContainer: true,
      toastConfig: {
        timeout: 5000,
        toastMessages: {
          submittedCard: 'Custom submitted message',
          dismissedCard: 'Custom dismissed message',
          snoozedCard: 'Custom snoozed message',
          feedbackReceived: 'Custom feedback message'
        }
      },
      cardListHeader: true,
      customContainerHeader: {
        scrollHeader: true,
        headerElement: `
        <div style="padding: 10px;background-color: cyan;border-radius: 5px;">
          <h1 style="color: grey;">Custom Header</h1>
        </div>
        `
      }
      launcherButton: {
        disabled: false,
        backgroundColor: '#00ffff',
        openIconSrc: 'https://example.com/icon-open.svg',
        closeIconSrc: 'https://example.com/icon-close.svg'
      }
    }
});

Functionality

  • onRuntimeVariablesRequested: an optional property that can be used on the configuration object to allow your app to resolve runtime variables. If this callback is not implemented, runtime variables will fall back to their default values, as defined in the Atomic Workbench.
  • runtimeVariableResolutionTimeout defaults to 5 seconds (5000 ms) if not provided.

Read more about runtime variables in the Runtime variables section.

CardListRefreshInterval

As of release 0.18.0, the Atomic Web SDK uses WebSockets to keep the card list up-to-date.

If a WebSocket connection cannot be established, or is not permitted, the SDK will revert to polling for new cards, which is the behaviour in SDK versions prior to 0.18.0. Also if the SDK has been configured to use HTTP for its communication protocol, via the setApiProtocol method, polling will be used to update the card list.

When the SDK reverts to polling, it will check for new cards every 15 seconds by default. You can customise how frequently this happens by specifying a value for the cardListRefreshInterval configuration option:

AtomicSDK.launch({
    ...
    cardListRefreshInterval: 3000
});

Custom strings

You can customize the following strings used by the Web SDK, using the customStrings configuration object:

  • The title displayed at the top of the card list (cardListTitle);
  • The message displayed when the user has never received any cards before (awaitingFirstCard);
  • The message displayed when the user has seen at least one card in the container before, but has no cards to complete (allCardsCompleted);
  • The title to display for the card snooze functionality in the card overflow menu, and at the top of the card snooze screen (cardSnoozeTitle).
  • The text displayed next to the option to indicate that a card was useful (votingUsefulTitle);
  • The text displayed next to the option to indicate that a card was not useful (votingNotUsefulTitle);
  • The title displayed at the top of the screen presented when a user indicates that a card was not useful (votingFeedbackTitle).
  • The error message shown when the user does not have an internet connection (noInternetConnectionMessage).
  • The error message shown when the theme or card list cannot be loaded due to an API error (dataLoadFailedMessage).
  • The title of the button allowing the user to retry the failed request for the card list or theme (tryAgainTitle).

If you don't provide these custom strings, the SDK defaults will be used:

  • cardListTitle: "Cards"
  • awaitingFirstCard: "Cards will appear here when there's something to action."
  • allCardsCompleted: "All cards completed"
  • cardSnoozeTitle: "Remind me"
  • votingUsefulTitle: "This is useful"
  • votingNotUsefulTitle: "This isn't useful"
  • votingFeedbackTitle: "Send feedback"
  • noInternetConnectionMessage: "No internet connection"
  • dataLoadFailedMessage: "Couldn't load data"
  • tryAgainTitle: "Try again"

The code snippet below shows how to customize some of these strings.

AtomicSDK.launch({
    ...
    customStrings: {
        cardListTitle: 'Things to do',
        awaitingFirstCard: 'Cards will appear here soon',
        allCardsCompleted: 'All cards completed',
        cardSnoozeTitle: 'Snooze',
        votingUsefulTitle: 'Positive feedback',
        votingNotUsefulTitle: 'Negative feedback',
        votingFeedbackTitle: 'Tell us more'
    }
});

Displaying a custom header

The Web SDK supports displaying a custom header above your card feed for stream containers created using the launch or embed methods. It has no effect for singleCard stream containers.

The custom header is supplied as an HTML string to the customContainerHeader property of the customized UI elements. Styles should be applied inline to the HTML elements. Do not attempt to reference classes or other styling from your host application stylesheets because these will not be applied.

Resizing standalone embeds to fit content

You can optionally choose to have standalone embeds resize to fit all of their content, so that they do not scroll. This allows you to embed a stream container inside of another scrolling container of your choice. This feature is enabled by setting the 3rd parameter of the AtomicSDK.embed method to true (by default, this value is false):

AtomicSDK.embed(document.querySelector('#embed'), {
    ...
    onSizeChanged: (width, height) => {
        console.log('Standalone embed changed size to', width, height)
    }
}, true);

When enabled, the height of the iframe will be automatically updated to reflect its content when it changes. The onSizeChanged callback will also be triggered when the height changes, allowing you to adjust your UI as necessary.

Card minimum height

You can enforce a minimum height for the cards displayed in your stream container, if you'd prefer them to be large enough to display the card overflow menu without scrolling:

AtomicSDK.launch({
    ...
    features: {
        ...
        cardMinimumHeight: 250 // Replace 250 with your desired minimum height
    }
});

The minimum height is specified in pixels.

Single card container toast messages

(introduced in 23.3.0)

Toast messages will now be displayed for the single card stream container. The toast messages are enabled by default, as they are for the other stream container variants. The single card toast message can be configured (or disabled) in the same way as they can for the other stream container variants, see the style and presentation section of the Web SDK for details on how to do this.

The default position of single card toast notifications is in the centre at the bottom of the viewport and with a maximum width of 500px. The SDK exposes a class (toast-container) on the iframe containing the toast messages which can be used to apply your own styling should you wish to do so. See the CSS code snippet below for an example of how to reposition single card toasts to the bottom right of the viewport and with a smaller width, if your embed element id was host-embed-element.

#host-embed-element iframe.toast-container {
  max-width: 300px;
  right: 0;
  left: initial;
  transform: initial;
}

Reposition launcher or standalone (vertical & horizontal) stream container toast messages

(introduced in 23.4.2)

You have the ability customize the positioning of toast messages displayed by the standalone or launcher stream container variants if you wish. To do so set the customToastContainer option to true style and presentation

Once you have done so the toast position will default to the centre at the bottom of the viewport and with a maximum width of 500px, the same as for single card toasts. In the same manner as for single card toasts you can use the toast-container class to reposition the iframe containing the toast messages.

Displaying a launcher

The Web SDK supports an additional implementation option - the launcher. This is implemented as a stream container that automatically resizes itself to accommodate its content, without growing beyond the bounds of the browser window. A trigger button is provided which allows you to open and close the stream container. This trigger button is positioned in the bottom right of your page by default. It can be re-positioned by using the .atomic-sdk-launcher-wrapper selector in the host app CSS. The visual appearance of the trigger button can be controlled using a combination of the .atomic-sdk-launcher-wrapper and .atomic-sdk-launcher selectors.

In addition, it is possible to control the size and position of the launcher container itself via the iframe.atomic-sdk-frame.launcher selector in the host app CSS.

The launcher is not supported in any of the other SDKs.

Embed with a launcher button

The code sample below shows how to use the AtomicSDK.launch(config) method, to create an instance of a stream container that is toggled by clicking the provided launcher button on screen.

<html>
  ...
  <body>
    <!-- Installation -->
    <script src="https://downloads.atomic.io/web-sdk/release/24.1.0/sdk.js"></script>

    <script>
      AtomicSDK.initialise('<apiHost>', '<apiKey>', '<environmentId>')
      AtomicSDK.setSessionDelegate(() => {
        return Promise.resolve('<authToken>')
      })

      AtomicSDK.launch({
        streamContainerId: '1234',
        onCardCountChanged: count => {
          console.log('Card count is now', count)
        },
        customStrings: {
          cardListTitle: 'Things to do'
        }
      })
    </script>
  </body>
</html>

Responding to the launcher opening or closing

When creating a stream container in the launcher mode you can supply an optional callback that will be invoked whenever the stream container is opened or closed, this only applies to the launcher container type. To use this callback set it on the onLauncherToggled property of the configuration object supplied to the AtomicSDK.launch(config) method. The function you set there will be called with one argument; a boolean representing whether the launcher has just been opened (true) or closed (false). The code sample below shows how to set this callback.

      AtomicSDK.launch({
        ...
        onLauncherToggled: isOpen => {
          if (isOpen) {
            console.log('the launcher is has been opened')
          } else {
            console.log('the launcher has been closed')
          }
        }
      })

Opening and closing the launcher externally

If you choose to embed an Atomic stream container in the launcher mode (using AtomicSDK.launch), you can open or close the stream container from another trigger, such as a button or link, instead of using the launcher button in the bottom right of the screen. If required you can disable the built-in launcher button using the enabledUiElements property of the customized UI elements.

Read the manually controlling a launcher stream container section for more details.

Displaying a single card

Use AtomicSDK.singleCard(element, config) to create an instance of a stream container that displays a single card, without any surrounding UI. The card is embedded inside of the specified element. Any subviews open inside a separate frame.

When displaying a single card (using the AtomicSDK.singleCard method), the top most card in the given stream container is shown. This is the card with the highest priority that was sent most recently. The iframe that renders the single card automatically adjusts to the height of the card - this is set directly on the iframe's style property. When the card is actioned, dismissed or snoozed, and there are no other cards in the stream container, the card is removed, and the single card view collapses to a height of 0.

When a new card arrives, the single card view will resize to fit that card.

You can respond to changes in the height of the single card view using:

  1. CSS classes on the single card view. If the single card view is displaying a card, it has a class of has-card. The frame itself always has a class of single-card.
  2. Setting the onSizeChanged callback, on the configuration object that is passed to the stream container when calling AtomicSDK.singleCard. This callback is triggered when the size of the single card view changes, and you can use this to perform additional actions such as animating the card in or out, or removing it from the page.
AtomicSDK.singleCard(document.querySelector('#embed'), {
  onSizeChanged: (width, height) => {
    console.log(`The single card view now has a height of ${height}.`)
  }
})

When displaying a single card view, all card subviews, full image/video views, and the snooze selection screen all display inside a modal iframe alongside the card. You can position this modal wherever you like on your page. It can be targeted using the class modal-subview, and when the modal iframe is displaying a subview, it has a class of has-subview.

The iframe generated by the singleCard method can be styled just like any other DOM element with CSS.

<html>
  ...
  <body>
    <!--Installation-->
    <script src="https://downloads.atomic.io/web-sdk/release/24.1.0/sdk.js"></script>

    <script>
      AtomicSDK.initialise('<apiHost>', '<apiKey>', '<environmentId>')
      AtomicSDK.setSessionDelegate(() => {
        return Promise.resolve('<authToken>')
      })

      AtomicSDK.singleCard(document.querySelector('#embed'), {
        streamContainerId: '1234',
        onCardCountChanged: count => {
          console.log('Card count is now', count)
        },
        customStrings: {
          cardListTitle: 'Things to do'
        }
      })
    </script>
  </body>
</html>

Displaying a vertical stream container

This code sample shows how to use the AtomicSDK.embed(element, config, autosize) method to create an instance of a stream container, embedded as an iframe inside of the specified element.

The iframe generated by the embed method can be styled just like any other DOM element with CSS.

<html>
  ...
  <body>
    <!--Installation-->
    <script src="https://downloads.atomic.io/web-sdk/release/24.1.0/sdk.js"></script>

    <script>
      AtomicSDK.initialise('<apiHost>', '<apiKey>', '<environmentId>')
      AtomicSDK.setSessionDelegate(() => {
        return Promise.resolve('<authToken>')
      })

      AtomicSDK.embed(document.querySelector('#embed'), {
        streamContainerId: '1234',
        onCardCountChanged: count => {
          console.log('Card count is now', count)
        },
        customStrings: {
          cardListTitle: 'Things to do'
        }
      })
    </script>
  </body>
</html>

Displaying a horizontal stream container

The Web SDK also supports displaying stream containers created with embed as a horizontally orientated stream of cards. In this horizontal view the cards are rendered from left to right.

When creating a stream container with the embed method, pass a configuration object which contains a HorizontalContainerConfig object within the features property:

AtomicSDK.embed({
  streamContainerId: "1234",
  ...
  features: {
    horizontalContainerConfig: {
      enabled: true,
      cardWidth: 400,
      emptyStyle: "standard",
      headerAlignment: "center",
      scrollMode: "snap",
      lastCardAlignment: "left"
    }
  }
})

The iframe generated by the embed methods can be styled just like any other DOM element with CSS.

If a stream container is specified to be horizontal (by setting enabled to true on the HorizontalContainerConfig object), you must also supply a cardWidth property. The SDK will throw an exception for your stream container without this.

Configuration object

This object allows you to configure the horizontal stream container via the following properties:

  • enabled: A boolean flag that instructs the SDK to display this stream container in horizontal layout.
  • cardWidth: The width of each card in the stream container. All cards in the container will have this same width and it must be assigned explicitly.
  • emptyStyle: The style of the empty state (when there are no cards) of the container. Possible values are:
    • standard: Default value. The stream container displays a no-card user interface.
    • shrink: The stream container shrinks out of view.
  • headerAlignment: The alignment of the card list title in the horizontal stream container header. Possible values are:
    • center: Default value. The title is aligned in the middle of the header.
    • left: The title is aligned to the left of the header.
  • scrollMode: The scrolling behaviour of the stream container. Possible values are:
    • snap: Default value. The stream container snaps between cards when scrolling.
    • free: The container scrolls freely.
  • lastCardAlignment: The alignment of the card when there is only one present in the stream container. Possible values are:
    • left: Default value. The last card is aligned to the left of the container.
    • center: The last card is aligned in the middle of the container.

API-driven card containers

(introduced in 23.4.0)

The SDK provides the ability to create an "API-driven" card container that can be used for observing a stream container without rendering any UI. This is done using the SDK method AtomicSDK.observableStreamContainer which accepts a configuration object that has a subset of the properties accepted by the other stream container variants:

  • streamContainerId: a string representing the id of the stream container you want to observe.
  • cardFeedHandler: a callback function that will be invoked with a cards parameter when the card feed is updated, this parameter is an array of cards.
  • cardListRefreshInterval: an optional number value representing the interval in milliseconds between HTTP polls of the card feed when the SDK is operating with the HTTP communication protocol, defaults to 15 seconds if not provided.
  • onRuntimeVariablesRequested: an optional function that the SDK will use to resolve runtime variables, read more about these in the runtime variables section.
  • runtimeVariableResolutionTimeout: an optional number value representing the time in milliseconds the SDK will wait for your app to resolve runtime variables, defaults to 5 seconds if not provided.
  • onCardCountChanged: an optional callback function that will be invoked when the card count changes in the container, read more in the onCardCountChanged callback section.
  • features: an optional object that accepts one property runtimeVariableAnalytics which is a boolean value indicating whether runtime variable analytics are enabled for this container.

When you initialize one of these stream containers you are returned an instance of AACHeadlessStreamContainer. Calling the start method on this instance will start observing changes in the card feed, using either WebSockets or HTTP polling depending on how you have configured the SDK network protocol using AtomicSDK.setApiProtocol. Updates to the card feed will be passed to the callback function provided as the cardFeedHandler.

To stop observing card feed updates call the stop method on the instance. Observation will also stop when you call the AtomicSDK.logout method.

The following code snippet illustrates how to initialise one of these API-driven containers:

const observableContainer = AtomicSDK.observableStreamContainer({
  streamContainerId: '1234',
  cardFeedHandler: cards => {
    console.log('handling card update', cards)
  }
})

// start observing card feed changes
observableContainer.start()

// stop observing card feed changes
observableContainer.stop()

Examples

Accessing card metadata

Card metadata encompasses data that, while not part of the card's content, are still critical pieces of information. Key metadata elements include:

  • Card instance ID: This is the unique identifier assigned to a card upon its publication.
  • Card priority: Defined in the Workbench, this determines the card's position within the feed. The priority will be an integer between 1 & 10, a priority of 1 indicates the highest priority, placing the card at the top of the feed.
  • Action flags: Also defined in the Workbench, these flags dictate the visibility of options such as dismissing, snoozing, and voting menus for the card.

The following code snippet illustrates how to access these card metadata values for a card instance:

const onCardsChanged = (cards) => {
  cards.forEach(card => {
    console.log('Card instance id is: ', card.instance.id)
    console.log('Card priority is: ', card.metadata.priority)
    console.log('Card actions are: ', card.actions)
  })
}

const observableContainer = AtomicSDK.observeStreamContainer({
  ...
  cardFeedHandler: onCardsChanged
})

Traversing card elements

A card consists of Elements which are defined in the Workbench in the TOP CARD section of a card template. The elements intended for the top level of your card are accessible via the defaultView property on a card, this is a CardLayout which contains a list of the elements in its nodes property.

note: If you are using TypeScript in your application the card types are distributed with the SDK and should assist with discovery of the available properties on a CardInstance.

The code snippet below illustrates how you would traverse the cards received and access the layout nodes for each card, viewing content from some common card elements:

const onCardsChanged = (cards) => {
  cards.forEach(card => {
    card.defaultView.nodes.forEach(node => {
        // some common card elements
        node.type === 'cardDescription' && console.log('Card category is: ', node.attributes.text)
        node.type ===  'headline' && console.log('Card headline is: ', node.attributes.text)
        node.type ===  'text' && console.log('Card text block is: ', node.attributes.text)
        node.type ===  'list' && console.log('First card list item is: ', node.children[0].attributes.text)
    })
  })
}

const observableContainer = AtomicSDK.observeStreamContainer({
  ...
  cardFeedHandler: onCardsChanged
})

Accessing subviews

A card can have additional layouts known as "subviews", these are defined in the Workbench in the SUBVIEWS section of a card template. Each subview has a unique ID used to identify it, see the link to subview section for information on how to get this ID.

The code snippet below illustrates how you can access a particular subview layout for a card:

const onCardsChanged = (cards) => {
  const targetSubviewId = 'my-subview-id'
  const firstCard = cards[0]
  const subviewToDisplay = firstCard.subviews[targetSubviewId]
  console.log('Subview title is: ', subviewToDisplay.title)
  console.log('Subview layout nodes are: ', subviewToDisplay.nodes)
}

const observableContainer = AtomicSDK.observeStreamContainer({
  ...
  cardFeedHandler: onCardsChanged
})

API-driven card actions

(introduced in 23.4.0)

The SDK provides the ability to execute card actions through pure SDK API. The currently supported actions are: dismiss, submit, and snooze. To execute these card actions, call the AtomicSDK.onCardAction method with the target stream container and card instance ID then call the appropriate card action method from the object that is returned:

Dismissing a card

Call the dismiss method with onActionSuccess and onActionFailed parameters, these are functions to be invoked on success or failure of the dismiss action. The code snippet below illustrates how you would do this:

const successHandler = () => {
  console.log('successfully dismissed card')
}
const failureHandler = error => {
  console.error('failed to dismiss card', error)
}
AtomicSDK.onCardAction('stream-container-id', 'card-id').dismiss(
  successHandler,
  failureHandler
)

Snoozing a card

Call the snooze method with onActionSuccess and onActionFailed parameters, these are functions to be invoked on success or failure of the dismiss action. Also a third number parameter representing the time in seconds that the card should be snoozed for, this must be a positive number. The code snippet below illustrates how you would do this:

const successHandler = () => {
  console.log('successfully snoozed card')
}
const failureHandler = error => {
  console.error('failed to snooze card', error)
}
const snoozeIntervalSeconds = 60
AtomicSDK.onCardAction('stream-container-id', 'card-id').snooze(
  successHandler,
  failureHandler,
  snoozeIntervalSeconds
)

Submitting a card

Call the submit method with onActionSuccess and onActionFailed parameters, these are functions to be invoked on success or failure of the dismiss action. Optionally a third parameter may be supplied for the response object that you wish to submit with the card. This object can only contain values with are strings, numbers or booleans. The code snippet below illustrates how you would do this:

const successHandler = () => {console.log('successfully submitted card')}
const failureHandler = (error) => {console.error('failed to submit card', error)}
const cardResponse = {
  email: 'user@example.com'
  subscribed: true,
  count: 5
}
// submit with a payload
AtomicSDK.onCardAction('stream-container-id', 'card-id').submit(successHandler, failureHandler, cardResponse)

Manually controlling the open state of a stream container

Manually controlling a launcher stream container

If you have a launcher type stream container, you can open or close this container via another trigger, instead of the launcher button supplied by the SDK.

To do this, call the setOpen method on the stream container instance to open or close the stream container:

let instance = AtomicSDK.launch({
    ...
});

instance.setOpen(true);

Manually controlling other stream container variants

If you have a single card, horizontal or vertical stream container that is selectively displayed to the user (such as one that is hidden inside of a notification drawer) you need to inform the SDK when this stream container is "open" and viewable by the user. This is important so that analytics events such as stream-displayed & card-displayed are correctly dispatched. Failing to do so will result in an incorrect count of seen and unread cards, as described in the retrieving the count of cards section of this guide.

Use the controlledContainerOpenState feature flag in the configuration object when initialising your stream container. This ensures that your container will be initialised in the "closed" state. After initialisation of the container, it is then the responsibility of the host app to call the setOpen method on the stream container instance when the stream container is being displayed to or hidden from the user:

const instance = AtomicSDK.embed({
  streamContainerId: "1234",
  ...
  features: {
    controlledContainerOpenState: true
  }
});

// when the host app has displayed the container to the user call
instance.setOpen(true);

// when the host app is hiding the container from the user call
instance.setOpen(false);

Note: The controlledContainerOpenState feature flag is not required for the launcher stream container and has no effect on it.

Closing a stream container

To stop a stream container, and remove it from your web page, call the stop method on the previously created instance:

let instance = AtomicSDK.embed(document.querySelector('#embed'), {
    ...
})

instance.stop()

Customizing the first time loading experience

When a stream container with a given ID is launched for the first time on a user's device, the SDK loads the theme and caches it in the browser for future use. On subsequent launches of the same stream container, the cached theme is used and the theme is updated in the background, for the next launch. Note that this first time loading screen is not presented in single card view - if a single card view fails to load, it collapses to a height of 0.

The SDK supports some basic properties to style the first time load screen, which displays a loading spinner in the center of the container. If the theme fails to load for the first time, an error message is displayed with a 'Try again' button. One of two default error messages are possible - 'Couldn't load data' or 'No internet connection'. See the custom strings section of this guide if you want to change the default wording.

First time loading screen colors are customized using the following SDK configuration properties:

  • backgroundColor: the background of the first time loading screen. Defaults to #FFFFFF.
  • textColor: the color to use for the error message shown when the theme fails to load. Defaults to rgba(0,0,0,0.5).
  • loadingSpinnerColor: the color to use for the loading spinner on the first time loading screen. Defaults to #000000.
  • buttonTextColor: the color to use for the 'Try again' button, shown when the theme fails to load. Defaults to #000000.
AtomicSDK.launch({
    ...
    firstLoadStyles: {
        backgroundColor: '#FFFFFF',
        textColor: '#000000',
        loadingSpinnerColor: '#000000',
        buttonTextColor: '#000000'
    }
});

Dark mode

Stream containers in the Atomic Web SDK support dark mode. You can configure an optional dark theme for your stream container in the Atomic Workbench.

The interface style (interfaceStyle) property determines which theme is rendered:

  • automatic: If the user's device is currently set to light mode, the stream container will use the light (default) theme. If the user's device is currently set to dark mode, the stream container will use the dark theme (or fallback to the light theme if this has not been configured). If the stream container does not have a dark theme configured, the light theme will always be used.
  • light: The stream container will always render in light mode, regardless of the device setting.
  • dark: The stream container will always render in dark mode, regardless of the device setting.

To change the interface style, set the corresponding value for the interfaceStyle property on the configuration object when creating the stream container.

Filtering cards

Stream containers (vertical or horizontal) and single card containers can have one or more filters applied. These filters determine which cards are displayed.

When you have created a stream container, the stream container instance that is returned has a streamFilters property. This can be used to set filters to be applied to that stream container. Each stream filter consists of both a filter value and an operator. To set a stream filter you need to call the desired filter value function from the streamFilters object, and chain off from that the desired filter operator. After setting the stream filters call the apply function:

const instance = AtomicSDK.launch({
  ...
})

// this will set a card priority stream filter with the greaterThan operator
instance.streamFilters.addCardPriorityFilter().greaterThan(3)
instance.streamFilters.apply()

Multiple stream filters can be applied, the snippet below shows how you would set filters to only show cards with a card priority greater than 5 & created after 15th February 2020, for a launcher type container. The apply function needs to be called just once and must be called after you have set all the filters you wish to apply:

const instance = AtomicSDK.launch({
  ...
})

instance.streamFilters.addCardPriorityFilter().greaterThan(5)
instance.streamFilters.addCardCreatedFilter().greaterThan('2020-02-15T00:00:00.000Z')
instance.streamFilters.apply()

Filter values

The filter value is used to filter cards in a stream container. The table below summarises the different card attributes that can be filtered on, as well as the permitted data type for that filter and the filter operators that can be applied to it.

Card attributeDescriptionFilter functionValue typePermitted operators
PriorityCard priority defined in Workbench, Card -> DeliverystreamFilters.addCardPriorityFilter()number between 1 & 10 inclusiveequalsnotEqualTogreaterThangreaterThanOrEqualTolessThanlessThanOrEqualToinnotInbetween
Card template IDThe template ID of a card, see below for how to get itstreamFilters.addCardTemplateIdFilter()stringequalsnotEqualToinnotIn
Card template nameThe template name of a cardstreamFilters.addCardTemplateNameFilter()stringequalsnotEqualToinnotIn
Card template created dateThe date time when a card template is createdstreamFilters.addCardCreatedFilter()ISO date stringequalsnotEqualTogreaterThangreaterThanOrEqualTolessThanlessThanOrEqualTo
Custom variableThe default value for variables defined for a card in Workbench, Card -> VariablesstreamFilters.addVariableFilter()multipleequalsnotEqualTogreaterThangreaterThanOrEqualTolessThanlessThanOrEqualToinnotInbetween
Payload variableThe value for variables as defined in API event payloadstreamFilters.addPayloadVariableFilter()multipleequalsnotEqualTogreaterThangreaterThanOrEqualTolessThanlessThanOrEqualToinnotInbetween
Payload metadataThe value for metadata as defined in API event payloadstreamFilters.addPayloadMetadataFilter()multipleequalsnotEqualTogreaterThangreaterThanOrEqualTolessThanlessThanOrEqualToinnotInbetween

Note: It's important to specify the right value type when referencing custom variables for filter value. There are five types of variables in the Workbench, currently four are supported: String, Number, Date and Boolean.

Filter operators

The filter operator is the operational logic applied to a filter. The table below summarises the available operators as well as the value types each will accept. The available value types are further narrowed depending on which filter value you are filtering on.

OperatorDescriptionSupported value types
equalsEqual to the filter valuenumber string iso date string boolean null
notEqualToNot equal to the filter valuenumber string iso date string boolean null
greaterThanGreater than the filter valueiso date string number
greaterThanOrEqualToGreater than or equal to the filter valueiso date string number
lessThanLess than the filter valueiso date string number
lessThanOrEqualToLess than or equal to the filter valueiso date string number
inIn the set of filter values suppliednumber[] string[]
notInNot in the set of filter values suppliednumber[] string[]
betweenIn the range bound by the two values supplied. Will only accept an array containing two numbers e.g. 2, 8 will match values between 2 and 8 inclusive.number[]

Passing correct value type to an operator:

Each operator supports different value types. For example, the operator lessThan only supports an iso date string or a number. So passing any other value types will raise an exception.

Removing filters

You have the ability to clear filters on a stream container if required. To clear the filters you should call the clearFilters function on the on the streamFilters property for the relevant stream container instance. For example:

const instance = AtomicSDK.launch({
  ...
})

// applying filters to your stream container instance
instance.streamFilters.addCardPriorityFilter().greaterThan(5)
instance.streamFilters.addCardCreatedFilter().greaterThan('2020-02-15T00:00:00.000Z')
instance.streamFilters.apply()

// at some later stage in order to clear the filters you should trigger
instance.streamFilters.clearFilters()

Image linking

(introduced in 24.1.0) This is a beta feature in the Atomic Workbench

Image elements can be used to trigger a navigation action. In the Atomic Workbench you can configure the behavior of the link to trigger a subview navigation, open a URL or to send a payload to your app. For information on how to handle the image link payload see custom action payloads on image links

Custom action payloads

Supporting custom action payloads on link & submit buttons

In the Atomic Workbench, you can create a link button or submit button with a custom action payload. When such a button is tapped, the appropriate callback, onLinkButtonPressed or onSubmitButtonPressed is triggered, allowing you to perform an action in your web app based on that payload.

The callback is passed an object, containing the payload that was defined in the Workbench for that button, as well as the stream container ID and card instance ID that triggered the button.

AtomicSDK.launch({
    ...
    streamContainerId: "1234",
    onLinkButtonPressed: (data) => {
        if(data.streamContainerId === "1234" &&
           data.cardInstanceId === "abcd-1234" &&
           data.actionPayload.screen === 'home') {
            navigateToHomeScreen()
        }
    },
    onSubmitButtonPressed: (data) => {
        if(data.streamContainerId === "1234" &&
           data.cardInstanceId === "abcd-1234" &&
           data.actionPayload.screen === 'home') {
            navigateToHomeScreen()
        }
    }
});

Supporting custom action payloads on image links

Similar to action payloads on buttons you can also create an image link with a custom action payload. When such an image is tapped, the onLinkButtonPressed callback is triggered and is passed an object with the same properties as for a button with a custom action payload.

Customizing toast messages for card events

You can customize any of the toast messages used when dismissing, completing, snoozing and placing feedback on a card. This is configurable for each stream container. You simply supply a string for each custom message. If you do not supply a string, the defaults will be used. See the custom strings section of this guide if you want to change the default wording.

Read the Style and presentation section to understand how to do this using the toastConfig configuration object. That section also has a code example.

Card snoozing

The Atomic SDKs provide the ability to snooze a card from a stream container or single card view. Snooze functionality is exposed through the card’s action buttons, overflow menu and the quick actions menu (exposed by swiping a card to the left, on iOS and Android).

Selecting snooze option from either location brings up the snooze date and time selection screen. The user selects a date and time in the future until which the card will be snoozed. Snoozing a card will result in the card disappearing from the user’s card list or single card view, and reappearing again at the selected date and time. A user can snooze a card more than once.

See the custom strings section of this guide if you want to change the default wording.

Card voting

The Atomic SDKs support card voting, which allows you to gauge user sentiment towards the cards you send. When integrating the SDKs, you can choose to enable options for customers to indicate whether a card was useful to the user or not, accessible when they tap on the overflow button in the top right of a card.

If the user indicates that the card was useful, a corresponding analytics event is sent for that card (card-voted-up).

If they indicate that the card was not useful, they are presented with a secondary screen where they can choose to provide further feedback. The available reasons for why a card wasn’t useful are:

  • It’s not relevant;
  • I see this too often;
  • Something else.

If they select "Something else", a free-form input is presented, where the user can provide additional feedback. The free form input is limited to 280 characters. After tapping "Submit", an analytics event containing this feedback is sent (card-voted-down).

See the custom strings section of this guide if you want to change the default wording.

Card voting is disabled by default. You can enable positive card voting ("This is useful"), negative card voting ("This isn’t useful"), or both:

AtomicSDK.launch({
    ...
    features: {
        cardVoting: {
            canVoteUseful: true, // Whether the user can vote that a card is useful.
            canVoteNotUseful: true // Whether the user can vote that a card is not useful.
        }
    }
})

Responding to card events

The SDK allows you to perform custom actions in response to events occurring on a card, such as when a user:

  • submits (or fails to submit) a card;
  • dismisses (or fails to dismiss) a card;
  • snoozes (or fails to snooze) a card;
  • indicates a card is useful (when card voting is enabled);
  • indicates a card is not useful (when card voting is enabled).

To be notified when these happen, assign an onCardEvent callback when creating your stream container:

AtomicSDK.launch({
    ...
    // Callback notified when card events occur.
    onCardEvent: (event) => {
        console.log(`Card event occurred: ${event.type}`)
    }
    ...
});

The identifier for the event is available in the type property, and will be one of the following:

  • submitted
  • submit-failed
  • dismissed
  • dismiss-failed
  • snoozed
  • snooze-failed
  • voted-useful
  • voted-not-useful

Sending custom events

A custom event can be used in the Workbench to create segments for card targeting. For more details of custom events, see Custom Events.

You can send custom events directly to the Atomic Platform for the logged in user, via the sendCustomEvent method, passing it an object with an eventName and optionally properties where you can add additional data for your event.

The event will be created for the user defined by the authentication token returned in the session delegate. As such, you cannot specify target user IDs using this method.

AtomicSDK.sendCustomEvent({
  eventName: 'myCustomEvent',
  properties: {
    action: 'updated-profile'
  }
}).catch(error => {
  // An error is thrown if something prevents the custom event from being sent to the Platform
})

SDK Event Observer

(introduced in 23.3.0)

The SDK provides the ability to observe actions within the SDK via the SDK event observer, this observer is a callback that you set via the observeSDKEvents SDK method. The callback will be invoked with an event object that conforms to a particular event type.

The code snippet below shows how to set the event observer callback:

AtomicSDK.observeSDKEvents(event => {
  console.log('sdk event observed: ', event)
})

The actions that will trigger this callback include card & stream actions, the table below contains the full list of actions that the event observer may be called with and their corresponding event type.

Event nameEvent typeDescription
card-completedSDKCardCompletedEventThe user has completed a card
card-dismissedSDKCardDismissedEventThe user has dismissed a card
card-snoozedSDKCardSnoozedEventThe user has snoozed a card
card-feed-updatedSDKFeedEventA stream container has had its card feed updated
card-displayedSDKCardDisplayedEventA card has been displayed to the user
card-voted-upSDKCardVotedUpEventThe user provided positive feedback on a card
card-voted-downSDKCardVotedDownEventThe user provided negative feedback on a card
runtime-vars-updatedSDKRuntimeVarsUpdatedEventOne or more runtime variables have been resolved
stream-displayedSDKStreamDisplayedEventA stream container has been displayed to the user
user-redirectedSDKRedirectedEventThe user is redirected by a URL or a custom payload
snooze-options-displayedSDKSnoozeOptionsDisplayedEventThe snooze date/time selector has been displayed
snooze-options-canceledSDKSnoozeOptionsCanceledEventThe user has exited the snooze date/time selector
card-subview-displayedSDKSubviewDisplayedEventA card subview has been opened
card-subview-exitedSDKSubviewExitedEventA card subview has been exited
video-playedSDKVideoPlayedEventThe user has started playback of a video
video-completedSDKVideoCompletedEventThe user has watched a video to completion
sdk-initializedSDKInitEventThe SDK has been initialized and supplied with a valid auth token
request-failedSDKRequestFailedEventA request to the Atomic client API has failed or a WebSocket failure has caused a fallback to HTTP polling
notification-receivedSDKNotificationReceivedEventA push notification has been received

Accessing properties for a particular event

If using TypeScript the event types are distributed with the SDK and you will get event property suggestions via your IDE. If your project is written in JavaScript refer to this resource for examples showing the shape of event objects.

AtomicSDK.observeSDKEvents(event => {
  if (event.eventName === SDKEventName.cardFeedUpdated) {
    // properties for that event will be suggested via your IDE
    console.log('card count', atomicEvent.properties.cardCount)
  }
})

:::info There are some additional properties on the event objects not specified in the types or the provided examples. These properties are provided for debugging purposes and are subject to change so should not be relied upon in production code. :::

Stopping event observation

To stop observing events call the observeSDKEvents SDK method passing in a null value for the callback:

AtomicSDK.observeSDKEvents(null)

Event observer use cases

Trigger a user metrics request on SDK event

The SDK event observer can be used to determine when it is appropriate to update the user metrics for a logged in user. To assist with this the SDK provides you with a set, AtomicSDK.userMetricsTriggerEvents, containing the event names that indicate the user metrics could have changed and should be refreshed.

The code snippet below illustrates how to use this set, in combination with the event observer, to keep card count values in your application up to date:

AtomicSDK.observeSDKEvents(event => {
  if (AtomicSDK.userMetricsTriggerEvents.has(event.eventName)) {
    // observed SDK event is one that indicates user metrics should be refreshed
    AtomicSDK.requestUserMetrics().then(metrics => {
      // use the returned user metrics response to update card counts in your application
      console.log('user metrics updated', metrics)
    })
  }
})

Push notifications

Web push notifications are currently not supported in the Web SDK. It is possible to set up notifications similarly to our native iOS and Android SDKs by integrating the Web SDK inside a native mobile application (e.g. Cordova or Capacitor/Ionic).

Cordova / Capacitor

The Web SDK can support push notifications when the SDK is embedded within a web view on a native iOS or Android app. For example, if the SDK is embedded in a Cordova or Capacitor app.

In order to integrate support for push notifications, you will need to use either native code, or a plugin to expose the native callbacks and device information for push notifications.

info:

If using Cordova, one possible plugin is cordova-plugin-push(ht

23.3.5

1 month ago

23.4.3

1 month ago

1.6.4

1 month ago

24.1.0

1 month ago

24.1.0-beta2

2 months ago

23.4.2

3 months ago

24.1.0-beta1

3 months ago

23.4.1

3 months ago

23.3.4

3 months ago

1.6.3

3 months ago

23.4.0

5 months ago

23.3.3

5 months ago

1.6.2

5 months ago

23.4.0-beta1

6 months ago

23.3.2

7 months ago

23.3.1

7 months ago

23.3.0

7 months ago

1.6.1

9 months ago

23.3.0-beta2

9 months ago

23.3.0-beta1

10 months ago

1.5.2

12 months ago

1.6.0

12 months ago

1.5.1

1 year ago

1.5.0

1 year ago

1.4.1

1 year ago

1.4.0

1 year ago

1.3.4

1 year ago

1.3.3

1 year ago

1.3.2

1 year ago

1.3.1

1 year ago

1.3.0

2 years ago

1.2.0

2 years ago

1.1.0

2 years ago

1.0.0

2 years ago

0.19.1-beta.1

2 years ago

0.19.1

2 years ago

0.19.0-beta.3

2 years ago

0.19.0-beta.2

2 years ago

0.19.0-beta.1

2 years ago

0.0.5

5 years ago

0.0.3

5 years ago

0.0.1

5 years ago