@atomic.io/action-cards-web-sdk-cdn-icons
v24.3.0
Published
The Atomic Web SDK
Downloads
1,556
Keywords
Readme
Web SDK - Current (24.3.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.3.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.3.0
, and is hosted on our CDN at https://downloads.atomic.io/web-sdk/release/24.3.0/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.3.0/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.3.0/sdk.js"></script>
</body>
</html>
The SDK can be installed via npm, with the bundled font variant being @atomic.io/action-cards-web-sdk and the variant excluding icon fonts being @atomic.io/action-cards-web-sdk-cdn-icons.
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 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. 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
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: log-out behavior
- 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, with the exception of toastConfig
). 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.customToastContainer
- defaults tofalse
. Set totrue
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 customize 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
&fileUploadFailed
. 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,
customToastContainer: true,
toastConfig: {
timeout: 5000,
toastMessages: {
submittedCard: 'Custom submitted message',
dismissedCard: 'Custom dismissed message',
snoozedCard: 'Custom snoozed message',
feedbackReceived: 'Custom feedback message',
fileUploadFailed: 'Custom file upload failed 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 behavior 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 customize 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
). - The text displayed on the card overlay while a file upload is in progress (
processingStateMessage
). - The title of the button on the card overlay allowing the user to cancel file uploads that are currently in progress (
processingStateCancelButtonTitle
).
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"processingStateMessage
: "Sending, please wait..."processingStateCancelButtonTitle
: "Cancel process"
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',
noInternetConnectionMessage: 'No internet connection available',
dataLoadFailedMessage: 'Failed to load cards',
tryAgainTitle: 'Please try again',
processingStateMessage: 'File uploads in progress',
processingStateCancelButtonTitle: 'Cancel file upload'
}
});
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
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.3.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:
- 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.3.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.3.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 acards
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 propertyruntimeVariableAnalytics
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
Atomic cards now include button names when they are submitted. The name will be added to analytics to enable referencing the triggering button in an Action Flow. Resulting from this change as of version 24.2.0
the submitButtonName
parameter must be supplied when performing an API-driven card submission.
Call the submit
method with onActionSuccess
, onActionFailed
parameters, these are functions to be invoked on success or failure of the dismiss action. Also supply a submitButtonName
parameter which is the button "name" attribute obtained from the card data. Optionally a fourth 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 following code snippet illustrates how to obtain a button name from the top-level of the first card:
const onCardsChanged = (cards) => {
let submitButton
const actionButtons = cards[0]?.defaultView.nodes.find(
node => node.type === 'form'
)
if (actionButtons.children.length > 0) {
submitButton = actionButtons.children.find(
node => node.type === 'submitButton'
)
}
const submitButtonName = submitButton?.attributes?.name
}
const observableContainer = AtomicSDK.observeStreamContainer({
...
cardFeedHandler: onCardsChanged
})
The next code snippet shows how to perform a card submit action:
const successHandler = () => {console.log('successfully submitted card')}
const failureHandler = (error) => {console.error('failed to submit card', error)}
// The name attribute of your submit button as obtained from the above code snippet
const submitButtonName = 'submit-button-123'
const cardResponse = {
email: '[email protected]'
subscribed: true,
count: 5
}
// submit with a payload
AtomicSDK.onCardAction('stream-container-id', 'card-id').submit(successHandler, failureHandler, submitButtonName, 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 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 default value for 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 summarizes 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.
Preventing snoozing beyond card expiry date
Selecting a date & time combination beyond a card's expiry date is prevented when snoozing a card using the SDK's built-in interface.
There are three ways to snooze a card in the Atomic SDK:
- Overflow Menu: Select the overflow menu item (default "Remind me"), then choose a date & time in the built-in selector.
- Snooze Button: Click a snooze button on the card and select a date & time via the built-in selector.
- Pre-set Snooze Button: Click a snooze button with a pre-set snooze period, which snoozes the card immediately without showing the selector.
If an expiry date is set on the card, you cannot select dates beyond this expiry in scenarios 1 and 2. Scenario 3 remains unaffected, as the snooze period is explicitly pre-configured in the Workbench.
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
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