Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Instance/newsletter #30

Merged
merged 19 commits into from
Jun 10, 2024
Merged
Show file tree
Hide file tree
Changes from 4 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
130 changes: 130 additions & 0 deletions app/content/newsletter-manual.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
<script async
subscriptions-control="manual"
type="application/javascript"
src="https://news.google.com/swg/js/v1/swg.js">
</script>

# Newsletter prompts
## Test the manual newsletter invocation

<button id="prompt">Prompt the newsletter sign-up</button>

## Newsletter Prompt Overview

A publisher can configure one or more newsletters for manual invocation by using an
initialized `swg.js` instance. In order to use this feature:

1. A publisher will provide Google with a prompt configuration per newsletter, and
will receive a `promptId` in response to call this newsletter configuration.
1. A publisher will fetch a valid prompt using the `promptId`, and then display it.
1. When configuring the prompt display code, a publisher will provide a callback
that will be used to store the responses from the newsletter signup, and
acknowledge to Google that the email address has been saved.

!!! caution JavaScript API is **in progress**
As the newsletter feature is currently in alpha, the following API exposed by
`swg.js` should be considered as being in draft, and not the final implementation.
!!!

## Configure Prompts

### Provide Prompt Configuration to Google

During the manual configuration beta of the Newsletter feature of RRM:E, publishers must
provide a manual configuration for each newsletter that they would like configured.

- **Publication Id** (as found in the Publisher Center configuration for the RRM:E publication)
- **Newsletter name** _(text)_ - The name of the newsletter
- **Newsletter description** _(text)_ - A description of the newsletter
- **Show a permission checkbox?** _(true/false)_ - A checkbox to determine if additional acceptance should be required of the newsletter subscriber
- **Permission** _(text)_ _optional_- A label for the permission checkbox. Required if showing a permission checkbox is required.

In response, Google will provide a `promptId` for each newsletter.

### Invoke Newsletter Prompts

To configure newsletter prompts, `swg.js` must first be configured on the page.
These examples show using the initialization of the library in `manual` mode, but the
APIs are also available in automatic mode.

### Get the prompt instance to display

To invoke a newsletter prompt, a publisher must use the `promptId` provided by
Google in response to submitting a prompt configuration. Publishers use the
`promptId` to fetch a valid prompt instance using the `subscriptions.getAvailableInterventions()` method from the initialized `swg.js` library.

```javascript
const newsletterId = '<id returend after submitting a newsletter config>';

const availableInterventions = await subscriptions.getAvailableInterventions();

const prompt = availableInterventions.find(({id}) => {
return id === newsletterId;
});
```

### Show the prompt, and handle the response

To display a prompt, use the returned value from `subscriptions.getAvailableInterventions()` and use the `show` method:

```javascript
prompt?.show({
isClosable: true,
onResult: (result) => {
//Store the result, which is the email of the newsletter signup.

//Return true to let Google know that you have received and processed
//the returned email.
return true;
}
});
```

#### Complete Example

