Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions __tests__/api/push/alerts_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,17 @@ describe('PushAlertsAPI', () => {
expect(response.succeeded).toBe(true)
})

it('posts the saved Push identity with a registration', async () => {
await API.pushAlerts.create({ section: 'homepage', kind: 'registered', pushIdentity: 'identity-id' })

expect(JSON.parse(global.fetch.mock.calls[0][1].body)).toEqual({
session: 'session-id',
section: 'homepage',
kind: 'registered',
push_identity: 'identity-id',
})
})

it('uses the latest SDK session for each request', async () => {
await API.pushAlerts.create({ section: 'homepage', kind: 'shown' })
jest.spyOn(Hellotext, 'session', 'get').mockReturnValue('next-session-id')
Expand Down
207 changes: 205 additions & 2 deletions __tests__/controllers/alert_controller_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@ const sections = ['homepage', 'product_collection', 'product_details'].map(kind
secondary_action: `${kind} dismiss`,
}))

const registration = (id = 'push-identity') => ({
succeeded: true,
data: { clone: () => ({ json: async () => ({ id }) }) },
})
const flush = () => new Promise(resolve => setTimeout(resolve, 0))

const alertHTML = (content = sections) => {
const element = document.createElement('article')
element.setAttribute('hidden', '')
Expand Down Expand Up @@ -44,6 +50,15 @@ describe('Smart Alert interactions', () => {
const primary = () => alert.element.querySelector('[data-hellotext--alert-target="primaryAction"]')
const secondary = () => alert.element.querySelector('[data-hellotext--alert-target="secondaryAction"]')
const saved = () => JSON.parse(localStorage.getItem(`hellotext:alert:${business.id}`))
const pending = () => JSON.parse(localStorage.getItem(`hellotext:alert:${business.id}:registration`))
const leavePending = acceptance =>
localStorage.setItem(`hellotext:alert:${business.id}:registration`, JSON.stringify(acceptance))
const reload = async () => {
alert.dispose()
alert = new Alert({ html: alertHTML() }, business, push)
await alert.ready
await flush()
}

beforeEach(async () => {
previousPage = Hellotext.page
Expand All @@ -62,7 +77,7 @@ describe('Smart Alert interactions', () => {
disposed: false,
subscribe: jest.fn().mockImplementation(async () => {
push.subscribed = true
return { succeeded: true }
return registration()
}),
}
application = Application.start()
Expand Down Expand Up @@ -380,7 +395,7 @@ describe('Smart Alert interactions', () => {
expect(saved()).toBeNull()

push.subscribed = true
complete({ succeeded: true })
complete(registration())
await Promise.resolve()
expect(alert.element.hidden).toBe(true)
expect(primary().disabled).toBe(false)
Expand Down Expand Up @@ -440,6 +455,194 @@ describe('Smart Alert interactions', () => {
expect(events.dismissed).not.toHaveBeenCalled()
})

it.each([
['granted', ['shown', 'accepted', 'granted', 'registered']],
['denied', ['shown', 'accepted', 'denied']],
])('records the %s permission answer the browser gives', async (permission, kinds) => {
push.subscribe.mockImplementation(async ({ onPermission }) => {
Notification.permission = permission
onPermission(permission)
if (permission === 'denied') throw new Error('Push permission was not granted')

push.subscribed = true
return registration()
})
await alert.show('product_details')
await alert.controller.subscribe()
await flush()
expect(API.pushAlerts.create.mock.calls.map(([data]) => data.kind)).toEqual(kinds)
expect(API.pushAlerts.create).toHaveBeenCalledWith({ section: 'product_details', kind: permission, page: Hellotext.page.trackingData.page })
})

it('records the permission answer before the registration finishes', async () => {
push.subscribe.mockImplementation(({ onPermission }) => {
onPermission('granted')
return new Promise(() => {})
})
await alert.show('homepage')
alert.controller.subscribe()
expect(API.pushAlerts.create.mock.calls.map(([data]) => data.kind)).toEqual(['shown', 'accepted', 'granted'])
})

it('records the Push identity the server saved with the registration', async () => {
push.subscribe.mockImplementation(async ({ onPermission }) => {
onPermission('granted')
push.subscribed = true
return registration('saved-identity')
})
await alert.show('homepage')
await alert.controller.subscribe()
await flush()
expect(API.pushAlerts.create).toHaveBeenLastCalledWith({
section: 'homepage',
kind: 'registered',
page: Hellotext.page.trackingData.page,
pushIdentity: 'saved-identity',
})
})

it.each(['failed response', 'rejection'])('records no registration after a %s', async failure => {
push.subscribe.mockImplementation(async ({ onPermission }) => {
onPermission('granted')
if (failure === 'rejection') throw new Error('Sync failed')

return { failed: true }
})
await alert.show('homepage')
await alert.controller.subscribe()
await flush()
expect(API.pushAlerts.create.mock.calls.map(([data]) => data.kind)).toEqual(['shown', 'accepted', 'granted'])
})

it('records the permission answer under the acceptance after another section is shown', async () => {
let answer
let complete
push.subscribe.mockImplementation(({ onPermission }) => new Promise(resolve => {
answer = onPermission
complete = resolve
}))
Hellotext.page = new Page('https://shop.example.com/products/shirt')
const page = Hellotext.page.trackingData.page
await alert.show('product_details')
const subscribing = alert.controller.subscribe()

Hellotext.page = new Page('https://shop.example.com/')
await alert.show('homepage')

answer('granted')
push.subscribed = true
complete(registration())
await subscribing
await flush()
expect(API.pushAlerts.create).toHaveBeenCalledWith({ section: 'product_details', kind: 'granted', page })
expect(API.pushAlerts.create).toHaveBeenLastCalledWith({ section: 'product_details', kind: 'registered', page, pushIdentity: 'push-identity' })
})

it('keeps a granted acceptance pending until its registration is saved', async () => {
let complete
push.subscribe.mockImplementation(({ onPermission }) => new Promise(resolve => {
onPermission('granted')
complete = resolve
}))
await alert.show('product_details')
const subscribing = alert.controller.subscribe()
expect(pending()).toEqual({ section: 'product_details', page: Hellotext.page.trackingData.page })

push.subscribed = true
complete(registration())
await subscribing
expect(pending()).toBeNull()
})

it('finishes a pending registration on the next page without a click', async () => {
const page = { url: 'https://shop.example.com/products/shirt', title: 'Shirt', path: '/products/shirt' }
leavePending({ section: 'product_details', page })
Notification.permission = 'granted'

await reload()

expect(push.subscribe).toHaveBeenCalledWith()
expect(API.pushAlerts.create.mock.calls).toEqual([
[{ section: 'product_details', kind: 'registered', page, pushIdentity: 'push-identity' }],
])
expect(pending()).toBeNull()
await expect(alert.show('homepage')).resolves.toBe(false)
})

it('waits for a pending registration before showing', async () => {
let complete
push.subscribe.mockImplementation(() => new Promise(resolve => { complete = resolve }))
leavePending({ section: 'homepage', page: {} })
Notification.permission = 'granted'
await reload()

const showing = alert.show('homepage')
await flush()
expect(alert.element.hidden).toBe(true)

push.subscribed = true
complete(registration())
await expect(showing).resolves.toBe(false)
})

it('drops a pending registration when the visitor unsubscribes', async () => {
leavePending({ section: 'homepage', page: {} })
Hellotext.eventEmitter.dispatch('push:unsubscribed')
expect(pending()).toBeNull()

Notification.permission = 'granted'
await reload()

expect(push.subscribe).not.toHaveBeenCalled()
})

it('does not resume when the visitor unsubscribes while restoration is pending', async () => {
let resolveReady
push.ready = new Promise(resolve => { resolveReady = resolve })
leavePending({ section: 'homepage', page: {} })
Notification.permission = 'granted'
await reload()

Hellotext.eventEmitter.dispatch('push:unsubscribed')
resolveReady()
await flush()

expect(push.subscribe).not.toHaveBeenCalled()
expect(pending()).toBeNull()
})

it.each(['default', 'denied'])('drops a pending registration once permission is %s', async permission => {
leavePending({ section: 'homepage', page: {} })
Notification.permission = permission

await reload()

expect(push.subscribe).not.toHaveBeenCalled()
expect(pending()).toBeNull()
})

it('keeps a pending registration when finishing it fails', async () => {
push.subscribe.mockRejectedValue(new Error('Worker unavailable'))
leavePending({ section: 'homepage', page: {} })
Notification.permission = 'granted'

await reload()

expect(push.subscribe).toHaveBeenCalledTimes(1)
expect(API.pushAlerts.create).not.toHaveBeenCalled()
expect(pending()).toEqual({ section: 'homepage', page: {} })
})

it('records no permission answer when the prompt closes unanswered', async () => {
push.subscribe.mockImplementation(async ({ onPermission }) => {
onPermission('default')
throw new Error('Push permission was not granted')
})
await alert.show('homepage')
await alert.controller.subscribe()
expect(API.pushAlerts.create.mock.calls.map(([data]) => data.kind)).toEqual(['shown', 'accepted'])
})

it('keeps actions available after a subscription failure and emits the error', async () => {
const error = new Error('Subscription failed')
const onError = jest.fn()
Expand Down
62 changes: 62 additions & 0 deletions __tests__/models/push_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import API, { Response } from '../../src/api'
import { Configuration } from '../../src/core'
import Hellotext from '../../src/hellotext'
import { Push } from '../../src/models/push'

const deferred = () => {
Expand Down Expand Up @@ -157,6 +158,48 @@ describe('Push', () => {
await expect(response.json()).resolves.toEqual({ id: 'identity-id' })
})

it('gives onPermission the answer before subscribing and registering', async () => {
Notification.permission = 'default'
const onPermission = jest.fn()

await push.subscribe({ onPermission })

expect(onPermission).toHaveBeenCalledTimes(1)
expect(onPermission).toHaveBeenCalledWith('granted')
expect(onPermission.mock.invocationCallOrder[0]).toBeLessThan(registration.pushManager.subscribe.mock.invocationCallOrder[0])
expect(onPermission.mock.invocationCallOrder[0]).toBeLessThan(API.pushIdentities.create.mock.invocationCallOrder[0])
})

it.each(['denied', 'default'])('gives onPermission the %s answer and rejects', async answer => {
Notification.permission = 'default'
Notification.requestPermission.mockResolvedValue(answer)
const onPermission = jest.fn()

await expect(push.subscribe({ onPermission })).rejects.toThrow('Push permission was not granted')

expect(onPermission).toHaveBeenCalledWith(answer)
expect(registration.pushManager.subscribe).not.toHaveBeenCalled()
})

it('gives onPermission an existing answer without prompting', async () => {
const onPermission = jest.fn()

await push.subscribe({ onPermission })

expect(Notification.requestPermission).not.toHaveBeenCalled()
expect(onPermission).toHaveBeenCalledWith('granted')
})

it('does not give the answer to a call that joins a pending request', async () => {
const first = jest.fn()
const second = jest.fn()

await Promise.all([push.subscribe({ onPermission: first }), push.subscribe({ onPermission: second })])

expect(first).toHaveBeenCalledTimes(1)
expect(second).not.toHaveBeenCalled()
})

it.each(['http', 'network'])('retries a failed %s request using the same browser subscription', async failure => {
jest.useFakeTimers()
if (failure === 'http') {
Expand Down Expand Up @@ -230,6 +273,8 @@ describe('Push', () => {
})

it('preserves the browser subscription when disabling the server identity fails', async () => {
const unsubscribed = jest.fn()
Hellotext.on('push:unsubscribed', unsubscribed)
storedSubscription = subscription
await push.initialize()
API.pushIdentities.destroy.mockResolvedValueOnce(responseFor(false))
Expand All @@ -238,6 +283,23 @@ describe('Push', () => {

expect(subscription.unsubscribe).not.toHaveBeenCalled()
expect(push.subscribed).toBe(true)
expect(unsubscribed).not.toHaveBeenCalled()
Hellotext.removeEventListener('push:unsubscribed', unsubscribed)
})

it.each([
['after removing the subscription', true],
['when there was no subscription to remove', false],
])('fires push:unsubscribed %s', async (_case, subscribed) => {
const unsubscribed = jest.fn()
Hellotext.on('push:unsubscribed', unsubscribed)
if (subscribed) storedSubscription = subscription
await push.initialize()

await push.unsubscribe()

expect(unsubscribed).toHaveBeenCalledTimes(1)
Hellotext.removeEventListener('push:unsubscribed', unsubscribed)
})

it.each([
Expand Down
2 changes: 1 addition & 1 deletion dist/hellotext.js

Large diffs are not rendered by default.

22 changes: 22 additions & 0 deletions docs/push.md
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,14 @@ if (Hellotext.push) {

The same method can be called when the visitor already has a Hellotext subscription; you do not need a separate "subscribe again" implementation.

To act on the visitor's answer before the subscription is registered, pass `onPermission`. It receives `granted`, `denied`, or `default` when the prompt was closed without an answer:

```js
await Hellotext.push.subscribe({
onPermission: permission => console.log('Push permission:', permission),
})
```

## 4. Connect your Unsubscribe button

Run the following code from your Unsubscribe button's click handler. Wait for the result before showing confirmation. A `null` result means there was no subscription to remove and can be treated as already unsubscribed:
Expand All @@ -178,6 +186,15 @@ if (Hellotext.push) {
}
```

Once the visitor has no subscription, including when there was none to remove, Hellotext fires
`push:unsubscribed`:

```js
Hellotext.on('push:unsubscribed', () => {
console.log('Push turned off')
})
```

## Show a Smart Alert

Enable the Smart Alert playbook in Hellotext and configure its sections. After initializing
Expand All @@ -196,6 +213,11 @@ Push subscription, and returns whether it displayed the alert. A disabled or unk
is not displayed. `Hellotext.alert` is unavailable when the playbook or Push is disabled,
or when the browser does not support Push.

If the page closes after the visitor allows notifications from the alert, but before their
subscription is saved, the next page that loads the alert finishes it without asking again.
`show` waits for that to finish, so the alert does not appear while it does. Permission the
visitor gave another tool on your site never subscribes them this way.

A [popup](/docs/popups.md) comes first, so the two never ask for Push at the same time. While
the popup loads, `show` waits. A popup showing only its bubble, or hidden by device targeting,
then lets the alert show. Once the visitor opens the popup, the alert does not show on that
Expand Down
Loading
Loading