@atomic.io/action-cards-web-sdk v24.2.1
Web SDK - Current (24.2.1)
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.2.1.
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.2.1
, and is hosted on our CDN at https://downloads.atomic.io/web-sdk/release/24.2.1/sdk.js
.
As of version 24.2.1
the Web SDK also offers a bundle variant which does not include the font used for icons in action cards. Instead this font is fetched via CDN as required, allowing the size of your initial bundle loaded by the browser to be smaller. Both variations function identically in all other respects.
This variant is hosted on our CDN at https://downloads.atomic.io/web-sdk/release/24.2.1/sdk-cdn-icons.js
.
To integrate it, add the script for your chosen variant as a source to your web page:
<html>
...
<body>
<script src="https://downloads.atomic.io/web-sdk/release/24.2.1/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.
Directive | Required Resources |
---|---|
frame-src | blob: |
connect-src | https://*.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 Atomic SDK allows you to configure the time interval to determine whether the JSON Web Token (JWT) has expired. If the interval between the current time and the token's exp
field is smaller than that interval, the token is considered to be expired. To set the token expiry interval call the setTokenExpiryInterval
method, passing it a number greater than 0, representing the time in seconds for the expiry interval. If this method is not called, the default value is 60 seconds.
// sets the token expiry interval to 180 seconds
AtomicSDK.setTokenExpiryInterval(180)
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 hostapiKey
: a string value representing your API keyenvironmentId
: a string value representing your environment idsessionDelegate
: a function that resolves to a promise which supplies an authentication token to the SDKretryInterval
: (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
orAtomicSDK.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 thestop
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 totrue
. Set tofalse
to turn off toast messages on the card list.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 totrue
. Set tofalse
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 alaunch
orembed
type stream container.scrollHeader
: an optional boolean to control whether the custom header scrolls with the card feed, defaults totrue
.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 alaunch
type stream container. Accepts the following properties:disabled
: defaults tofalse
. Set totrue
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,
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 {#single-card-toasts}
(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;
}
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.2.1/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:
- 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 ofsingle-card
. - Setting the
onSizeChanged
callback, on the configuration object that is passed to the stream container when callingAtomicSDK.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.2.1/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.2.1/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.
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 torgba(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 attribute | Description | Filter function | Value type | Permitted operators |
---|---|---|---|---|
Priority | Card priority defined in Workbench, Card -> Delivery | streamFilters.addCardPriorityFilter() | number between 1 & 10 inclusive | equals notEqualTo greaterThan greaterThanOrEqualTo lessThan lessThanOrEqualTo in notIn between |
Card template ID | The template ID of a card, see below for how to get it | streamFilters.addCardTemplateIdFilter() | string | equals notEqualTo in notIn |
Card template name | The template name of a card | streamFilters.addCardTemplateNameFilter() | string | equals notEqualTo in notIn |
Card template created date | The date time when a card template is created | streamFilters.addCardCreatedFilter() | ISO date string | equals notEqualTo greaterThan greaterThanOrEqualTo lessThan lessThanOrEqualTo |
Custom variable | The variables defined for a card in Workbench, Card -> Variables | streamFilters.addVariableFilter() | multiple | equals notEqualTo greaterThan greaterThanOrEqualTo lessThan lessThanOrEqualTo in notIn between |
Payload variable | The value for variables as defined in API event payload | streamFilters.addPayloadVariableFilter() | multiple | equals notEqualTo greaterThan greaterThanOrEqualTo lessThan lessThanOrEqualTo in notIn between |
Payload metadata | The value for metadata as defined in API event payload | streamFilters.addPayloadMetadataFilter() | multiple | equals notEqualTo greaterThan greaterThanOrEqualTo lessThan lessThanOrEqualTo in notIn between |
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.
Operator | Description | Supported value types |
---|---|---|
equals | Equal to the filter value | number string iso date string boolean null |
notEqualTo | Not equal to the filter value | number string iso date string boolean null |
greaterThan | Greater than the filter value | iso date string number |
greaterThanOrEqualTo | Greater than or equal to the filter value | iso date string number |
lessThan | Less than the filter value | iso date string number |
lessThanOrEqualTo | Less than or equal to the filter value | iso date string number |
in | In the set of filter values supplied | number[] string[] |
notIn | Not in the set of filter values supplied | number[] string[] |
between | In 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 {#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 name | Event type | Description |
---|---|---|
card-completed | SDKCardCompletedEvent | The user has completed a card |
card-dismissed | SDKCardDismissedEvent | The user has dismissed a card |
card-snoozed | SDKCardSnoozedEvent | The user has snoozed a card |
card-feed-updated | SDKFeedEvent | A stream container has had its card feed updated |
card-displayed | SDKCardDisplayedEvent | A card has been displayed to the user |
card-voted-up | SDKCardVotedUpEvent | The user provided positive feedback on a card |
card-voted-down | SDKCardVotedDownEvent | The user provided negative feedback on a card |
runtime-vars-updated | SDKRuntimeVarsUpdatedEvent | One or more runtime variables have been resolved |
stream-displayed | SDKStreamDisplayedEvent | A stream container has been displayed to the user |
user-redirected | SDKRedirectedEvent | The user is redirected by a URL or a custom payload |
snooze-options-displayed | SDKSnoozeOptionsDisplayedEvent | The snooze date/time selector has been displayed |
snooze-options-canceled | SDKSnoozeOptionsCanceledEvent | The user has exited the snooze date/time selector |
card-subview-displayed | SDKSubviewDisplayedEvent | A card subview has been opened |
card-subview-exited | SDKSubviewExitedEvent | A card subview has been exited |
video-played | SDKVideoPlayedEvent | The user has started playback of a video |
video-completed | SDKVideoCompletedEvent | The user has watched a video to completion |
sdk-initialized | SDKInitEvent | The SDK has been initialized and supplied with a valid auth token |
request-failed | SDKRequestFailedEvent | A request to the Atomic client API has failed or a WebSocket failure has caused a fallback to HTTP polling |
notification-received | SDKNotificationReceivedEvent | A 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.
The SDK events which may be emitted are available on the AtomicSDK.SDKEvents
property, you can use this to check which event you are receiving:
AtomicSDK.observeSDKEvents(event => {
if (event.eventName === AtomicSDK.SDKEvents.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, if using the Capacitor/Ionic framework @capacitor/push-notifications may be used.
First, follow the instructions in the plugin's documentation to integrate it inside your app.
You will need to create a push certificate or token for iOS apps. On Android you need to set up Firebase Cloud Messaging which will generate a server key. These will be required to configure push notifications in the workbench.
Then, in your app you will need to provide the Atomic Web SDK with information about the app and device it is running on.
Finally, the app must register the device for notifications and let Atomic know which stream containers to receive push notifications for.
For a complete example of integrating push notifications in a Cordova application, see our Cordova boilerplate app on GitHub
1. Set the device details for the SDK
You must pass information about the native device to the Atomic SDK before registering for notifications. Using the setNativeDeviceInfo
method which expects a single argument, a DeviceInfo
object with the following keys:
platform
- either'iOS'
or'Android'
.deviceId
- the unique device identifier.appId
- either the application identifier of your device on Android, or the bundle identifier on iOS, it should also exactly match theappId
set when configuring the app for notifications in the workbench.
If you are using Cordova, you may use the cordova-plugin-device to get the device information.
The following code snippets shows how to call this method, using the cordova-plugin-device
plugin to get the device platform and uuid.
AtomicSDK.setNativeDeviceInfo({
platform: device.platform,
deviceId: device.uuid,
appId: 'com.example.yourApp'
})
2. Register the user against specific stream containers for push notifications
You need to signal to the Atomic Platform which stream containers are eligible to receive push notifications in your app for the current device.
AtomicSDK.registerStreamContainersForNotifications([containerId])
You will need to do this each time the logged-in user changes.
This method takes an optional parameter - notificationsEnabled
. This parameter updates the user's notificationsEnabled
preference in the Atomic Platform. You can also inspect and update this preference using the Atomic API documentation for user preferences or using the updateUser method.
If you pass false
for this parameter, the user's notificationsEnabled
preference will be set to false
, which means that they will not receive notifications on any eligible devices, even if their device is registered in this step, and the device push token is passed to Atomic in the next step. If you pass true
, the user's notificationEnabled
preference will be set to true
, which is the default, and allows the user to receive notifications on any eligible device. This allows you to explicitly enable or disable notifications for the current user, via UI in your own app - such as a notification settings screen.
If you call registerStreamContainersForNotifications
, without supplying the notificationsEnabled
parameter, the user's notificationsEnabled
preference in the Atomic Platform is not affected.
AtomicSDK.registerStreamContainersForNotifications([containerId], true)
3. Send the push token to the Atomic Platform
Send the device's push token to the Atomic Platform when it changes.
When using the cordova-plugin-push plugin the device token can be accessed as data.registrationId
on the registration
callback.
Pass this token as a string to the registerDeviceForNotifications
method, for example:
AtomicSDK.registerDeviceForNotifications(deviceToken)
You can call the registerDeviceForNotifications
method any time you want to update the push token stored for the user in the Atomic Platform. We recommend calling it each time the app is launched to ensure the token is always up-to-date.
You will also need to update this token every time the logged-in user changes in your app, so the Atomic Platform knows who to send notifications to.
4. Deregister the device from notifications
To deregister the device for Atomic notifications for your app, such as when a user completely logs out of your app, call deregisterDeviceForNotifications
on AtomicSDK
.
:::caution
Calling AtomicSDK.logout()
will automatically invoke this method.
:::
If the deregistration fails, the promise will be rejected, returning a description of the failure that occurred.
try {
await AtomicSDK.deregisterDeviceForNotifications()
} catch (e) {
// `e` contains the reason for the failure to deregister the device for notifications.
}
5. (Optional) Parse the Atomic data from the push notification
Every push notification from the Atomic platform includes an object with the key atomic
. This object includes:
- information about the card that generated the push notification
- the stream container ID of that card
- (optional) extra detail in a custom object that is included in the notification.
You can check if a push notification originated from the platform and parse the data into a structured object using the AtomicSDK.notificationFromPushPayload
method.
The method will either return a structured AACPushNotification
object if the notification came from the Atomic platform, or null if it came from another source.
The AACPushNotification object has three keys:
cardInstanceId: string
The instance ID of the card that the push notification relates to. Can be used to apply a filter on a stream container.containerId: string
The ID of the stream container that generated the notification.detail: object
A custom object defined asnotificationDetail
and sent as part of the flow that generated the card.
Here is an example of using this method with the cordova-plugin-push plugin:
push.on('notification', data => {
const notificationData = AtomicSDK.notificationFromPushPayload(
data.additionalData
)
console.log(`Notification data from atomic is: ${notificationData}`)
})
6. (Optional) Track when push notifications are received
Due to the limitations of the mobile platforms, tracking when a push notification is received is not straightforward if the app is not open when the notification is received.
On iOS, to track when push notifications are delivered to your user's device you must use a native Notification Service Extension. This requires you to write native code and to use our iOS native SDK - further information on tracking notification receipt is available in the iOS SDK guide.
On Android tracking if the notification is received in the background is not supported by the Atomic SDK, but delivery can be tracked using Firebase.
If you do not wish to build a native notification service extension, or you wish to keep analytics comparable between iOS and Android, you can choose instead to track notification delivery when a user taps on the notification. On both iOS and Android this will automatically open your app.
If you are using the cordova-plugin-push plugin, a user tapping on the notification will trigger the notification
callback.
At this point you can call the trackPushNotificationReceived
method, which will return true if the notification is from the Atomic platform, and false otherwise.
This will send the 'notification-received' analytics event to the platform.
Notifications received while the app is in the foreground will also trigger this callback, but by default they will not display a banner. You may wish to filter out these notifications from tracking, by checking if the additionalData.foreground
attribute is set to true and not calling the trackPushNotification
received method in these cases. This will ensure that the notification-received
analytics events correspond directly to a user tapping on a push notification.
Here is an example of using this method with the cordova-plugin-push plugin:
push.on('notification', data =
1 year ago
11 months ago
11 months ago
1 year ago
1 year ago
1 year ago
11 months ago
1 year ago
11 months ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
6 years ago
6 years ago
6 years ago