```html
<!-- manual swg.js initialization -->
<script async
subscriptions-control="manual"
type="application/javascript"
src="https://news.google.com/swg/js/v1/swg.js">
</script>

<!-- configuring swg.js to invoke and handle newsletter prompts -->
<script type="module">
import { NewsletterPersistence } from 'js/newsletter-persistence.js';
const newsletterPersistence = new NewsletterPersistence();

(self.SWG = self.SWG || []).push( subscriptions => {
subscriptions.configure({paySwgVersion: '2'});
subscriptions.init('CAowqfCKCw');

const promptId = `newsletterId`;
const button = document.querySelector('#prompt');

button.onclick = async () => {
let promptInstanceId = await getPrompt(promptId);
await launchPrompt(promptInstanceId);
}
});

async function getPrompt(newsletterId) {
const availableInterventions = await subscriptions.getAvailableInterventions();

return availableInterventions.find(({id}) => {
return id === newsletterId;
});
}

async function launchPrompt(promptId) {
const prompt = await getPrompt(promptId);
prompt?.show({
isClosable: true,
onResult: (result) => {
newsletter.email = result;
return true;
}
});
}
</script>
```
6 changes: 5 additions & 1 deletion app/content/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -153,14 +153,18 @@ required unless specified:
{
"section": "Section label", // Label that appears for the section
"template": "app/views/layouts/demo-layout.html" // (optional) Handlebars template, defaults to demo-layout.html
"options": { //Optional section-level options
"suppressInNav": true //Hide this section from the nav, but preserve access directly
},
"links": [
{
"label": "Test", // Visible label
"url": "/", // Url (relative to root)
"content": "app/content/test.md" // .md or .html to render,
"script": "js/script.js" // Optional, relative to the /public folder
"options": { //Optional, passed directly to template rendering
"suppressStructuredDataMarkup" : true // suppressed the ld+json block rendering
"suppressStructuredDataMarkup" : true, // suppressed the ld+json block rendering
"suppressInNav": true //Hide this route from this section, but preserve access
}
}
// Insert more links for this section
Expand Down
6 changes: 5 additions & 1 deletion app/views/layouts/demo-layout.html
Original file line number Diff line number Diff line change
Expand Up @@ -111,17 +111,21 @@
<div class="developer-site-nav">

{{#each data.nav}}
<hr />
{{#unless this.options.suppressInNav}}
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This level of suppression suppresses the entire category from displaying.

<hr />
<h3 class="developer-site-nav-header developer-site-nav-title" >{{this.section}}</h3>
<ul class="developer-site-nav-list">
{{#each this.links}}
{{#unless this.options.suppressInNav}}
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This level of suppression only suppresses this item within the category.

<li id="{{this.id}}" class="{{this.current}}">
<a href="{{this.url}}">
{{this.label}}
</a>
</li>
{{/unless}}
{{/each}}
</ul>
{{/unless}}
{{/each}}
</div>

Expand Down
18 changes: 18 additions & 0 deletions lib/nav/documentation.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,23 @@ const sections = [
}
]
},
{
section: 'Newsletter',
links: [
{
label: 'Manual prompt invocation',
url: '/newsletter/manual',
content: 'app/content/newsletter-manual.md',
options: {
suppressStructuredDataMarkup: true
},
script: 'js/newsletter-manual.js'
}
],
options: {
suppressInNav: true
}
},
{
section: 'Using Extended Access',
links: [{
Expand Down Expand Up @@ -140,6 +157,7 @@ export function nav(req) {
section: current.section || '',
template: current.template || 'app/views/layouts/demo-layout.html',
script: script(req),
options: current?.options,
links: current.links.map((link) => {
link.id = link.label
.toLowerCase()
Expand Down
53 changes: 53 additions & 0 deletions public/js/newsletter-manual.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/**
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/**
* @fileoverview This client-side js file to handle newsletter prompts
*/

import { NewsletterPersistence } from './newsletter-persistence.js';
const newsletter = new NewsletterPersistence();

(self.SWG = self.SWG || []).push( subscriptions => {
subscriptions.configure({paySwgVersion: '2'});
subscriptions.init('CAowqfCKCw');

const promptId = `<pre-defined id>`;
const button = document.querySelector('#prompt');

button.onclick = async () => {
launchPrompt(promptId)
}
});

async function getPrompt(promptId) {
const availableInterventions = await subscriptions.getAvailableInterventions();

return availableInterventions.find(({id}) => {
return id === `<pre-defined string>`;
});
}

async function launchPrompt(promptId) {
const prompt = await getPrompt(promptId);
prompt?.show({
isClosable: true,
onResult: (result) => {
newsletter.email = result;
return true;
}
});
}
64 changes: 64 additions & 0 deletions public/js/newsletter-persistence.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/**
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/**
* @fileoverview Class for use with managing and persisting newsletter signups in the browser's localStorage.
*/


/**
* newsletterPersistence
* A class that exposes convenience functions for storing newsletter signups using the browser's localStorage as a cache.
*
* Note: In a production environment, a class like this could be used to
* store and retrieve access_tokens and state information from a database.
* This example stores state only
* in the browser's localStorage, which is temporary.
*/
class NewsletterPersistence {
constructor() {
this._signups = [];
}

set email(email) {
this._signups.push(email);
this.save();
}

get emails() {
return this._signups;
}

refresh() {
try {
const {signups} = JSON.parse(localStorage.getItem("newsletterPersistence"));
this._signups = signups;
} catch (e) {
console.log("Unable to restore signups from localStorage");
}
}

save() {
const {signups} = this;
localStorage.setItem("newsletterPersistence", JSON.stringify({signups}));
}

reset() {
localStorage.removeItem("newsletterPersistence");
}
}

export {NewsletterPersistence};